blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9f800488f761682a6f2281e27528e185e417363c
|
5ba90779651bb27480d84b0db3848b3db1fbe0ba
|
/aula_03/main.cpp
|
ecc21c52d6da0a0d62670c619f7b1d131b0dee73
|
[] |
no_license
|
LuizAFF/cpp_course
|
ce58dd26313e67e6241d37255da8dc52a56db919
|
7a9cb76e52339b3b66d0b6192bc3ed4c6187ccfd
|
refs/heads/master
| 2020-05-05T08:35:21.588069
| 2019-04-18T23:18:29
| 2019-04-18T23:18:29
| 179,869,727
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 588
|
cpp
|
main.cpp
|
#include <iostream>
#include "vector2d.h"
void print_vector(const math::Vector2D& v)
{
std::cout << "{" << v.x() << ", " << v.y() << "}\n";
}
int main()
{
using math::Vector2D;
auto v = Vector2D{3, 5};
print_vector(v);
v += {7, 8};
print_vector(v);
auto iv = inverted(v);
print_vector(v);
print_vector(iv);
v.invert();
print_vector(v);
v*=(0.5);
print_vector(v);
auto w = v + Vector2D{7, 8};
print_vector(v);
print_vector(w);
auto u = v * 0.5;
print_vector(v);
print_vector(u);
const auto &v2 = v;
}
|
746b7790ebcc3fbe80590a37009ba1824e1977fd
|
a5f3b0001cdb692aeffc444a16f79a0c4422b9d0
|
/main/autodoc/source/parser/cpp/pev.hxx
|
1a4c6acffc7dc879dfaa80d3a658ea6cfbfb745b
|
[
"Apache-2.0",
"CPL-1.0",
"bzip2-1.0.6",
"LicenseRef-scancode-other-permissive",
"Zlib",
"LZMA-exception",
"LGPL-2.0-or-later",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-philippe-de-muyter",
"OFL-1.1",
"LGPL-2.1-only",
"MPL-1.1",
"X11",
"LGPL-2.1-or-later",
"GPL-2.0-only",
"OpenSSL",
"LicenseRef-scancode-cpl-0.5",
"GPL-1.0-or-later",
"NPL-1.1",
"MIT",
"MPL-2.0",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"MPL-1.0",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"BSL-1.0",
"LicenseRef-scancode-docbook",
"LicenseRef-scancode-mit-old-style",
"Python-2.0",
"BSD-3-Clause",
"IJG",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-or-later",
"LGPL-2.0-only",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown",
"BSD-2-Clause",
"Autoconf-exception-generic",
"PSF-2.0",
"NTP",
"LicenseRef-scancode-python-cwi",
"Afmparse",
"W3C",
"W3C-19980720",
"curl",
"LicenseRef-scancode-x11-xconsortium-veillard",
"Bitstream-Vera",
"HPND-sell-variant",
"ICU"
] |
permissive
|
apache/openoffice
|
b9518e36d784898c6c2ea3ebd44458a5e47825bb
|
681286523c50f34f13f05f7b87ce0c70e28295de
|
refs/heads/trunk
| 2023-08-30T15:25:48.357535
| 2023-08-28T19:50:26
| 2023-08-28T19:50:26
| 14,357,669
| 907
| 379
|
Apache-2.0
| 2023-08-16T20:49:37
| 2013-11-13T08:00:13
|
C++
|
UTF-8
|
C++
| false
| false
| 10,745
|
hxx
|
pev.hxx
|
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef ADC_CPP_PEV_HXX
#define ADC_CPP_PEV_HXX
// USED SERVICES
// BASE CLASSES
#include <tokens/tokproct.hxx>
// COMPONENTS
// PARAMETERS
#include <ary/cpp/c_types4cpp.hxx>
namespace ary
{
namespace cpp
{
class Gate;
class InputContext;
class Namespace;
class Class;
class Enum;
class Typedef;
class Function;
class Variable;
class EnumValue;
class DefineEntity;
}
class Documentation;
}
namespace cpp
{
class PeEnvironment : protected TokenProcessing_Types
{
public:
// INQUIRY
virtual ~PeEnvironment() {}
// OPERATIONS
// Token results
void SetTokenResult(
E_TokenDone i_eDone,
E_EnvStackAction i_eWhat2DoWithEnvStack,
ParseEnvironment * i_pParseEnv2Push = 0 );
// Owner stack
void OpenNamespace(
ary::cpp::Namespace &
io_rOpenedNamespace );
void OpenExternC(
bool i_bOnlyForOneDeclaration = false );
void OpenClass(
ary::cpp::Class & io_rOpenedClass );
void OpenEnum(
ary::cpp::Enum & io_rOpenedEnum );
void CloseBlock(); /// Handles a '}' on file scope.
void CloseClass();
void CloseEnum();
void SetCurProtection( /// Handles 'public:', 'protected:' and 'private:' on class scope.
ary::cpp::E_Protection
i_eProtection );
void OpenTemplate(
const StringVector &
i_rParameters );
/// Removes parameters from this object.
DYN StringVector * Get_CurTemplateParameters();
/// Checks, if a template is still open, and if yes, closes it.
void Close_OpenTemplate();
// Special events
void Event_Class_FinishedBase(
const String & i_sParameterName );
void Event_Store_Typedef(
ary::cpp::Typedef & io_rTypedef );
void Event_Store_EnumValue(
ary::cpp::EnumValue &
io_rEnumValue );
void Event_Store_CppDefinition(
ary::cpp::DefineEntity &
io_rDefinition );
void Event_EnterFunction_ParameterList();
void Event_Function_FinishedParameter(
const String & i_sParameterName );
void Event_LeaveFunction_ParameterList();
void Event_EnterFunction_Implementation();
void Event_LeaveFunction_Implementation();
void Event_Store_Function(
ary::cpp::Function &
io_rFunction );
void Event_Store_Variable(
ary::cpp::Variable &
io_rVariable );
// Error recovery
void StartWaitingFor_Recovery();
// INQUIRY
ary::cpp::Gate & AryGate() const;
const ary::cpp::InputContext &
Context() const;
String CurFileName() const;
uintt LineCount() const;
bool IsWaitingFor_Recovery() const;
bool IsExternC() const;
private:
virtual void do_SetTokenResult(
E_TokenDone i_eDone,
E_EnvStackAction i_eWhat2DoWithEnvStack,
ParseEnvironment * i_pParseEnv2Push ) = 0;
virtual void do_OpenNamespace(
ary::cpp::Namespace &
io_rOpenedNamespace ) = 0;
virtual void do_OpenExternC(
bool i_bOnlyForOneDeclaration ) = 0;
virtual void do_OpenClass(
ary::cpp::Class & io_rOpenedClass ) = 0;
virtual void do_OpenEnum(
ary::cpp::Enum & io_rOpenedEnum ) = 0;
virtual void do_CloseBlock() = 0;
virtual void do_CloseClass() = 0;
virtual void do_CloseEnum() = 0;
virtual void do_SetCurProtection(
ary::cpp::E_Protection
i_eProtection ) = 0;
virtual void do_OpenTemplate(
const StringVector &
i_rParameters ) = 0;
virtual DYN StringVector *
do_Get_CurTemplateParameters() = 0;
virtual void do_Close_OpenTemplate() = 0;
virtual void do_Event_Class_FinishedBase(
const String & i_sBaseName ) = 0;
virtual void do_Event_Store_Typedef(
ary::cpp::Typedef & io_rTypedef ) = 0;
virtual void do_Event_Store_EnumValue(
ary::cpp::EnumValue &
io_rEnumValue ) = 0;
virtual void do_Event_Store_CppDefinition(
ary::cpp::DefineEntity &
io_rDefinition ) = 0;
virtual void do_Event_EnterFunction_ParameterList() = 0;
virtual void do_Event_Function_FinishedParameter(
const String & i_sParameterName ) = 0;
virtual void do_Event_LeaveFunction_ParameterList() = 0;
virtual void do_Event_EnterFunction_Implementation() = 0;
virtual void do_Event_LeaveFunction_Implementation() = 0;
virtual void do_Event_Store_Function(
ary::cpp::Function &
io_rFunction ) = 0;
virtual void do_Event_Store_Variable(
ary::cpp::Variable &
io_rVariable ) = 0;
virtual void do_StartWaitingFor_Recovery() = 0;
virtual ary::cpp::Gate &
inq_AryGate() const = 0;
virtual const ary::cpp::InputContext &
inq_Context() const = 0;
virtual String inq_CurFileName() const = 0;
virtual uintt inq_LineCount() const = 0;
virtual bool inq_IsWaitingFor_Recovery() const = 0;
virtual bool inq_IsExternC() const = 0;
};
// IMPLEMENTATION
inline void
PeEnvironment::SetTokenResult( E_TokenDone i_eDone,
E_EnvStackAction i_eWhat2DoWithEnvStack,
ParseEnvironment * i_pParseEnv2Push )
{ do_SetTokenResult(i_eDone, i_eWhat2DoWithEnvStack, i_pParseEnv2Push); }
inline void
PeEnvironment::OpenNamespace( ary::cpp::Namespace & io_rOpenedNamespace )
{ do_OpenNamespace(io_rOpenedNamespace); }
inline void
PeEnvironment::OpenExternC( bool i_bOnlyForOneDeclaration )
{ do_OpenExternC(i_bOnlyForOneDeclaration); }
inline void
PeEnvironment::OpenClass( ary::cpp::Class & io_rOpenedClass )
{ do_OpenClass(io_rOpenedClass); }
inline void
PeEnvironment::OpenEnum( ary::cpp::Enum & io_rOpenedEnum )
{ do_OpenEnum(io_rOpenedEnum); }
inline void
PeEnvironment::CloseBlock()
{ do_CloseBlock(); }
inline void
PeEnvironment::CloseClass()
{ do_CloseClass(); }
inline void
PeEnvironment::CloseEnum()
{ do_CloseEnum(); }
inline void
PeEnvironment::SetCurProtection( ary::cpp::E_Protection i_eProtection )
{ do_SetCurProtection(i_eProtection); }
inline void
PeEnvironment::OpenTemplate( const StringVector & i_rParameters )
{ do_OpenTemplate(i_rParameters); }
inline DYN StringVector *
PeEnvironment::Get_CurTemplateParameters()
{ return do_Get_CurTemplateParameters(); }
inline void
PeEnvironment::Close_OpenTemplate()
{ do_Close_OpenTemplate(); }
inline void
PeEnvironment::Event_Class_FinishedBase( const String & i_sBaseName )
{ do_Event_Class_FinishedBase(i_sBaseName); }
inline void
PeEnvironment::Event_Store_Typedef( ary::cpp::Typedef & io_rTypedef )
{ do_Event_Store_Typedef(io_rTypedef); }
inline void
PeEnvironment::Event_Store_EnumValue( ary::cpp::EnumValue & io_rEnumValue )
{ do_Event_Store_EnumValue(io_rEnumValue); }
inline void
PeEnvironment::Event_Store_CppDefinition( ary::cpp::DefineEntity & io_rDefinition )
{ do_Event_Store_CppDefinition(io_rDefinition); }
inline void
PeEnvironment::Event_EnterFunction_ParameterList()
{ do_Event_EnterFunction_ParameterList(); }
inline void
PeEnvironment::Event_Function_FinishedParameter( const String & i_sParameterName )
{ do_Event_Function_FinishedParameter(i_sParameterName); }
inline void
PeEnvironment::Event_LeaveFunction_ParameterList()
{ do_Event_LeaveFunction_ParameterList(); }
inline void
PeEnvironment::Event_EnterFunction_Implementation()
{ do_Event_EnterFunction_Implementation(); }
inline void
PeEnvironment::Event_LeaveFunction_Implementation()
{ do_Event_LeaveFunction_Implementation(); }
inline void
PeEnvironment::Event_Store_Function( ary::cpp::Function & io_rFunction )
{ do_Event_Store_Function(io_rFunction); }
inline void
PeEnvironment::Event_Store_Variable( ary::cpp::Variable & io_rVariable )
{ do_Event_Store_Variable(io_rVariable); }
inline void
PeEnvironment::StartWaitingFor_Recovery()
{ do_StartWaitingFor_Recovery(); }
inline ary::cpp::Gate &
PeEnvironment::AryGate() const
{ return inq_AryGate(); }
inline const ary::cpp::InputContext &
PeEnvironment::Context() const
{ return inq_Context(); }
inline String
PeEnvironment::CurFileName() const
{ return inq_CurFileName(); }
inline uintt
PeEnvironment::LineCount() const
{ return inq_LineCount(); }
inline bool
PeEnvironment::IsWaitingFor_Recovery() const
{ return inq_IsWaitingFor_Recovery(); }
inline bool
PeEnvironment::IsExternC() const
{ return inq_IsExternC(); }
} // namespace cpp
#endif
|
537f19bfea8123c6c4421250e9c5585d33595ab2
|
b8fa15bb04db522221ca70e10895981ad87bc864
|
/swalib_example/Code/Game/Entities/Components/menu_comp.cpp
|
e7b62038617317afece83daeb46fe7d3fb7e7b46
|
[
"BSD-2-Clause"
] |
permissive
|
yamikadesu/Minijuego
|
3e02e609b8c6e3261253b1347a87d4abbfbd2cfd
|
83a6a8d736c33fd866ff37a18633940b75d19b40
|
refs/heads/master
| 2022-03-25T15:59:07.330270
| 2019-12-03T21:08:08
| 2019-12-03T21:08:08
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,690
|
cpp
|
menu_comp.cpp
|
#include "../../../../../common/stdafx.h"
#include "menu_comp.h"
#include <assert.h>
#include "../entity.h"
#include "../../Managers/world.h"
#include ".././../../../../common/sys.h"
#include "../Messages/collision_msg.h"
#include "../Messages/new_pos_msg.h"
#include "../Player.h"
#include "../Messages/damage_msg.h"
#include "../Bullet.h"
#include "../Boss.h"
#include "../Messages/input_msg.h"
#include "../Upgrade.h"
#include "../Messages/entity_msg.h"
#include "../../Managers/Level.h"
#include "../../Managers/InterfaceController.h"
#include "../Messages/reset_msg.h"
#include "life_comp.h"
#include "bullet_comp.h"
#include "../Messages/render_msg.h"
#include "../../Managers/graphics_engine.h"
#include "../Messages/menu_msg.h"
#include "linear_vel_comp.h"
cMenuComp::cMenuComp()
{
}
cMenuComp::~cMenuComp()
{
RemoveEntities();
}
void cMenuComp::Slot(float fTimeDiff)
{
for (unsigned int i = 0; i < m_entities.size(); i++) {
m_entities[i]->Slot(fTimeDiff);
}
}
void cMenuComp::ReceiveMessage(cMessage &message)
{
cEntity *pOwnEnt = GetOwner();
assert(pOwnEnt != nullptr);
World* world = dynamic_cast<World*>(pOwnEnt);
const cClickMsg *pMsg6 = dynamic_cast<const cClickMsg *>(&message);
if (pMsg6 != nullptr) {
if (world->GetState() == World::MENU) {
for (unsigned int i = 0; i < m_entities.size(); i++) {
if (stopLogic) {
RemoveEntities();
break;
}
m_entities[i]->onClick(reinterpret_cast<void*>(world), pMsg6->GetPos());
}
}
return;
}
}
void cMenuComp::BeginDestroy() {
stopLogic = true;
}
void cMenuComp::RemoveEntities()
{
for (unsigned int i = 0; i < m_entities.size(); i++) {
DEL(m_entities[i]);
}
m_entities.clear();
}
|
0e13a3852be907597e9a90d9be04563f40b1cc4a
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/remoting/codec/video_decoder_verbatim.h
|
99027ff96f7ff80af441c2c2bac1b814f51a5d47
|
[
"BSD-3-Clause"
] |
permissive
|
chromium/chromium
|
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
|
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
|
refs/heads/main
| 2023-08-24T00:35:12.585945
| 2023-08-23T22:01:11
| 2023-08-23T22:01:11
| 120,360,765
| 17,408
| 7,102
|
BSD-3-Clause
| 2023-09-10T23:44:27
| 2018-02-05T20:55:32
| null |
UTF-8
|
C++
| false
| false
| 1,189
|
h
|
video_decoder_verbatim.h
|
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef REMOTING_CODEC_VIDEO_DECODER_VERBATIM_H_
#define REMOTING_CODEC_VIDEO_DECODER_VERBATIM_H_
#include "base/compiler_specific.h"
#include "remoting/codec/video_decoder.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_region.h"
namespace remoting {
// Video decoder implementations that decodes video packet encoded by
// VideoEncoderVerbatim. It just copies data from incoming packets to the
// video frames.
class VideoDecoderVerbatim : public VideoDecoder {
public:
VideoDecoderVerbatim();
VideoDecoderVerbatim(const VideoDecoderVerbatim&) = delete;
VideoDecoderVerbatim& operator=(const VideoDecoderVerbatim&) = delete;
~VideoDecoderVerbatim() override;
// VideoDecoder implementation.
void SetPixelFormat(PixelFormat pixel_format) override;
bool DecodePacket(const VideoPacket& packet,
webrtc::DesktopFrame* frame) override;
};
} // namespace remoting
#endif // REMOTING_CODEC_VIDEO_DECODER_VERBATIM_H_
|
a10692c2a2d4ea16ba1f5bf4ce54ad66a950bbd7
|
fce02052f360cf099a4607791dc02df8fb5c652f
|
/src/sot-tiago-steel-controller.cpp
|
b1a790adbf14343fbac94d06c44e5b3ce5269fb1
|
[
"BSD-2-Clause"
] |
permissive
|
olivier-stasse/sot-tiago
|
6fbad51331c5af51fe6eeb39b4ac1b1e286df618
|
bb5067736de6e94b4a8c376d4ea7dcfcc5f69fc5
|
refs/heads/master
| 2020-04-30T21:05:30.116346
| 2019-05-01T16:35:36
| 2019-05-15T08:15:44
| 177,086,509
| 0
| 0
| null | 2019-03-22T06:47:14
| 2019-03-22T06:47:14
| null |
UTF-8
|
C++
| false
| false
| 1,086
|
cpp
|
sot-tiago-steel-controller.cpp
|
/*
* Copyright 2018,
*
* Joseph Mirabel
*
* LAAS, CNRS
*
* This file is part of TIAGOController.
* TIAGOController is a free software,
*
*/
#include <sot/core/debug.hh>
/* TiagoSteel is the instance of TIAGO named "steel" */
#define ROBOTNAME std::string("TIAGOSTEEL")
#include "sot-tiago-steel-controller.hh"
const std::string SoTTiagoSteelController::LOG_PYTHON_TIAGOSTEEL="/tmp/TiagoSteelController_python.out";
SoTTiagoSteelController::SoTTiagoSteelController():
SoTTiagoController(ROBOTNAME)
{
startupPython();
interpreter_->startRosService ();
}
void SoTTiagoSteelController::startupPython()
{
SoTTiagoController::startupPython();
std::ofstream aof(LOG_PYTHON_TIAGOSTEEL.c_str());
runPython
(aof,
"from dynamic_graph.sot.tiago.steel.prologue import robot",
*interpreter_);
aof.close();
}
extern "C"
{
dgsot::AbstractSotExternalInterface * createSotExternalInterface()
{
return new SoTTiagoSteelController;
}
}
extern "C"
{
void destroySotExternalInterface(dgsot::AbstractSotExternalInterface *p)
{
delete p;
}
}
|
ec3f9dcd8ea3e3bfd82b7ccfb733090a843396be
|
7c2036e39b6317c7c8d5c2515eb19da6a8d21659
|
/Tiger-Zone/GameSrc/board.h
|
3c4e0ee14d06cc51eb4d5f3b62602148f28a9136
|
[] |
no_license
|
TigerZoneH/TigerZone
|
96c7fb2550d4c0a06abfac86ce8cdc9c4f9fff4f
|
e4d79b4fb7a644170fa9ba6e0d89518019dcb1e0
|
refs/heads/master
| 2020-06-14T12:07:52.473163
| 2016-11-29T00:44:23
| 2016-11-29T00:44:23
| 75,026,939
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,178
|
h
|
board.h
|
#ifndef board_h
#define board_h
#include <stdio.h>
#include "card.h"
#include "deck.h"
#include "trail.h"
#include "lake.h"
#include "jungle.h"
#include "regs.h"
#define ROWS 11 //MAXCARDS*2+1
#define COLS 11 //MAXCARDS*2+1
class Board {
public:
Board(Card* card); // board constructer
void printBoard(); // print the state of the board
void updatePossibleMoves(Card * card); // update valid moves array
bool checkIfFits(int i, int j, Card * card ); // check if a given card fits at a given location
bool placeCard(int i, int j, Card * card); // place a card onto the board
Deck * getDeck();
bool * getPossibleMoves();
bool checkPossibleMove(int i, int j);
bool isPossibleMove();
Card getCard(int i, int j);
int numJungles, numTrails, numLakes;
Jungle * jungles;
Trail * trails;
Lake * lakes;
void printRegions(int i, int j);
private:
Card ** board; // will point to 2D array of Cards a.k.a. the board
bool possibleMoves[ROWS][COLS]; // 2D array which holds valid moves
};
#endif /* board_hpp */
|
a57287edfa332bd2d3c6a4f05a274b781c6add43
|
4baaed7d17519c0e6ca4def1ccd3fe791cf4abce
|
/Offline 3/1305112.cpp
|
188a8cfca200f1609410b7e238a26120d5e8b930
|
[] |
no_license
|
rifatarefin/Computational-Geometry
|
d1cb0a80dcfa7f37560a9b6853150c4b16032cf3
|
cdd59fa9689afc4fc4cc5fb8e4fbac143537523e
|
refs/heads/master
| 2021-07-18T11:48:53.377419
| 2020-04-21T18:15:16
| 2020-04-21T18:15:16
| 129,820,398
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,861
|
cpp
|
1305112.cpp
|
#define XX -99999
#include<bits/stdc++.h>
#include<algorithm>
#include<GL/glut.h>
using namespace std;
#define pi (2*acos(0.0))
ifstream fin("input3.txt");
struct point
{
double x,y;
};
class triangle
{
public:
point a,b,c;
int idx;
map<point,int>opp_triangle_idx;
int child1=-1,child2=-1,child3=-1;
point center;
triangle(point x, point y, point z, int order)
{
a=x;
b=y;
c=z;
idx=order;
// opp_triangle_idx.clear();
opp_triangle_idx[a]=-1;
opp_triangle_idx[b]=-1;
opp_triangle_idx[c]=-1;
}
};
triangle tri_null({XX,XX}, {XX,XX}, {XX,XX},-1);
point p0= {-1500,1500};
point p1= {0,-3000};
point p2= {1500,1500};
vector<triangle>trlist;
vector<point>points;
void printTriangle(triangle x)
{
cout<<"\n";
cout<<x.a.x<<" "<<x.a.y<<"\n";
cout<<x.b.x<<" "<<x.b.y<<"\n";
cout<<x.c.x<<" "<<x.c.y<<"\n";
}
inline bool operator==(const point& lhs, const point& rhs)
{
return lhs.x == rhs.x && lhs.y==rhs.y ;
}
inline bool operator!=(const point& lhs, const point& rhs)
{
return lhs.x != rhs.x || lhs.y!=rhs.y ;
}
inline bool operator<(const point& lhs, const point& rhs)
{
return lhs.x < rhs.x || ((lhs.x == rhs.x)&&(lhs.y<rhs.y));
}
void input()
{
int n;
double a, b;
point np;
fin>>n;
points.clear();
for(int i=0; i<n; i++)
{
fin>>a>>b;
np.x=a;
np.y=b;
points.push_back(np);
}
}
double dist(point a,point b)
{
return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
}
double checkTurn(point a, point b, point c)
{
double v1x=b.x-a.x;
double v1y=b.y-a.y;
double v2x=c.x-a.x;
double v2y=c.y-a.y;
return v1x*v2y-v1y*v2x;
}
int position(triangle t, point p)
{
if(checkTurn(t.a,t.b,p)>0 && checkTurn(t.b,t.c,p)>0 && checkTurn(t.c,t.a,p)>0)return 1;
else if(checkTurn(t.a,t.b,p)>=0 && checkTurn(t.b,t.c,p)>=0 && checkTurn(t.c,t.a,p)>=0)return 2;
else return -1;
}
point getOppositePoint(triangle tr,point pr)
{
triangle *tmp;
tmp=&trlist[tr.opp_triangle_idx[pr]];
point p;
if(tmp->a!=tr.a && tmp->a!=tr.b && tmp->a!=tr.c)p=tmp->a;
else if(tmp->b!=tr.a && tmp->b!=tr.b && tmp->b!=tr.c)p=tmp->b;
else if(tmp->c!=tr.a && tmp->c!=tr.b && tmp->c!=tr.c)p=tmp->c;
return p;
}
//{
void lineFromPoints(point P, point Q, double &a,
double &b, double &c)
{
a = Q.y - P.y;
b = P.x - Q.x;
c = a*(P.x)+ b*(P.y);
}
void perpendicularBisectorFromLine(point P, point Q,
double &a, double &b, double &c)
{
point mid_point = {(P.x + Q.x)/2,
(P.y + Q.y)/2
};
// c = -bx + ay
c = -b*(mid_point.x) + a*(mid_point.y);
double temp = a;
a = -b;
b = temp;
}
point lineLineIntersection(double a1, double b1, double c1,
double a2, double b2, double c2)
{
double determinant = a1*b2 - a2*b1;
point a;
if (determinant == 0)
{
// The lines are parallel. This is simplified
// by returning a pair of FLT_MAX
return a= {FLT_MAX, FLT_MAX};
}
else
{
double x = (b2*c1 - b1*c2)/determinant;
double y = (a1*c2 - a2*c1)/determinant;
return a= {x, y};
}
}
point findCircumCenter(point P, point Q, point R)
{
// Line PQ is represented as ax + by = c
double a, b, c;
lineFromPoints(P, Q, a, b, c);
// Line QR is represented as ex + fy = g
double e, f, g;
lineFromPoints(Q, R, e, f, g);
// Converting lines PQ and QR to perpendicular
// vbisectors. After this, L = ax + by = c
// M = ex + fy = g
perpendicularBisectorFromLine(P, Q, a, b, c);
perpendicularBisectorFromLine(Q, R, e, f, g);
// The point of intersection of L and M gives
// the circumcenter
point circumcenter =
lineLineIntersection(a, b, c, e, f, g);
return circumcenter;
}
//}
bool checkIllegal(triangle tr, point k) //true=illegal
{
point i,j;
if(k==tr.a)
{
i=tr.b;
j=tr.c;
}
else if(k==tr.b)
{
i=tr.c;
j=tr.a;
}
else if(k==tr.c)
{
i=tr.a;
j=tr.b;
}
if((i==p0 || i==p1 || i==p2) &&(j==p0 || j==p1 || j==p2))return false; //false=legal
point l=getOppositePoint(tr,k);
if((i==p0 || i==p1 || i==p2) || (j==p0 || j==p1 || j==p2) || (k==p0 || k==p1 || k==p2) || (l==p0 || l==p1 || l==p2))
{
//cout<<l.x<<" "<<l.y<<endl;
if((k==p0 || k==p1 || k==p2) || (l==p0 || l==p1 || l==p2))return false;
point center=findCircumCenter(tr.a,tr.b,tr.c);
if(dist(center,l)>=dist(center,tr.a))return false;
return true;
}
point center=findCircumCenter(tr.a,tr.b,tr.c);
if(dist(center,l)<dist(center,tr.a))return true;
return false;
//return true;////
}
void update_opposite(triangle t1, int t2)
{
if(t2==-1)
{
return;
}
triangle tmp=trlist[t2];
if(tmp.a!=t1.a && tmp.a!=t1.b && tmp.a!=t1.c)tmp.opp_triangle_idx[tmp.a]=t1.idx;
else if(tmp.b!=t1.a && tmp.b!=t1.b && tmp.b!=t1.c)tmp.opp_triangle_idx[tmp.b]=t1.idx;
else if(tmp.c!=t1.a && tmp.c!=t1.b && tmp.c!=t1.c)tmp.opp_triangle_idx[tmp.c]=t1.idx;
trlist[t2]=tmp;
}
void legalize(triangle tr, point pr)
{
if(checkIllegal(tr,pr)==false)return;
// cout<<"legalizing "<<pr.x<<" "<<pr.y<<endl;
// printTriangle(tr);
// point f,g,h;
// f=getOppositePoint(tr,tr.a);
// g=getOppositePoint(tr,tr.b);
// h=getOppositePoint(tr,tr.c);
// cout<<"opposite"<<endl;
// cout<<f.x<<" "<<f.y<<endl;
// cout<<g.x<<" "<<g.y<<endl;
// cout<<h.x<<" "<<h.y<<endl;
point l=getOppositePoint(tr,pr);
triangle tr2=trlist[tr.opp_triangle_idx[pr]];
point i,j,k;
if(pr==tr.a)
{
i=tr.b;
j=tr.c;
k=tr.a;
}
else if(pr==tr.b)
{
i=tr.c;
j=tr.a;
k=tr.b;
}
else if(pr==tr.c)
{
i=tr.a;
j=tr.b;
k=tr.c;
}
int len=trlist.size();
triangle t1(k,l,j,len);
triangle t2(k,i,l,len+1);
t1.opp_triangle_idx[l]=tr.opp_triangle_idx[i];
t1.opp_triangle_idx[j]=t2.idx;
t1.opp_triangle_idx[k]=tr2.opp_triangle_idx[i];
update_opposite(t1,tr.opp_triangle_idx[i]);
update_opposite(t1,tr2.opp_triangle_idx[i]);
t2.opp_triangle_idx[i]=t1.idx;
t2.opp_triangle_idx[l]=tr.opp_triangle_idx[j];
t2.opp_triangle_idx[k]=tr2.opp_triangle_idx[j];
update_opposite(t2,tr.opp_triangle_idx[j]);
update_opposite(t2,tr2.opp_triangle_idx[j]);
trlist[tr.idx].child1=len;
trlist[tr.idx].child2=len+1;
trlist[tr2.idx].child1=len;
trlist[tr2.idx].child2=len+1;
trlist.push_back(t1);
trlist.push_back(t2);
legalize(trlist[t1.idx],k);
legalize(trlist[t2.idx],k);
//checkIllegal(i,j,zr)
}
void splitA(triangle t0, point z1)
{
int len=trlist.size();
triangle t1(t0.a,t0.b,z1,len);
triangle t2(t0.b,t0.c,z1,len+1);
triangle t3(t0.c,t0.a,z1,len+2);
t1.opp_triangle_idx[t1.a]=t2.idx;
t1.opp_triangle_idx[t1.b]=t3.idx;
t1.opp_triangle_idx[t1.c]=t0.opp_triangle_idx[t0.c];
update_opposite(t1,t0.opp_triangle_idx[t0.c]);
t2.opp_triangle_idx[t2.a]=t3.idx;
t2.opp_triangle_idx[t2.b]=t1.idx;
t2.opp_triangle_idx[t2.c]=t0.opp_triangle_idx[t0.a];
update_opposite(t2,t0.opp_triangle_idx[t0.a]);
t3.opp_triangle_idx[t3.a]=t1.idx;
t3.opp_triangle_idx[t3.b]=t2.idx;
t3.opp_triangle_idx[t3.c]=t0.opp_triangle_idx[t0.b];
update_opposite(t3,t0.opp_triangle_idx[t0.b]);
trlist[t0.idx].child1=len;
trlist[t0.idx].child2=len+1;
trlist[t0.idx].child3=len+2;
trlist.push_back(t1);
trlist.push_back(t2);
trlist.push_back(t3);
legalize(trlist[t1.idx],z1);
legalize(trlist[t2.idx],z1);
legalize(trlist[t3.idx],z1);
//Tlist.erase(remove(Tlist.begin(),Tlist.end(),t0),Tlist.end());
// vector<T>::iterator it=find(Tlist.begin(),Tlist.end(),t0);
// if(it!=Tlist.end())Tlist.erase(it);
}
void splitB(triangle tr,point pr)
{
point i,j,k,l;
if(checkTurn(tr.a,tr.b,pr)==0)
{
i=tr.a;
j=tr.b;
k=tr.c;
}
else if(checkTurn(tr.b,tr.c,pr)==0)
{
i=tr.b;
j=tr.c;
k=tr.a;
}
else if(checkTurn(tr.c,tr.a,pr)==0)
{
i=tr.c;
j=tr.a;
k=tr.b;
}
l=getOppositePoint(tr,k);
triangle tr2=trlist[tr.opp_triangle_idx[k]];
int len=trlist.size();
triangle t1(k,pr,j,len);
triangle t2(k,i,pr,len+1);
triangle t3(pr,l,j,len+2);
triangle t4(pr,i,l,len+3);
t1.opp_triangle_idx[k]=t3.idx;
t1.opp_triangle_idx[j]=t2.idx;
t1.opp_triangle_idx[pr]=tr.opp_triangle_idx[i];
update_opposite(t1,tr.opp_triangle_idx[i]);
t2.opp_triangle_idx[k]=t4.idx;
t2.opp_triangle_idx[i]=t1.idx;
t2.opp_triangle_idx[pr]=tr.opp_triangle_idx[j];
update_opposite(t2,tr.opp_triangle_idx[j]);
t3.opp_triangle_idx[j]=t4.idx;
t3.opp_triangle_idx[l]=t1.idx;
t3.opp_triangle_idx[pr]=tr2.opp_triangle_idx[i];
update_opposite(t3,tr2.opp_triangle_idx[i]);
t4.opp_triangle_idx[l]=t2.idx;
t4.opp_triangle_idx[i]=t3.idx;
t4.opp_triangle_idx[pr]=tr2.opp_triangle_idx[j];
update_opposite(t4,tr2.opp_triangle_idx[j]);
trlist[tr.idx].child1=len;
trlist[tr.idx].child2=len+1;
trlist[tr2.idx].child1=len+2;
trlist[tr2.idx].child2=len+4;
trlist.push_back(t1);
trlist.push_back(t2);
trlist.push_back(t3);
trlist.push_back(t4);
// printTriangle(t1);
// printTriangle(t2);
// printTriangle(t3);
// printTriangle(t4);
// cout<<checkIllegal(t1,pr)<<endl;
legalize(trlist[t1.idx],pr);
legalize(trlist[t2.idx],pr);
legalize(trlist[t3.idx],pr);
legalize(trlist[t4.idx],pr);
}
//{
bool containCorner(triangle t)
{
if(t.a==p0 || t.b==p0 || t.c==p0)return true;
else if(t.a==p1 || t.b==p1 || t.c==p1)return true;
else if(t.a==p2 || t.b==p2 || t.c==p2)return true;
return false;
}
int drawaxes,draw1=1,draw2=1;
void drawAxes()
{
if(drawaxes==1)
{
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINES);
{
glVertex3f( 100,0,0);
glVertex3f(-100,0,0);
glVertex3f(0,-100,0);
glVertex3f(0, 100,0);
glVertex3f(0,0, 100);
glVertex3f(0,0,-100);
}
glEnd();
}
}
void specialKeyListener(int key, int x,int y)
{
switch(key)
{
case GLUT_KEY_RIGHT:
draw1=1-draw1;
break;
case GLUT_KEY_LEFT:
draw2=1-draw2;
break;
case GLUT_KEY_DOWN:
drawaxes=1-drawaxes;
break;
}
}
void display()
{
//clear the display
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(0,0,0,0); //color black
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/********************
/ set-up camera here
********************/
//load the correct matrix -- MODEL-VIEW matrix
glMatrixMode(GL_MODELVIEW);
//initialize the matrix
glLoadIdentity();
//now give three info
//1. where is the camera (viewer)?
//2. where is the camera looking?
//3. Which direction is the camera's UP direction?
//gluLookAt(100,100,100, 0,0,0, 0,0,1);
//gluLookAt(200*cos(cameraAngle), 200*sin(cameraAngle), cameraHeight, 0,0,0, 0,0,1);
gluLookAt(0,0,200, 0,0,0, 0,1,0);
//again select MODEL-VIEW
glMatrixMode(GL_MODELVIEW);
/****************************
/ Add your objects from here
****************************/
//add objects
glScalef(10,10,1);
glPointSize(3);
for(vector<point>::iterator it=points.begin(); it!=points.end(); it++) //print
{
point tr=*it;
glColor3f(1.0, 1.0, 0);
glBegin(GL_POINTS);
{
glVertex3f(tr.x,tr.y,0);
}
glEnd();
}
if(draw1==1)
{
for(vector<triangle>::iterator it=trlist.begin(); it!=trlist.end(); it++) //print
{
triangle t=(*it);
if(t.child1!=-1)continue;
// if(t.a==p0 || t.b==p0 || t.c==p0)continue;
// else if(t.a==p1 || t.b==p1 || t.c==p1)continue;
// else if(t.a==p2 || t.b==p2 || t.c==p2)continue;
glColor3f(1.0,0,0);
glBegin(GL_LINES);
{
glVertex3f( t.a.x,t.a.y,0);
glVertex3f(t.b.x,t.b.y,0);
glVertex3f( t.b.x,t.b.y,0);
glVertex3f(t.c.x,t.c.y,0);
glVertex3f( t.c.x,t.c.y,0);
glVertex3f(t.a.x,t.a.y,0);
}
glEnd();
}
}
if(draw2==1)
{
for(vector<triangle>::iterator it=trlist.begin(); it!=trlist.end(); it++) //print
{
triangle t=(*it);
if(t.child1!=-1)continue;
if(t.a==p0 || t.b==p0 || t.c==p0)continue;
else if(t.a==p1 || t.b==p1 || t.c==p1)continue;
else if(t.a==p2 || t.b==p2 || t.c==p2)continue;
glColor3f(0,1.0,0);
triangle x1=trlist[t.opp_triangle_idx[t.a]];
if(containCorner(x1)==false)
{
glBegin(GL_LINES);
{
glVertex3f( t.center.x,t.center.y,0);
glVertex3f(x1.center.x,x1.center.y,0);
}
glEnd();
}
else
{
double vx1=t.c.x-t.b.x;
double vy1=t.c.y-t.b.y;
glBegin(GL_LINES);
{
glVertex3f( t.center.x,t.center.y,0);
glVertex3f(t.center.x+vy1,t.center.y-vx1,0);
}
glEnd();
}
triangle x2=trlist[t.opp_triangle_idx[t.b]];
if(containCorner(x2)==false)
{
glBegin(GL_LINES);
{
glVertex3f( t.center.x,t.center.y,0);
glVertex3f(x2.center.x,x2.center.y,0);
}
glEnd();
}
else
{
double vx1=t.a.x-t.c.x;
double vy1=t.a.y-t.c.y;
glBegin(GL_LINES);
{
glVertex3f( t.center.x,t.center.y,0);
glVertex3f(t.center.x+vy1,t.center.y-vx1,0);
}
glEnd();
}
triangle x3=trlist[t.opp_triangle_idx[t.c]];
if(containCorner(x3)==false)
{
glBegin(GL_LINES);
{
glVertex3f( t.center.x,t.center.y,0);
glVertex3f(x3.center.x,x3.center.y,0);
}
glEnd();
}
else
{
double vx1=t.b.x-t.a.x;
double vy1=t.b.y-t.a.y;
glBegin(GL_LINES);
{
glVertex3f( t.center.x,t.center.y,0);
glVertex3f(t.center.x+vy1,t.center.y-vx1,0);
}
glEnd();
}
}
}
drawAxes();
//ADD this line in the end --- if you use double buffer (i.e. GL_DOUBLE)
glutSwapBuffers();
}
void animate()
{
//angle+=0.05;
//codes for any changes in Models, Camera
glutPostRedisplay();
}
void init()
{
//codes for initialization
drawaxes=1;
//clear the screen
glClearColor(0,0,0,0);
/************************
/ set-up projection here
************************/
//load the PROJECTION matrix
glMatrixMode(GL_PROJECTION);
//initialize the matrix
glLoadIdentity();
//give PERSPECTIVE parameters
gluPerspective(80, 1, 1, 1000.0);
//field of view in the Y (vertically)
//aspect ratio that determines the field of view in the X direction (horizontally)
//near distance
//far distance
}
//}
int main(int argc, char **argv)
{
input();
triangle t0(p0,p1,p2,0);
trlist.push_back(t0);
// point z1=points[0];
//
// splitA(t0,z1);
int len=points.size();
for(int i=0; i<len; i++)
{
point z1=points[i];
triangle tq=trlist[0];
while(true)
{
if(tq.child1==-1)break;
if(position(trlist[tq.child1],z1)>0)
tq=trlist[tq.child1];
else if(position(trlist[tq.child2],z1)>0)
tq=trlist[tq.child2];
else tq=trlist[tq.child3];
}
if(position(tq,z1)==1)
splitA(tq,z1);
else if(position(tq,z1)==2)
splitB(tq,z1);
printTriangle(tq);
}
for(vector<triangle>::iterator it=trlist.begin(); it!=trlist.end(); it++) //print
{
triangle t=(*it);
if(t.child1!=-1)continue;
point p=findCircumCenter(t.a,t.b,t.c);
(*it).center=p;
// printTriangle(t);
// cout<<"opposite"<<endl;
// point f,g,h;
// f=getOppositePoint(t,t.a);
// g=getOppositePoint(t,t.b);
// h=getOppositePoint(t,t.c);
// cout<<f.x<<" "<<f.y<<endl;
// cout<<g.x<<" "<<g.y<<endl;
// cout<<h.x<<" "<<h.y<<endl;
// if(t.opp_triangle_idx[t.a]!=-1)printTriangle(trlist[t.opp_triangle_idx[t.a]]);
// if(t.opp_triangle_idx[t.b]!=-1)printTriangle(trlist[t.opp_triangle_idx[t.b]]);
// if(t.opp_triangle_idx[t.c]!=-1)printTriangle(trlist[t.opp_triangle_idx[t.c]]);
// cout<<"*****\n";
}
glutInit(&argc,argv);
glutInitWindowSize(700, 600);
glutInitWindowPosition(0, 0);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGB); //Depth, Double buffer, RGB color
glutCreateWindow("My OpenGL Program");
init();
glEnable(GL_DEPTH_TEST); //enable Depth Testing
glutDisplayFunc(display); //display callback function
glutIdleFunc(animate); //what you want to do in the idle time (when no drawing is occuring)
glutSpecialFunc(specialKeyListener);
glutMainLoop();
}
// for(vector<point>::iterator it=points.begin();it!=points.end();it++) //print
// {
// point tr=*it;
// cout<<tr.x<<" "<<tr.y<<" "<<endl;
// }
//
//cout<<bottom.x<<" "<<bottom.y<<endl; //prinnt
// cout<<rt.x<<" "<<rt.y<<endl;
// cout<<top.x<<" "<<top.y<<endl;
// cout<<lf.x<<" "<<lf.y<<endl;
|
2217068f7fbd29fecd61e9f97d54f16489d85966
|
eda03521b87da8bdbef6339b5b252472a5be8d23
|
/Userland/Libraries/LibGfx/ImageFormats/PortableImageMapLoader.h
|
21199a63fdf260e793f64737b06e3fa3ccb90334
|
[
"BSD-2-Clause"
] |
permissive
|
SerenityOS/serenity
|
6ba3ffb242ed76c9f335bd2c3b9a928329cd7d98
|
ef9b6c25fafcf4ef0b44a562ee07f6412aeb8561
|
refs/heads/master
| 2023-09-01T13:04:30.262106
| 2023-09-01T08:06:28
| 2023-09-01T10:45:38
| 160,083,795
| 27,256
| 3,929
|
BSD-2-Clause
| 2023-09-14T21:00:04
| 2018-12-02T19:28:41
|
C++
|
UTF-8
|
C++
| false
| false
| 3,726
|
h
|
PortableImageMapLoader.h
|
/*
* Copyright (c) 2020, Hüseyin ASLITÜRK <asliturk@hotmail.com>
* Copyright (c) 2022, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/BufferedStream.h>
#include <AK/MemoryStream.h>
#include <AK/RefPtr.h>
#include <AK/StringView.h>
#include <AK/Types.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/ImageFormats/PortableImageLoaderCommon.h>
namespace Gfx {
template<class TFormatDetails>
struct PortableImageMapLoadingContext {
using FormatDetails = TFormatDetails;
enum class Type {
Unknown,
ASCII,
RAWBITS
};
enum class State {
NotDecoded = 0,
Error,
HeaderDecoded,
BitmapDecoded,
};
Type type { Type::Unknown };
State state { State::NotDecoded };
size_t width { 0 };
size_t height { 0 };
FormatDetails format_details {};
RefPtr<Gfx::Bitmap> bitmap;
NonnullOwnPtr<SeekableStream> stream;
PortableImageMapLoadingContext(NonnullOwnPtr<SeekableStream> stream)
: stream(move(stream))
{
}
};
template<typename TContext>
class PortableImageDecoderPlugin final : public ImageDecoderPlugin {
public:
static bool sniff(ReadonlyBytes);
static ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> create(ReadonlyBytes);
virtual ~PortableImageDecoderPlugin() override = default;
virtual IntSize size() override;
virtual ErrorOr<ImageFrameDescriptor> frame(size_t index, Optional<IntSize> ideal_size = {}) override;
virtual ErrorOr<Optional<ReadonlyBytes>> icc_data() override;
private:
PortableImageDecoderPlugin(NonnullOwnPtr<SeekableStream> stream);
OwnPtr<TContext> m_context;
};
template<typename TContext>
PortableImageDecoderPlugin<TContext>::PortableImageDecoderPlugin(NonnullOwnPtr<SeekableStream> stream)
{
m_context = make<TContext>(move(stream));
}
template<typename TContext>
IntSize PortableImageDecoderPlugin<TContext>::size()
{
return { m_context->width, m_context->height };
}
template<typename TContext>
ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> PortableImageDecoderPlugin<TContext>::create(ReadonlyBytes data)
{
auto stream = TRY(try_make<FixedMemoryStream>(data));
auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) PortableImageDecoderPlugin<TContext>(move(stream))));
TRY(read_header(*plugin->m_context));
return plugin;
}
template<typename TContext>
bool PortableImageDecoderPlugin<TContext>::sniff(ReadonlyBytes data)
{
using Context = TContext;
if (data.size() < 2)
return false;
if (data.data()[0] == 'P' && data.data()[1] == Context::FormatDetails::ascii_magic_number)
return true;
if (data.data()[0] == 'P' && data.data()[1] == Context::FormatDetails::binary_magic_number)
return true;
return false;
}
template<typename TContext>
ErrorOr<ImageFrameDescriptor> PortableImageDecoderPlugin<TContext>::frame(size_t index, Optional<IntSize>)
{
if (index > 0)
return Error::from_string_literal("PortableImageDecoderPlugin: Invalid frame index");
if (m_context->state == TContext::State::Error)
return Error::from_string_literal("PortableImageDecoderPlugin: Decoding failed");
if (m_context->state < TContext::State::BitmapDecoded) {
if (decode(*m_context).is_error()) {
m_context->state = TContext::State::Error;
return Error::from_string_literal("PortableImageDecoderPlugin: Decoding failed");
}
}
VERIFY(m_context->bitmap);
return ImageFrameDescriptor { m_context->bitmap, 0 };
}
template<typename TContext>
ErrorOr<Optional<ReadonlyBytes>> PortableImageDecoderPlugin<TContext>::icc_data()
{
return OptionalNone {};
}
}
|
e609c7c86d3ea38385097a8ea0836a339f6a9ec5
|
b36f34b6a24d019d624d1cc74f5b29062eef2ba4
|
/frameworks/cocos2d-x/cocos/editor-support/spine/Bone.cpp
|
be28bd790b8cb48395ae8cafa44e90f2f275bec3
|
[
"MIT"
] |
permissive
|
zhongfq/cocos-lua
|
f49c1639f2c9a2a7678f9ed67e58114986ac882f
|
c2cf0f36ac0f0c91fb3456b555cacd8e8587be46
|
refs/heads/main
| 2023-08-17T17:13:05.705639
| 2023-08-17T06:06:36
| 2023-08-17T06:06:36
| 192,316,318
| 165
| 63
|
MIT
| 2023-08-14T23:59:30
| 2019-06-17T09:27:37
|
C
|
UTF-8
|
C++
| false
| false
| 14,299
|
cpp
|
Bone.cpp
|
/******************************************************************************
* Spine Runtimes License Agreement
* Last updated September 24, 2021. Replaces all prior versions.
*
* Copyright (c) 2013-2021, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
#include <spine/Bone.h>
#include <spine/BoneData.h>
#include <spine/Skeleton.h>
using namespace spine;
RTTI_IMPL(Bone, Updatable)
bool Bone::yDown = false;
void Bone::setYDown(bool inValue) {
yDown = inValue;
}
bool Bone::isYDown() {
return yDown;
}
Bone::Bone(BoneData &data, Skeleton &skeleton, Bone *parent) : Updatable(),
_data(data),
_skeleton(skeleton),
_parent(parent),
_x(0),
_y(0),
_rotation(0),
_scaleX(0),
_scaleY(0),
_shearX(0),
_shearY(0),
_ax(0),
_ay(0),
_arotation(0),
_ascaleX(0),
_ascaleY(0),
_ashearX(0),
_ashearY(0),
_a(1),
_b(0),
_worldX(0),
_c(0),
_d(1),
_worldY(0),
_sorted(false),
_active(false) {
setToSetupPose();
}
void Bone::update() {
updateWorldTransform(_ax, _ay, _arotation, _ascaleX, _ascaleY, _ashearX, _ashearY);
}
void Bone::updateWorldTransform() {
updateWorldTransform(_x, _y, _rotation, _scaleX, _scaleY, _shearX, _shearY);
}
void Bone::updateWorldTransform(float x, float y, float rotation, float scaleX, float scaleY, float shearX, float shearY) {
float cosine, sine;
float pa, pb, pc, pd;
Bone *parent = _parent;
_ax = x;
_ay = y;
_arotation = rotation;
_ascaleX = scaleX;
_ascaleY = scaleY;
_ashearX = shearX;
_ashearY = shearY;
if (!parent) { /* Root bone. */
float rotationY = rotation + 90 + shearY;
float sx = _skeleton.getScaleX();
float sy = _skeleton.getScaleY();
_a = MathUtil::cosDeg(rotation + shearX) * scaleX * sx;
_b = MathUtil::cosDeg(rotationY) * scaleY * sx;
_c = MathUtil::sinDeg(rotation + shearX) * scaleX * sy;
_d = MathUtil::sinDeg(rotationY) * scaleY * sy;
_worldX = x * sx + _skeleton.getX();
_worldY = y * sy + _skeleton.getY();
return;
}
pa = parent->_a;
pb = parent->_b;
pc = parent->_c;
pd = parent->_d;
_worldX = pa * x + pb * y + parent->_worldX;
_worldY = pc * x + pd * y + parent->_worldY;
switch (_data.getTransformMode()) {
case TransformMode_Normal: {
float rotationY = rotation + 90 + shearY;
float la = MathUtil::cosDeg(rotation + shearX) * scaleX;
float lb = MathUtil::cosDeg(rotationY) * scaleY;
float lc = MathUtil::sinDeg(rotation + shearX) * scaleX;
float ld = MathUtil::sinDeg(rotationY) * scaleY;
_a = pa * la + pb * lc;
_b = pa * lb + pb * ld;
_c = pc * la + pd * lc;
_d = pc * lb + pd * ld;
return;
}
case TransformMode_OnlyTranslation: {
float rotationY = rotation + 90 + shearY;
_a = MathUtil::cosDeg(rotation + shearX) * scaleX;
_b = MathUtil::cosDeg(rotationY) * scaleY;
_c = MathUtil::sinDeg(rotation + shearX) * scaleX;
_d = MathUtil::sinDeg(rotationY) * scaleY;
break;
}
case TransformMode_NoRotationOrReflection: {
float s = pa * pa + pc * pc;
float prx, rx, ry, la, lb, lc, ld;
if (s > 0.0001f) {
s = MathUtil::abs(pa * pd - pb * pc) / s;
pa /= _skeleton.getScaleX();
pc /= _skeleton.getScaleY();
pb = pc * s;
pd = pa * s;
prx = MathUtil::atan2(pc, pa) * MathUtil::Rad_Deg;
} else {
pa = 0;
pc = 0;
prx = 90 - MathUtil::atan2(pd, pb) * MathUtil::Rad_Deg;
}
rx = rotation + shearX - prx;
ry = rotation + shearY - prx + 90;
la = MathUtil::cosDeg(rx) * scaleX;
lb = MathUtil::cosDeg(ry) * scaleY;
lc = MathUtil::sinDeg(rx) * scaleX;
ld = MathUtil::sinDeg(ry) * scaleY;
_a = pa * la - pb * lc;
_b = pa * lb - pb * ld;
_c = pc * la + pd * lc;
_d = pc * lb + pd * ld;
break;
}
case TransformMode_NoScale:
case TransformMode_NoScaleOrReflection: {
float za, zc, s;
float r, zb, zd, la, lb, lc, ld;
cosine = MathUtil::cosDeg(rotation);
sine = MathUtil::sinDeg(rotation);
za = (pa * cosine + pb * sine) / _skeleton.getScaleX();
zc = (pc * cosine + pd * sine) / _skeleton.getScaleY();
s = MathUtil::sqrt(za * za + zc * zc);
if (s > 0.00001f) s = 1 / s;
za *= s;
zc *= s;
s = MathUtil::sqrt(za * za + zc * zc);
if (_data.getTransformMode() == TransformMode_NoScale &&
(pa * pd - pb * pc < 0) != (_skeleton.getScaleX() < 0 != _skeleton.getScaleY() < 0))
s = -s;
r = MathUtil::Pi / 2 + MathUtil::atan2(zc, za);
zb = MathUtil::cos(r) * s;
zd = MathUtil::sin(r) * s;
la = MathUtil::cosDeg(shearX) * scaleX;
lb = MathUtil::cosDeg(90 + shearY) * scaleY;
lc = MathUtil::sinDeg(shearX) * scaleX;
ld = MathUtil::sinDeg(90 + shearY) * scaleY;
_a = za * la + zb * lc;
_b = za * lb + zb * ld;
_c = zc * la + zd * lc;
_d = zc * lb + zd * ld;
}
}
_a *= _skeleton.getScaleX();
_b *= _skeleton.getScaleX();
_c *= _skeleton.getScaleY();
_d *= _skeleton.getScaleY();
}
void Bone::setToSetupPose() {
BoneData &data = _data;
_x = data.getX();
_y = data.getY();
_rotation = data.getRotation();
_scaleX = data.getScaleX();
_scaleY = data.getScaleY();
_shearX = data.getShearX();
_shearY = data.getShearY();
}
void Bone::worldToLocal(float worldX, float worldY, float &outLocalX, float &outLocalY) {
float a = _a;
float b = _b;
float c = _c;
float d = _d;
float invDet = 1 / (a * d - b * c);
float x = worldX - _worldX;
float y = worldY - _worldY;
outLocalX = (x * d * invDet - y * b * invDet);
outLocalY = (y * a * invDet - x * c * invDet);
}
void Bone::localToWorld(float localX, float localY, float &outWorldX, float &outWorldY) {
outWorldX = localX * _a + localY * _b + _worldX;
outWorldY = localX * _c + localY * _d + _worldY;
}
float Bone::worldToLocalRotation(float worldRotation) {
float sin = MathUtil::sinDeg(worldRotation);
float cos = MathUtil::cosDeg(worldRotation);
return MathUtil::atan2(_a * sin - _c * cos, _d * cos - _b * sin) * MathUtil::Rad_Deg + this->_rotation -
this->_shearX;
}
float Bone::localToWorldRotation(float localRotation) {
localRotation -= this->_rotation - this->_shearX;
float sin = MathUtil::sinDeg(localRotation);
float cos = MathUtil::cosDeg(localRotation);
return MathUtil::atan2(cos * _c + sin * _d, cos * _a + sin * _b) * MathUtil::Rad_Deg;
}
void Bone::rotateWorld(float degrees) {
float a = _a;
float b = _b;
float c = _c;
float d = _d;
float cos = MathUtil::cosDeg(degrees);
float sin = MathUtil::sinDeg(degrees);
_a = cos * a - sin * c;
_b = cos * b - sin * d;
_c = sin * a + cos * c;
_d = sin * b + cos * d;
}
float Bone::getWorldToLocalRotationX() {
Bone *parent = _parent;
if (!parent) {
return _arotation;
}
float pa = parent->_a;
float pb = parent->_b;
float pc = parent->_c;
float pd = parent->_d;
float a = _a;
float c = _c;
return MathUtil::atan2(pa * c - pc * a, pd * a - pb * c) * MathUtil::Rad_Deg;
}
float Bone::getWorldToLocalRotationY() {
Bone *parent = _parent;
if (!parent) {
return _arotation;
}
float pa = parent->_a;
float pb = parent->_b;
float pc = parent->_c;
float pd = parent->_d;
float b = _b;
float d = _d;
return MathUtil::atan2(pa * d - pc * b, pd * b - pb * d) * MathUtil::Rad_Deg;
}
BoneData &Bone::getData() {
return _data;
}
Skeleton &Bone::getSkeleton() {
return _skeleton;
}
Bone *Bone::getParent() {
return _parent;
}
Vector<Bone *> &Bone::getChildren() {
return _children;
}
float Bone::getX() {
return _x;
}
void Bone::setX(float inValue) {
_x = inValue;
}
float Bone::getY() {
return _y;
}
void Bone::setY(float inValue) {
_y = inValue;
}
float Bone::getRotation() {
return _rotation;
}
void Bone::setRotation(float inValue) {
_rotation = inValue;
}
float Bone::getScaleX() {
return _scaleX;
}
void Bone::setScaleX(float inValue) {
_scaleX = inValue;
}
float Bone::getScaleY() {
return _scaleY;
}
void Bone::setScaleY(float inValue) {
_scaleY = inValue;
}
float Bone::getShearX() {
return _shearX;
}
void Bone::setShearX(float inValue) {
_shearX = inValue;
}
float Bone::getShearY() {
return _shearY;
}
void Bone::setShearY(float inValue) {
_shearY = inValue;
}
float Bone::getAppliedRotation() {
return _arotation;
}
void Bone::setAppliedRotation(float inValue) {
_arotation = inValue;
}
float Bone::getAX() {
return _ax;
}
void Bone::setAX(float inValue) {
_ax = inValue;
}
float Bone::getAY() {
return _ay;
}
void Bone::setAY(float inValue) {
_ay = inValue;
}
float Bone::getAScaleX() {
return _ascaleX;
}
void Bone::setAScaleX(float inValue) {
_ascaleX = inValue;
}
float Bone::getAScaleY() {
return _ascaleY;
}
void Bone::setAScaleY(float inValue) {
_ascaleY = inValue;
}
float Bone::getAShearX() {
return _ashearX;
}
void Bone::setAShearX(float inValue) {
_ashearX = inValue;
}
float Bone::getAShearY() {
return _ashearY;
}
void Bone::setAShearY(float inValue) {
_ashearY = inValue;
}
float Bone::getA() {
return _a;
}
void Bone::setA(float inValue) {
_a = inValue;
}
float Bone::getB() {
return _b;
}
void Bone::setB(float inValue) {
_b = inValue;
}
float Bone::getC() {
return _c;
}
void Bone::setC(float inValue) {
_c = inValue;
}
float Bone::getD() {
return _d;
}
void Bone::setD(float inValue) {
_d = inValue;
}
float Bone::getWorldX() {
return _worldX;
}
void Bone::setWorldX(float inValue) {
_worldX = inValue;
}
float Bone::getWorldY() {
return _worldY;
}
void Bone::setWorldY(float inValue) {
_worldY = inValue;
}
float Bone::getWorldRotationX() {
return MathUtil::atan2(_c, _a) * MathUtil::Rad_Deg;
}
float Bone::getWorldRotationY() {
return MathUtil::atan2(_d, _b) * MathUtil::Rad_Deg;
}
float Bone::getWorldScaleX() {
return MathUtil::sqrt(_a * _a + _c * _c);
}
float Bone::getWorldScaleY() {
return MathUtil::sqrt(_b * _b + _d * _d);
}
void Bone::updateAppliedTransform() {
Bone *parent = _parent;
if (!parent) {
_ax = _worldX - _skeleton.getX();
_ay = _worldY - _skeleton.getY();
_arotation = MathUtil::atan2(_c, _a) * MathUtil::Rad_Deg;
_ascaleX = MathUtil::sqrt(_a * _a + _c * _c);
_ascaleY = MathUtil::sqrt(_b * _b + _d * _d);
_ashearX = 0;
_ashearY = MathUtil::atan2(_a * _b + _c * _d, _a * _d - _b * _c) * MathUtil::Rad_Deg;
}
float pa = parent->_a, pb = parent->_b, pc = parent->_c, pd = parent->_d;
float pid = 1 / (pa * pd - pb * pc);
float ia = pd * pid, ib = pb * pid, ic = pc * pid, id = pa * pid;
float dx = _worldX - parent->_worldX, dy = _worldY - parent->_worldY;
_ax = (dx * ia - dy * ib);
_ay = (dy * id - dx * ic);
float ra, rb, rc, rd;
if (_data.getTransformMode() == TransformMode_OnlyTranslation) {
ra = _a;
rb = _b;
rc = _c;
rd = _d;
} else {
switch (_data.getTransformMode()) {
case TransformMode_NoRotationOrReflection: {
float s = MathUtil::abs(pa * pd - pb * pc) / (pa * pa + pc * pc);
float sa = pa / _skeleton.getScaleX();
float sc = pc / _skeleton.getScaleY();
pb = -sc * s * _skeleton.getScaleX();
pd = sa * s * _skeleton.getScaleY();
pid = 1 / (pa * pd - pb * pc);
ia = pd * pid;
ib = pb * pid;
break;
}
case TransformMode_NoScale:
case TransformMode_NoScaleOrReflection: {
float cos = MathUtil::cosDeg(_rotation), sin = MathUtil::sinDeg(_rotation);
pa = (pa * cos + pb * sin) / _skeleton.getScaleX();
pc = (pc * cos + pd * sin) / _skeleton.getScaleY();
float s = MathUtil::sqrt(pa * pa + pc * pc);
if (s > 0.00001f) s = 1 / s;
pa *= s;
pc *= s;
s = MathUtil::sqrt(pa * pa + pc * pc);
if (_data.getTransformMode() == TransformMode_NoScale && pid < 0 != (_skeleton.getScaleX() < 0 != _skeleton.getScaleY() < 0)) s = -s;
float r = MathUtil::Pi / 2 + MathUtil::atan2(pc, pa);
pb = MathUtil::cos(r) * s;
pd = MathUtil::sin(r) * s;
pid = 1 / (pa * pd - pb * pc);
ia = pd * pid;
ib = pb * pid;
ic = pc * pid;
id = pa * pid;
break;
}
default:
break;
}
ra = ia * _a - ib * _c;
rb = ia * _b - ib * _d;
rc = id * _c - ic * _a;
rd = id * _d - ic * _b;
}
_ashearX = 0;
_ascaleX = MathUtil::sqrt(ra * ra + rc * rc);
if (_ascaleX > 0.0001f) {
float det = ra * rd - rb * rc;
_ascaleY = det / _ascaleX;
_ashearY = -MathUtil::atan2(ra * rb + rc * rd, det) * MathUtil::Rad_Deg;
_arotation = MathUtil::atan2(rc, ra) * MathUtil::Rad_Deg;
} else {
_ascaleX = 0;
_ascaleY = MathUtil::sqrt(rb * rb + rd * rd);
_ashearY = 0;
_arotation = 90 - MathUtil::atan2(rd, rb) * MathUtil::Rad_Deg;
}
}
bool Bone::isActive() {
return _active;
}
void Bone::setActive(bool inValue) {
_active = inValue;
}
|
30cb04f202d0bc8140ec49c4750d9c9ba606de75
|
3fe692c3ebf0b16c0a6ae9d8633799abc93bd3bb
|
/Contests/Training/Summer2018/day2/utility.h
|
6a0ef3e42358d3a79835c355e0a76ddde32b0ea1
|
[] |
no_license
|
kaloronahuang/KaloronaCodebase
|
f9d297461446e752bdab09ede36584aacd0b3aeb
|
4fa071d720e06100f9b577e87a435765ea89f838
|
refs/heads/master
| 2023-06-01T04:24:11.403154
| 2023-05-23T00:38:07
| 2023-05-23T00:38:07
| 155,797,801
| 14
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 206
|
h
|
utility.h
|
class intCollection
{
public:
int* array;
void add(int element);
int enumerate(int index);
void remove(int element, bool isOnly);
void outputElements();
}
class dictionary
{
}
|
97e8ea1f46886cda2252880db02143006afedbfe
|
9eb2c1fba5044d22ecf9354b58c76bab57937a48
|
/auto_curtain/auto_curtain.ino
|
1ee131a0ddcecd44fc66fc4db8b5f27734db798a
|
[] |
no_license
|
Gyumin-Kimm/arduino_auto_curtain
|
bc22597ad27ca4f1d93cc4000b2d52de39e9133a
|
7b192e2277eed11d3d98dac1e1c46ca081f13978
|
refs/heads/main
| 2023-03-02T20:54:54.603877
| 2021-02-12T04:37:46
| 2021-02-12T04:37:46
| 338,224,657
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,547
|
ino
|
auto_curtain.ino
|
int DC_MOTOR[6] = {42,44,46,48,4,5};
int LED[8] = {22,24,26,28,30,32,34,36};
int SWITCH[8] = {23,25,27,29,31,33,35,37};
int LED_EN_PIN =6, SW_EN_PIN = 7;
int light_sensor = A1;
int open_detect1 = 3, open_detect2 = 2;
int z=0;
#define LED_EN 1
#define SW_EN 1
void setup() {
Serial.begin(9600);
LED_SW_EN();
for(z=0;z<8;z++){
pinMode(LED[z],OUTPUT);
pinMode(SWITCH[z],INPUT);
}
for(z=0;z<6;z++){
pinMode(DC_MOTOR[z],OUTPUT);
}
pinMode(light_sensor,INPUT);
pinMode(open_detect1,INPUT);
pinMode(open_detect2,INPUT);
}
void loop() {
float light_data = analogRead(light_sensor)/204.6;
Serial.print("light_data[v] : ");
Serial.println(light_data);
if(light_data <= 3.00){ // low
MOTOR_control(10); // turn
PWM_open(0);
PWM_close(7); // move to od1
Serial.println("turn");
if(digitalRead(open_detect1)){
Serial.println("detect1111"); // od1 detect
PWM_close(0); // stop
delay(2000);
LED_blank();
Serial.println("open_d1 is detected");
}else{
MOTOR_control(10); // turn
PWM_open(0);
PWM_close(7); // move to od1
}
}else{ // high
PWM_open(0);
MOTOR_control(5); // turn reverse
PWM_close(0);
PWM_open(7); // move to od2
Serial.println("turn reverse");
if(digitalRead(open_detect2)){ // od2 detect
Serial.println("detect22222");
//DC_MOTOR stop
PWM_open(0); // stop
delay(2000);
LED_blank();
Serial.println("open_d2 is detected");
}else{
MOTOR_control(5); // turn reverse
PWM_close(0);
PWM_open(7); // move to od2
}
}
}
void MOTOR_control(unsigned char da){
for(z=0;z<4;z++){
if(da & 0x08){
digitalWrite(DC_MOTOR[z],HIGH);
}else{
digitalWrite(DC_MOTOR[z],LOW);
}
da *= 2;
}
}
void PWM_open(unsigned char spe){
analogWrite(DC_MOTOR[4],spe);
}
void PWM_close(unsigned char spe){
analogWrite(DC_MOTOR[5],spe);
}
void LED_blank(){
for(z=0;z<8;z++){
digitalWrite(LED[z],HIGH);
}
delay(100);
for(z=0;z<8;z++){
digitalWrite(LED[z],LOW);
}
delay(100);
}
void LED_SW_EN(){
pinMode(LED_EN_PIN,OUTPUT);
pinMode(SW_EN_PIN,OUTPUT);
#ifdef LED_EN
digitalWrite(LED_EN_PIN,LOW);
#else
digitalWrite(LED_EN_PIN,HIGH);
#endif
#ifdef SW_EN
digitalWrite(SW_EN_PIN,LOW);
#else
digitalWrite(SW_EN_PIN,HIGH);
#endif
}
|
65f2b8a510a2263478bcc45111ae04733936a08e
|
957f580a7cdb8fd628b2ed7855695817e790aa4c
|
/Framework/ObjectTypeRegistration.h
|
0211ef60be3a4d8f7cac71f2480441db3ff41a0b
|
[] |
no_license
|
foolhuang/Helium
|
b2a1a44b2da2310321ddbe02a096330ddbdc5c9f
|
ca0c7d6870b0bef2a70cba2bf2cb1337253032b5
|
refs/heads/master
| 2021-01-17T12:22:18.732439
| 2012-12-06T03:16:37
| 2012-12-06T03:16:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,098
|
h
|
ObjectTypeRegistration.h
|
//----------------------------------------------------------------------------------------------------------------------
// ObjectTypeRegistration.h
//
// Copyright (C) 2010 WhiteMoon Dreams, Inc.
// All Rights Reserved
//----------------------------------------------------------------------------------------------------------------------
#pragma once
#ifndef HELIUM_FRAMEWORK_OBJECT_TYPE_REGISTRATION_H
#define HELIUM_FRAMEWORK_OBJECT_TYPE_REGISTRATION_H
#include "Framework/Framework.h"
namespace Helium
{
/// Base class for GameObject type registration support.
///
/// This handles registration and unregistration for the following modules:
/// - Engine
/// - Graphics
/// - Framework
class HELIUM_FRAMEWORK_API ObjectTypeRegistration
{
public:
/// @name Construction/Destruction
//@{
virtual ~ObjectTypeRegistration();
//@}
/// @name Type Registration
//@{
virtual void Register();
virtual void Unregister();
//@}
};
}
#endif // HELIUM_FRAMEWORK_OBJECT_TYPE_REGISTRATION_H
|
dd5c17b77152bd3e12e2f36e57882ca572ed2530
|
49240dda24175feb158a9d9ab6523e643dd7f844
|
/CLI/Source.cpp
|
d4a0c0856a368f8d816a245a9679e3e259665232
|
[] |
no_license
|
drjphogan/vs1
|
69602fa4a37c63e6a6b9ebe632f8eae28c281dd5
|
7f0d024c99167e28903749f322483e280e35de24
|
refs/heads/master
| 2021-01-21T14:32:23.010183
| 2017-06-24T12:17:55
| 2017-06-24T12:17:55
| 95,294,843
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 345
|
cpp
|
Source.cpp
|
#include "ImportExport.h"
#include "Header.h"
#include "Header1.h"
using namespace System;
System::Double Example::CLI::Add_Doubles(System::Double fn1,
System::Double fn2
)
{
// comment to look at git fucntionality again
// comment number 2
// comment number 3
Vanilla v;
v.doSomething();
return fn1 + fn2;
}
|
122fc7b061b66a31a0695414655f02ba75ab2629
|
5736e29ff53dd51541e8d1a44a26a62cf7b1c936
|
/highscore.cpp
|
5b056b6e92445e99a143ae61d917e1547cc50f03
|
[] |
no_license
|
AlexStopar/Underfire
|
84d64c408631efbc82db70f3649bdcc744df91e7
|
bea7d9dabbeb367aa1844a35c8255dc4095c78e3
|
refs/heads/master
| 2020-12-24T13:36:24.040158
| 2015-08-23T20:58:22
| 2015-08-23T20:58:22
| 41,267,387
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,677
|
cpp
|
highscore.cpp
|
#include <vector>
#include <fstream>
#include <string>
#include <algorithm>
#include "highscore.h"
#include "common.h"
void HighScore::ReadScore()
{
std::string line;
std::ifstream highScoreFile("highscores.txt");
for (int i = 0; i < 11; i++)
{
std::getline(highScoreFile, line);
scores.push_back(std::make_pair(line.substr(0, line.find(",")),
atoi(line.substr(line.find(",") + 1, line.size() - 1).c_str())));
}
highScoreFile.close();
}
void HighScore::WriteScore()
{
std::ofstream highScoreFile("highscores.txt");
for (int i = 0; i < 11; i++)
{
highScoreFile << scores[i].first << "," << scores[i].second;
highScoreFile << "\n";
}
highScoreFile.close();
}
bool HighScore::checkAndAddNewScore(int newScore)
{
bool isNewScore = addScore(newScore, scores);
return isNewScore;
}
bool HighScore::addScore(int score, std::vector<std::pair<std::string, int>>& scores)
{
bool isNewScore = false;
for (std::vector<std::pair<std::string, int>>::iterator it = scores.begin(); it != scores.end(); ++it) {
if (score == it->second) return false;
}
scores.push_back(std::make_pair("AAA", score));
std::sort(scores.begin(), scores.end(), [](const std::pair<std::string, int> &p1, const std::pair<std::string, int> &p2)
{
return p1.second > p2.second;
});
if (scores[11].second != score) isNewScore = true;
scores.pop_back();
return isNewScore;
}
void HighScore::addInitials(std::string inputText)
{
for (std::vector<std::pair<std::string, int>>::iterator it = scores.begin(); it != scores.end(); ++it) {
if (it->second == score) it->first = inputText;
}
}
std::vector<std::pair<std::string, int>> HighScore::getScores()
{
return scores;
}
|
8a7b2fc0b373299ecdf711dc3ebd2d8ad102dbab
|
30ff5fcf25c42b132301950f6abc10bcb50aef81
|
/src/libradsrc/isotope.h
|
7abe48e6382833c98a5d9cdaa4a9a4ec7c922ac7
|
[
"BSD-3-Clause"
] |
permissive
|
crbates/radsrc
|
fd6f06bd83c24d77a587814af7ab827301538749
|
43f482b62b62bfd89522014c9c37783f44b348c6
|
refs/heads/master
| 2020-05-15T14:54:53.026907
| 2014-04-19T05:21:22
| 2014-04-19T05:21:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,287
|
h
|
isotope.h
|
/*
Copyright (c) 2006 The Regents of the University of California.
All rights reserved.
UCRL-CODE-224806
This software was developed by Lawrence Livermore National Laboratory.
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. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
/* Classes for storing information about isotopes */
#ifndef ISOTOPE_H_INCLUDE
#define ISOTOPE_H_INCLUDE
#include <string>
#include <vector>
#include <math.h>
#include "dbmanager.h" // temporary include for friendship
namespace radsrc {
/* -------------------------------------------------------------------- */
/*! \class CIsotope
* \brief Unique identification of each isotope (isomer)
*/
/* -------------------------------------------------------------------- */
class CIsotope {
public:
// Constructors, etc.
//! Null Isotope
CIsotope(void) : Z(0), A(0), m(0) { }
//! Construct Isotope
CIsotope(int z, int a, int mm=0) : Z(z), A(a), m(mm) { }
// operators
//! Two isotopes are equal
bool operator==(const CIsotope& iso) const { return Z==iso.Z && A==iso.A && m==iso.m; }
//! Order Isotopes first by Z, then A, then m
bool operator<(const CIsotope& iso) const { return Z<iso.Z || (Z==iso.Z && A<iso.A) ||
(Z==iso.Z && A==iso.A && m<iso.m);
}
// Public Methods
//! get atomic number (Z)
int getAtomicNumber(void) const { return Z; }
//! get mass number (A)
int getMassNumber(void) const { return A; }
//! get metastable designation (m)
int getMetastableNumber(void) const { return m; }
//! \brief write the canonical name of the isotope to a char buffer as a nul-terminated string
//! \param[out] str buffer to contain the isotope name
void toString(char *str) const;
//! \brief write the canonical name of the isotope to a STL string
//! \param[out] str string to contain the isotope name
void toString(std::string& str) const { char tmp[10]; toString(tmp); str=tmp; }
//! \brief write the canonical name of the isotope to a STL string
//! \return string to contain the isotope name
std::string toString() const { char tmp[10]; toString(tmp); return tmp; }
//! \brief Assign isotope from variations of the isotope name in a nul-terminated C string
//! \param[in] str string containing the isotope name
//! \return a reference to this object
CIsotope& fromString(const char *str);
//! \brief Assign isotope from variations of the isotope name in a STL string
//! \param[in] str string containing the isotope name
//! \return a reference to this object
CIsotope& fromString(const std::string& str) { return fromString(str.c_str()); }
//! is this a valid isotope (conversion from strings can fail)
bool isValid(void) const { return Z > 0 && A > 0; }
private:
int Z; //!< The atomic number.
int A; //!< The mass number.
int m; //!< The metastable state.
};
}
#endif
|
ecbe291b3b037506d0563fb6054b114a6e459e56
|
6827eb7ee2d1685ad49528021e43c84e1ff4c376
|
/1_semestre/If-algoritmos/exercícios1/atv2.cpp
|
d47ace063eb2138f7f754d5eb9b954d166634787
|
[] |
no_license
|
Darian-Mello/ciencia_computcao
|
d38bab4511a098afd35a92ec59993278ec21c981
|
bc55f8ca2df78c03f529902eb7cb5a5e6f875eae
|
refs/heads/main
| 2023-08-25T13:45:07.658041
| 2021-11-06T00:23:09
| 2021-11-06T00:23:09
| 425,117,018
| 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 318
|
cpp
|
atv2.cpp
|
#include <iostream>
using namespace std;
main(){
setlocale(LC_ALL, "portuguese");
float val1, val2, media;
cout << "digite um nímero:\n";
cin >> val1;
cout << "digite outro número\n";
cin >> val2;
media = (val1 + val2) / 2;
cout << "A média entre os números é:\n" << media;
}
|
c1398da6ac1568eebbc93ff9338d9ea02c16e7d3
|
336f202589113546d6afcf8e955a5f227cbc7321
|
/client/src/network/listener/ListenerConnection.cpp
|
64393986f2948714f4066af77b9b377c5809fe71
|
[] |
no_license
|
arodrigue003/poisson
|
a7310a4f460df74b0719fb0011e1bba047c4596c
|
45551464f3e86040d0ee1a5537abd1dd7406d95e
|
refs/heads/master
| 2021-06-14T20:23:13.331673
| 2017-03-20T08:41:49
| 2017-03-20T08:41:49
| 84,531,499
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 320
|
cpp
|
ListenerConnection.cpp
|
//
// Created by clejacquet on 18/03/17.
//
#include "ListenerConnection.h"
ListenerConnection::ListenerConnection(const std::string &address, unsigned short port) :
Connection(address, port)
{
}
void ListenerConnection::onReceive(const std::string &message) {
_listening_context->onResponse(message);
}
|
c1e1f99138d976969bd5d3e7d709b861bc4aa6e4
|
b460fa3bea2a2edf01c45cb70622a0a97246a0cd
|
/human_experiments/lab_software/video_capture/src/data_stream/LSLStream.h
|
64116444525c1190a29407135ed6e399744bb261
|
[
"MIT"
] |
permissive
|
ml4ai/tomcat
|
bfc36cb21971ff77e7d57889eb81b78a1e646646
|
e38f02fac40eb9ae6f0eee429e9a12faa00ecbaa
|
refs/heads/master
| 2023-08-16T07:05:13.574339
| 2023-07-30T13:24:33
| 2023-07-30T13:24:33
| 194,728,107
| 21
| 9
|
MIT
| 2023-09-14T15:29:30
| 2019-07-01T18:58:26
|
Python
|
UTF-8
|
C++
| false
| false
| 678
|
h
|
LSLStream.h
|
#pragma once
#include <string>
#include <lsl_cpp.h>
class LSLStream {
public:
lsl::stream_info stream_info;
LSLStream(const std::string& name,
int num_channels,
const std::string& source_id,
const std::string& stream_type,
int sampling_rate);
~LSLStream() = default;
LSLStream(const LSLStream&) = delete;
LSLStream& operator=(const LSLStream&) = delete;
LSLStream(LSLStream&&) = default;
LSLStream& operator=(LSLStream&&) = default;
/**
* Opens the stream and wait for consumers.
*
*/
void open();
protected:
std::unique_ptr<lsl::stream_outlet> outlet;
};
|
7eea042ccbdbac784a981fdf6bdd6312ffe4bdda
|
62150b03dd3a24d698d481eac85d5b86a4770139
|
/lableng1/p23.anulo.cpp
|
3eb5fe19d3cc26666813e5d1c729c0721347421a
|
[] |
no_license
|
castruaz/programa2020
|
1478ffa93c5a7317160f4041783a81ee74050f02
|
7a0ccc61002326fc3e0233f0d7c6f097b620f34b
|
refs/heads/main
| 2023-01-20T07:35:04.511698
| 2020-11-20T16:39:10
| 2020-11-20T16:39:10
| 310,668,639
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 630
|
cpp
|
p23.anulo.cpp
|
// Dado un angulo en radianes, mostrar su tipo
// Carlos Castaneda R
// 18 de Septiembre 2020
#include<stdio.h>
main(){
float angulo;
printf("Dado un angulo en radianes, mostrar su tipo \n");
printf("Dame un angulo en radianes \n");
scanf("%f", &angulo);
// angulo = ( angulo * 180 ) / 3.1416; // asumiendo que viene en radianes
if(angulo<90)
printf("El angulo es AGUDO\n");
if(angulo==90)
printf("El angulo es RECTO\n");
if(angulo>90 && angulo<180)
printf("El angulo es OBTUSO\n");
if(angulo==180)
printf("El angulo es LLANO\n");
if(angulo>180 && angulo<=360)
printf("El angulo es concavo");
}
|
7bd648bad5e64dc1d6f31ab152912ad147a711d6
|
7e6764389a9052b692cd830ce4b4baa59b8ae32d
|
/ex2_src/LightWeapon.cpp
|
3f2e53d9df6d2186fdea48fc60592dd0a9406ff4
|
[] |
no_license
|
IdanZimbler/Soldiers-Game-Project
|
132d9e5a0a2550f8bdde5489f58d06725bb99991
|
36db47d986b9a2b6009f7d3480646da1f6e388f2
|
refs/heads/master
| 2022-09-19T03:51:57.027966
| 2018-02-18T15:15:24
| 2018-02-18T15:15:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 634
|
cpp
|
LightWeapon.cpp
|
#include "LightWeapon.h"
//_________ Ctors & Dtors ___________
LightWeapon::LightWeapon(){}
LightWeapon::LightWeapon(Point & pos, double damage, int numOfShots) : AWeapon(pos,numOfShots) ,weaponPower(damage) {}
LightWeapon::LightWeapon(const LightWeapon & other)
{
copyVal(other);
}
LightWeapon::~LightWeapon(){}
//___________ Getter ___________
double LightWeapon::getWeaponPower() const
{
return weaponPower;
}
//___________ Method ___________
void LightWeapon::copyVal(const LightWeapon& other)
{
this->position = new Point(*other.position);
this->numOfShots = other.numOfShots;
this->weaponPower = other.weaponPower;
};
|
35c21ef0f04698b78a2ecad949eb9ffeb43b604d
|
dccd1058e723b6617148824dc0243dbec4c9bd48
|
/csacademy/round-25/0-sum-array.cpp
|
3457034e65814341f88a20fc0aef944298e1c430
|
[] |
no_license
|
imulan/procon
|
488e49de3bcbab36c624290cf9e370abfc8735bf
|
2a86f47614fe0c34e403ffb35108705522785092
|
refs/heads/master
| 2021-05-22T09:24:19.691191
| 2021-01-02T14:27:13
| 2021-01-02T14:27:13
| 46,834,567
| 7
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 600
|
cpp
|
0-sum-array.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr)
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
int solve()
{
int n;
cin >>n;
vector<ll> a(n);
rep(i,n) cin >>a[i];
rep(i,n)
{
a[i]=-a[i];
ll sum=0;
rep(j,n) sum+=a[j];
if(sum==0) return i+1;
a[i]=-a[i];
}
return -1;
}
int main()
{
cout << solve() << endl;
return 0;
}
|
4e761548fbd9b47103758f3f719a49bea2329da8
|
294621274eae9de26f5184167e9ff2a2df40e9da
|
/include/game/GroundUnit.hpp
|
3eb71843c3918d640c877ddfb853f6ad95fc4460
|
[] |
no_license
|
narzull/MarinesSaveTheQueen
|
fc18ec22ee602e683814247dc104c353c469e2ea
|
f4e65ce55fb6f1c984e5eb1f9de2edc8c3224db8
|
refs/heads/master
| 2016-09-05T21:56:22.576861
| 2013-03-23T18:36:48
| 2013-03-23T18:36:48
| 7,947,687
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,081
|
hpp
|
GroundUnit.hpp
|
#ifndef __GROUNDUNIT_HPP__
#define __GROUNDUNIT_HPP__
#include "../api/Entity.hpp"
#include <iostream>
#define GRASS_TYPE 1
#define ROCK_TYPE 2
//GroundUnit class
namespace game {
class GroundUnit : public api::Entity{
public:
//Static attribute
const static float s_GROUNDUNIT_WIDTH = 0.5 + 0.01;
const static float s_GROUNDUNIT_HEIGHT = 0.5 + 0.01;
//Constructor
GroundUnit(unsigned int X, unsigned int Y, unsigned int centralX, unsigned int centralY);
virtual ~GroundUnit(){};
//Getters
std::pair<unsigned int, unsigned int> getGroundUnitCoord()const{return m_Coord;};
unsigned int getType()const{return m_Type;};
int getWeight()const{return m_Weight;};
bool isOccupied()const{ return m_IsOccupied;};
//Setters
void setWeight(int weight){ m_Weight = weight;};
void setOccupied(bool occupation){m_IsOccupied = occupation;};
private:
std::pair<unsigned int, unsigned int> m_Coord;
unsigned int m_Type;
int m_Weight;
bool m_IsOccupied;
};
} // namespace game
#endif // __GROUNDUNIT_HPP__
|
739a97605e391613c2d87e7960b47a323eefc74a
|
362533a63fa41de2ff507f5e1115c1e36040f215
|
/SamSrc/sam/TopK.hpp
|
0c13ccce0b6289350bba7d77ade471c4799601a1
|
[
"MIT"
] |
permissive
|
elgood/SAM
|
9b1f842dc4c4b50204adc88fa5239c3abafbbc6c
|
aae417e670611a108a036c5fa5cb7308a5949822
|
refs/heads/master
| 2023-05-27T11:05:46.749021
| 2023-05-13T00:25:05
| 2023-05-13T00:25:05
| 81,900,152
| 6
| 5
|
NOASSERTION
| 2023-05-13T00:25:07
| 2017-02-14T03:24:45
|
C++
|
UTF-8
|
C++
| false
| false
| 3,489
|
hpp
|
TopK.hpp
|
#ifndef TOPK_HPP
#define TOPK_HPP
#include <vector>
#include <string>
#include <map>
#include <sam/SlidingWindow.hpp>
#include <sam/AbstractConsumer.hpp>
#include <sam/BaseComputation.hpp>
#include <sam/Util.hpp>
#include <sam/FeatureProducer.hpp>
namespace sam {
class TopKException : public std::runtime_error {
public:
TopKException(char const * message) : std::runtime_error(message) { }
};
template <typename EdgeType,
size_t valueField,
size_t... keyFields>
class TopK: public AbstractConsumer<EdgeType>,
public BaseComputation,
public FeatureProducer
{
public:
typedef typename EdgeType::LocalTupleType TupleType;
typedef typename std::tuple_element<valueField, TupleType>::type ValueType;
private:
size_t N; ///>Total number of elements
size_t b; ///>Number of elements per window
size_t k; ///>Top k elements managed
std::map<std::string, std::shared_ptr<SlidingWindow<ValueType>>> allWindows;
public:
/**
* Constructor
* \param N Total number of elements in big window.
* \param b Number of elements in smaller window.
* \param k Top k elements to be managed.
* \param nodeId The id of the node running this computation.
* \param featureMap The FeatureMap object that stores results.
* \param identifier The identifier for this feature producer.
*/
TopK(size_t N, size_t b, size_t k,
size_t nodeId,
std::shared_ptr<FeatureMap> featureMap,
string identifier);
bool consume(EdgeType const& edge);
void terminate() {}
};
template <typename EdgeType,
size_t valueField, size_t... keyFields>
TopK<EdgeType, valueField, keyFields...>::TopK(
size_t N,
size_t b,
size_t k,
size_t nodeId,
std::shared_ptr<FeatureMap> featureMap,
std::string identifier) :
BaseComputation(nodeId, featureMap, identifier)
{
this->N = N;
this->b = b;
this->k = k;
}
template <typename EdgeType,
size_t valueField, size_t... keyFields>
bool TopK<EdgeType, valueField, keyFields...>::consume(
EdgeType const& edge)
{
DEBUG_PRINT("Node %lu TopK::consume %s\n", nodeId,
sam::toString(edge.tuple).c_str());
this->feedCount++;
if (this->feedCount % this->metricInterval == 0) {
std::cout << "NodeId " << this->nodeId << " allWindows.size() "
<< allWindows.size() << std::endl;
}
// Creating a hopefully unique key from the key fields
std::string key = generateKey<keyFields...>(edge.tuple);
// Create a new sliding window if we haven't seen this key before
if (allWindows.count(key) == 0) {
auto sw = std::shared_ptr<SlidingWindow<ValueType>>(
new SlidingWindow<ValueType>(N,b,k));
std::pair<std::string, std::shared_ptr<
SlidingWindow<ValueType>>> p(key, sw);
allWindows[key] = sw;
}
ValueType value = std::get<valueField>(edge.tuple);
auto sw = allWindows[key];
sw->add(value);
std::vector<string> keys = sw->getKeys();
std::vector<double> frequencies = sw->getFrequencies();
if (keys.size() > 0 && frequencies.size() > 0) {
TopKFeature feature(keys, frequencies);
DEBUG_PRINT("Node %lu TopK::consume keys.size() %lu\n",
nodeId, keys.size());
this->featureMap->updateInsert(key, this->identifier, feature);
// notifySubscribers only takes doubles right now
notifySubscribers(edge.id, frequencies[0]);
}
return true;
}
}
#endif
|
efda8818ba1ee8faac0b2fbe2340230e801b3348
|
1a2ea9999d1ca66bf86074e4dbb077eaadb07cd8
|
/contest11/3.cpp
|
f76bf9399572c8b85777febf31e75748f9db6f89
|
[] |
no_license
|
olegtsts/contests
|
e06c5f06b1fd9938c04751537cc2d034bca17e01
|
ee3c26d85033fd411f057ea2b700e6fe9beca65a
|
refs/heads/master
| 2021-06-07T00:27:14.104607
| 2021-01-17T23:34:23
| 2021-01-17T23:34:23
| 92,220,220
| 0
| 0
| null | 2020-12-19T19:48:04
| 2017-05-23T21:04:35
|
C++
|
UTF-8
|
C++
| false
| false
| 2,777
|
cpp
|
3.cpp
|
#include <iostream>
#include <vector>
struct Move {
public:
Move()
{}
Move(const bool is_row, const int index)
: is_row(is_row)
, index(index)
{}
bool is_row;
int index;
};
std::vector<int> get_reverse_matrix(
std::vector<int>& matrix,
const int n,
const int m
) {
std::vector<int> new_matrix(n * m);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
new_matrix[j * n + i] = matrix[i * m + j];
}
}
return new_matrix;
}
void reverse_solution(
std::vector<Move>& solution
) {
for (auto& move: solution) {
move.is_row = !move.is_row;
}
}
std::vector<Move> solve(
std::vector<int>& matrix,
const int n,
const int m
) {
int min_index = -1;
int min_value = 501;
for (int j = 0; j < m; ++j) {
if (min_value > matrix[j]) {
min_value = matrix[j];
min_index = j;
}
}
std::vector<Move> solution;
for (int j = 0; j < m; ++j) {
int total_steps = matrix[j] - min_value;
for (int steps = 0; steps < total_steps; ++steps) {
solution.push_back(Move(false, j));
}
for (int i = 0; i < n; ++i) {
matrix[i * m + j] -= total_steps;
}
}
int first_col_actions = matrix[0] - min_value;
for (int i = 0; i < n; ++i) {
int total_steps = matrix[i * m];
for (int steps = 0; steps < total_steps; ++steps) {
solution.push_back(Move(true, i));
}
for (int j = 0; j < m; ++j) {
matrix[i * m + j] -= total_steps;
}
}
return solution;
}
bool is_matrix_zero(
std::vector<int>& matrix
) {
for (auto& el: matrix) {
if (el != 0) {
return false;
}
}
return true;
}
int main() {
int n,m;
std::cin >> n >> m;
std::vector<int> matrix(n * m);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
std::cin >> matrix[i * m + j];
}
}
std::vector<Move> solution;
if (n <= m) {
solution = solve(matrix, n, m);
if (!is_matrix_zero(matrix)) {
std::cout << -1 << std::endl;
return 0;
}
} else {
auto new_matrix = get_reverse_matrix(matrix, n, m);
solution = solve(new_matrix, m ,n);
reverse_solution(solution);
if (!is_matrix_zero(new_matrix)) {
std::cout << -1 << std::endl;
return 0;
}
}
std::cout << solution.size() << std::endl;
for (auto& move: solution) {
if (move.is_row) {
std::cout << "row ";
} else {
std::cout << "col ";
}
std::cout << move.index + 1 << std::endl;
}
return 0;
}
|
25a5ff8f425fb1b494f14dfc04991589080158f7
|
2b5bc02a4d50964ddbf0c66ae1cfa5e6c194a32f
|
/base/base/eventloop.h
|
2b7929b94fc06b7fb72106efb528196cbe9121e8
|
[] |
no_license
|
XiDianZuoYun/exerciseformuduo
|
b226930f42f2cc8ebcb25b4868d0264480c6bb01
|
9e39b59de3fae5c05e6117f713f3c51144fb90f8
|
refs/heads/master
| 2020-03-12T09:11:51.893369
| 2019-04-19T12:30:27
| 2019-04-19T12:30:27
| 130,547,099
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,065
|
h
|
eventloop.h
|
#ifndef EVENTLOOP_H
#define EVENTLOOP_H
#include <map>
#include <vector>
#include <unordered_map>
#include <jemalloc/include/jemalloc/jemalloc.h>
#include <memory>
#include <assert.h>
#include "timer.h"
#include "poller.h"
#include "channel.h"
#include "acceptor.h"
#include "tcpconnection.h"
#ifdef DEBUG
#include <iostream>
#endif
class TcpServer;
class UdpServer;
class EventLoop
{
public:
typedef std::shared_ptr<Channel> ChanPTR;
EventLoop(int maxevents=1024,TcpServer* ts=nullptr);
EventLoop(int maxevents=1024,UdpServer* us=nullptr);
~EventLoop();
//nocopyable
EventLoop(const EventLoop& other)=delete;
EventLoop& operator =(const EventLoop& other)=delete;
//The core function ,witch loops through the events on the epoll descriptor
//and processes them according to the user-registered callback function.
void loop();
//Modify an existing channel or regist a new channel
void updateChannel(Channel* channel)
{
poller->update_channel(channel);
}
//Remove an existing channel
void RemoveChannel(Channel* channel)
{
poller->remove_channel(channel);
}
void RemoveChannel(int fd)
{
poller->remove_channel(fd);
}
//Regist a new connection to this loop
//Register a timer with the eventloop and specify its callback function and time
void runAfter(Channel::functor &func,float time);
void runEvery(Channel::functor &func,float time);
//End loop, wake up poller
void stop(){
looping=false;
poller->Wakeup();
}
private:
//The following objects are owned by eventloop:a RB tree of timer file descriptor,a hash table that manage all the connection
//accepted by this port,a poller that can manage an IO-multiplexing file descriptor,an acceptor binded on the user's port.
std::map<float,timer*> timer_tree;
union ServerPtr{
TcpServer* Tcpserver_;
UdpServer* Udpserver_;
};
//0:Udp 1:Tcp
int8_t protocol;
ServerPtr server_;
Poller* poller;
bool looping=false;
};
#endif
|
9a9b56c720ca5e3f91e4f755cb41faa6bed4afa4
|
21f5e0cef9e8111c3dea689a5603b2e7a1e71e9b
|
/基础/1321棋盘问题.cpp
|
18d2df4918d9e8dfb8ddbe8660739da3e464f90b
|
[] |
no_license
|
q3erf/POJ-algorithm
|
2fa6e94fa26c59788347fcb586a3b7b084194853
|
6b70488bfa21e1a0d9d4253b71736d14097299ae
|
refs/heads/master
| 2023-02-17T10:44:12.575416
| 2021-01-17T12:03:12
| 2021-01-17T12:03:12
| 330,332,061
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 792
|
cpp
|
1321棋盘问题.cpp
|
#include<cstdio>
#include<cstring>
using namespace std;
char a[10][10];
//递归
bool visc[10];
int n;
int dothing(int r, int k){
if(k==0) return 1;
if(r>n) return 0;
int ans = 0;
for(int i=1; i<=n; i++){
if(a[r][i]=='#' && !visc[i]) {
visc[i] = 1;
ans += dothing(r+1, k-1);
visc[i] = 0;
}
}
ans += dothing(r+1, k);
return ans;
}
int main(){
int k;
while(scanf("%d%d", &n, &k) && n!=-1){
memset(visc, 0, sizeof(visc));
for(int i=1; i<=n; i++){
getchar();
for(int j=1; j<=n;j++){
scanf("%c", &a[i][j]);
}
}
printf("%d\n", dothing(1,k));
}
}
|
53e5131c5940ed12e8556357e904436c17ce91e5
|
46140229f8f8c99be20e7bbee5538bf7b6297857
|
/src/vtkh/filters/communication/MemStream.cpp
|
1dd1d2719c5233a7be279cf5b600afd3679d44a3
|
[
"BSD-3-Clause"
] |
permissive
|
jameskress/vtk-h
|
a44a6f5a5b5ce6c65f098f1faa4f83e29c19e847
|
241ae681365fb5d4b5d59ffaab4e18b7855563a6
|
refs/heads/master
| 2022-02-20T14:31:07.353835
| 2019-09-18T18:04:25
| 2019-09-18T18:04:25
| 132,791,486
| 0
| 1
| null | 2018-06-19T13:54:56
| 2018-05-09T17:31:35
|
C++
|
UTF-8
|
C++
| false
| false
| 2,109
|
cpp
|
MemStream.cpp
|
#include "MemStream.h"
using namespace std;
namespace vtkh
{
MemStream::MemStream(size_t sz0)
{
_pos = 0; _len = 0;
_maxLen = _len;
_data = NULL;
CheckSize(sz0);
}
MemStream::MemStream(size_t sz, const unsigned char *buff)
{
_pos = 0;
_len = sz;
_maxLen = _len;
_data = new unsigned char[_len];
memcpy(_data, buff, _len);
}
MemStream::MemStream(const MemStream &s)
{
_pos = 0;
_len = s.len();
_maxLen = _len;
_data = new unsigned char[_len];
memcpy(_data, s.data(), _len);
}
MemStream::~MemStream()
{
ClearMemStream();
}
void
MemStream::ClearMemStream()
{
if (_data)
{
delete [] _data;
_data = NULL;
}
_pos = 0;
_len = 0;
_maxLen = 0;
}
void
MemStream::CheckSize(size_t sz)
{
size_t reqLen = _pos+sz;
if (reqLen > _maxLen)
{
size_t newLen = 2*_maxLen; // double current size.
if (newLen < reqLen)
newLen = reqLen;
unsigned char *newData = new unsigned char[newLen];
if (_data)
{
memcpy(newData, _data, _len); // copy existing data to new buffer.
delete [] _data;
}
_data = newData;
_maxLen = newLen;
}
}
void
MemStream::SaveFile( const char *filename )
{
FILE *fp = fopen( filename, "wb" );
if( fp )
{
fwrite( &_len, sizeof(_len), 1, fp );
fwrite( _data, sizeof(_data[0]), _len, fp );
fflush( fp );
fclose( fp );
}
}
void
MemStream::LoadFile( const char *filename )
{
FILE *fp = fopen( filename, "rb" );
if( fp )
{
int res = 0;
ClearMemStream();
res = fread( &_len, sizeof(_len), 1, fp );
if (res != sizeof(_len))
{
cerr << "Bad read of MemStream from " << filename << endl;
}
CheckSize( _len );
res = fread( _data, sizeof(_data[0]), _len, fp );
if ((size_t)res != sizeof(_data[0])*_len)
{
cerr << "Bad read of MemStream from " << filename << endl;
}
fclose( fp );
}
}
} // namespace vtkh
|
62d11f5bf777ed5ad7ed0f973bd3bc8c52d82bbc
|
f05d2dbf0443ee2eaf130f54a85969f0c3892606
|
/APG4b/ex12.cpp
|
5eff5a05049a7b65214dcf29e2678f3e4be8244d
|
[] |
no_license
|
adako768/AtCoderContest
|
2f25d62dcd768528f7e7d87daf189b52e1093152
|
2ece75a85393e059471f4d19968d6a2df0a35f93
|
refs/heads/master
| 2022-12-17T08:36:16.515532
| 2020-09-21T07:24:49
| 2020-09-21T07:24:49
| 297,259,458
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 256
|
cpp
|
ex12.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int a=1;
for (int i=0;i<s.size();i++) {
char op = s[i];
if (op == '+') a ++;
else if (op == '-') a --;
}
cout << a << endl;
}
|
007bd2723544ba2c77539cfe36f7a47d498d411c
|
670d382e9f15b2ff0d8c8dbff964c2ff69d72dc1
|
/src/voronoi_generator.cpp
|
a81c1fe567528edda7e7b2f22634cfb9b908d9d6
|
[] |
no_license
|
andrewexo/VoronoiSphere
|
a92ddf2414a739a9ac6353df9b5e1d59dc8f4836
|
1a21c13671081a8397cadb06aceb4460578adbc1
|
refs/heads/master
| 2022-05-23T00:49:44.931566
| 2022-05-08T00:49:50
| 2022-05-08T00:49:50
| 161,680,746
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,284
|
cpp
|
voronoi_generator.cpp
|
#include "voronoi_generator.h"
#include "voronoi.h"
#include "globals.h"
#include <fstream>
#include <iostream>
#include <math.h>
#include <algorithm>
#include <cstring>
#include <boost/chrono.hpp>
#include <boost/timer/timer.hpp>
VoronoiGenerator::VoronoiGenerator()
{
cell_vector = NULL;
}
VoronoiGenerator::VoronoiGenerator(unsigned int seed) : sample_generator(seed)
{
cell_vector = NULL;
}
VoronoiGenerator::~VoronoiGenerator()
{
delete[] cell_vector;
}
void VoronoiGenerator::clear()
{
delete[] cell_vector;
cell_vector = NULL;
}
glm::dvec3 * VoronoiGenerator::genRandomInput(int count)
{
return sample_generator.getRandomPointsSphere(count);
}
void VoronoiGenerator::generate(glm::dvec3* points, int count, int gen, bool writeToFile)
{
{
//boost::timer::auto_cpu_timer total;
m_size = count;
m_gen = gen;
cell_vector = new VoronoiCell[count];
TaskGraph taskGraph; buildTaskGraph(&taskGraph, points);
taskGraph.processTasks(6);
completedCells = 0;
//std::cout << "total:\n";
}
if (writeToFile) writeDataToOBJ();
}
inline void VoronoiGenerator
::generateInitCellsTasks(
TaskGraph * tg,
glm::dvec3 * points,
SyncTask *& syncOut)
{
InitCellsTask* ict1 = new InitCellsTask;
InitCellsTask* ict2 = new InitCellsTask;
InitCellsTask* ict3 = new InitCellsTask;
ict1->td = {
cell_vector,
points,
0,
(unsigned int)(1.f / 6.f * m_size) - 1 };
ict2->td = {
cell_vector,
points,
(unsigned int)(1.f / 6.f * m_size),
(unsigned int)(2.f / 6.f * m_size) - 1 };
ict3->td = {
cell_vector,
points,
(unsigned int)(2.f / 6.f * m_size),
(unsigned int)(3.f / 6.f * m_size) - 1 };
tg->addTask(ict1);
tg->addTask(ict2);
tg->addTask(ict3);
InitCellsAndResizeSitesTask* icrt1 = new InitCellsAndResizeSitesTask;
InitCellsAndResizeSitesTask* icrt2 = new InitCellsAndResizeSitesTask;
InitCellsAndResizeSitesTask* icrt3 = new InitCellsAndResizeSitesTask;
icrt1->td = {
cell_vector,
points,
(unsigned int)(3.f / 6.f * m_size),
(unsigned int)(4.f / 6.f * m_size) - 1,
&m_sitesX,
m_size };
icrt2->td = {
cell_vector,
points,
(unsigned int)(4.f / 6.f * m_size),
(unsigned int)(5.f / 6.f * m_size) - 1,
&m_sitesY,
m_size };
icrt3->td = {
cell_vector,
points,
(unsigned int)(5.f / 6.f * m_size),
m_size - 1,
&m_sitesZ,
m_size };
tg->addTask(icrt1);
tg->addTask(icrt2);
tg->addTask(icrt3);
SyncTask* sync = new SyncTask;
tg->addTask(sync);
tg->addDependency(ict1, sync);
tg->addDependency(ict2, sync);
tg->addDependency(ict3, sync);
tg->addDependency(icrt1, sync);
tg->addDependency(icrt2, sync);
tg->addDependency(icrt3, sync);
syncOut = sync;
}
inline void VoronoiGenerator
::generateInitSitesTasks(
TaskGraph * tg,
SyncTask * syncIn,
SyncXYZ & syncOut)
{
InitSitesTask<X>* ist1 = new InitSitesTask<X>;
InitSitesTask<X>* ist2 = new InitSitesTask<X>;
InitSitesTask<Y>* ist3 = new InitSitesTask<Y>;
InitSitesTask<Y>* ist4 = new InitSitesTask<Y>;
InitSitesTask<Z>* ist5 = new InitSitesTask<Z>;
InitSitesTask<Z>* ist6 = new InitSitesTask<Z>;
ist1->td = {
cell_vector,
0,
(unsigned int)m_size / 2 - 1,
&m_sitesX };
ist2->td = {
cell_vector,
(unsigned int)m_size / 2,
(unsigned int)m_size - 1,
&m_sitesX };
ist3->td = {
cell_vector,
0,
(unsigned int)m_size / 2 - 1,
&m_sitesY };
ist4->td = {
cell_vector,
(unsigned int)m_size / 2,
(unsigned int)m_size - 1,
&m_sitesY };
ist5->td = {
cell_vector,
0,
(unsigned int)m_size / 2 - 1,
&m_sitesZ };
ist6->td = {
cell_vector,
(unsigned int)m_size / 2,
(unsigned int)m_size - 1,
&m_sitesZ };
tg->addTask(ist1);
tg->addTask(ist2);
tg->addTask(ist3);
tg->addTask(ist4);
tg->addTask(ist5);
tg->addTask(ist6);
tg->addDependency(syncIn, ist1);
tg->addDependency(syncIn, ist2);
tg->addDependency(syncIn, ist3);
tg->addDependency(syncIn, ist4);
tg->addDependency(syncIn, ist5);
tg->addDependency(syncIn, ist6);
SyncTask* syncX = new SyncTask;
SyncTask* syncY = new SyncTask;
SyncTask* syncZ = new SyncTask;
tg->addTask(syncX);
tg->addTask(syncY);
tg->addTask(syncZ);
tg->addDependency(ist1, syncX);
tg->addDependency(ist2, syncX);
tg->addDependency(ist3, syncY);
tg->addDependency(ist4, syncY);
tg->addDependency(ist5, syncZ);
tg->addDependency(ist6, syncZ);
syncOut.syncX = syncX;
syncOut.syncY = syncY;
syncOut.syncZ = syncZ;
}
inline void VoronoiGenerator::generateSortPointsTasks(TaskGraph * tg, SyncXYZ & syncInOut)
{
SortPoints1Task* sp1 = new SortPoints1Task;
SortPoints2Task* sp2 = new SortPoints2Task;
SortPoints1Task* sp3 = new SortPoints1Task;
SortPoints2Task* sp4 = new SortPoints2Task;
SortPoints1Task* sp5 = new SortPoints1Task;
SortPoints2Task* sp6 = new SortPoints2Task;
std::promise<VoronoiSite*>* p_temps1 = new std::promise<VoronoiSite*>[2];
std::promise<VoronoiSite*>* p_temps2 = new std::promise<VoronoiSite*>[2];
std::promise<VoronoiSite*>* p_temps3 = new std::promise<VoronoiSite*>[2];
std::promise<bool>* p_done1 = new std::promise<bool>[2];
std::promise<bool>* p_done2 = new std::promise<bool>[2];
std::promise<bool>* p_done3 = new std::promise<bool>[2];
sp1->td = { &m_sitesX, p_temps1, p_done1,
(p_temps1+1)->get_future(),
(p_done1+1)->get_future() };
sp2->td = { &m_sitesX, p_temps1 + 1, p_done1 + 1,
p_temps1->get_future(),
p_done1->get_future() };
sp3->td = { &m_sitesY, p_temps2, p_done2,
(p_temps2+1)->get_future(),
(p_done2+1)->get_future() };
sp4->td = { &m_sitesY, p_temps2 + 1, p_done2 + 1,
p_temps2->get_future(),
p_done2->get_future() };
sp5->td = { &m_sitesZ, p_temps3, p_done3,
(p_temps3+1)->get_future(),
(p_done3+1)->get_future() };
sp6->td = { &m_sitesZ, p_temps3 + 1, p_done3 + 1,
p_temps3->get_future(),
p_done3->get_future() };
tg->addTask(sp1);
tg->addTask(sp2);
tg->addTask(sp3);
tg->addTask(sp4);
tg->addTask(sp5);
tg->addTask(sp6);
tg->addDependency(syncInOut.syncX, sp1);
tg->addDependency(syncInOut.syncX, sp2);
tg->addDependency(syncInOut.syncY, sp3);
tg->addDependency(syncInOut.syncY, sp4);
tg->addDependency(syncInOut.syncZ, sp5);
tg->addDependency(syncInOut.syncZ, sp6);
SyncTask* syncX = new SyncTask;
SyncTask* syncY = new SyncTask;
SyncTask* syncZ = new SyncTask;
tg->addTask(syncX);
tg->addTask(syncY);
tg->addTask(syncZ);
tg->addDependency(sp1, syncX);
tg->addDependency(sp2, syncX);
tg->addDependency(sp3, syncY);
tg->addDependency(sp4, syncY);
tg->addDependency(sp5, syncZ);
tg->addDependency(sp6, syncZ);
syncInOut.syncX = syncX;
syncInOut.syncY = syncY;
syncInOut.syncZ = syncZ;
}
inline void VoronoiGenerator
::generateSweepTasks(
TaskGraph * tg,
SyncXYZ & syncIn,
SyncTask *& syncOut)
{
SweepTask<Increasing, X>* sweepIX = new SweepTask<Increasing, X>;
SweepTask<Decreasing, X>* sweepDX = new SweepTask<Decreasing, X>;
SweepTask<Increasing, Y>* sweepIY = new SweepTask<Increasing, Y>;
SweepTask<Decreasing, Y>* sweepDY = new SweepTask<Decreasing, Y>;
SweepTask<Increasing, Z>* sweepIZ = new SweepTask<Increasing, Z>;
SweepTask<Decreasing, Z>* sweepDZ = new SweepTask<Decreasing, Z>;
sweepIX->td = { &m_sitesX, m_gen, 1 };
sweepDX->td = { &m_sitesX, m_gen, 1 << 1 };
sweepIY->td = { &m_sitesY, m_gen, 1 << 2 };
sweepDY->td = { &m_sitesY, m_gen, 1 << 3 };
sweepIZ->td = { &m_sitesZ, m_gen, 1 << 4 };
sweepDZ->td = { &m_sitesZ, m_gen, 1 << 5 };
tg->addTask(sweepIX);
tg->addTask(sweepIY);
tg->addTask(sweepIZ);
tg->addTask(sweepDX);
tg->addTask(sweepDY);
tg->addTask(sweepDZ);
tg->addDependency(syncIn.syncX, sweepIX);
tg->addDependency(syncIn.syncX, sweepDX);
tg->addDependency(syncIn.syncY, sweepIY);
tg->addDependency(syncIn.syncY, sweepDY);
tg->addDependency(syncIn.syncZ, sweepIZ);
tg->addDependency(syncIn.syncZ, sweepDZ);
SyncTask* sync = new SyncTask;
tg->addTask(sync);
tg->addDependency(sweepIX, sync);
tg->addDependency(sweepIY, sync);
tg->addDependency(sweepIZ, sync);
tg->addDependency(sweepDX, sync);
tg->addDependency(sweepDY, sync);
tg->addDependency(sweepDZ, sync);
syncOut = sync;
}
inline void VoronoiGenerator::generateSortCellCornersTasks(TaskGraph * tg, SyncTask * syncIn)
{
for (int i = 0; i<6; i++)
{
SortCellCornersTask* scct = new SortCellCornersTask;
scct->td = { cell_vector, (unsigned int)(i / 6.f * m_size), (unsigned int)((i + 1) / 6.f * m_size - 1) };
tg->addTask(scct);
tg->addDependency(syncIn, scct);
}
}
void VoronoiGenerator::buildTaskGraph(TaskGraph* tg, glm::dvec3* points)
{
SyncTask* sync;
SyncXYZ syncXYZ;
generateInitCellsTasks(tg, points, sync);
generateInitSitesTasks(tg, sync, syncXYZ);
generateSortPointsTasks(tg, syncXYZ);
generateSweepTasks(tg, syncXYZ, sync);
generateSortCellCornersTasks(tg, sync);
tg->finalizeGraph();
}
inline void VoronoiGenerator::writeCell(std::ofstream & os, int i)
{
if (cell_vector[i].m_arcs != 0)
return;
int numCorners = (int)cell_vector[i].corners.size();
if (numCorners < 3)
return;
os.write(reinterpret_cast <const char*>(&numCorners), sizeof(int));
#ifdef CENTROID
os.write(reinterpret_cast <const char*>(&(cell_vector[i].position.x)), sizeof(double));
os.write(reinterpret_cast <const char*>(&(cell_vector[i].position.y)), sizeof(double));
os.write(reinterpret_cast <const char*>(&(cell_vector[i].position.z)), sizeof(double));
#endif
for (int j = 0; j < numCorners; j++)
{
os.write(reinterpret_cast <const char*>(&(cell_vector[i].corners[j].x)), sizeof(double));
os.write(reinterpret_cast <const char*>(&(cell_vector[i].corners[j].y)), sizeof(double));
os.write(reinterpret_cast <const char*>(&(cell_vector[i].corners[j].z)), sizeof(double));
}
}
void VoronoiGenerator::writeDataToFile()
{
boost::timer::auto_cpu_timer t;
std::ofstream file;
file.open("output/voronoi_data", std::ofstream::binary);
if (!file.is_open())
{
std::cout << "Unable to write data to file.\n";
return;
}
for (unsigned int i = 0; i < m_size; i++)
{
writeCell(file, i);
}
file.close();
std::cout << "Data written to: output/voronoi_data\n";
}
void VoronoiGenerator::writeDataToOBJ()
{
boost::timer::auto_cpu_timer t;
std::ofstream file;
file.open("output/voronoi_data.obj", std::ofstream::binary);
if (!file.is_open())
{
std::cout << "Unable to write data to file.\n";
return;
}
for (unsigned int i = 0; i < m_size; i++)
{
writeCellOBJ(file, i);
}
file.close();
std::cout << "Data written to: output/voronoi_data\n";
}
inline void VoronoiGenerator::writeCellOBJ(std::ofstream & os, int i)
{
if (cell_vector[i].m_arcs != 0)
return;
int numCorners = (int)cell_vector[i].corners.size();
if (numCorners < 3)
return;
std::string idx = "f ";
for (int j = 0; j < numCorners; j++)
{
os.write("v ", 2);
std::string x = std::to_string(cell_vector[i].corners[j].x); x += " ";
std::string y = std::to_string(cell_vector[i].corners[j].y); y += " ";
std::string z = std::to_string(cell_vector[i].corners[j].z); z += "\n";
os.write(x.c_str(), x.length());
os.write(y.c_str(), y.length());
os.write(z.c_str(), z.length());
idx += std::to_string(j-numCorners) + " ";
}
// write face
idx += "\n";
os.write(idx.c_str(), idx.length());
}
void InitCellsTask::process()
{
for (unsigned int i = td.start; i <= td.end; i++)
{
new(td.cells + i) VoronoiCell(td.points[i]);
}
}
void InitCellsAndResizeSitesTask::process()
{
for (unsigned int i = td.start; i <= td.end; i++)
{
new(td.cells + i) VoronoiCell(td.points[i]);
}
td.sites->resize(td.size);
}
template<Axis A>
void InitSitesTask<A>::process()
{
for (unsigned int i = td.start; i <= td.end; i++)
{
VoronoiSite site((td.cells)[i].position, td.cells + i, A);
(*(td.sites))[i] = site;
}
}
template class InitSitesTask<X>;
template class InitSitesTask<Y>;
template class InitSitesTask<Z>;
void SortPoints1Task::process()
{
// sort array half
unsigned int size = (unsigned int)td.sites->size() / 2;
VoronoiSiteCompare voronoiSiteCompare;
std::sort(td.sites->begin(), td.sites->begin() + size, voronoiSiteCompare);
// copy into scratch array
VoronoiSite* scratch = (VoronoiSite*)new char[size * sizeof(VoronoiSite)];
memcpy(scratch, td.sites->data(), size * sizeof(VoronoiSite));
// send data to other thread
td.p_temps->set_value(scratch);
VoronoiSite* scratch2 = td.f_temps.get();
// merge into original array
int a = 0; int b = 0;
for (unsigned int i = 0; i < size; i++)
{
if (voronoiSiteCompare(scratch[a], scratch2[b]))
(*td.sites)[i] = scratch[a++];
else
(*td.sites)[i] = scratch2[b++];
}
// wait for other thread
td.p_done->set_value(true);
bool ready = td.f_done.get();
// cleanup temp memory
delete[] scratch;
delete[] td.p_temps;
delete[] td.p_done;
}
void SortPoints2Task::process()
{
// sort array half
unsigned int size1 = (unsigned int)td.sites->size() / 2;
unsigned int size = (unsigned int)td.sites->size() - size1;
VoronoiSiteCompare voronoiSiteCompare;
std::sort(td.sites->begin() + size1, td.sites->end(), voronoiSiteCompare);
// copy into scratch array
VoronoiSite* scratch = (VoronoiSite*)new char[size * sizeof(VoronoiSite)];
memcpy(scratch, td.sites->data() + size, size * sizeof(VoronoiSite));
// send data to other thread
td.p_temps->set_value(scratch);
VoronoiSite* scratch1 = td.f_temps.get();
// merge into original array
int a = size1 - 1; int b = size - 1;
for (unsigned int i = (unsigned int)td.sites->size() - 1; i >= size1; i--)
{
if (voronoiSiteCompare(scratch1[a], scratch[b]))
(*td.sites)[i] = scratch[b--];
else
(*td.sites)[i] = scratch1[a--];
}
// wait for other thread
td.p_done->set_value(true);
bool ready = td.f_done.get();
// delete scratch
delete[] scratch;
}
template<Order O, Axis A>
inline void SweepTask<O, A>::process()
{
VoronoiSweeper<O, A> voronoiSweeper(td.sites, td.gen, td.taskId);
voronoiSweeper.sweep();
// std::cout << "Sweeper done\n";
}
template class SweepTask<Increasing, X>;
template class SweepTask<Increasing, Y>;
template class SweepTask<Increasing, Z>;
template class SweepTask<Decreasing, X>;
template class SweepTask<Decreasing, Y>;
template class SweepTask<Decreasing, Z>;
void SortCellCornersTask::process()
{
for (unsigned int i = td.start; i <= td.end; i++)
{
if (td.cell_vector[i].corners.size() == 0)
continue;
(td.cell_vector[i]).sortCorners();
#ifdef CENTROID
(td.cell_vector[i]).computeCentroid();
#endif
}
}
|
03e4177123bb3004af46236e63d0397a3f3aa23c
|
1e864ab10358c9a7afbbbec0c21a44f5d54f6787
|
/TestCpp/Student.h
|
b9a21b608ebf9e13a1e1251ff3f09dc07a27a91b
|
[] |
no_license
|
paulmedok/StudentManagerCpp
|
408452fabc1bb4dcaa2c8ef0d291319f6883f133
|
7569d8f80561e748c2e52faed8e5d28f5475a0f5
|
refs/heads/master
| 2020-04-23T13:46:22.733914
| 2015-05-05T16:13:50
| 2015-05-05T16:13:50
| 35,105,430
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 864
|
h
|
Student.h
|
#include "stdafx.h"
#include "stdio.h"
#include <iostream>
using namespace std;
int const NUMOFSUBJECTS = 5;
char* subj[];
struct Subject{
string title;
int mark;
};
struct Student{
string surname;
string name;
int age;
Subject subject[NUMOFSUBJECTS];
};
void EnterNumberOfStudents(int &studnumber);
void EnterStudentsFromCLI(Student* &s, int studnumber);
void PrintStudentsToCLI(Student* &s, int studnumber);
double GetAverangeMark(Student* &s);
void SortStudentsByMark(Student* &s, int studnumber, int subjindex);
Student* Dummy_5_Students();
void SwapStudents(Student* &s1, Student* &s2);
void SwapStudentsPtr(Student* &s1, Student* &s2);
void WriteStudentsToFileTXT(Student* &s, int studnumber);
void WriteStudentsToFileBIN(Student* &s, int studnumber);
void ReadStudentsFromFileBIN(Student* &s, int studnumber);
|
a4dc4b868f82becf2a2d5c9592e71d9a49a0c2b6
|
21ad87b624631f93773c19f92b71c2ff2f5d8744
|
/day04/ex03/Ice.cpp
|
394bede5259b05ab4d9f18d5bfe043fd0381f99e
|
[] |
no_license
|
WildBoarGonnaGo/42-Piscine-CPP
|
87799484255d2fae2247d0cbf99cd6a32de1c9ab
|
3f7132e5333713d73260eb577f84350198ffcffc
|
refs/heads/main
| 2023-06-07T00:04:56.954928
| 2021-05-19T11:43:05
| 2021-05-19T11:43:05
| 359,222,546
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 470
|
cpp
|
Ice.cpp
|
#include "Ice.hpp"
#include <iostream>
Ice::Ice() : AMateria("ice") { }
AMateria *Ice::clone() const
{
AMateria *res = new Ice();
return (res);
}
Ice::Ice(Ice const &ref)
{
*this = ref;
return ;
}
Ice &Ice::operator=(Ice const &ref)
{
this->setXP(ref.getXP());
return (*this);
}
void Ice::use(ICharacter &target)
{
std::cout << "* shoots an ice bolt at "
<< target.getName() << " *"
<< std::endl;
this->setXP(this->getXP() + 10);
}
Ice::~Ice( ) { }
|
5c111a855ff4d208858060d87589ec4ccf1b5ff5
|
91f511557a026f5ee2632a408a4a8c6dbe54dd03
|
/alica_tests/include/alica_tests/TestWorldModel.h
|
dfe93bac64726f5680bb66b50a2adfa2d7e300ea
|
[
"MIT"
] |
permissive
|
rapyuta-robotics/alica
|
c7bda986f132da5475451d2c42a823a33a933d4c
|
836684f35d5c7fe7920bd95da540da68a19864e5
|
refs/heads/devel
| 2023-08-03T14:39:47.569636
| 2023-07-18T05:40:03
| 2023-07-18T05:40:03
| 124,324,765
| 33
| 8
|
NOASSERTION
| 2023-09-07T05:24:18
| 2018-03-08T02:28:08
|
C++
|
UTF-8
|
C++
| false
| false
| 5,516
|
h
|
TestWorldModel.h
|
#pragma once
#include <alica/test/TestContext.h>
#include <atomic>
#include <string>
#include <unordered_map>
#include <vector>
namespace alicaTests
{
class TestWorldModelNew
{
public:
TestWorldModelNew(alica::test::TestContext* tc)
: _tc(tc)
{
}
alica::test::TestContext* getTestContext() { return _tc; }
private:
alica::test::TestContext* _tc;
};
class [[deprecated("Use TestWorldModelNew instead")]] TestWorldModel
{
public:
TestWorldModel();
virtual ~TestWorldModel();
bool isTransitionCondition1413201227586() const;
void setTransitionCondition1413201227586(bool transitionCondition1413201227586);
bool isTransitionCondition1413201389955() const;
void setTransitionCondition1413201389955(bool transitionCondition1413201389955);
bool isTransitionCondition1413201052549() const;
void setTransitionCondition1413201052549(bool transitionCondition1413201052549);
bool isTransitionCondition1413201367990() const;
void setTransitionCondition1413201367990(bool transitionCondition1413201367990);
bool isTransitionCondition1413201370590() const;
void setTransitionCondition1413201370590(bool transitionCondition1413201370590);
bool isTransitionCondition1625614729978() const;
void setTransitionCondition1625614729978(bool transitionCondition1625610805110);
bool isTransitionCondition1625776897472() const;
void setTransitionCondition1625776897472(bool transitionCondition1625776897472);
bool isTransitionCondition1625783869825() const;
void setTransitionCondition1625783869825(bool transitionCondition1625783869825);
bool isTransitionCondition1625783867495() const;
void setTransitionCondition1625783867495(bool transitionCondition1625783867495);
bool isTransitionCondition1626848015861() const;
void setTransitionCondition1626848015861(bool transitionCondition1626848015861);
// MasterPlanTestSyncTransition
bool isTransitionCondition1418825427317() const;
void setTransitionCondition1418825427317(bool transitionCondition1418825427317);
bool isTransitionCondition1418825428924() const;
void setTransitionCondition1418825428924(bool transitionCondition1418825428924);
bool isPreCondition1418042929966() const;
void setPreCondition1418042929966(bool preCondition1418042929966);
bool isRuntimeCondition1418042967134() const;
void setRuntimeCondition1418042967134(bool runtimeCondition1418042967134);
// Adjacent plans success test transitions
bool isTransitionCondition1747408236004727286() const;
void setTransitionCondition1747408236004727286(bool transitionCondition1747408236004727286);
bool isTransitionCondition1067314038887345208() const;
void setTransitionCondition1067314038887345208(bool transitionCondition1067314038887345208);
// Test Tracing MasterPlan
bool isPreCondition1840401110297459509() const;
void setPreCondition1840401110297459509(bool preCondition1840401110297459509);
bool isSwitchingEntryPoints() const;
void setSwitchingEntryPoints(bool switchEntryPoints);
std::vector<double> robotsXPos;
double x;
std::unordered_map<std::string, int> passedParameters;
std::vector<std::string> configParameter;
std::vector<std::pair<std::string, std::string>> tracingTags;
std::vector<std::pair<std::string, std::string>> tracingLogs;
std::unordered_map<std::string, std::string> tracingParents;
void reset();
// Failure handling tests
void failurePlanInitCalled();
int failurePlanInitCallCount() const;
void enableTransitionCondition3194919312481305139();
bool transitionCondition3194919312481305139Enabled() const;
void setTransitionCondition1446293122737278544(bool value);
bool isTransitionCondition1446293122737278544() const;
void setTransitionCondition1023566846009251524(bool value);
bool isTransitionCondition1023566846009251524() const;
private:
std::atomic<bool> transitionCondition1413201227586;
std::atomic<bool> transitionCondition1413201389955;
std::atomic<bool> transitionCondition1413201052549;
std::atomic<bool> transitionCondition1413201367990;
std::atomic<bool> transitionCondition1413201370590;
// SyncTransitionTest
std::atomic<bool> transitionCondition1418825427317;
std::atomic<bool> transitionCondition1418825428924;
// PlanTypeTest
std::atomic<bool> preCondition1418042929966;
std::atomic<bool> runtimeCondition1418042967134;
// Engine rules scheduling test
std::atomic<bool> transitionCondition1625614729978;
// Engine rules scheduling test failure transition
std::atomic<bool> transitionCondition1625776897472;
// Top level failure
std::atomic<bool> transitionCondition1625783869825;
// SubPlan
std::atomic<bool> transitionCondition1625783867495;
// master plan final transition
std::atomic<bool> transitionCondition1626848015861;
// tracing master plan
std::atomic<bool> preCondition1840401110297459509;
// Adjacent plans success test
std::atomic<bool> transitionCondition1747408236004727286;
std::atomic<bool> transitionCondition1067314038887345208;
std::atomic<bool> switchEntryPoints;
// Failure handling tests
std::atomic<int> failurePlanInitCallCounter;
std::atomic<bool> transitionCondition3194919312481305139;
std::atomic<bool> transitionCondition1446293122737278544;
std::atomic<bool> transitionCondition1023566846009251524;
};
} // namespace alicaTests
|
ebb5aa5f9ff75a889d5d84a98ea111948dd62ee2
|
b995c93827f17daab1a767738b7fef26ca09ccdc
|
/problems/PAT/PATA1067_solution2.cpp
|
47078e8c3e835b33714bfd7a970e0f04de88cf5d
|
[] |
no_license
|
JIANGLY33/AlgorithmProblems
|
2c67de5156236f5710b7fe24cc51e509408e0061
|
8ebf3e2826abf150a8c8f915411d150e36a02a1d
|
refs/heads/master
| 2020-07-18T21:39:44.920375
| 2019-10-05T09:00:30
| 2019-10-05T09:00:30
| 206,316,899
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 760
|
cpp
|
PATA1067_solution2.cpp
|
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100010;
int main() {
int n;
scanf("%d",&n);
//除0以外未在自己位置上的数字个数,交换次数
int left = n-1,ans = 0,pos[n];
for(int i = 0; i < n; i++) {
int temp;
scanf("%d",&temp);
pos[temp] = i;
if(temp == i && temp != 0) {
left--;
}
}
int k = 1;
while(left > 0){
if(pos[0] == 0){
while(k < n){
if(pos[k] != k){
swap(pos[0],pos[k]);
ans++; //交换次数+1,left不变,因为未归位的数并未减少
break;
}
k++;
}
}
while(pos[0] != 0){
swap(pos[0],pos[pos[0]]);//将0的位置和0的坐标数的位置进行交换
ans++;
left--;
}
}
printf("%d",ans);
return 0;
}
|
0cf7dbb650f81a7fcbb64a003e4b476334875e9f
|
ea522b45c62af588c8dcd0912cff465e0e895dfd
|
/src/mcmc.h
|
eecff5f1f12b0c869aecfcc138e07e27af459beb
|
[
"MIT"
] |
permissive
|
tristanz/OpenIRT
|
18e54747d3502cd7215b7753275b7f15ab4b007e
|
5ffea140c8efcaed7de80a5fe07c76419fbb9f4e
|
refs/heads/master
| 2021-01-02T23:06:47.572773
| 2014-04-21T19:42:06
| 2014-04-21T19:42:06
| 18,816,881
| 1
| 7
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 39,649
|
h
|
mcmc.h
|
/*! \mainpage
<table>
<tr><th>Library <td>Scythe MCMC - A Scythe Markov Chain Monte Carlo C++ Framework
<tr><th>Author <td>Tristan Zajonc (tristanz@gmail.com)
<tr><th>Source <td>http://ksghome.harvard.edu/~zajonct/
<tr><th>Version <td>0.1
</table>
\section NOTE Note
This version of Scythe MCMC has been customized for OpenIRT and should not be used
for other projects. See Scythe MCMC instead.
\section license MIT LICENSE
The license text below is the boilerplate "MIT License" used from:
http://www.opensource.org/licenses/mit-license.php
Copyright (c) 2009, Tristan Zajonc
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/progress.hpp>
#include <boost/timer.hpp>
#include <boost/algorithm/string.hpp>
#include <ctime>
#include <iostream>
#include <fstream>
#include "scythestat/rng/mersenne.h"
#include "scythestat/distributions.h"
#include "scythestat/matrix.h"
#include "scythestat/rng.h"
#include "scythestat/smath.h"
#include "scythestat/stat.h"
#include "scythestat/optimize.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include "Simple/SimpleOpt.h"
#include "Simple/SimpleIni.h"
// #include <mkl_vml_functions.h>
// #include <mkl_vml_defines.h>
/// Scythe MCMC version.
#define SCYTHE_MCMC_VERSION "0.1"
/// Value of missing data. If data is stored as double, use round(x)==MISSING.
#define MISSING -9999
using namespace scythe;
using namespace std;
/// Scythe column-oriented double matrix typedef.
typedef Matrix<double, Col> matrix;
/// Scythe column-oriented integer matrix typedef.
typedef Matrix<int, Col> imatrix;
/// Pair typedef for integers. Used to store (x, y) coordinates of a matrix location.
typedef pair<int, int> ipair;
/// Global positive infinity representation.
double dInf = std::numeric_limits<double>::infinity();
double iInf = std::numeric_limits<int>::infinity();
/// Global Mersenne-Twister random number generator.
mersenne myrng;
/*! \brief Basic MCMC options.
*
* These options are generally specified at the command line and are generic to all
* MCMC samplers. Other options are passed through an .ini config file.
*/
struct MCMCOptions {
/// Sample size. (iterations - burnin)/(thin + 1).
int sample_size;
/// Thinning interval
int thin;
/// Burn in period.
int burnin;
/// Chains.
int chains;
/// Seed for random number generator.
int random_seed;
/// Config file (.ini style).
string config_file;
/// Test description file
string test_file;
/// Response file
string response_file;
/// Out file to save parameter chains.
string test_outfile;
string response_outfile;
};
/// Global MCMCOptions object. It is convenient to store command line options globally to avoid passing them
/// around everwhere.
MCMCOptions mcmc_options;
// For MCMC results, to save memory.
struct Results {
matrix theta_eap;
matrix theta_pv;
matrix theta_mle;
matrix theta_mle_se;
matrix a_eap;
matrix a_pv;
matrix b_eap;
matrix b_pv;
matrix c_eap;
matrix c_pv;
};
Results results;
/// 2PL code
#define TYPE_2PL 1
/// 3PL code
#define TYPE_3PL 2
/// GPC code
#define TYPE_GPC 3
/// Default to Normal-Ogive metric, consistent with NAEP and TIMSS.
/// Set to 1 to use logistic metric.
#define D 1.7
/// Model specific options
struct ModelOptions {
string sampler;
double tune_theta;
double tune_a;
double tune_b;
double tune_c;
double tune_d;
};
/// Global ModelOptions instance.
ModelOptions model_options;
/// Group parameters
struct Groups {
matrix mu;
matrix sigma;
};
// Global groups object
Groups groups;
/// Priors
struct Priors {
// 2PL/3PL priors
double a_mu;
double a_sigma;
double b_mu;
double b_sigma;
// 3PL priors
double c_alpha;
double c_beta;
// GPC priors
double aGPC_mu;
double aGPC_sigma;
double bGPC_mu;
double bGPC_sigma;
double dGPC_mu;
double dGPC_sigma;
// Means
double mu_mu;
double mu_sigma;
double sigma_alpha;
double sigma_beta;
};
/// Global priors object
Priors priors;
/// Item data
struct Items {
imatrix id;
imatrix type;
imatrix num_categories;
matrix a;
matrix b;
matrix c;
matrix d;
int num_items;
};
/// Global items object
Items items;
/// Response data
struct Responses {
imatrix id;
imatrix group;
matrix theta;
imatrix x; // item responses
int num_responses;
int num_items;
int num_groups;
};
/// Global response object
Responses responses;
// Init results
void InitResults() {
matrix tmp1(responses.num_responses, 1, true, 0);
matrix tmp2(responses.num_responses, 5, true, 0);
matrix tmp3(items.num_items, 1, true, 0);
matrix tmp4(items.num_items, 5, true, 0);
results.theta_eap = tmp1;
results.theta_pv = tmp2;
results.theta_mle = tmp1;
results.theta_mle_se = tmp1;
results.a_eap = tmp3;
results.a_pv = tmp4;
results.b_eap = tmp3;
results.b_pv = tmp4;
results.c_eap = tmp3;
results.c_pv = tmp4;
}
// Write out results to file
void SaveResults() {
// cout << "Save response output: " << mcmc_options.response_outfile << endl;
ofstream outfile(mcmc_options.response_outfile.c_str());
if (!outfile.is_open()) {
cerr << "ERROR: Cannot open file!";
exit(1);
}
outfile << "id, group, theta_eap, theta_pv1, theta_pv2, theta_pv3, theta_pv4, theta_pv5, theta_mle, theta_mle_se" << endl;
for(int i = 0; i < responses.num_responses; ++i) {
outfile << responses.id(i) << ", "
<< responses.group(i) << ", "
<< results.theta_eap(i) << ", "
<< results.theta_pv(i, 0) << ", "
<< results.theta_pv(i, 1) << ", "
<< results.theta_pv(i, 2) << ", "
<< results.theta_pv(i, 3) << ", "
<< results.theta_pv(i, 4) << ", "
<< results.theta_mle(i) << ", "
<< results.theta_mle_se(i) << endl;
}
outfile.close();
// cout << "Save item output: " << mcmc_options.test_outfile << endl;
ofstream outfile2(mcmc_options.test_outfile.c_str());
if (!outfile2.is_open()) {
cerr << "ERROR: Cannot open file!";
exit(1);
}
outfile2 << "id, type, a_eap, b_eap, c_eap, a_pv1, b_pv1, c_pv1, a_pv2, b_pv2, c_pv2, a_pv3, b_pv3, c_pv3, a_pv4, b_pv4, c_pv4, a_pv5, b_pv5, c_pv5" << endl;
for(int i = 0; i < items.num_items; ++i) {
outfile2 << items.id(i) << ", "
<< items.type(i) << ", "
<< results.a_eap(i) << ", "
<< results.b_eap(i) << ", "
<< results.c_eap(i) << ", "
<< results.a_pv(i, 0) << ", "
<< results.b_pv(i, 0) << ", "
<< results.c_pv(i, 0) << ", "
<< results.a_pv(i, 1) << ", "
<< results.b_pv(i, 1) << ", "
<< results.c_pv(i, 1) << ", "
<< results.a_pv(i, 2) << ", "
<< results.b_pv(i, 2) << ", "
<< results.c_pv(i, 2) << ", "
<< results.a_pv(i, 3) << ", "
<< results.b_pv(i, 3) << ", "
<< results.c_pv(i, 3) << ", "
<< results.a_pv(i, 4) << ", "
<< results.b_pv(i, 4) << ", "
<< results.c_pv(i, 4) << endl;
}
outfile2.close();
}
/*! \brief Check if file exists.
*
\param strFilename Filename to check.
\returns True is file exists. False otherwise.
\note Source: http://www.techbytes.ca/techbyte103.html.
*/
bool FileExists(string strFilename) {
struct stat stFileInfo;
bool blnReturn;
int intStat;
// Attempt to get the file attributes
intStat = stat(strFilename.c_str(), &stFileInfo);
if (intStat == 0) {
// We were able to get the file attributes
// so the file obviously exists.
blnReturn = true;
} else {
// We were not able to get the file attributes.
// This may mean that we don't have permission to
// access the folder which contains this file. If you
// need to do that level of checking, lookup the
// return values of stat which will give you
// more details on why stat failed.
blnReturn = false;
}
return(blnReturn);
}
/*! \brief Convert any streaming type to CSV.
*
*/
template <class T>
inline string to_csv (const T& t) {
std::stringstream ss;
ss << t;
string s = ss.str();
replace(s.begin(), s.end(), ' ', ',');
return s;
}
/*! \brief Convert any streaming type to string
*
*/
template <class T>
inline string to_string (const T& t) {
std::stringstream ss;
ss << t;
string s = ss.str();
return s;
}
/*! \brief Shows command line usage.
*/
void ShowUsage() {
cout << " Usage:" << endl
<< " --help \t\t\t displays help message" << endl
<< " --config-file=filename \t config file name" << endl
<< " --test-file=filename \t test file name" << endl
<< " --response-file=filename \t response file name" << endl
<< " --test-outfile=filename \t test out file name" << endl
<< " --response-outfile=filename \t response out file name" << endl
<< " --sample-size=arg \t\t retained sample size" << endl
<< " --burnin=arg \t\t burn in period" << endl
<< " --thin=arg \t\t\t thinning iterval (1 = no thinning)" << endl
<< " --random-seed=arg \t\t random number seed" << endl << endl;
cout << " Example: ./openirt --config-file=openirt.ini --test-file=test.txt --response-file=responses.txt" << endl
<< "\t --test-outfile=test_out.txt --response-outfile=response_out.txt" << endl
<< "\t --sample-size=1000 --burnin=1000 --thin=1 --random-seed=12345" << endl << endl;
}
/*! \brief Parses command line options.
Parses and stores command line options and stores them in MCMCOptions instance
mcmc_options. Initializes random mersenne instance myrng.
\see ShowUsage.
\see mcmc_options.
\see myrng.
*/
void DefaultStartUp(int argc, char* argv[]) {
// cout << "OpenIRT v. 1.0" << endl << endl;
// Config parser is based on SimpleOpt Library.
// See: http://code.jellycan.com/simpleopt/
enum { OPT_SAMPLE_SIZE, OPT_THIN, OPT_BURNIN, OPT_RANDOM_SEED, OPT_CONFIG_FILE,
OPT_TEST_OUTFILE, OPT_RESPONSE_OUTFILE, OPT_TEST_FILE, OPT_RESPONSE_FILE, OPT_HELP };
CSimpleOpt::SOption g_rgOptions[] = {
{ OPT_HELP, "--help", SO_NONE },
{ OPT_CONFIG_FILE, "--config-file", SO_REQ_CMB },
{ OPT_TEST_FILE, "--test-file", SO_REQ_CMB },
{ OPT_RESPONSE_FILE, "--response-file", SO_REQ_CMB },
{ OPT_TEST_OUTFILE, "--test-outfile", SO_REQ_CMB },
{ OPT_RESPONSE_OUTFILE, "--response-outfile", SO_REQ_CMB },
{ OPT_SAMPLE_SIZE, "--sample-size", SO_REQ_CMB },
{ OPT_BURNIN, "--burnin", SO_REQ_CMB },
{ OPT_THIN, "--thin", SO_REQ_CMB },
{ OPT_RANDOM_SEED, "--random-seed", SO_REQ_CMB },
SO_END_OF_OPTIONS
};
CSimpleOpt args(argc, argv, g_rgOptions);
int setflags = 0;
while (args.Next()) {
if (args.LastError() == SO_SUCCESS) {
switch (args.OptionId()) {
case OPT_HELP:
ShowUsage();
exit(0);
break;
case OPT_CONFIG_FILE:
setflags++;
mcmc_options.config_file = args.OptionArg();
break;
case OPT_TEST_OUTFILE:
setflags++;
mcmc_options.test_outfile = args.OptionArg();
break;
case OPT_RESPONSE_OUTFILE:
setflags++;
mcmc_options.response_outfile = args.OptionArg();
break;
case OPT_TEST_FILE:
setflags++;
mcmc_options.test_file = args.OptionArg();
break;
case OPT_RESPONSE_FILE:
setflags++;
mcmc_options.response_file = args.OptionArg();
break;
case OPT_SAMPLE_SIZE:
setflags++;
mcmc_options.sample_size = atoi(args.OptionArg());
break;
case OPT_BURNIN:
setflags++;
mcmc_options.burnin = atoi(args.OptionArg());
break;
case OPT_THIN:
setflags++;
mcmc_options.thin = atoi(args.OptionArg());
break;
case OPT_RANDOM_SEED:
setflags++;
mcmc_options.random_seed = atoi(args.OptionArg());
break;
}
} else {
cout << "Invalid argument: " << args.OptionText() << endl;
exit(1);
}
}
// Check that all required flags are set.
if (setflags != 9) {
ShowUsage();
exit(1);
}
// Check argument values.
if (mcmc_options.sample_size <= 0) {
cout << "Sample size must be positive.\n";
exit(1);
}
if (mcmc_options.burnin < 0) {
cout << "Burn in cannot be negative.\n";
exit(1);
}
if (mcmc_options.thin < 1) {
cout << "Thinning interval must be at least 1.\n";
exit(1);
}
if (!FileExists(mcmc_options.config_file)) {
cout << "Config file does not exist:" << mcmc_options.config_file << endl;
exit(1);
}
if (!FileExists(mcmc_options.test_file)) {
cout << "Test file does not exist:" << mcmc_options.test_file << endl;
exit(1);
}
if (!FileExists(mcmc_options.response_file)) {
cout << "Response file does not exist:" << mcmc_options.response_file << endl;
exit(1);
}
// Seed random number generator.
myrng.initialize(mcmc_options.random_seed);
// Print mcmc options.
// cout << "Arguments:" << endl;
cout // << " Config file: " << mcmc_options.config_file << endl
// << " Test file: " << mcmc_options.test_file << endl
// << " Response file: " << mcmc_options.response_file << endl
// << " Test out file: " << mcmc_options.test_outfile << endl
// << " Response out file: " << mcmc_options.response_outfile << endl
<< "Sample size: " << mcmc_options.sample_size << endl
<< "Burn in period: " << mcmc_options.burnin << endl
<< "Thinning interval: " << mcmc_options.thin << endl
<< "Random number seed: " << mcmc_options.random_seed << endl << endl;
}
/*! \brief Main parameter class.
*
* The model is defined as many instances of parameter subclasses. Different Step types require different methods
* to be implemented in each Parameter subclass.
*
* \section overwrite Methods that should be implemented in subclass:
* Required for all step types:
* - Constructor that sets, at least, Parameter::track_ and Parameter::name_
* - Parameter::Value
* - Parameter::Save
*
* GibbsStep:
* - Parameter::StartingValue
* - Parameter::RandomPosterior
*
* Metropolis-Hastings:
* - Parameter::StartingValue
* - Parameter::LogDensity
*
* Slice:
* - Parameter::StartingValue
* - Parameter::LogDensity
*
* FunctionStep (deterministic):
* - Parameter::Function
*
* \section examples Examples:
*
* \subsection example1 Normal mean parameter with normal prior, known standard deviation:
*
\code
// Priors
double mean_mu = 0;
double mean_sigma = 2;
// Parameters
double mean = 0; // free parameter
double sd = 1; // known
// Data
matrix X('X.txt');
// Define the mean parameter, implementing methods required for GibbsStep.
class MeanParameter : public Parameter<double> {
public:
/// Default constructors that call base constructors. (REQUIRED)
MeanParameter() : Parameter<double>() {}
MeanParameter(bool track, string name) : Parameter<double>(track, name) {}
/// Draw a random value from analytical posterior for GibbsStep.
double RandomPosterior() {
// Posterior of mean with known variance, (Gelman et al (2004) p 49.)
double x_mean = mean(X);
int n = X.rows();
double denom = 1/(1/pow(mean_sigma,2) + n / pow(sd,2))
double posterior_mean = ((1/pow(mean_sigma,2)) * mean_mu + (n / pow(sd,2)) * x_mean) / denom
double posterior_sd = sqrt(denom);
return myrng.rnorm(posterior_mean, posterior_sd);
}
/// Draw starting value from prior.
double StartingValue() {
return myrng.rnorm(mean_mu, mean_sigma);
}
/// Save back to global location
void Save(double new_value) {
mean = new_value;
}
/// Return value from global location.
double Value() {
return mean;
}
};
\endcode
*/
template<typename ParameterStorageType>
class Parameter {
public:
/// Default class constructor.
Parameter() {}
/*! \brief Base class constructor
*
* \param track True if parameter should be tracked and saved.
* \param label Label of parameter for tracking purposes.
*/
Parameter(bool track, string label) : track_(track), label_(label) {}
/// Function for deterministic nodes.
/// \return Function value.
virtual ParameterStorageType Function() {
return 0.0;
};
/// Starting value.
/// \return Starting value.
virtual ParameterStorageType StartingValue() {
return 0.0;
};
/// Log of the probability density (plus constant)
/// \param value Value of parameter to evaluate density at.
/// \return Log of probability density (plus constant)
virtual double LogDensity(double value) {
return 0.0;
}
/// Return a random draw from the posterior.
/// Random draw from posterior is called by GibbsStep.
/// \return Random draw from posterior.
virtual ParameterStorageType RandomPosterior() {
return 0.0;
}
/// Value of parameter.
/// \return Parameter value
virtual ParameterStorageType Value() {
return 0.0;
};
/// Save a new value of the parameter.
/// \param new_value New value to save.
virtual void Save(ParameterStorageType new_value) {};
/// Parameter is tracked / saved.
/// \return True if parameter is tracked.
bool Track() {
return track_;
}
/// String label of parameter.
/// \return Label of parameter, for purposes of saving output.
string Label() {
return label_;
}
private:
/// Should this variable be tracked?
bool track_;
/// Name of variable for tracking purposes.
string label_;
};
/*! \defgroup steps Implemented MCMC Step Types
*
* MCMC algorithms typically consist of many steps. While users will often want
* to implement their own step types, Scythe MCMC has implemented several that arise
* over and over. MetropStep and SliceStep in particular only require specification of
* a log density function (minus an unknown constant).
*
*/
/*! \brief Base step class.
*
* \ingroup steps
*
* The step (Gibbs, Metropolis-Hastings, Slice, etc) describes how the sampler
* calculates the next value of each parameter. The key function is Step::DoStep, which is
* equivalent to the Execute function in a <a href="http://en.wikipedia.org/wiki/Command_pattern">Command Pattern</a>.
* Samplers consists of a many of steps.
*
* \see GibbsStep
* \see FunctionStep
* \see MetropStep
* \see SliceStep
* \see Sampler
*/
class Step {
public:
/*! \brief Take step.
*
* Executes the main step function, such as taking a MH step or deterministic step.
*/
virtual void DoStep() {}
/*! \brief Set starting value.
*
* Calls the parameter's Parameter::Starting function and then saves the result using Parameter::Save.
*/
virtual void Start() {}
/*! \brief Return parameter value
*
* \return String representation of parameter value for csv output.
* \see Parameter::Value
*/
virtual string ParameterValue() {
return "";
}
/*! \brief Return parameter label
*
* \return The label of the parameter associated with the step instance.
* \see Parameter::Label
*/
virtual string ParameterLabel() {
return "";
}
/*! Return the tracking status
*
* \return The tracking status of the parameter associated with the step instance.
* \see Parameter::Track
*/
virtual bool ParameterTrack() {
return true;
}
};
/*! \brief Gibbs step.
*
* \ingroup steps
*
* A univariate Gibbs step draws from the Parameter::RandomPosterior function of a Parameter and then saves the result
* using Parameter:Save.
*/
template <typename ParameterType, typename ParameterStorageType>
class GibbsStep: public Step {
public:
/// Default constructor, for copy assignments, etc.
GibbsStep() {}
/*! \brief Main constructor taking a Parameter object.
* \param parameter A Parameter that implements Parameter::RandomPosterior.
*/
GibbsStep(ParameterType parameter) : parameter_(parameter) {
}
/*! \brief Take a Gibbs step for the parameter.
*
* Draws from the parameter's Parameter::RandomPosterior function and then saves the result using Parameter::Save.
*/
void DoStep() {
parameter_.Save(parameter_.RandomPosterior());
}
void Start() {
parameter_.Save(parameter_.StartingValue());
}
string ParameterLabel() {
return parameter_.Label();
}
string ParameterValue() {
return to_csv<ParameterStorageType>(parameter_.Value());
}
bool ParameterTrack() {
return parameter_.Track();
}
private:
/// Parameter associated with step instance.
ParameterType parameter_;
};
/*! \brief Deterministic function step.
*
* \ingroup steps
*
* Deterministic nodes can be helpful to track summary statistics or to reduce computations through intermediate use
* of sufficient statistics across multiple parameters. FunctionStep calls the parameters Parameter::Function method
* and saves the result using Parameter::Save.
*/
template <typename ParameterType, typename ParameterStorageType>
class FunctionStep: public Step {
public:
/// Default constructor, for copy assignments, etc.
FunctionStep() {}
/*! \brief Main constructor taking a Parameter object.
*
* \param parameter A Parameter that implements Parameter::Function.
*/
FunctionStep(ParameterType parameter) : parameter_(parameter) {
}
/*! \brief Take a function step for the parameter.
*
* Calculates the value of Parameter::Function and then saves the result using Parameter::Save.
*/
void DoStep() {
parameter_.Save(parameter_.Function());
}
/*! \brief Set function step starting value.
*
*/
void Start() {
parameter_.StartingValue();
}
string ParameterLabel() {
return parameter_.Label();
}
string ParameterValue() {
return to_csv<ParameterStorageType>(parameter_.Value());
}
bool ParameterTrack() {
return parameter_.Track();
}
private:
/// Parameter associated with step instance.
ParameterType parameter_;
};
/*! \defgroup proposals Metropolis-Hastings Proposals
*
* The MetropStep Metropolis-Hastings class requires both a Parameter instance
* and a Proposal instance. Proposal instances define a Draw and LogDensity method.
* The constructor should set a tuning parameter.
*
* MetroStep::DoStep uses the Draw method to draw new proposed values for the parameter
* and the LogDensity to calculate the proposal terms in the acceptance \f$\alpha\f$. For
* symmetric proposal distributions returning 0.0 is enough.
*/
/*! \brief Normal proposal for Metropolis-Hastings.
*
* \ingroup proposals
*
* Normal proposal draws from N(starting_value, standard_deviation).
*/
class NormalProposal {
public:
NormalProposal() {}
/*! \brief Constructor
*
* \param standard_deviation Tuning parameter for normal proposal.
*/
NormalProposal(double standard_deviation) : standard_deviation_(standard_deviation) {}
/*! \brief Draw from normal proposal
*
* \param starting_value Starting value.
*/
double Draw(double starting_value) {
return myrng.rnorm(starting_value, standard_deviation_);
}
/*! \brief Log probability of proposal new value, given starting value.
*
* \note Needs to be implemented but can be 0.0 if proposal is symmetric, which it is.
* \param starting_value Starting value.
* \param new_value Proposed new value.
*/
double LogDensity(double new_value, double starting_value) {
return 0.0; // Symmetric, doesn't matter.
}
private:
double standard_deviation_;
};
/*! \brief Beta proposal for Metropolis-Hastings.
*
* \ingroup proposals
*
* Useful proposal type for parameters with support between 0 and 1.
*
* The beta proposal is parameterized using the mean and the inverse denominator. The denominator
* is a measure a scale and can be thought of as the number of observed trials bernoulli. We use the inverse
* of the denominator so that larger values imply bigger steps, consistent with NormalProposal. For the Beta distribution
* the mean is
* \f[ m = \frac{\alpha}{\alpha + \beta} \f]
* and the denominator is
* \f[ d = \alpha + \beta. \f]
* Therefore
* \f[ \alpha = m \cdot d \f]
* and
* \f[ \beta = d \cdot (1-m). \f]
*
*/
class BetaProposal {
public:
/*! \brief Empy constructor */
BetaProposal() {}
/*! \brief Main constructor
*
* Scale of steps are parameterized using the inverse denominator of a Beta distribution:
* \f[ \frac{1}{d} = \frac{1}{\alpha + \beta} \f]
*
* \param idenominator Tuning parameter equal to the inverse denominator \f$1/d\f$ of a Beta distribution.
*/
BetaProposal(double idenominator) {
denom_ = 1 / idenominator;
}
/*! \brief Draw from Beta proposal
*
* \param starting_value Starting value (mean of Beta distribution).
*/
double Draw(double starting_value) {
double alpha = starting_value * denom_;
double beta = alpha - denom_;
return myrng.rbeta(alpha, beta);
}
/*! \brief Log probability of proposal new value, given starting value.
*
* \param starting_value Starting value.
* \param new_value Proposed new value.
*/
double LogDensity(double new_value, double starting_value) {
double alpha = starting_value * denom_;
double beta = alpha - denom_;
return dbeta(new_value, alpha, beta);
}
private:
double denom_;
};
/*! \brief Log normal proposal for Metropolis-Hastings.
*
* \ingroup proposals
*
* Useful proposal type for parameters with support between 0 and positive infinity.
*
* For convenience, the log normal proposal is parameterized using the unlogged mean (starting value)
* and the (positive) log standard deviation. This differs from how scythe::dlnorm is parameterized.
*
*/
class LogNormalProposal {
public:
/*! \brief Empy constructor */
LogNormalProposal() {}
/*! \brief Main constructor
*
* Scale of steps are standard deviation of the logged parameter value:
*
* \param logsd Tuning parameter equal to the log standard deviation.
*/
LogNormalProposal(double logsd) : logsd_(logsd) {}
/*! \brief Draw from log normal proposal
*
* \param starting_value Starting value (unlogged mean of log normal).
*/
double Draw(double starting_value) {
double logmean = log(starting_value);
return myrng.rlnorm(logmean, logsd_);
}
/*! \brief Log probability of proposal new value, given starting value.
*
* \param starting_value Starting value.
* \param new_value Proposed new value.
*/
double LogDensity(double new_value, double starting_value) {
double logmean = log(starting_value);
return dlnorm(new_value, logmean, logsd_);
}
private:
double logsd_;
};
/*! \brief Metropolis Hastings step
*
* \ingroup steps
*
* Basic univariate Metropolis-Hastings step. Requires both a Parameter and Proposal instance.
*/
template <typename ParameterType, typename ProposalType>
class MetropStep: public Step {
public:
/*! \brief Default constructor, for copy assignments, etc.
*/
MetropStep() {}
/*! \brief Main constructor taking a Parameter and Proposal object.
*
* \param parameter A Parameter that implements Parameter::LogDensity
* \param proposal A Proposal instance that implements Proposal::LogDensity and Proposal::Draw.
*/
MetropStep(ParameterType parameter, ProposalType proposal) : parameter_(parameter), proposal_(proposal) {}
/*! \brief Take a function step for the parameter.
*
* Calculates the value of Parameter::Function and then saves the result using Parameter::Save.
*/
void DoStep() {
// Draw a new parameter
double new_value = proposal_.Draw(parameter_.Value());
double old_value = parameter_.Value();
// MH accept/reject criteria
double alpha = parameter_.LogDensity(new_value) - parameter_.LogDensity(old_value)
+ proposal_.LogDensity(old_value, new_value) - proposal_.LogDensity(new_value, old_value);
if (myrng.runif() < min(exp(alpha), 1.0)) {
parameter_.Save(new_value);
}
}
void Start() {
parameter_.Save(parameter_.StartingValue());
}
string ParameterLabel() {
return parameter_.Label();
}
string ParameterValue() {
return to_csv<double>(parameter_.Value());
}
bool ParameterTrack() {
return parameter_.Track();
}
private:
/// Parameter associated with step instance.
ParameterType parameter_;
ProposalType proposal_;
};
/*! \brief Univariate slice sampling step.
*
* \ingroup steps
*
* Basic univariate slice sampling step with stepping out and shrinkage. Performs a slice sampling update from an initial
* point to a new point that leaves invariant the distribution with the specifified log density functions.
*
* The log desnity function may return -Inf for points outside the support of the distribution.
* If a lower and/or upper bound is specified for the support, the log density function will not be called outside
* such limits.
*
* \note See Neal, R. M (2003) "Slice Sampling" (with discussion), <i>Annals of Statistics</i>,
* vol. 31, no. 3, pp. 705-767.
* \note Code and description based on Neal's R code (March 17, 2008): http://www.cs.toronto.edu/~radford/ftp/slice-R-prog
* \note With poor initial values or choice of w, slice sampling can get take a very long time to find
* a suitable slice. This may appear like a crash. Experimenting with w may speed sampling, but things tends
* to work pretty well with default values in many cases.
*/
template <typename ParameterType>
class SliceStep: public Step {
public:
/// Default constructor, for copy assignments, etc.
SliceStep() {}
/*! \brief Main constructor for slice sampling step.
*
* \param parameter A Parameter that implements Parameter::LogDensity
* \param w Size of the steps for creating interval (default = 1)
* \param lower Lower bound on the support of the distribution (default = -Infinity)
* \param upper Upper bound on the support of the distribution (default = Infinity)
*/
SliceStep(ParameterType parameter, double w, double lower, double upper) :
parameter_(parameter), w_(w), lower_(lower), upper_(upper) {
step_count_ = 0;
}
/*! \brief Take a slice sampling step for the parameter.
*
*/
void DoStep() {
// Find the log density at the initial point.
double x0 = parameter_.Value();
double gx0 = parameter_.LogDensity(x0);
//cout << parameter_.Label() << " : " << x0 << " = " << gx0 << endl;
// Determine slice level, in log terms
double logy = gx0 - myrng.rexp(1);
//Find the initial interval to sample from.
double u = myrng.runif() * w_;
double L = x0 - u;
double R = x0 + (w_ - u);
// Expand the interval until its ends are outside the slice, or
// until the limit on steps is reached.
// allow infinite steps... could hang!
// FIXME: Add check for too many iterations and exit with error message.
while (true) {
if (L <= lower_) {
break;
}
if (parameter_.LogDensity(L) <= logy) {
break;
}
L = L - w_;
}
while (true) {
if (R >= upper_) {
break;
}
if (parameter_.LogDensity(R) <= logy) {
break;
}
R = R + w_;
}
// Shrink interval to lower and upper bounds.
if (L < lower_) {
L = lower_;
}
if (R > upper_) {
R = upper_;
}
// Sample from the interval, shrinking it on each rejection
double x1, gx1;
while (true) {
x1 = myrng.runif() * (R - L) + L; // Sample between L and R, uniformly.
gx1 = parameter_.LogDensity(x1);
if (gx1 >= logy) {
break;
}
if (x1 > x0) {
R = x1;
} else {
L = x1;
}
}
// Adapt
//step_count_++;
//w_ = (step_count_/(step_count_+1)) * w_ + (1/(step_count_+1))*(R - L);
// Save the point sampled
parameter_.Save(x1);
}
void Start() {
parameter_.Save(parameter_.StartingValue());
}
string ParameterLabel() {
return parameter_.Label();
}
string ParameterValue() {
return to_csv<double>(parameter_.Value());
}
bool ParameterTrack() {
return parameter_.Track();
}
private:
/// Parameter associated with step instance.
ParameterType parameter_;
/// Slice sampling control values
double w_;
double lower_;
double upper_;
int step_count_;
};
/*! \brief MCMC sampler.
*
* The sampler is the main MCMC object that holds all the MCMC steps for each parameter. Running the sampler
* performs MCMC sampling for the model, saving results, and displaying progress. In the language of the Command Pattern, the
* sampler is the Invoker or Command Manager.
*
* After instantiating the sampler, users should add all the required steps using the Sampler::AddStep method, which places
* each step onto a stack. The entire sampling process is run using Sampler::Run.
*/
class Sampler {
public:
/*! \brief Constructor to initialize sampler.
*
* \param options MCMC options object that defines sample_size, burnin, thinning interval, etc.
*/
Sampler(MCMCOptions options) {
cout << "Creating Sampler... " << endl;
sample_size_ = options.sample_size;
burnin_ = options.burnin;
thin_ = options.thin;
}
/*! \brief Add Step to Sampler execution stack.
*
* All parameters should have an associated Step that is added to the sampler. The sampler stack
* defines one sampler iteration.
* \param step Step object for a given parameter.
*/
void AddStep(Step* step) {
// Add step to step stack.
steps_.push_back(step);
// Add index to tracking stack, if necessary tracked.
if (steps_.back().ParameterTrack()) {
tracks_.push_back(steps_.size() - 1);
}
}
/*! \brief Run sampler for a specific number of iterations.
*
* \param number_of_iterations Number of iterations to run sampler.
* \param progress Display a progress bar.
*/
void Iterate(int number_of_iterations, bool progress = false) {
if(progress) {
//boost::progress_display show_progress(number_of_iterations);
for(int iter = 0; iter < number_of_iterations; ++iter) {
cout << "Iteration " << iter << endl;
for(int i = 0; i < steps_.size(); ++i) {
//cout << "Step " << i << endl;
steps_[i].DoStep();
}
//++show_progress;
}
}
else {
for(int iter = 0; iter < number_of_iterations; ++iter) {
for(int i = 0; i < steps_.size(); ++i) {
steps_[i].DoStep();
}
}
}
}
/*! \brief Run sampler.
*
* Run the MCMC sampling procedure, including burning in, sampling, thinning, displaying progress,
* and saving results.
*/
void Run() {
// Status of sampler...
cout << "Running sampler..." << endl;
cout << "Number of steps added: " << NumberOfSteps() << endl;
cout << "Number of tracked steps added: " << NumberOfTrackedSteps() << endl;
/*
// Opening output file
cout << "Opening output file: " << out_file_ << endl;
ofstream outfile(out_file_.c_str());
if (!outfile.is_open()) {
cerr << "ERROR: Cannot open file!";
exit(1);
}
for (int k = 0; k < tracks_.size(); ++k) {
if (k == tracks_.size() - 1) {
outfile << steps_[tracks_[k]].ParameterLabel() << endl;
} else {
outfile << steps_[tracks_[k]].ParameterLabel() << ",";
}
// cout << steps_[tracks_[k]].ParameterLabel() << endl;
}
*/
// Setting starting value:
cout << "Setting starting values..." << endl;
for (int i = 0; i < steps_.size(); ++i) {
steps_[i].Start();
}
// Burn in
cout << "Burning in... (" << burnin_ << " iterations)" << endl;
Iterate(burnin_, true);
cout << endl << "Sampling... (" << sample_size_ * thin_ << " iterations)" << endl;
double weight = (1.0 / sample_size_);
int pvspan = sample_size_ / 5;
int pv = 0;
boost::progress_display show_progress(sample_size_);
for (int i = 0; i < sample_size_; ++i) {
Iterate(thin_);
// Save data
/*
for (int k = 0; k < tracks_.size(); ++k) {
if (k == tracks_.size() - 1) {
outfile << steps_[tracks_[k]].ParameterValue() << endl;
} else {
outfile << steps_[tracks_[k]].ParameterValue() << ",";
}
}
*/
// Update EAP
// cout.precision(10);
// cout << weight * responses.theta;
// exit(1);
results.theta_eap += weight * responses.theta;
results.a_eap += weight * items.a;
results.b_eap += weight * items.b;
results.c_eap += weight * items.c;
// PV
if(((i+1) % pvspan) == 0) {
results.theta_pv(_,pv) = responses.theta;
results.a_pv(_,pv) = items.a;
results.b_pv(_,pv) = items.b;
results.c_pv(_,pv) = items.c;
pv++;
}
//Show progress
++show_progress;
}
//outfile.close();
}
/*! \brief Number of steps in one sampler iteration.
*
* \return Number of steps.
*/
int NumberOfSteps() {
return steps_.size();
}
/*! \brief Number of tracked steps in one sampler iteration.
*
* \return Number of tracked steps.
*/
int NumberOfTrackedSteps() {
return tracks_.size();
}
private:
int sample_size_;
int burnin_;
int thin_;
boost::ptr_vector<Step> steps_;
vector<int> tracks_;
};
/*! \brief Approximately equal.
*
* Checks if two doubles are within the numeric_limits<double>::epsilon() precision of each other.
* Useful if === is too strict.
*/
bool approx_equal(double a, double b) {
return abs(a - b) <= numeric_limits<double>::epsilon() ? true : false;
}
/* \brief Find minimum of functor using a golden section search
*
* \note Based on http://pagesperso-orange.fr/jean-pierre.moreau/Cplus/golden_cpp.txt
*/
template<class T>
double GoldenSectionSearch(const T &F, double ax, double cx, double tol) {
double bx = (cx - ax) / 2;
// golden section search
double f0,f1,f2,f3,x0,x1,x2,x3;
double R,C;
R=0.61803399; C=1.0-R; // golden ratios
x0=ax; //At any given time we will keep trace of 4 points: x0,x1,x2,x3
x3=cx;
if (fabs(cx-bx) > fabs(bx-ax)) {
x1=bx; x2=bx+C*(cx-bx);
}
else {
x2=bx; x1=bx-C*(bx-ax);
};
f1=F(x1); f2=F(x2); //Initial function evaluations
//main loop
while (fabs(x3-x0) > tol*(fabs(x1)+fabs(x2))) {
if (f2 < f1) {
x0=x1; x1=x2;
x2=R*x1+C*x3;
f0=f1; f1=f2;
f2=F(x2);
}
else {
x3=x2; x2=x1;
x1=R*x2+C*x0;
f3=f2; f2=f1;
f1=F(x1);
}
}
if (f1 < f2) {
return x1;
}
else {
return x2;
}
} // Function Golden()
/* Calculate second derivative of a scalar function using central differences.
*
*/
template<class T>
double SecondDerivative(const T &F, double at, double h) {
return (F(at + h) - 2 * F(at) + F(at - h)) / (h*h);
}
|
faa008a5b463bf21dff122b70bf7e3f52c8d5608
|
d1484f472702bb409ad5b1b6068f6f2a359dcd3f
|
/无人机定位系统/calibration/stereo/undistortRectify/undistortRectify.cpp
|
31635975d285780489dcad9cb86ebd4694787685
|
[] |
no_license
|
501201611/Binocular-distance-measurement
|
a6b59ff91d694b4799b926e9c1ba2128ec03f66d
|
2bfeac2226da3f679888ecaa384eb3ed2c173aa7
|
refs/heads/master
| 2020-06-27T22:23:46.276995
| 2017-07-13T03:16:30
| 2017-07-13T03:16:30
| 97,070,762
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 5,323
|
cpp
|
undistortRectify.cpp
|
// 立体校正,把右相机图像变换到左相机平面,输出校正后的图片
#include <opencv2/core/core.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <stdio.h>
#include <iostream>
using namespace std;
using namespace cv;
int main(int argc, char const *argv[])
{
char* leftimg_directory = "..//..//imgs//leftImgs//"; // 左摄像头图像路径
char* rightimg_directory = "..//..//imgs//rightImgs//"; // 右摄像头图像路径
char* leftimg_filename = "left"; // 左摄像头图像名
char* rightimg_filename = "right"; // 右摄像头图像名
char* extension = "jpg"; // 图像格式
char* calib_file = "..//..//parms//calibParms.xml"; // 立体校正参数文件
char* rectifiedImg_directory = "..//..//result//rectifiedImg//";// 图像校正结果路径
char* leftout_directory = "..//..//result//left//"; // 左摄像头图像校正结果路径
char* rightout_directory = "..//..//result//right//"; // 右摄像头图像校正结果路径
char* rectifiedImg_filename = "rectifiedImg"; // 校正结果图像文件名
char* leftout_filename = "leftOut"; // 左摄像头图像校正结果文件名
char* rightout_filename = "rightOut"; // 左摄像头图像校正结果文件名
int num_imgs = 17;
Size imgSize = Size(640,480);
Mat R1, R2, P1, P2, Q;
Mat cameraMatrixL, cameraDistcoeffL, cameraMatrixR, cameraDistcoeffR, R, T;
cv::FileStorage fs(calib_file, cv::FileStorage::READ);
if (!fs.isOpened())
{
printf("打开参数文件失败!\n");
return -1;
}
fs["cameraMatrixL"] >> cameraMatrixL;
fs["cameraDistcoeffL"] >> cameraDistcoeffL;
fs["cameraMatrixR"] >> cameraMatrixR;
fs["cameraDistcoeffR"] >> cameraDistcoeffR;
fs["R"] >> R;
fs["T"] >> T;
fs["R1"] >> R1;//输出第一个相机的3x3矫正变换(旋转矩阵)
fs["R2"] >> R2;
fs["P1"] >> P1;//在第一台相机的新的坐标系统(矫正过的)输出 3x4 的投影矩阵
fs["P2"] >> P2;
fs["Q"] >> Q; //深度视差映射矩阵
cout << "参数:" << endl << endl;
cout << "cameraMatrixL :" << endl << cameraMatrixL << endl << endl;
cout << "cameraDistcoeffL :" << endl << cameraDistcoeffL << endl << endl;
cout << "cameraMatrixR :" << endl << cameraMatrixR << endl << endl;
cout << "cameraDistcoeffR :" << endl << cameraDistcoeffR << endl << endl;
cout << "R :" << endl << R << endl << endl;
cout << "T :" << endl << T << endl << endl;
cv::Mat lmapx, lmapy, rmapx, rmapy;
cv::initUndistortRectifyMap(cameraMatrixL, cameraDistcoeffL, R1, P1, imgSize, CV_32F, lmapx, lmapy);
cv::initUndistortRectifyMap(cameraMatrixR, cameraDistcoeffR, R2, P2, imgSize, CV_32F, rmapx, rmapy);
cv::Rect validROIL,validROIR;
stereoRectify(cameraMatrixL, cameraDistcoeffL, cameraMatrixR, cameraDistcoeffR, imgSize, R, T,
R1, R2, P1, P2, Q, CALIB_ZERO_DISPARITY, -1, imgSize, &validROIL, &validROIR);
cout << "按任意键继续..." << endl;
for (int k = 1; k <= num_imgs; k++)
{
char leftimg_file[100];
char rightimg_file[100];
sprintf(leftimg_file, "%s%s%d.%s", leftimg_directory, leftimg_filename, k, extension);
sprintf(rightimg_file, "%s%s%d.%s", rightimg_directory, rightimg_filename, k, extension);
Mat img1 = imread(leftimg_file, CV_LOAD_IMAGE_COLOR);
Mat img2 = imread(rightimg_file, CV_LOAD_IMAGE_COLOR);
if (img1.empty() || img2.empty())
{
printf("读入图像错误!\n");
return -1;
}
cv::Mat imgU1, imgU2;
cv::remap(img1, imgU1, lmapx, lmapy, cv::INTER_LINEAR);
cv::remap(img2, imgU2, rmapx, rmapy, cv::INTER_LINEAR);
char leftout_file[100];
sprintf(leftout_file, "%s%s%d.%s", leftout_directory, leftout_filename, k, extension);
imwrite(leftout_file, imgU1);
char rightout_file[100];
sprintf(rightout_file, "%s%s%d.%s", rightout_directory, rightout_filename, k, extension);
imwrite(rightout_file, imgU2);
cout << k << ". rectified!" << endl;
// 显示部分
Mat rectifiedImg;
double sf = 1.0;
int w = cvRound(imgSize.width * sf), h = cvRound(imgSize.height * sf);
rectifiedImg.create(h, w * 2, CV_8UC3);
// 画上左右图像
Mat rectifiedImgPartL = rectifiedImg(Rect(w * 0, 0, w, h));
Mat rectifiedImgPartR = rectifiedImg(Rect(w, 0, w, h));
resize(imgU1, rectifiedImgPartL, rectifiedImgPartL.size(), 0, 0, INTER_AREA);
resize(imgU2, rectifiedImgPartR, rectifiedImgPartR.size(), 0, 0, INTER_LINEAR);
Rect vroiL(cvRound(validROIL.x * sf), cvRound(validROIL.y * sf),
cvRound(validROIL.width * sf), cvRound(validROIL.height * sf)); // 缩放有效区域
Rect vroiR(cvRound(validROIR.x * sf), cvRound(validROIR.y * sf),
cvRound(validROIR.width * sf), cvRound(validROIR.height * sf));
rectangle(rectifiedImgPartL, vroiL, Scalar(0, 0, 255), 3, 8); // 在有效区域画上矩形
rectangle(rectifiedImgPartR, vroiR, Scalar(0, 0, 255), 3, 8);
// 画上对应的线条
for (int i = 0; i < rectifiedImg.rows; i += 16)
line(rectifiedImg, Point(0, i), Point(rectifiedImg.cols, i), Scalar(0, 255, 0), 1, 8);
imshow("rectified", rectifiedImg);
// 保存图像
char rectifiedImg_file[100];
sprintf(rectifiedImg_file, "%s%s%d.%s", rectifiedImg_directory, rectifiedImg_filename, k, extension);
imwrite(rectifiedImg_file, rectifiedImg);
waitKey(0);
}
return 0;
}
|
330c3c2f92c444ae888a97d3433528f932fa4a4e
|
aac4d4a6ab7339505d65d527eff672ee4bc5a525
|
/ProgrammrCode/Task10_Factorial/main.cpp
|
05ce9f5da8ef227b39effa2d63129a97bae33692
|
[] |
no_license
|
Vecnik88/easyCpp
|
c3313bbabf27d47a628417ebe9bf6d5358229e15
|
f8a7151b0470263896bca3a06aef3c5b8c7708f8
|
refs/heads/master
| 2021-06-21T19:10:02.144650
| 2017-08-12T16:49:17
| 2017-08-12T16:49:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 476
|
cpp
|
main.cpp
|
/* ### Task 10 ### Created by Vecnik88
Find the factorial of a number n.
Input:
Enter the value of n:
1
Output:
Value of factorial is: 1
Input:
Enter the value of n:
4
Output:
Value of factorial is:
24
*/
#include <iostream>
using namespace std;
int main()
{
int n, fact=1;
cout << "Enter the value of n:\n";
cin >> n;
for(int i{1}; i <= n; ++i)
fact *= i;
cout<< "Value of factorial is :\n" << fact;
return 0;
}
|
b8e8bbc3332f963acd8ce64c28fe97691d8daebd
|
d4033732101c18e892a0b1ddfb311d5547b662fd
|
/src/ObjectDisplayGrid.cpp
|
584ba170a3c3b75671ad2234b7ad4b1656c9a0ac
|
[] |
no_license
|
jehanshah8/RogueLike
|
6c0a278daff9aa9b1c53d868118d8e18863c96a4
|
be7c20cc10fe51921f0b43801544cd8a87790e53
|
refs/heads/main
| 2023-01-23T04:54:20.679298
| 2020-11-25T08:05:03
| 2020-11-25T08:05:03
| 303,008,713
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,843
|
cpp
|
ObjectDisplayGrid.cpp
|
#include "ObjectDisplayGrid.hpp"
ObjectDisplayGrid::ObjectDisplayGrid(int gameHeight, int gameWidth, int topHeight, int bottomHeight) : gameHeight(gameHeight),
gameWidth(gameWidth),
topHeight(topHeight),
bottomHeight(bottomHeight),
//charGrid(gameWidth, std::vector<std::stack<char>>(gameHeight + topHeight + bottomHeight, std::stack<char>())),
objectGrid(gameWidth, std::vector<std::stack<std::shared_ptr<Displayable>>>(gameHeight + topHeight + bottomHeight, std::stack<std::shared_ptr<Displayable>>())),
keepRunning(true)
{
// initializes ncurses
initscr();
// makes characters typed immediately available, instead of waiting for enter to be pressed
cbreak();
// stops typed characters from being shown, makes it easier to get keypresses
noecho();
// clears the screen to start
clear();
}
void ObjectDisplayGrid::addObjectToDisplay(int x, int y, const std::shared_ptr<Displayable> displayable)
{
if ((0 <= x) && (x <= gameWidth))
{
if ((0 <= y) && (y <= gameHeight))
{
objectGrid[x][y].push(displayable);
mvaddch(y, x, displayable->getDisplayCode());
}
}
}
void ObjectDisplayGrid::removeObjectFromDisplay(int x, int y)
{
if ((0 <= x) && (x <= gameWidth))
{
if ((0 <= y) && (y <= gameHeight))
{
if (!objectGrid[x][y].empty())
{
objectGrid[x][y].top().reset();
objectGrid[x][y].pop();
mvaddch(y, x, objectGrid[x][y].top()->getDisplayCode());
}
}
}
}
void ObjectDisplayGrid::update()
{
// refreshes ncurses
refresh();
}
const std::shared_ptr<Displayable> ObjectDisplayGrid::getDisplayable(int x, int y) const
{
if (objectGrid[x][y].empty())
{
return nullptr;
}
return objectGrid[x][y].top();
}
void ObjectDisplayGrid::setTopMessage(int hitPoints, int score)
{
std::string topMessage;
topMessage += "HP: " + std::to_string(hitPoints);
topMessage += "\tScore: " + std::to_string(score) + "\n";
mvaddstr(0, 0, topMessage.c_str());
clrtoeol();
}
void ObjectDisplayGrid::setBottomMessage1(const std::string &message)
{
std::string bottomMessage = message;
mvaddstr(topHeight + gameHeight, 0, bottomMessage.c_str());
clrtoeol();
}
void ObjectDisplayGrid::setBottomMessage2(const std::string &message)
{
std::string bottomMessage = message;
mvaddstr(topHeight + gameHeight + bottomHeight / 2, 0, bottomMessage.c_str());
clrtoeol();
}
void ObjectDisplayGrid::removeAllObjects()
{
for (auto &it1 : objectGrid)
{
for (auto &it2 : it1)
{
while (!it2.empty())
{
it2.top().reset();
it2.pop();
}
}
it1.clear();
}
objectGrid.clear();
objectGrid.shrink_to_fit();
}
ObjectDisplayGrid::~ObjectDisplayGrid()
{
// free ncurses data
endwin();
}
|
9c1f1f077e2c454b6b9672f511d5e4705cc815b8
|
784c398207895131ea406613f52e635af386a109
|
/src/trunk/sstest.cpp
|
5d93c53239a3bf729fdc7e60e55cc97f9b4d2d06
|
[] |
no_license
|
sidred123/stochastic-msa
|
17b9253e8772677a4f95dda0b358dda32c00796a
|
68d620e61b1453387738c0b45f1cd1b5261c311a
|
refs/heads/master
| 2021-01-23T02:23:20.241526
| 2009-04-30T20:58:02
| 2009-04-30T20:58:02
| 32,217,667
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 675
|
cpp
|
sstest.cpp
|
#include "util.h"
#include "storage.h"
int main(void) {
srandom(time(NULL));
size_t arr[3000];
for (int i=0; i<3000; i++)
if ((i % 10) == 0)
arr[i] = 1600;
else
arr[i] = 40;
size_t res[3000];
for (size_t i=0; i<300; i++)
res[stochasticSelect(arr, 3000)]++;
for (int i=0; i<3000; i++) {
if (res[i] == 0) {
if ((i%10) == 0)
printf("%d: *\n", i);
else
printf("%d: \n", i);
} else {
if ((i%10) == 0)
printf("%d: %4d*\n", i, res[i]);
else
printf("%d: %4d\n", i, res[i]);
}
}
//printf("%d %d %d %d %d\n", res[0], res[1], res[2], res[3], res[4]);
}
/*int main(void) {
GISeq
}*/
|
a487559e7c138cf0bde6ea7a5e89b69af125d24c
|
f4173138b361d145422848b937e7c9775ee8aab0
|
/SP1Framework/Render_Story.cpp
|
ffa7081a6d2bc804cd2dfaa3bf3a5dffe3b1d437
|
[] |
no_license
|
theduckhorse/SP1Framework
|
65d9ea7dc7fd8fecb46e92839b98c5fc724d4cfc
|
b99fda305c62c7c776c963892d8640982fc42906
|
refs/heads/master
| 2022-09-29T08:09:44.308216
| 2016-09-03T07:13:22
| 2016-09-03T07:13:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,907
|
cpp
|
Render_Story.cpp
|
#include "Render_Story.h"
extern bool g_abKeyPressed[K_COUNT];
extern EGAMESTATES g_eGameState;
void renderStory()
{
if (g_abKeyPressed[K_ESCAPE])
g_bQuitGame = true;
if (g_dBounceTime > g_dElapsedTime)
return;
if (g_abKeyPressed[K_TAB])
{
printStory++;
g_dBounceTime = g_dElapsedTime + 0.125;
}
if (printStory == 0)
{
loadMap(8, map, mapFog); //Starting story
}
if (printStory == 1)
{
loadMap(9, map, mapFog); //Tutorial
}
if (printStory == 2)
{
g_eGameState = S_GAME_TUT;
newMap = true;
printStory = 3;
}
else if (*changeHealth != 0 && printStory > 2)
{
switch (refreshMap)
{
case 0:
loadMap(10, map, mapFog); //levers
if (g_abKeyPressed[K_TAB])
{
printStory = 3;
g_eGameState = S_GAME_1;
newMap = true;
}
break;
case 1:
loadMap(11, map, mapFog); //questions
if (g_abKeyPressed[K_TAB])
{
printStory = 4;
g_eGameState = S_GAME_2;
newMap = true;
}
break;
case 2:
loadMap(12, map, mapFog); //boxes
if (g_abKeyPressed[K_TAB])
{
printStory = 5;
g_eGameState = S_GAME_3;
newMap = true;
}
break;
case 3:
loadMap(13, map, mapFog); //teleporters
if (g_abKeyPressed[K_TAB])
{
printStory = 6;
g_eGameState = S_GAME_4;
newMap = true;
}
break;
case 4:
loadMap(19, map, mapFog); //Final map
if (g_abKeyPressed[K_TAB])
{
printStory = 7;
g_eGameState = S_GAME_5;
newMap = true;
}
break;
case 5:
loadMap(14, map, mapFog); //success
if (g_abKeyPressed[K_TAB])
{
g_eGameState = S_LEADERBOARD;
newMap = true;
}
break;
}
}
else if (*changeHealth == 0)
{
totalTime = 0.0;
loadMap(15, map, mapFog); //fail
if (g_abKeyPressed[K_TAB])
{
g_eGameState = S_MAIN_MENU;
newMap = true;
}
}
printMap(mapSizeWidth, mapSizeHeight, &timeToWait, false, false, &printHealth,false,mapFog, false, false);
}
|
83b2fbd40e6e28431c4521a4607c5f3fe6259d4d
|
8441b948c675606383818a60527fd14c1128a0a4
|
/lighting-demo/light-switch/App.cpp
|
7a6956a5567c84a9cef181ba086307fe9bee48bb
|
[
"Apache-2.0"
] |
permissive
|
mrjerryjohns/weave-demo-apps
|
64e63a38331bfaafd95174293a69bc5d82357c6f
|
bf56b9e663e072e6b198ee671fde5ce97ffddf33
|
refs/heads/master
| 2022-12-11T11:10:22.333237
| 2020-08-24T22:12:02
| 2020-08-24T22:12:02
| 290,050,210
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,752
|
cpp
|
App.cpp
|
/*
*
* Copyright (c) 2020 Google.
* 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.
*/
/**
* @file
* Main application.
*/
#include "Debug.h"
#include <SystemLayer/SystemLayer.h>
#include <InetLayer/InetLayer.h>
#include <Weave/Core/WeaveCore.h>
#include <InetLayer/InetLayer.h>
#include <SystemLayer/SystemFaultInjection.h>
#include <Weave/Support/WeaveFaultInjection.h>
#include <InetLayer/InetFaultInjection.h>
#include "App.h"
using namespace nl::Weave;
using namespace nl::Weave::Profiles::DataManagement;
// When initially sending a message to a peer before they've responded,
// how often we should re-transmit a message.
#define DEVICE_WRM_INITIAL_RETRANS_TIMEOUT_MS 500
// When the peer has responded, how often to re-transmit a message after that.
#define DEVICE_WRM_ACTIVE_RETRANS_TIMEOUT_MS 500
#define DEVICE_WRM_MAX_RETRANS 3
// Define the timeout for piggybacking a WRM acknowledgment message
#define DEVICE_WRM_PIGGYBACK_ACK_TIMEOUT_MS 200
const nl::Weave::WRMPConfig gWRMPConfig = { DEVICE_WRM_INITIAL_RETRANS_TIMEOUT_MS,
DEVICE_WRM_ACTIVE_RETRANS_TIMEOUT_MS,
DEVICE_WRM_PIGGYBACK_ACK_TIMEOUT_MS,
DEVICE_WRM_MAX_RETRANS };
void BindingEventCallback (void * const apAppState,
const Binding::EventType aEvent,
const Binding::InEventParam & aInParam,
Binding::OutEventParam & aOutParam)
{
switch (aEvent) {
default:
Binding::DefaultEventHandler(apAppState, aEvent, aInParam, aOutParam);
}
}
CommandSender *gCommandSender = NULL;
void CommandEventHandler(void * const appState, CommandSender::EventType event, const CommandSender::InEventParam &inParam, CommandSender::OutEventParam &outEventParam)
{
switch (event) {
case CommandSender::kEvent_InProgressReceived:
DEBUG_PRINT(kAPP, "Received In Progress message. Waiting for a response");
break;
case CommandSender::kEvent_StatusReportReceived:
DEBUG_PRINT(kAPP, "Received Status Report 0x%08x : 0x%04x", inParam.StatusReportReceived.statusReport->mProfileId, inParam.StatusReportReceived.statusReport->mStatusCode);
break;
case CommandSender::kEvent_CommunicationError:
DEBUG_PRINT(kAPP, "Communication Error: %d", inParam.CommunicationError.error);
break;
case CommandSender::kEvent_ResponseReceived:
DEBUG_PRINT(kAPP, "Response message, end");
break;
case CommandSender::kEvent_DefaultCheck:
gCommandSender->DefaultEventHandler(appState, event, inParam, outEventParam);
break;
}
}
App::App()
{
}
WEAVE_ERROR
App::Start(GtkApplication *application, uint64_t destinationNodeId)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
// Create a new view controller to manage our UI/screen.
_viewController = new ViewController(this, application);
// Create the data sinks to handle the incoming data, and appropriately
// modify the view
_onOffSink = new ZclOnOffClusterSink(_viewController);
// Allocate a new binding to use to setup a conversation with the bulb
_binding = ExchangeMgr.NewBinding(BindingEventCallback, NULL);
// Initialize the binding with the details of the transport we want, which includes
// UDP + Weave Reliable Messaging.
_binding->BeginConfiguration()
.Target_NodeId(destinationNodeId)
.TargetAddress_WeaveFabric(0x1)
.Transport_UDP_WRM()
.Transport_DefaultWRMPConfig(gWRMPConfig)
.Security_None()
.Exchange_ResponseTimeoutMsec(2000)
.PrepareBinding();
// Start a subscription to the bulb for the on/off cluster
_subscriptionManager = new OutboundSubscriptionManager(_binding);
_subscriptionManager->AddSink(_onOffSink);
_subscriptionManager->Start();
err = _commandSender.Init(_binding, CommandEventHandler, this);
SuccessOrExit(err);
exit:
return err;
}
gboolean App::ToggleBulbState(void *data)
{
WEAVE_ERROR err = WEAVE_NO_ERROR;
CommandSender::SendParams sendParams;
App *_this = static_cast<App *>(data);
DEBUG_PRINT(kAPP, "Toggling Light State...");
memset(&sendParams, 0, sizeof(sendParams));
// We're targeting the on/off trait instance on the remote device, which is the same that our on/off sink is tracking. There is
// a convenience method here to auto populate the path based on the sink itself.
err = sendParams.PopulateTraitPath(&_this->_subscriptionManager->GetCatalog(), _this->_onOffSink, kRootPropertyPathHandle);
SuccessOrExit(err);
// The command ID is set to the toggle command.
sendParams.CommandType = Schema::Zigbee::Cluster::General::OnOffCluster::kToggleRequestId;
// This command has no payload. Now, send it!
err = _this->_commandSender.SendCommand(NULL, NULL, sendParams);
SuccessOrExit(err);
exit:
WeaveLogFunctError(err);
return true;
}
|
808b4df629df1dddbe5d1dd48025e3b0d1720be6
|
8f7230bf62db408524c2932967f68c8bb4779540
|
/src/apib_cpu_proc.cc
|
f69ee6140d20f311c1380a1bdf9bb520f81989ad
|
[
"Apache-2.0"
] |
permissive
|
jwcastillo/apib
|
dd7ada683b20ac18dee7b0dd06171c3ff59223f6
|
4653dcb42f2ec446ef429a0df761bce2c65bec24
|
refs/heads/master
| 2020-09-04T03:48:58.844750
| 2019-11-02T01:26:21
| 2019-11-02T01:26:21
| 219,650,801
| 1
| 0
|
Apache-2.0
| 2019-11-05T03:35:49
| 2019-11-05T03:35:47
| null |
UTF-8
|
C++
| false
| false
| 4,904
|
cc
|
apib_cpu_proc.cc
|
/*
Copyright 2019 Google LLC
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
https://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 <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <cstring>
#include <fstream>
#include <iostream>
#include "absl/strings/numbers.h"
#include "src/apib_cpu.h"
#include "src/apib_lines.h"
#include "src/apib_time.h"
#define PROC_BUF_LEN 8192
namespace apib {
static int CPUCount;
static double TicksPerSecond;
/* Count the CPUs in a simple way by counting "processor" lines in /proc/cpuinfo
*/
int cpu_Count() {
std::ifstream in("/proc/cpuinfo");
if (in.fail()) {
return 1;
}
LineState line(PROC_BUF_LEN);
int count = 0;
int rc;
do {
rc = line.readStream(in);
if (rc > 0) {
while (line.next()) {
const auto l = line.line();
const auto ten = l.substr(0, 10);
if (("processor " == ten) || ("processor\t" == ten)) {
count++;
}
}
line.consume();
}
} while (rc > 0);
in.close();
if (count < 1) {
count = 1;
}
return count;
}
int cpu_Init() {
struct stat statBuf;
int err = stat("/proc/stat", &statBuf);
if (err != 0) {
return -1;
}
err = stat("/proc/meminfo", &statBuf);
if (err != 0) {
return -2;
}
TicksPerSecond = sysconf(_SC_CLK_TCK);
const char* countStr = getenv("CPU_COUNT");
if (countStr != NULL) {
CPUCount = atoi(countStr);
return 0;
}
CPUCount = cpu_Count();
if (CPUCount < 0) {
return -3;
}
return 0;
}
double cpu_GetMemoryUsage() {
std::ifstream meminfo("/proc/meminfo");
if (meminfo.fail()) {
return 0.0;
}
// PROC_BUF_LEN should be big enough to hold all of /proc/meminfo!
LineState line(PROC_BUF_LEN);
int rc = line.readStream(meminfo);
if (rc < 0) {
return 0.0;
}
long totalMem = 0;
long freeMem = 0;
long buffers = 0;
long cache = 0;
while (line.next()) {
const auto n = line.nextToken(" ");
const auto v = line.nextToken(" ");
if ("MemTotal:" == n) {
if (!absl::SimpleAtoi(v, &totalMem)) {
return 0.0;
}
} else if ("MemFree:" == n) {
if (!absl::SimpleAtoi(v, &freeMem)) {
return 0.0;
}
} else if ("Buffers:" == n) {
if (!absl::SimpleAtoi(v, &buffers)) {
return 0.0;
}
} else if ("Cached:" == n) {
if (!absl::SimpleAtoi(v, &cache)) {
return 0.0;
}
}
}
if ((totalMem <= 0) || (freeMem <= 0)) {
return 0.0;
}
return (double)(totalMem - (freeMem + buffers + cache)) / (double)totalMem;
}
static int getTicks(CPUUsage* cpu) {
std::ifstream stat("/proc/stat");
if (stat.fail()) {
return 0;
}
LineState line(PROC_BUF_LEN);
const int rc = line.readStream(stat);
if (rc < 0) {
return 0;
}
while (line.next()) {
const auto l = line.line();
if ("cpu " == l.substr(0, 4)) {
// Read the "cpu" line, which is a sum of all CPUs
int64_t idleCount = 0LL;
int64_t nonIdleCount = 0LL;
int i = 0;
absl::string_view tok;
line.nextToken(" \t");
do {
tok = line.nextToken(" \t");
if (!tok.empty()) {
int64_t c;
if (!absl::SimpleAtoi(tok, &c)) {
continue;
}
switch (i) {
case 3:
case 4:
case 7:
/* The fourth and fifth columns are "idle" and "iowait".
We consider both to be idle CPU.
The eigth is "steal", which is time lost to virtualization
as a client -- that's idle too in our estimation */
idleCount += c;
break;
default:
nonIdleCount += c;
break;
}
i++;
}
} while (!tok.empty());
cpu->nonIdle = nonIdleCount;
cpu->idle = idleCount;
return 1;
}
}
return 0;
}
void cpu_GetUsage(CPUUsage* cpu) {
getTicks(cpu);
cpu->timestamp = GetTime();
}
double cpu_GetInterval(CPUUsage* oldCpu) {
CPUUsage cpu;
if (!getTicks(&cpu)) {
return 0;
}
cpu.timestamp = GetTime();
const long long idleTicks = cpu.idle - oldCpu->idle;
const long long usageTicks = cpu.nonIdle - oldCpu->nonIdle;
const long long allUsageTicks = idleTicks + usageTicks;
memcpy(oldCpu, &cpu, sizeof(CPUUsage));
if (allUsageTicks == 0) {
return 0.0;
}
return ((double)usageTicks / (double)allUsageTicks);
}
} // namespace apib
|
dcb5fed675c433bc4062fd0d4fbdcee1d3ae2efc
|
2e0291056d7bd97af04e14aaa11a482edb48a406
|
/android-samples-master/EndlessTunnel/Tunnel/jni/welcome_scene.cpp
|
da893e1fa36bcc878cea9e04b3bf395c411ae501
|
[
"Apache-2.0"
] |
permissive
|
modstam/Stupid-Ship
|
7c3963d18445320731e132a9ab5f7bb51c57e3bd
|
03dea39bc23dbacba8b3056c2c4da0509e381db5
|
refs/heads/master
| 2020-05-27T06:09:20.012438
| 2014-11-20T22:00:09
| 2014-11-20T22:00:09
| 26,922,844
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,145
|
cpp
|
welcome_scene.cpp
|
/*
* Copyright (C) 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "anim.hpp"
#include "dialog_scene.hpp"
#include "game_ids.hpp"
#include "java_bgnactivity.hpp"
#include "java_ouractivity.hpp"
#include "our_shader.hpp"
#include "play_scene.hpp"
#include "tex_quad.hpp"
#include "welcome_scene.hpp"
#include "data/blurb.inl"
#include "data/gplus_texture.inl"
#include "data/strings.inl"
#define TITLE_POS center, 0.85f
#define TITLE_FONT_SCALE 1.0f
#define TITLE_COLOR 0.0f, 1.0f, 0.0f
// button defaults:
#define BUTTON_COLOR 0.0f, 1.0f, 0.0f
#define BUTTON_SIZE 0.2f, 0.2f
#define BUTTON_FONT_SCALE 0.5f
// button geometry
#define BUTTON_PLAY_POS center, 0.5f
#define BUTTON_PLAY_SIZE 0.4f, 0.4f
#define BUTTON_PLAY_FONT_SCALE 1.0f
// size of all side buttons (achievements, leaderboards, story, about)
#define BUTTON_SIDEBUTTON_WIDTH (center - 0.4f)
#define BUTTON_SIDEBUTTON_HEIGHT 0.2f
#define BUTTON_SIDEBUTTON_SIZE BUTTON_SIDEBUTTON_WIDTH, BUTTON_SIDEBUTTON_HEIGHT
// position of each side button (the buttons on the sides of the PLAY button)
#define BUTTON_ACHIEVEMENTS_POS 0.1f + 0.5f * BUTTON_SIDEBUTTON_WIDTH, 0.6f
#define BUTTON_LEADERBOARD_POS 0.1f + 0.5f * BUTTON_SIDEBUTTON_WIDTH, 0.4f
#define BUTTON_STORY_POS center + 0.3f + 0.5f * BUTTON_SIDEBUTTON_WIDTH, 0.6f
#define BUTTON_ABOUT_POS center + 0.3f + 0.5f * BUTTON_SIDEBUTTON_WIDTH, 0.4f
#define BUTTON_SIGN_IN_POS 0.35f, 0.1f
#define BUTTON_SIGN_IN_WIDTH 0.4f
#define BUTTON_SIGN_IN_HEIGHT 0.15f
#define BUTTON_SIGN_IN_SIZE BUTTON_SIGN_IN_WIDTH, BUTTON_SIGN_IN_HEIGHT
#define BUTTON_SIGN_IN_COLOR 0xdd/256.0f, 0x4b/256.0f, 0x39/256.0f
#define BUTTON_SIGN_IN_FONT_SCALE 0.55f
#define BUTTON_SIGN_OUT_POS 0.2f, 0.1f
#define BUTTON_SIGN_OUT_SIZE 0.3f, 0.13f
#define BUTTON_SIGN_OUT_COLOR 0.0f, 0.4f, 0.0f
#define BUTTON_WHY_POS 0.8f, 0.1f
#define BUTTON_WHY_SIZE 0.3f, 0.2f
// position of the Google+ icon
#define GPLUS_ICON_POS 0.23f, 0.1f
#define GPLUS_ICON_SIZE 0.065f
WelcomeScene::WelcomeScene() {
UiWidget *w;
mOurShader = NULL;
mGooglePlusTexture = NULL;
mGooglePlusTexQuad = NULL;
}
WelcomeScene::~WelcomeScene() {
}
void WelcomeScene::RenderBackground() {
RenderBackgroundAnimation(mShapeRenderer);
}
void WelcomeScene::OnButtonClicked(int id) {
SceneManager *mgr = SceneManager::GetInstance();
if (id == mPlayButtonId) {
mgr->RequestNewScene(new PlayScene());
} else if (id == mSignInButtonId) {
BGNActivity_StartSignIn();
} else if (id == mSignOutButtonId) {
mgr->RequestNewScene((new DialogScene())->SetText(BLURB_SIGNOUT)->SetTwoButtons(
S_YES, DialogScene::ACTION_SIGN_OUT, S_NO, DialogScene::ACTION_RETURN));
} else if (id == mAchievementsButtonId && BGNActivity_IsSignedIn()) {
BGNActivity_ShowAchievements();
} else if (id == mLeaderboardButtonId && BGNActivity_IsSignedIn()) {
BGNActivity_ShowLeaderboard(LEADERBOARD_ID);
} else if (id == mStoryButtonId) {
mgr->RequestNewScene((new DialogScene())->SetText(BLURB_STORY)->SetSingleButton(S_OK,
DialogScene::ACTION_RETURN));
} else if (id == mAboutButtonId) {
mgr->RequestNewScene((new DialogScene())->SetText(BLURB_ABOUT)->SetSingleButton(S_OK,
DialogScene::ACTION_RETURN));
} else if (id == mWhyButtonId) {
mgr->RequestNewScene((new DialogScene())->SetText(BLURB_WHY_SIGN_IN)->SetSingleButton(S_OK,
DialogScene::ACTION_RETURN));
}
}
void WelcomeScene::DoFrame() {
// update widget states based on signed-in status
UpdateWidgetStates();
// if the sign in or cloud save process is in progress, show a wait screen. Otherwise, not:
SetWaitScreen(BGNActivity_IsInProgress() ||
(BGNActivity_IsSignedIn() && OurActivity_GetCloudData() == OURACTIVITY_CLOUD_WAITING));
// draw the UI
UiScene::DoFrame();
// draw the Google+ icon, if needed
if (!BGNActivity_IsSignedIn() && !mWaitScreen) {
mGooglePlusTexQuad->Render();
}
}
void WelcomeScene::UpdateWidgetStates() {
bool signedIn = BGNActivity_IsSignedIn();
GetWidgetById(mSignInButtonId)->SetVisible(!signedIn);
GetWidgetById(mSignOutButtonId)->SetVisible(signedIn);
GetWidgetById(mWhyButtonId)->SetVisible(!signedIn);
GetWidgetById(mAchievementsButtonId)->SetEnabled(signedIn);
GetWidgetById(mLeaderboardButtonId)->SetEnabled(signedIn);
// Build navigation
AddNav(mPlayButtonId, UI_DIR_RIGHT, mStoryButtonId);
AddNav(mPlayButtonId, UI_DIR_LEFT, signedIn ? mAchievementsButtonId : -1);
AddNav(mPlayButtonId, UI_DIR_DOWN, signedIn ? mSignOutButtonId : mSignInButtonId);
AddNav(mAchievementsButtonId, UI_DIR_DOWN, mLeaderboardButtonId);
AddNav(mAchievementsButtonId, UI_DIR_RIGHT, mPlayButtonId);
AddNav(mLeaderboardButtonId, UI_DIR_DOWN, mSignOutButtonId);
AddNav(mLeaderboardButtonId, UI_DIR_UP, mAchievementsButtonId);
AddNav(mLeaderboardButtonId, UI_DIR_RIGHT, mPlayButtonId);
AddNav(mStoryButtonId, UI_DIR_LEFT, mPlayButtonId);
AddNav(mStoryButtonId, UI_DIR_DOWN, mAboutButtonId);
AddNav(mAboutButtonId, UI_DIR_LEFT, mPlayButtonId);
AddNav(mAboutButtonId, UI_DIR_UP, mStoryButtonId);
AddNav(mAboutButtonId, UI_DIR_DOWN, signedIn ? mSignOutButtonId : mSignInButtonId);
AddNav(mSignInButtonId, UI_DIR_UP, mPlayButtonId);
AddNav(mSignInButtonId, UI_DIR_RIGHT, mWhyButtonId);
AddNav(mWhyButtonId, UI_DIR_LEFT, mSignInButtonId);
AddNav(mWhyButtonId, UI_DIR_UP, mPlayButtonId);
AddNav(mSignOutButtonId, UI_DIR_UP, mPlayButtonId);
AddNav(mSignOutButtonId, UI_DIR_RIGHT, mPlayButtonId);
}
void WelcomeScene::OnStartGraphics() {
UiScene::OnStartGraphics();
mOurShader = new OurShader();
mOurShader->Compile();
mGooglePlusTexture = new Texture();
mGooglePlusTexture->InitFromRawRGB(GPLUS_TEXTURE.width, GPLUS_TEXTURE.height, false,
GPLUS_TEXTURE.pixel_data);
mGooglePlusTexQuad = new TexQuad(mGooglePlusTexture, mOurShader, 0.0f, 0.0f, 1.0f, 1.0f);
mGooglePlusTexQuad->SetCenter(GPLUS_ICON_POS);
mGooglePlusTexQuad->SetWidth(GPLUS_ICON_SIZE);
mGooglePlusTexQuad->SetHeight(GPLUS_ICON_SIZE);
}
void WelcomeScene::OnCreateWidgets() {
// create widgets
float maxX = SceneManager::GetInstance()->GetScreenAspect();
float center = 0.5f * maxX;
// create the static title
NewWidget()->SetText(S_TITLE)->SetCenter(TITLE_POS)->SetTextColor(TITLE_COLOR)
->SetFontScale(TITLE_FONT_SCALE)->SetTransition(UiWidget::TRANS_FROM_TOP);
// create the "play" button
mPlayButtonId = NewWidget()->SetText(S_PLAY)->SetTextColor(BUTTON_COLOR)
->SetCenter(BUTTON_PLAY_POS)->SetSize(BUTTON_PLAY_SIZE)
->SetFontScale(BUTTON_PLAY_FONT_SCALE)->SetIsButton(true)
->SetTransition(UiWidget::TRANS_SCALE)->GetId();
// create the "sign out" button
mSignOutButtonId = NewWidget()->SetTextColor(BUTTON_SIGN_OUT_COLOR)->SetText(S_SIGN_OUT)
->SetCenter(BUTTON_SIGN_OUT_POS)->SetSize(BUTTON_SIGN_OUT_SIZE)
->SetFontScale(BUTTON_SIGN_IN_FONT_SCALE)->SetIsButton(true)
->SetTransition(UiWidget::TRANS_FROM_BOTTOM)->GetId();
// create the "sign in" button
mSignInButtonId = NewWidget()->SetTextColor(1.0f, 1.0f, 1.0f)->SetText(S_SIGN_IN)
->SetBackColor(BUTTON_SIGN_IN_COLOR)
->SetCenter(BUTTON_SIGN_IN_POS)->SetSize(BUTTON_SIGN_IN_SIZE)
->SetFontScale(BUTTON_SIGN_IN_FONT_SCALE)->SetIsButton(true)
->SetHasBorder(false)->SetTransition(UiWidget::TRANS_FROM_BOTTOM)->GetId();
// create the "why sign in" button
mWhyButtonId = NewWidget()->SetTextColor(BUTTON_SIGN_IN_COLOR)->SetText(S_WHY_SIGN_IN)
->SetCenter(BUTTON_WHY_POS)->SetSize(BUTTON_WHY_SIZE)
->SetFontScale(BUTTON_FONT_SCALE)->SetIsButton(true)->SetHasBorder(false)
->SetTransparent(true)->SetTransition(UiWidget::TRANS_FROM_BOTTOM)->GetId();
// achievements button
mAchievementsButtonId = NewWidget()->SetTextColor(BUTTON_COLOR)->SetText(S_ACHIEVEMENTS)
->SetCenter(BUTTON_ACHIEVEMENTS_POS)->SetSize(BUTTON_SIDEBUTTON_SIZE)
->SetFontScale(BUTTON_FONT_SCALE)->SetIsButton(true)
->SetTransition(UiWidget::TRANS_FROM_LEFT)->GetId();
// leaderboard button
mLeaderboardButtonId = NewWidget()->SetTextColor(BUTTON_COLOR)->SetText(S_LEADERBOARD)
->SetCenter(BUTTON_LEADERBOARD_POS)->SetSize(BUTTON_SIDEBUTTON_SIZE)
->SetFontScale(BUTTON_FONT_SCALE)->SetIsButton(true)
->SetTransition(UiWidget::TRANS_FROM_LEFT)->GetId();
// story button
mStoryButtonId = NewWidget()->SetTextColor(BUTTON_COLOR)->SetText(S_STORY)
->SetCenter(BUTTON_STORY_POS)->SetSize(BUTTON_SIDEBUTTON_SIZE)
->SetFontScale(BUTTON_FONT_SCALE)->SetIsButton(true)
->SetTransition(UiWidget::TRANS_FROM_RIGHT)->GetId();
// about button
mAboutButtonId = NewWidget()->SetTextColor(BUTTON_COLOR)->SetText(S_ABOUT)
->SetCenter(BUTTON_ABOUT_POS)->SetSize(BUTTON_SIDEBUTTON_SIZE)
->SetFontScale(BUTTON_FONT_SCALE)->SetIsButton(true)
->SetTransition(UiWidget::TRANS_FROM_RIGHT)->GetId();
// "Play" button is the default button
SetDefaultButton(mPlayButtonId);
// enable/disable widgets as appropriate to signed in state
UpdateWidgetStates();
}
void WelcomeScene::OnKillGraphics() {
UiScene::OnKillGraphics();
CleanUp(&mGooglePlusTexQuad);
CleanUp(&mGooglePlusTexture);
CleanUp(&mOurShader);
}
|
e01b8662f16e4cdb2b59f9b5bf784ec0303553fe
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/ash/wm/overview/overview_item_view.h
|
f14725a9e8783ab2f61085a465e04ed95ccb08bc
|
[
"BSD-3-Clause"
] |
permissive
|
chromium/chromium
|
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
|
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
|
refs/heads/main
| 2023-08-24T00:35:12.585945
| 2023-08-23T22:01:11
| 2023-08-23T22:01:11
| 120,360,765
| 17,408
| 7,102
|
BSD-3-Clause
| 2023-09-10T23:44:27
| 2018-02-05T20:55:32
| null |
UTF-8
|
C++
| false
| false
| 4,204
|
h
|
overview_item_view.h
|
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ASH_WM_OVERVIEW_OVERVIEW_ITEM_VIEW_H_
#define ASH_WM_OVERVIEW_OVERVIEW_ITEM_VIEW_H_
#include "ash/wm/overview/overview_highlightable_view.h"
#include "ash/wm/window_mini_view.h"
#include "base/memory/raw_ptr.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/views/controls/button/button.h"
namespace aura {
class Window;
} // namespace aura
namespace views {
class View;
} // namespace views
namespace ash {
class CloseButton;
class OverviewItem;
// OverviewItemView covers the overview window, provides an overview only header
// and handles events. It hosts a mirror view if the window is minimized.
class ASH_EXPORT OverviewItemView : public WindowMiniView,
public OverviewHighlightableView {
public:
METADATA_HEADER(OverviewItemView);
// The visibility of the header. It may be fully visible or invisible, or
// everything but the close button is visible.
enum class HeaderVisibility {
kInvisible,
kCloseButtonInvisibleOnly,
kVisible,
};
// If `show_preview` is true, this class will contain a child view which
// mirrors `window`.
OverviewItemView(OverviewItem* overview_item,
views::Button::PressedCallback close_callback,
aura::Window* window,
bool show_preview);
OverviewItemView(const OverviewItemView&) = delete;
OverviewItemView& operator=(const OverviewItemView&) = delete;
~OverviewItemView() override;
// Fades the app icon and title out if `visibility` is kInvisible, in
// otherwise. If `close_button_` is not null, also fades the close button in
// if `visibility` is kVisible, out otherwise. Sets
// `current_header_visibility_` to `visibility`. Fades in if `animate` is
// true, otherwise shows immediately.
void SetHeaderVisibility(HeaderVisibility visibility, bool animate);
// Hides the close button instantaneously, and then fades it in slowly and
// with a long delay. Sets `current_header_visibility_` to kVisible. Assumes
// that `close_button_` is not null, and that `current_header_visibility_` is
// not kInvisible.
void HideCloseInstantlyAndThenShowItSlowly();
// Called when `overview_item_` is about to be restored to its original state
// outside of overview.
void OnOverviewItemWindowRestoring();
// Refreshes `preview_view_` so that its content is up-to-date. Used by tab
// dragging.
void RefreshPreviewView();
// WindowMiniView:
gfx::Rect GetHeaderBounds() const override;
gfx::Size GetPreviewViewSize() const override;
// WindowMiniViewBase:
void RefreshItemVisuals() override;
// OverviewHighlightableView:
views::View* GetView() override;
void MaybeActivateHighlightedView() override;
void MaybeCloseHighlightedView(bool primary_action) override;
void MaybeSwapHighlightedView(bool right) override;
bool MaybeActivateHighlightedViewOnOverviewExit(
OverviewSession* overview_session) override;
void OnViewHighlighted() override;
void OnViewUnhighlighted() override;
gfx::Point GetMagnifierFocusPointInScreen() override;
CloseButton* close_button() const { return close_button_; }
protected:
// views::View:
bool OnMousePressed(const ui::MouseEvent& event) override;
bool OnMouseWheel(const ui::MouseWheelEvent& event) override;
bool OnMouseDragged(const ui::MouseEvent& event) override;
void OnMouseReleased(const ui::MouseEvent& event) override;
void OnGestureEvent(ui::GestureEvent* event) override;
bool CanAcceptEvent(const ui::Event& event) override;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
void OnThemeChanged() override;
private:
// The OverviewItem which owns the widget which houses this view. Non-null
// until `OnOverviewItemWindowRestoring` is called.
raw_ptr<OverviewItem, ExperimentalAsh> overview_item_;
raw_ptr<CloseButton, ExperimentalAsh> close_button_;
HeaderVisibility current_header_visibility_ = HeaderVisibility::kVisible;
};
} // namespace ash
#endif // ASH_WM_OVERVIEW_OVERVIEW_ITEM_VIEW_H_
|
dcd9d7ec2db79a80f30197a039aaf179be3b563a
|
68b2292432a317469c6035be92b9a39659e40d00
|
/Devices/Device.hh
|
34bbe746b3b477682e711c4c3d15ca9f88710cc6
|
[] |
no_license
|
spartacus-technologies/Auxilo-box
|
4a45b7c611206531c0081800cbed27ea6d09fa7e
|
1e3d5a521982eb7b64fad4c8dae275469c457759
|
refs/heads/master
| 2021-01-17T05:34:47.870339
| 2014-03-12T18:11:10
| 2014-03-12T18:11:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 348
|
hh
|
Device.hh
|
#ifndef DEVICE_HH
#define DEVICE_HH
#include "../Communications/Protocol.pb.h"
class Device
{
public:
virtual ~Device(){}
virtual void initialize() = 0;
virtual void setStatus(auxilo::deviceState status) = 0;
virtual auxilo::deviceState getStatus() const = 0;
virtual std::string getID() const = 0;
};
#endif // DEVICE_HH
|
ea950a5b2e2a53ac9cb6a90c586acb18f025a5ec
|
c3f2ff06d6aab9f5ff7ed34eb3637a7abce75b44
|
/motordriver/src/motor_driver_publisher_node/motor_driver_publisher_node.ino
|
e15c7258c3fa9c42f8f48d884d99065d512c8640
|
[] |
no_license
|
mathew-wu/flexiblearm-with-Arduino
|
89da57619aabd5e7bdcdaaac083613fbe5c51441
|
520e365ff68fa74039d0770e1d08d1c6cbd37b35
|
refs/heads/master
| 2020-08-29T08:24:24.646379
| 2019-10-28T06:33:34
| 2019-10-28T06:33:34
| 217,980,788
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 594
|
ino
|
motor_driver_publisher_node.ino
|
#include <ros.h> // needed in every ros program
#include <geometry_msgs/Twist.h> //type of message sent by motor driver
ros::NodeHandle nh; // instantiate the node handle which will create the publisher node
geoemtry_msgs::Twist msg; //creates the message type twist
ros::Publisher pub("cmd_vel",&msg ); //creates the publisher pub with message type of twist
void setup()
{
nh.initNode(); //initializes the node
nh.advertise(pub);
}
void loop()
{
msg.linear.x = 1 //signal/thing that you want to send
pub.publish(&msg); //sends out the message
nh.spinOnce();
delay(1000);
}
|
a7933efa752cf97c0f7ec419f0a91a8ed568af1f
|
003fd3318cd113d295ca550e91631f761848153f
|
/Section13/Movie.h
|
fac9f8a718f456c5dc5589af602151de72333c92
|
[] |
no_license
|
tran-nick/Learning-CPP
|
744be4b9d50bea8d8fc3aa43231b69447adb0d39
|
7fa6c295723579748eb1c58dcaf3dce52d8ac69d
|
refs/heads/master
| 2022-04-24T10:00:44.053993
| 2020-04-25T22:47:20
| 2020-04-25T22:47:20
| 250,141,272
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 506
|
h
|
Movie.h
|
#pragma once
#include <string>
class Movie
{
private:
std::string name;
std::string rating;
int num_watched;
public:
void set_name(std::string name_val);
std::string get_name();
void set_rating(std::string rating_val);
std::string get_rating();
void watched();
int get_watched();
//constructor with defaults parameters
Movie(std::string name_val = "", std::string rating_val = "", int num_watched_val = 0);
//copy constructor
Movie(const Movie& source);
};
|
c7f9b401972215d44aa37af54dfd83c4348e5396
|
0c43ec2cc922d3cec7a0e8713d6654cd583b4e14
|
/Cavalcade/Timer.h
|
42dedb3c54941fc0c2a2991084bc4064482a3917
|
[] |
no_license
|
dblalock08/cavalcade
|
15f9c44d04c7cc873d0e3a75036d993f7e537fa1
|
55b25e5743bc5b235910de86bec41aa1b0ef0e7e
|
refs/heads/master
| 2020-06-04T05:38:50.635471
| 2012-12-05T15:48:10
| 2012-12-05T15:48:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 481
|
h
|
Timer.h
|
// Timer.h
#pragma once
#include <Windows.h>
#define WIN32_LEAN_AND_MEAN
class Timer
{
public:
Timer();
~Timer();
bool Initialize();
void Update(); // Query the system time and update the time since last query
float GetTime(); // Returns time since most recent update in ms
private:
INT64 m_frequency;
INT64 m_startTime;
float m_ticksPerMs;
float m_frameTime;
SYSTEM_INFO m_sysInfo;
DWORD m_numProcessors;
DWORD_PTR m_affinityMask;
HANDLE m_threadHandle;
};
|
1698648fe5162094126a1e8e31711ba5c004d695
|
097007b435b1bf420a19ce33aabee32f0789f145
|
/codeforces/e86_div2/c1.cpp
|
e2be56c06a9e323a5185b1c82885776017e927c0
|
[] |
no_license
|
Anshit01/Competitive-Programming
|
71f84a85dde49278f8c3318d00db70616d8ea470
|
13911ec7f622abc061fea1ccc1f35d34118641f7
|
refs/heads/master
| 2023-06-11T12:06:11.722865
| 2021-06-30T11:51:01
| 2021-06-30T11:51:01
| 266,321,296
| 5
| 2
| null | 2020-10-19T09:47:06
| 2020-05-23T11:21:40
|
C++
|
UTF-8
|
C++
| false
| false
| 1,160
|
cpp
|
c1.cpp
|
#include <bits/stdc++.h>
#define ll long long
#define f(i, x, n) for(int i = x; i < n; i++)
#define dbg(x) cout << x << endl
#define dbg2(x, y) cout << x << " " << y << endl
#define dbg3(x, y, z) cout << x << " " << y << " " << z << endl
#define mod 1000000007
using namespace std;
int lcm(int a, int b){
return (a*b)/__gcd(a, b);
}
int main(){
ios::sync_with_stdio(0);
cin.tie(NULL);
int t;
cin >> t;
while(t--){
ll a, b, n, x, y, lcmi;
cin >> a >> b >> n;
lcmi = lcm(a, b);
if(a > b){
int tmp = a;
a = b;
b = tmp;
}
f(i, 0, n){
cin >> x >> y;
int sumx = 0, sumy = 0;
x--;
if(x < lcmi){
sumx = (x < b)? 0 : x-b+1;
}else{
sumx = x - ((((x/lcmi)-1)*b) + min(x%lcmi, b) + b-1);
}
if(y < lcmi){
sumy = (y < b)? 0 : y-b+1;
}else{
sumy = y - ((((y/lcmi)-1)*b) + min(y%lcmi, b) + b-1);
}
cout << sumy - sumx << ' ';
}
cout << endl;
}
}
|
63e04a9e8c5dab688a45658be7707b00ab954c44
|
c74ee5e6386a94a2b6d0d461b9d33362008787da
|
/point.cpp
|
6f7e126ba7076964ca75360c7d5f54e2fba1c915
|
[] |
no_license
|
CPPLondonUniClassroom/point-exercise-2018-07-17-cha-ku
|
d3b93866502115644ddbf96fc50bc86ec77c6c65
|
ec891cb99c8cfc18d646f5cc238721b85598f9cf
|
refs/heads/master
| 2020-03-29T10:11:33.043860
| 2018-09-27T16:05:43
| 2018-09-27T16:05:43
| 149,793,475
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,115
|
cpp
|
point.cpp
|
//
// Created by Tristan Brindle on 10/07/2018.
//
#include "point.hpp"
#include <ostream>
bool operator==(const point& lhs, const point& rhs)
{
return lhs.x == rhs.x &&
lhs.y == rhs.y;
}
bool operator!=(const point& lhs, const point& rhs)
{
//Better to do it this way -
return !(lhs == rhs);
//Rather than
//return lhs.x != rhs.x ||
// lhs.y != rhs.y;
}
point operator+(const point& lhs, const point& rhs)
{
return point{lhs.x + rhs.x, lhs.y + rhs.y};
}
point operator-(const point& lhs, const point& rhs)
{
return point{lhs.x - rhs.x, lhs.y - rhs.y};
}
// This is a member function. Operates on an instance of point
point& point::operator+=(const point& val)
{
this->x += val.x;
this->y += val.y;
return *this;
}
// This is a member function. Operates on an instance of point
point& point::operator-=(const point& val)
{
//this-> is implicit in this case
x -= val.x;
y -= val.y;
return *this;
}
std::ostream& operator<<(std::ostream& os, const point& val)
{
os << '(' << val.x << " , " << val.y << ')' ;
return os;
}
|
91329630232463750de3e844a1692efb43272b71
|
b162de01d1ca9a8a2a720e877961a3c85c9a1c1c
|
/594.longest-harmonious-subsequence.cpp
|
b216bc5b32b54741c9d2f6e98cc1c36590859b63
|
[] |
no_license
|
richnakasato/lc
|
91d5ff40a1a3970856c76c1a53d7b21d88a3429c
|
f55a2decefcf075914ead4d9649d514209d17a34
|
refs/heads/master
| 2023-01-19T09:55:08.040324
| 2020-11-19T03:13:51
| 2020-11-19T03:13:51
| 114,937,686
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 834
|
cpp
|
594.longest-harmonious-subsequence.cpp
|
/*
* [594] Longest Harmonious Subsequence
*
* https://leetcode.com/problems/longest-harmonious-subsequence/description/
*
* algorithms
* Easy (42.16%)
* Total Accepted: 29.6K
* Total Submissions: 70.3K
* Testcase Example: '[1,3,2,2,5,2,3,7]'
*
* We define a harmonious array is an array where the difference between its
* maximum value and its minimum value is exactly 1.
*
* Now, given an integer array, you need to find the length of its longest
* harmonious subsequence among all its possible subsequences.
*
* Example 1:
*
* Input: [1,3,2,2,5,2,3,7]
* Output: 5
* Explanation: The longest harmonious subsequence is [3,2,2,2,3].
*
*
*
* Note:
* The length of the input array will not exceed 20,000.
*
*
*
*/
class Solution {
public:
int findLHS(vector<int>& nums) {
}
};
|
755efd5b0bfccabefe25841a6b502c20310d07b8
|
6348b3b6ceacd7dac91f44036b3df8ad5192a136
|
/examples/source/tutorials/pointer_lifetime.cpp
|
d3131df542bb1e9e795b6d0f0dbb068afbf26db4
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
ThePhD/sol2
|
b0167676fecf9c65f371f6319833393cdbda0bbe
|
9c882a28fdb6f4ad79a53a4191b43ce48a661175
|
refs/heads/develop
| 2023-08-22T21:48:22.328223
| 2023-08-06T21:47:47
| 2023-08-06T21:47:47
| 49,177,547
| 3,912
| 572
|
MIT
| 2023-07-18T17:46:18
| 2016-01-07T03:09:13
|
C++
|
UTF-8
|
C++
| false
| false
| 1,758
|
cpp
|
pointer_lifetime.cpp
|
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
struct my_type {
void stuff() {
}
};
int main() {
sol::state lua;
/*
// AAAHHH BAD
// dangling pointer!
lua["my_func"] = []() -> my_type* { return new my_type(); };
// AAAHHH!
lua.set("something", new my_type());
// AAAAAAHHH!!!
lua["something_else"] = new my_type();
*/
// :ok:
lua["my_func0"] = []() -> std::unique_ptr<my_type> {
return std::make_unique<my_type>();
};
// :ok:
lua["my_func1"] = []() -> std::shared_ptr<my_type> {
return std::make_shared<my_type>();
};
// :ok:
lua["my_func2"] = []() -> my_type { return my_type(); };
// :ok:
lua.set(
"something", std::unique_ptr<my_type>(new my_type()));
std::shared_ptr<my_type> my_shared
= std::make_shared<my_type>();
// :ok:
lua.set("something_else", my_shared);
// :ok:
auto my_unique = std::make_unique<my_type>();
lua["other_thing"] = std::move(my_unique);
// :ok:
lua["my_func5"] = []() -> my_type* {
static my_type mt;
return &mt;
};
// THIS IS STILL BAD DON'T DO IT AAAHHH BAD
// return a unique_ptr that's empty instead
// or be explicit!
lua["my_func6"] = []() -> my_type* { return nullptr; };
// :ok:
lua["my_func7"]
= []() -> std::nullptr_t { return nullptr; };
// :ok:
lua["my_func8"] = []() -> std::unique_ptr<my_type> {
// default-constructs as a nullptr,
// gets pushed as nil to Lua
return std::unique_ptr<my_type>();
// same happens for std::shared_ptr
};
// Acceptable, it will set 'something' to nil
// (and delete it on next GC if there's no more references)
lua.set("something", nullptr);
// Also fine
lua["something_else"] = nullptr;
return 0;
}
|
fc0bfc45dddf875e2b0628cc77e066cf4ef1b214
|
e969d76b10f6cc7d87566a32295b2c2997cd675f
|
/lab1/Lab_Sources/MyRender.cpp
|
8e8a4b868801602bbd7a2b84fb8b7c3d39b8a4c6
|
[] |
no_license
|
Aspirisha/CompGraphics
|
6b94e2c09fb612cb240e84c2759c1ebddf4b79e2
|
ea540e8ac94260d5e8ae01e724f430af2b0af4f0
|
refs/heads/master
| 2021-01-01T18:56:15.657519
| 2014-11-17T15:00:01
| 2014-11-17T15:00:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,736
|
cpp
|
MyRender.cpp
|
#include "stdafx.h"
#include <xnamath.h>
#include <d3dcompiler.h>
#include "MyRender.h"
#include "MyObject.h"
#include "macros.h"
#include "Log.h"
struct ConstantBuffer
{
XMMATRIX mWorld;
XMMATRIX mView;
XMMATRIX mProjection;
};
MyRender::MyRender(DWORD fps)
{
m_pVertexShader = nullptr;
m_pPixelShader = nullptr;
m_pVertexLayout = nullptr;
m_pVertexBuffer = nullptr;
m_pIndexBuffer = nullptr;
m_pConstantBuffer = nullptr;
m_verticesNumber = 0;
m_indicesNumber = 0;
m_fps = fps;
}
HRESULT MyRender::m_CompileShaderFromFile(LPCSTR fileName, LPCSTR EntryPoint, LPCSTR ShaderModel, ID3DBlob** ppBlobOut)
{
HRESULT hr = S_OK;
DWORD ShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS;
#if defined( DEBUG ) || defined( _DEBUG )
ShaderFlags |= D3DCOMPILE_DEBUG;
#endif
ID3DBlob* pErrorBlob;
hr = D3DX11CompileFromFile(fileName, 0, 0, EntryPoint, ShaderModel, 0, 0, 0, ppBlobOut, &pErrorBlob, 0);
if(FAILED(hr) && pErrorBlob != NULL)
OutputDebugStringA((char*)pErrorBlob->GetBufferPointer());
_RELEASE(pErrorBlob);
return hr;
}
bool MyRender::Init(HWND hwnd)
{
HRESULT hr = S_OK;
// compile vertex shader
ID3DBlob *pVSBlob = nullptr;
hr = m_CompileShaderFromFile("shader.fx", "VS", "vs_4_0", &pVSBlob);
if(FAILED(hr))
{
Log::Get()->Err("Error compiling shader.fx. Error = %lu", hr);
return false;
}
hr = m_pd3dDevice->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), nullptr, &m_pVertexShader);
if(FAILED(hr))
{
Log::Get()->Err("Error creating vertex shader.");
_RELEASE(pVSBlob);
return false;
}
D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } // 12 is 3 * 4 for POSITION element
};
UINT numElements = ARRAYSIZE( layout );
hr = m_pd3dDevice->CreateInputLayout(layout, numElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &m_pVertexLayout);
_RELEASE(pVSBlob);
if( FAILED(hr))
{
Log::Get()->Err("CreateInputLayout error.");
return false;
}
m_pImmediateContext->IASetInputLayout(m_pVertexLayout);
ID3DBlob *pPSBlob = nullptr;
hr = m_CompileShaderFromFile("shader.fx", "PS", "ps_4_0", &pPSBlob);
if (FAILED(hr))
{
Log::Get()->Err("Unable to compile file shader.fx.");
return false;
}
hr = m_pd3dDevice->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), nullptr, &m_pPixelShader);
_RELEASE(pPSBlob);
if(FAILED(hr))
{
Log::Get()->Err("Unable to create pixel shader.");
_RELEASE(pPSBlob);
return false;
}
m_torus = new MyObject;
D3D11_BUFFER_DESC bd;
RtlZeroMemory(&bd, sizeof(bd));
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof(SimpleVertex) * m_torus->GetVerticesNumber();
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = 0;
D3D11_SUBRESOURCE_DATA data;
RtlZeroMemory(&data, sizeof(data));
data.pSysMem = m_torus->GetVertices();
hr = m_pd3dDevice->CreateBuffer(&bd, &data, &m_pVertexBuffer);
if (FAILED(hr))
{
Log::Get()->Err("CreateBuffer error for vertex buffer.");
return false;
}
UINT stride = sizeof(SimpleVertex);
UINT offset = 0;
m_pImmediateContext->IASetVertexBuffers(0, 1, &m_pVertexBuffer, &stride, &offset);
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof(WORD) * m_torus->GetIndicesNumber();
bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
bd.CPUAccessFlags = 0;
data.pSysMem = m_torus->GetIndices();
hr = m_pd3dDevice->CreateBuffer(&bd, &data, &m_pIndexBuffer);
if(FAILED(hr))
{
Log::Get()->Err("CreateBuffer error for torus.");
return false;
}
m_pImmediateContext->IASetIndexBuffer(m_pIndexBuffer, DXGI_FORMAT_R16_UINT, 0);
m_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof(ConstantBuffer);
bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bd.CPUAccessFlags = 0;
hr = m_pd3dDevice->CreateBuffer(&bd, 0, &m_pConstantBuffer);
if(FAILED(hr))
{
Log::Get()->Err("CreateBuffer error for Constant buffer.");
return false;
}
m_camera = new MyCamera();
float width = 1280.0f;
float height = 1024.0f;
m_Projection = XMMatrixPerspectiveFovLH(XM_PI / 3.0f, width/height, 0.1f, 100.0f );
return true;
}
bool MyRender::Draw()
{
ConstantBuffer cb;
m_camera->Update();
XMMATRIX world1 = XMLoadFloat4x4(&(m_torus->GetWorldMatrix1()));
XMMATRIX world2 = XMLoadFloat4x4(&(m_torus->GetWorldMatrix2()));
XMMATRIX view = XMLoadFloat4x4(&(m_camera->GetViewMatrix()));
cb.mWorld = XMMatrixTranspose(world1);
cb.mView = XMMatrixTranspose(view);
cb.mProjection = XMMatrixTranspose(m_Projection);
m_pImmediateContext->UpdateSubresource( m_pConstantBuffer, 0, NULL, &cb, 0, 0 );
m_pImmediateContext->VSSetShader(m_pVertexShader, NULL, 0);
m_pImmediateContext->VSSetConstantBuffers( 0, 1, &m_pConstantBuffer);
m_pImmediateContext->PSSetShader(m_pPixelShader, NULL, 0);
m_pImmediateContext->DrawIndexed(m_torus->GetIndicesNumber(), 0, 0);
cb.mWorld = XMMatrixTranspose(world2);
m_pImmediateContext->UpdateSubresource(m_pConstantBuffer, 0, NULL, &cb, 0, 0);
m_pImmediateContext->DrawIndexed(m_torus->GetIndicesNumber(), 0, 0);
return true;
}
bool MyRender::Close()
{
_RELEASE(m_pVertexBuffer);
_RELEASE(m_pVertexLayout);
_RELEASE(m_pVertexShader);
_RELEASE(m_pPixelShader);
_RELEASE(m_pIndexBuffer);
_RELEASE(m_pConstantBuffer);
delete m_torus;
return true;
}
|
f5c60d25fc16253754b6c71b1b46ab70e58b1aa7
|
9b4816166b9597ac85aa25ac6b2c1cb3d0fce4b4
|
/Source/PluginEditor.cpp
|
6618a9a1337110e2c1d1aa3005514fee2d48b9fe
|
[] |
no_license
|
SilviaMessana/HW3_CMLS
|
7220262142d9523760154250e7b5fbb65cb7ec11
|
2aaa40a9bc55ce57a93c1a17d82c5c3fc5a0fbec
|
refs/heads/main
| 2023-05-07T12:27:49.790423
| 2021-05-30T10:26:50
| 2021-05-30T10:26:50
| 372,056,863
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,764
|
cpp
|
PluginEditor.cpp
|
/*
==============================================================================
This file contains the basic framework code for a JUCE plugin editor.
==============================================================================
*/
#include "PluginProcessor.h"
#include "PluginEditor.h"
//==============================================================================
DistorionEffectAudioProcessorEditor::DistorionEffectAudioProcessorEditor (DistorionEffectAudioProcessor& p)
: AudioProcessorEditor (&p), audioProcessor (p)
{
//KNOBS/LABELS
//OUTPUT
addAndMakeVisible(outputKnob = new juce::Slider("Output"));
outputKnob->setLookAndFeel(&myLookAndFeelV3);
outputKnob->setSliderStyle(juce::Slider::RotaryVerticalDrag);
outputKnob->setTextBoxStyle(juce::Slider::NoTextBox, false, 100, 100);
audioProcessor.getStateScopedPointer()->addParameterListener("output", this);
addAndMakeVisible(outputLabel = new juce::Label("outputLabel"));
outputLabel->setText("OUTPUT", juce::NotificationType::dontSendNotification);
outputLabel->setJustificationType(juce::Justification::centred);
outputLabel->setFont(juce::Font(20.0f, juce::Font::bold));
outputLabel->setColour(juce::Label::textColourId, juce::Colour(0.0f, 0.0f, 0.0f));
//DETUNE
addAndMakeVisible(detuneKnob = new juce::Slider("Detune"));
detuneKnob->setLookAndFeel(&myLookAndFeelV2);
detuneKnob->setSliderStyle(juce::Slider::RotaryVerticalDrag);
detuneKnob->setTextBoxStyle(juce::Slider::NoTextBox, false, 100, 100);
audioProcessor.getStateScopedPointer()->addParameterListener("detune", this);
addAndMakeVisible(detuneLabel = new juce::Label("detuneLabel"));
detuneLabel->setText("DETUNE", juce::NotificationType::dontSendNotification);
detuneLabel->setJustificationType(juce::Justification::centred);
detuneLabel->setFont(juce::Font(16.0f, juce::Font::bold));
detuneLabel->setFont(juce::Font(20.0f, juce::Font::bold));
detuneLabel->setColour(juce::Label::textColourId, juce::Colour(0.0f, 0.0f, 0.0f));
//BLEND
addAndMakeVisible(blendKnob = new juce::Slider("Blend"));
blendKnob->setLookAndFeel(&myLookAndFeelV2);
blendKnob->setSliderStyle(juce::Slider::RotaryVerticalDrag);
blendKnob->setTextBoxStyle(juce::Slider::NoTextBox, false, 100, 100);
audioProcessor.getStateScopedPointer()->addParameterListener("blend", this);
addAndMakeVisible(blendLabel = new juce::Label("blendLabel"));
blendLabel->setText("BLEND", juce::NotificationType::dontSendNotification);
blendLabel->setJustificationType(juce::Justification::centred);
blendLabel->setFont(juce::Font(16.0f, juce::Font::bold));
blendLabel->setFont(juce::Font(20.0f, juce::Font::bold));
blendLabel->setColour(juce::Label::textColourId, juce::Colour(0.0f, 0.0f, 0.0f));
//REVERB
addAndMakeVisible(reverbKnob = new juce::Slider("Reverb"));
reverbKnob->setLookAndFeel(&myLookAndFeelV2);
reverbKnob->setSliderStyle(juce::Slider::RotaryVerticalDrag);
reverbKnob->setTextBoxStyle(juce::Slider::NoTextBox, false, 100, 100);
audioProcessor.getStateScopedPointer()->addParameterListener("reverb", this);
addAndMakeVisible(reverbLabel = new juce::Label("reverbLabel"));
reverbLabel->setText("REVERB", juce::NotificationType::dontSendNotification);
reverbLabel->setJustificationType(juce::Justification::centred);
reverbLabel->setFont(juce::Font(16.0f, juce::Font::bold));
reverbLabel->setFont(juce::Font(20.0f, juce::Font::bold));
reverbLabel->setColour(juce::Label::textColourId, juce::Colour(0.0f, 0.0f, 0.0f));
//VOICE1
addAndMakeVisible(voice1_secLabel = new juce::Label("voice1_secLabel"));
voice1_secLabel->setText("VOICE 1", juce::NotificationType::dontSendNotification);
voice1_secLabel->setJustificationType(juce::Justification::centred);
voice1_secLabel->setFont(juce::Font(16.0f, juce::Font::bold));
voice1_secLabel->setFont(juce::Font(20.0f, juce::Font::bold));
voice1_secLabel->setColour(juce::Label::textColourId, juce::Colour(0.0f, 0.0f, 0.0f));
addAndMakeVisible(voice1Knob = new juce::Slider("Voice 1"));
voice1Knob->setLookAndFeel(&myLookAndFeelV1);
voice1Knob->setSliderStyle(juce::Slider::RotaryVerticalDrag);
voice1Knob->setTextBoxStyle(juce::Slider::NoTextBox, false, 100, 100);
audioProcessor.getStateScopedPointer()->addParameterListener("voice1", this);
addAndMakeVisible(voice1Label = new juce::Label("voice1Label"));
voice1Label->setText("PITCH", juce::NotificationType::dontSendNotification);
voice1Label->setJustificationType(juce::Justification::centred);
voice1Label->setFont(juce::Font(16.0f, juce::Font::bold));
voice1Label->setFont(juce::Font(20.0f, juce::Font::bold));
voice1Label->setColour(juce::Label::textColourId, juce::Colour(0.0f, 0.0f, 0.0f));
//VOLUME VOICE1
addAndMakeVisible(vol_v1Knob = new juce::Slider(" Volume Voice 1"));
vol_v1Knob->setLookAndFeel(&myLookAndFeelV1);
vol_v1Knob->setSliderStyle(juce::Slider::RotaryVerticalDrag);
vol_v1Knob->setTextBoxStyle(juce::Slider::NoTextBox, false, 100, 100);
audioProcessor.getStateScopedPointer()->addParameterListener("vol_v1", this);
addAndMakeVisible(voice1_volLabel = new juce::Label("voice1_volLabel"));
voice1_volLabel->setText("VOLUME", juce::NotificationType::dontSendNotification);
voice1_volLabel->setJustificationType(juce::Justification::centred);
voice1_volLabel->setFont(juce::Font(16.0f, juce::Font::bold));
voice1_volLabel->setFont(juce::Font(20.0f, juce::Font::bold));
voice1_volLabel->setColour(juce::Label::textColourId, juce::Colour(0.0f, 0.0f, 0.0f));
//VOICE2
addAndMakeVisible(voice2_secLabel = new juce::Label("voice2_secLabel"));
voice2_secLabel->setText("VOICE 2", juce::NotificationType::dontSendNotification);
voice2_secLabel->setJustificationType(juce::Justification::centred);
voice2_secLabel->setFont(juce::Font(16.0f, juce::Font::bold));
voice2_secLabel->setFont(juce::Font(20.0f, juce::Font::bold));
voice2_secLabel->setColour(juce::Label::textColourId, juce::Colour(0.0f, 0.0f, 0.0f));
addAndMakeVisible(voice2Knob = new juce::Slider("Voice 2"));
voice2Knob->setLookAndFeel(&myLookAndFeelV1);
voice2Knob->setSliderStyle(juce::Slider::RotaryVerticalDrag);
voice2Knob->setTextBoxStyle(juce::Slider::NoTextBox, false, 100, 100);
audioProcessor.getStateScopedPointer()->addParameterListener("voice2", this);
addAndMakeVisible(voice2Label = new juce::Label("voice2Label"));
voice2Label->setText("PITCH", juce::NotificationType::dontSendNotification);
voice2Label->setJustificationType(juce::Justification::centred);
voice2Label->setFont(juce::Font(16.0f, juce::Font::bold));
voice2Label->setFont(juce::Font(20.0f, juce::Font::bold));
voice2Label->setColour(juce::Label::textColourId, juce::Colour(0.0f, 0.0f, 0.0f));
//VOLUME VOICE2
addAndMakeVisible(vol_v2Knob = new juce::Slider("Volume Voice 2"));
vol_v2Knob->setLookAndFeel(&myLookAndFeelV1);
vol_v2Knob->setSliderStyle(juce::Slider::RotaryVerticalDrag);
vol_v2Knob->setTextBoxStyle(juce::Slider::NoTextBox, false, 100, 100);
audioProcessor.getStateScopedPointer()->addParameterListener("vol_v2", this);
addAndMakeVisible(voice2_volLabel = new juce::Label("voice2_volLabel"));
voice2_volLabel->setText("VOLUME", juce::NotificationType::dontSendNotification);
voice2_volLabel->setJustificationType(juce::Justification::centred);
voice2_volLabel->setFont(juce::Font(16.0f, juce::Font::bold));
voice2_volLabel->setFont(juce::Font(20.0f, juce::Font::bold));
voice2_volLabel->setColour(juce::Label::textColourId, juce::Colour(0.0f, 0.0f, 0.0f));
//VOICE3
addAndMakeVisible(voice3_secLabel = new juce::Label("voice3_secLabel"));
voice3_secLabel->setText("VOICE 3", juce::NotificationType::dontSendNotification);
voice3_secLabel->setJustificationType(juce::Justification::centred);
voice3_secLabel->setFont(juce::Font(16.0f, juce::Font::bold));
voice3_secLabel->setFont(juce::Font(20.0f, juce::Font::bold));
voice3_secLabel->setColour(juce::Label::textColourId, juce::Colour(0.0f, 0.0f, 0.0f));
addAndMakeVisible(voice3Knob = new juce::Slider("Voice 3"));
voice3Knob->setLookAndFeel(&myLookAndFeelV1);
voice3Knob->setSliderStyle(juce::Slider::RotaryVerticalDrag);
voice3Knob->setTextBoxStyle(juce::Slider::NoTextBox, false, 100, 100);
audioProcessor.getStateScopedPointer()->addParameterListener("voice3", this);
addAndMakeVisible(voice3Label = new juce::Label("voice3Label"));
voice3Label->setText("PITCH", juce::NotificationType::dontSendNotification);
voice3Label->setJustificationType(juce::Justification::centred);
voice3Label->setFont(juce::Font(16.0f, juce::Font::bold));
voice3Label->setFont(juce::Font(20.0f, juce::Font::bold));
voice3Label->setColour(juce::Label::textColourId, juce::Colour(0.0f, 0.0f, 0.0f));
//VOICE3
addAndMakeVisible(vol_v3Knob = new juce::Slider("Volume Voice 3"));
vol_v3Knob->setLookAndFeel(&myLookAndFeelV1);
vol_v3Knob->setSliderStyle(juce::Slider::RotaryVerticalDrag);
vol_v3Knob->setTextBoxStyle(juce::Slider::NoTextBox, false, 100, 100);
audioProcessor.getStateScopedPointer()->addParameterListener("vol_v3", this);
addAndMakeVisible(voice3_volLabel = new juce::Label("voice3_volLabel"));
voice3_volLabel->setText("VOLUME", juce::NotificationType::dontSendNotification);
voice3_volLabel->setJustificationType(juce::Justification::centred);
voice3_volLabel->setFont(juce::Font(16.0f, juce::Font::bold));
voice3_volLabel->setFont(juce::Font(20.0f, juce::Font::bold));
voice3_volLabel->setColour(juce::Label::textColourId, juce::Colour(0.0f, 0.0f, 0.0f));
//KNOB ATTACHMENTS
outputAttach = new juce::AudioProcessorValueTreeState::SliderAttachment(p.getState(), "output", *outputKnob);
blendAttach = new juce::AudioProcessorValueTreeState::SliderAttachment(p.getState(), "blend", *blendKnob);
detuneAttach = new juce::AudioProcessorValueTreeState::SliderAttachment(p.getState(), "detune", *detuneKnob);
reverbAttach = new juce::AudioProcessorValueTreeState::SliderAttachment(p.getState(), "reverb", *reverbKnob);
voice1Attach = new juce::AudioProcessorValueTreeState::SliderAttachment(p.getState(), "voice1", *voice1Knob);
voice2Attach = new juce::AudioProcessorValueTreeState::SliderAttachment(p.getState(), "voice2", *voice2Knob);
voice3Attach = new juce::AudioProcessorValueTreeState::SliderAttachment(p.getState(), "voice3", *voice3Knob);
vol_v1Attach = new juce::AudioProcessorValueTreeState::SliderAttachment(p.getState(), "vol_v1", *vol_v1Knob);
vol_v2Attach = new juce::AudioProcessorValueTreeState::SliderAttachment(p.getState(), "vol_v2", *vol_v2Knob);
vol_v3Attach = new juce::AudioProcessorValueTreeState::SliderAttachment(p.getState(), "vol_v3", *vol_v3Knob);
setSize (661, 615);
}
DistorionEffectAudioProcessorEditor::~DistorionEffectAudioProcessorEditor()
{
}
//==============================================================================
void DistorionEffectAudioProcessorEditor::paint (juce::Graphics& g)
{
// (Our component is opaque, so we must completely fill the background with a solid colour)
g.fillAll (getLookAndFeel().findColour (juce::ResizableWindow::backgroundColourId));
g.setColour (juce::Colours::white);
g.setFont (15.0f);
g.drawImageAt(juce::ImageCache::getFromMemory(BinaryData::sfondo_png, BinaryData::sfondo_pngSize), 0, 0);
}
void DistorionEffectAudioProcessorEditor::resized()
{
//BOUNDS
outputKnob->setBounds(((getWidth() / 5) * 2.5)- 75, (getHeight() / 2) -300, 130, 130);
reverbKnob->setBounds(((getWidth() / 5) * 4.10) - (100 / 2), (getHeight() / 2)-120, 125, 125);
detuneKnob->setBounds(((getWidth() / 5) * 0.75) - (100 / 2), (getHeight() / 2)-120, 125, 125);
blendKnob->setBounds(((getWidth() / 5) * 2.5) - 75, (getHeight() / 2) - 120, 125, 125);
voice1Knob->setBounds(((getWidth() / 5) * 3) - 250, (getHeight() / 2) + 75, 100, 100);
voice2Knob->setBounds(((getWidth() / 5) * 4) - 250, (getHeight() / 2) + 75, 100, 100);
voice3Knob->setBounds(((getWidth() / 5) * 5) - 250, (getHeight() / 2) + 75, 100, 100);
vol_v1Knob->setBounds(((getWidth() / 5) * 3) - 250, (getHeight() / 2) + 175, 100, 100);
vol_v2Knob->setBounds(((getWidth() / 5) * 4) - 250, (getHeight() / 2) + 175, 100, 100);
vol_v3Knob->setBounds(((getWidth() / 5) * 5) - 250, (getHeight() / 2) + 175, 100, 100);
outputLabel->setBounds(((getWidth() / 5) * 2.5) - 50, (getHeight() / 2) - 180, 80, 50);
reverbLabel->setBounds(((getWidth() / 5) * 4.10) - (60 / 2), (getHeight() / 2) - 15 , 80, 50);
detuneLabel->setBounds(((getWidth() / 5) * 0.75) - (60 / 2), (getHeight() / 2) - 15, 80, 50);
blendLabel->setBounds(((getWidth() / 5) * 2.5) - 50, (getHeight() / 2) - 15, 80, 50);
voice1_secLabel->setBounds(((getWidth() / 5) * 3) - 240, (getHeight() / 2) + 50, 80, 50);
voice2_secLabel->setBounds(((getWidth() / 5) * 4) - 240, (getHeight() / 2) + 50, 80, 50);
voice3_secLabel->setBounds(((getWidth() / 5) * 5) - 240, (getHeight() / 2) + 50, 80, 50);
voice1Label->setBounds(((getWidth() / 5) * 3) - 240, (getHeight() / 2) + 150, 80, 50);
voice2Label->setBounds(((getWidth() / 5) * 4) - 240, (getHeight() / 2) + 150, 80, 50);
voice3Label->setBounds(((getWidth() / 5) * 5) - 240, (getHeight() / 2) + 150, 80, 50);
voice1_volLabel->setBounds(((getWidth() / 5) * 3) - 240, (getHeight() / 2) + 250, 80, 50);
voice2_volLabel->setBounds(((getWidth() / 5) * 4) - 240, (getHeight() / 2) + 250, 80, 50);
voice3_volLabel->setBounds(((getWidth() / 5) * 5) - 240, (getHeight() / 2) + 250, 80, 50);
}
//4) SEND OSC MESSAGES WHEN SLIDER CHARACTERIZED BY "PARAMETERID" CHANGES
void DistorionEffectAudioProcessorEditor::parameterChanged(const juce::String& parameterID, float newValue)
{
//Input volume
if (parameterID == "output") {
audioProcessor.sendOscInput(parameterID, newValue);
}
//Blend
if (parameterID == "blend") {
audioProcessor.sendOscInput(parameterID, newValue);
}
//Detune
if (parameterID == "detune") {
audioProcessor.sendOscInput(parameterID, newValue);
}
//Reverb
if (parameterID == "reverb") {
audioProcessor.sendOscInput(parameterID, newValue);
}
//First Voice
//Pitch
if (parameterID == "voice1") {
audioProcessor.sendOscInput(parameterID, newValue);
}
//Volume
if (parameterID == "vol_v1") {
audioProcessor.sendOscInput(parameterID, newValue);
}
//Second Voice
//Pitch
if (parameterID == "voice2") {
audioProcessor.sendOscInput(parameterID, newValue);
}
//Volume
if (parameterID == "vol_v2") {
audioProcessor.sendOscInput(parameterID, newValue);
}
//Third Voice
//Pitch
if (parameterID == "voice3") {
audioProcessor.sendOscInput(parameterID, newValue);
}
//Volume
if (parameterID == "vol_v3") {
audioProcessor.sendOscInput(parameterID, newValue);
}
}
|
9c02314ac098a460f55901aa151c442e88f80d47
|
cdbd557e4714b6782ec096ff3ec43125c5d90712
|
/rounds.h
|
f75e78e7f0b5259dda893ea9dd64185b01e15398
|
[] |
no_license
|
sgarcia22/Term-Project-Team-9
|
77414f9e51bef2313417e080ef407c1a47caa6bd
|
cb4bd264996876a2562854fa136033ebf53ec792
|
refs/heads/master
| 2021-01-20T01:31:20.414715
| 2017-04-20T08:02:41
| 2017-04-20T08:02:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 314
|
h
|
rounds.h
|
#ifndef ROUNDS_H
#define ROUNDS_H
#include <QGraphicsTextItem>
#include <QGraphicsItem>
class rounds: public QGraphicsTextItem{
public:
QGraphicsTextItem * roundDisplay;
rounds(QGraphicsItem * parent=0);
void increase();
int getRounds();
int roundsCount = 0;
};
#endif
|
958375748efb92682df8273fb128381c1d2fa7a0
|
d37066762da870dde54f18ccb839856429d4c556
|
/puzzle_c/Numberjack.0.1.10-11-24/solvers/mistral/lib/src/mistral_scd.cpp
|
3cbf27692aea65cfb1cda6ba09d8cca78b9fdf33
|
[] |
no_license
|
maitreyak/discrete_optimization
|
b83743088145457fa0d501e4a1a835c3856a1f36
|
84e461fa139230c1dcda8158afec0023cc1aa1ab
|
refs/heads/master
| 2021-01-01T16:00:24.464431
| 2013-08-29T05:29:21
| 2013-08-29T05:29:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 50,425
|
cpp
|
mistral_scd.cpp
|
#include "mistral_scd.h"
using namespace MistralScheduler;
#define INFTY 0xffffff
#define BIG 0xffff
StatisticList::StatisticList() {
best_solution_index = 0;
branch_and_bound_index = 0;
lower_bound = INFTY;
upper_bound = 0;
num_nogoods = 0;
num_solutions = 0;
avg_distance = 0;
min_distance = INFTY;
max_distance = 0;
normalized_objective = 1.0;
}
StatisticList::~StatisticList() {}
bool StatisticList::solved() {
return (lower_bound == upper_bound);
}
double StatisticList::get_total_time() {
double total_time = 0.0;
for(unsigned int i=0; i<time.size(); ++i)
total_time += time[i];
return total_time;
}
double StatisticList::get_lowerbound_time() {
double total_time = 0.0;
for(unsigned int i=0; i<time.size(); ++i)
if(outcome[i] == UNSAT)
total_time += time[i];
return total_time;
}
void StatisticList::add_info(SchedulingSolver *s, const int objective, bool dichotomic) {
DBG("Update statistics%s\n", "");
time.push_back(s->ENDTIME);
soltime.push_back(s->SOLTIME);
nodes.push_back(s->NODES);
backtracks.push_back(s->BACKTRACKS);
fails.push_back(s->FAILURES);
propags.push_back(s->PROPAGS);
dicho_step.push_back(dichotomic);
outcome.push_back(s->status);
if(outcome.back() == SAT || outcome.back() == OPT) {
++num_solutions;
best_solution_index = outcome.size()-1;
upper_bound = objective;
if(outcome.back() == OPT) lower_bound = objective;
} else if(outcome.back() == UNSAT) {
lower_bound = objective+1;
}
}
std::ostream& StatisticList::print(std::ostream& os,
const char* prefix,
const int start,
const int end) {
int k, i=start, j=outcome.size();
if(end >= 0) j=end;
double total_time = 0.0;
double opt_time = 0.0;
double ub_time = 0.0;
double lb_time = 0.0;
double lost_time = 0.0;
double proof_time = 0.0;
double avg_cutoff_time = 0.0;
long unsigned int total_nodes = 0;
long unsigned int total_backtracks = 0;
long unsigned int total_fails = 0;
long unsigned int total_propags = 0;
int nb_unknown = 0;
for(k=i; k<j; ++k) {
// if(k<=best_solution_index) {
// if(outcome[k] != OPT)
// opt_time += time[k];
// else
// opt_time += soltime[k];
// }
if(k==best_solution_index) opt_time += soltime[k];
else opt_time += time[k];
if(outcome[k] != OPT && outcome[k] != UNSAT) {
lost_time += (time[k] - soltime[k]);
}
ub_time += soltime[k];
total_time += time[k];
total_nodes += nodes[k];
total_backtracks += backtracks[k];
total_fails += fails[k];
total_propags += propags[k];
if(dicho_step[k] && outcome[k] == UNKNOWN)
{
++nb_unknown;
avg_cutoff_time += time[k];
}
}
if(nb_unknown)
avg_cutoff_time /= (double)nb_unknown;
proof_time = (total_time - opt_time);
lb_time = (total_time - ub_time - lost_time);
if(lb_time < 0.00001) lb_time = 0.0;
if(lost_time < 0.00001) lost_time = 0.0;
if(proof_time < 0.00001) proof_time = 0.0;
int plength = 0;
while(prefix[plength] != '\0') ++plength;
os << "c =================[ statistics ]==================" << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "LOWERBOUND " << std::right << std::setw(21) << lower_bound << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "UPPERBOUND " << std::right << std::setw(21) << upper_bound << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "OBJECTIVE " << std::right << std::setw(21) << upper_bound << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "NORMOBJECTIVE " << std::right << std::setw(21) << normalized_objective << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "RUNTIME " << std::right << std::setw(21) << total_time << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "OPTTIME " << std::right << std::setw(21) << opt_time << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "PROOFTIME " << std::right << std::setw(21) << proof_time << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "UBTIME " << std::right << std::setw(21) << ub_time << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "LBTIME " << std::right << std::setw(21) << lb_time << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "LOSTTIME " << std::right << std::setw(21) << lost_time << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "NODES " << std::right << std::setw(21) << total_nodes << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "BACKTRACKS " << std::right << std::setw(21) << total_backtracks << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "FAILS " << std::right << std::setw(21) << total_fails << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "PROPAGS " << std::right << std::setw(21) << total_propags << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "NODES/s " << std::right << std::setw(21) ;
if(total_time > 0)
std::cout << (int)((double)total_nodes/total_time);
else
std::cout << "N/A";
std::cout << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "BACKTRACKS/s " << std::right << std::setw(21) ;
if(total_time > 0)
std::cout << (int)((double)total_backtracks/total_time);
else
std::cout << "N/A";
std::cout << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "FAILS/s " << std::right << std::setw(21) ;
if(total_time > 0)
std::cout << (int)((double)total_fails/total_time);
else
std::cout << "N/A";
std::cout << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "PROPAGS/s " << std::right << std::setw(21) ;
if(total_time > 0)
std::cout << (int)((double)total_propags/total_time);
else
std::cout << "N/A";
std::cout << std::endl
//<< "d " << prefix << std::left << std::setw(28-plength) << "RESTARTS " << std::right << std::setw(21) << total_restarts << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "SOLUTIONS " << std::right << std::setw(21) << num_solutions << std::endl
<< "d " << prefix << std::left << std::setw(28-plength) << "AVGCUTOFF " << std::right << std::setw(21) << avg_cutoff_time << std::endl
//<< std::left << std::setw(28) << "d AVGDISTANCE " << std::right << std::setw(21) << avg_distance << std::endl
//<< std::left << std::setw(28) << "d MINDISTANCE " << std::right << std::setw(21) << min_distance << std::endl
//<< std::left << std::setw(28) << "d MAXDISTANCE " << std::right << std::setw(21) << max_distance << std::endl;
<< "d " << prefix << std::left << std::setw(28-plength) << "OPTIMAL " << std::right << std::setw(21) << (lower_bound == upper_bound) << std::endl
<< "c =================[ statistics ]==================" << std::endl
<< std::endl;
return os;
}
const char* ParameterList::int_ident[ParameterList::nia] =
{"-ub", "-lb", "-check", "-seed", "-cutoff", "-dichotomy",
"-base", "-randomized", "-verbose", "-optimise", "-nogood",
"-dyncutoff", "-nodes", "-hlimit"};
const char* ParameterList::str_ident[ParameterList::nsa] =
{"-heuristic", "-restart", "-factor", "-decay", "-type",
"-value", "-dvalue", "-ivalue", "-skew", "-objective"};
// ParameterList::ParameterList() {
// }
// ParameterList::ParameterList(const ParameterList& pl) {
// initialise(pl);
// }
ParameterList::ParameterList(int length, char **commandline) {
if( length < 2 )
{
std::cerr << "need a data file" << std::endl;
exit( 0 );
}
data_file = commandline[1];
int i=0;
while(commandline[1][i] != '\0') ++i;
while(commandline[1][i] != '/') --i;
data_file_name = &(commandline[1][i+1]);
getCommandLine(ParameterList::int_ident,
int_param,
ParameterList::nia,
ParameterList::str_ident,
str_param,
ParameterList::nsa,
&commandline[1],length-1);
if(strcmp(str_param[4],"nil")) Type = str_param[4];
else {
Type = "jsp";
std::cout << "c Warning: no type specified, treating the data as Taillard's jsp" << std::endl;
}
UBinit = -1;
LBinit = -1;
Checked = true;
Seed = 12345;
Cutoff = 300;
NodeCutoff = 0;
NodeBase = 30;
Dichotomy = 128;
Base = 256;
Randomized = 1;
Precision = 100;
Hlimit = 20000;
Verbose = 1;
Optimise = 3600;
Rngd = 1;
Policy = "geom";
Factor = 1.3;
Decay = 0.0;
Value = "guided";
DValue = "guided";
IValue = "promise";
Skew = -1.0;
Objective = "makespan";
Heuristic = "osp-t";
PolicyRestart = GEOMETRIC;
}
// void ParameterList::initialise(const ParameterList& pl) {
// UBinit = pl.UBinit;
// LBinit = LBinit;
// Checked = Checked;
// Seed = Seed;
// Cutoff = Cutoff;
// NodeCutoff = NodeCutoff;
// NodeBase = NodeBase;
// Dichotomy = Dichotomy;
// Base = Base;
// Randomized = Randomized;
// Precision = Precision;
// Verbose = Verbose;
// Optimise = Optimise;
// Rngd = Rngd;
// Policy = Policy;
// Factor = Factor;
// Decay = Decay;
// Value = Value;
// DValue = DValue;
// IValue = IValue;
// Skew = Skew;
// Objective = Objective;
// Heuristic = Heuristic;
// PolicyRestart = PolicyRestart;
// std::memcpy(int_param, pl.int_param, nia*sizeof(int));
// data_file = pl.data_file;
// data_file_name = pl.data_file_name;
// }
//void ParameterList::initialise(const int n_constraints) {
void ParameterList::initialise(const SchedulingModel *model) {
if(Type == "osp") {
Objective = "makespan";
Heuristic = "osp-b";
} else if(Type == "sds") {
Objective = "makespan";
Heuristic = "osp-b";
} else if(Type == "jtl") {
Objective = "makespan";
Heuristic = "osp-t";
} else if(Type == "now") {
Objective = "makespan";
Heuristic = "osp-dw";
} else if(Type == "jla") {
Cutoff = 1000;
NodeBase *= 10;
Objective = "makespan";
Heuristic = "osp-t";
} else if(Type == "jsp") {
Cutoff = 1000;
NodeBase *= 10;
Objective = "makespan";
Heuristic = "osp-t";
} else if(Type == "jet") {
Objective = "tardiness";
Heuristic = "osp-t";
} else if(Type == "dyn") {
Objective = "tardiness";
Heuristic = "osp-t";
}
if(int_param[0] != NOVAL) UBinit = int_param[0];
if(int_param[1] != NOVAL) LBinit = int_param[1];
if(int_param[2] != NOVAL) Checked = int_param[2];
if(int_param[3] != NOVAL) Seed = int_param[3];
if(int_param[4] != NOVAL) Cutoff = int_param[4];
if(int_param[5] != NOVAL) Dichotomy = int_param[5];
if(int_param[6] != NOVAL) Base = int_param[6];
if(int_param[7] != NOVAL) Randomized = int_param[7];
if(int_param[8] != NOVAL) Verbose = int_param[8];
if(int_param[9] != NOVAL) Optimise = int_param[9];
if(int_param[10] != NOVAL) Rngd = int_param[10];
if(int_param[11] != NOVAL) NodeBase = int_param[11];
NodeCutoff = (int)((double)NodeBase *
(12500000.0/(double)(model->data->nDisjuncts()+
model->data->nPrecedences())));
if(model->ub_C_max - model->lb_C_max > 4000)
NodeCutoff /= 2;
if(model->ub_C_max - model->lb_C_max > 6000)
NodeCutoff /= 2;
if(int_param[12] != NOVAL) NodeCutoff = int_param[12];
if(int_param[13] != NOVAL) Hlimit = int_param[13];
if(strcmp(str_param[0],"nil")) Heuristic = str_param[0];
if(strcmp(str_param[1],"nil")) Policy = str_param[1];
if(strcmp(str_param[2],"nil")) Factor = atof(str_param[2]);
if(strcmp(str_param[3],"nil")) Decay = atof(str_param[3]);
if(strcmp(str_param[5],"nil")) Value = str_param[5];
if(strcmp(str_param[6],"nil")) DValue = str_param[6];
if(strcmp(str_param[7],"nil")) IValue = str_param[7];
if(strcmp(str_param[8],"nil")) Skew = atof(str_param[8]);
if(strcmp(str_param[9],"nil")) Objective = str_param[9];
if(Policy == "luby")
PolicyRestart = LUBY;
else if(Policy == "geom")
PolicyRestart = GEOMETRIC;
else
PolicyRestart = NO;
// if(model->ub_C_max - model->lb_C_max > 3000)
}
std::ostream& ParameterList::print(std::ostream& os) {
os << "c =================[ parameters ]==================" << std::endl;
os << std::left << std::setw(30) << "c data file " << ":" << std::right << std::setw(20) << data_file_name << std::endl;
os << std::left << std::setw(30) << "c type " << ":" << std::right << std::setw(20) << Type << std::endl;
os << std::left << std::setw(30) << "c seed " << ":" << std::right << std::setw(20) << Seed << std::endl;
os << std::left << std::setw(30) << "c time cutoff " << ":" << std::right << std::setw(20) << Cutoff << std::endl;
os << std::left << std::setw(30) << "c node cutoff " << ":" << std::right << std::setw(20) << NodeCutoff << std::endl;
os << std::left << std::setw(30) << "c dichotomy " << ":" << std::right << std::setw(20) << (Dichotomy ? "yes" : "no") << std::endl;
os << std::left << std::setw(30) << "c restart policy " << ":" << std::right << std::setw(20) << Policy << std::endl;
os << std::left << std::setw(30) << "c base " << ":" << std::right << std::setw(20) << Base << std::endl;
os << std::left << std::setw(30) << "c factor " << ":" << std::right << std::setw(20) << Factor << std::endl;
os << std::left << std::setw(30) << "c heuristic " << ":" << std::right << std::setw(20) << Heuristic << " (" << abs(Randomized) << ")" << std::endl;
os << std::left << std::setw(30) << "c value ordering (init step) " << ":" << std::right << std::setw(20) << IValue << std::endl;
os << std::left << std::setw(30) << "c value ordering (dichotomy) " << ":" << std::right << std::setw(20) << DValue << std::endl;
os << std::left << std::setw(30) << "c value ordering (optim) " << ":" << std::right << std::setw(20) << Value << std::endl;
os << "c =================[ parameters ]==================" << std::endl;
return os;
}
Instance::Instance(ParameterList& params) {
DBG("Build instance %s\n", params.data_file);
setup_time = NULL;
time_lag[0] = NULL;
time_lag[1] = NULL;
jsp_duedate = NULL;
jsp_latecost = NULL;
jsp_earlycost = NULL;
jsp_floatcost = NULL;
if(params.Type == "osp") {
osp_readData( params.data_file );
} else if(params.Type == "sds") {
sds_readData( params.data_file );
} else if(params.Type == "jtl") {
jtl_readData( params.data_file );
} else if(params.Type == "now") {
jtl_readData( params.data_file );
} else if(params.Type == "jla") {
jla_readData( params.data_file );
} else if(params.Type == "tsp") {
tsp_readData( params.data_file );
} else if(params.Type == "fsp") {
fsp_readData( params.data_file );
} else if(params.Type == "pfsp") {
fsp_readData( params.data_file );
} else if(params.Type == "jsp") {
jsp_readData( params.data_file );
} else if(params.Type == "jet") {
jet_readData( params.data_file );
} else if(params.Type == "dyn") {
dyn_readData( params.data_file, params.Precision );
}
// close();
//params.initialise(nDisjuncts()+nPrecedences());
//params.initialise(model);
}
Instance::~Instance() {
int i, j;
if(hasSetupTime()) {
for(i=0; i<nMachines(); ++i) {
for(j=0; j<nJobs(); ++j) {
delete [] setup_time[i][j];
}
delete [] setup_time[i];
}
delete [] setup_time;
}
if(hasTimeLag()) {
for(i=0; i<nJobs(); ++i) {
delete [] time_lag[0][i];
delete [] time_lag[1][i];
}
delete [] time_lag[0];
delete [] time_lag[1];
}
if(hasJobDueDate()) {
delete [] jsp_duedate;
}
if(hasLateCost()) {
delete [] jsp_latecost;
}
if(hasEarlyCost()) {
delete [] jsp_earlycost;
}
}
int Instance::addTask(const int dur, const int job, const int machine) {
int index = duration.size();
if(job >= 0) addTaskToJob(index, job);
if(machine >= 0) addTaskToMachine(index, machine);
duration.push_back(dur);
due_date.push_back(INFTY);
release_date.push_back(0);
return index;
}
void Instance::addTaskToJob(const unsigned int index, const unsigned int j) {
if(tasks_in_job.size() <= j) tasks_in_job.resize(j+1);
if(jobs_of_task.size() <= index) jobs_of_task.resize(index+1);
if(task_rank_in_job.size() <= index) task_rank_in_job.resize(index+1);
tasks_in_job[j].push_back(index);
jobs_of_task[index].push_back(j);
pair_ x(j, tasks_in_job[j].size()-1);
task_rank_in_job[index].push_back(x);
}
void Instance::addTaskToMachine(const unsigned int index, const unsigned int j) {
if(tasks_in_machine.size() <= j) tasks_in_machine.resize(j+1);
if(machines_of_task.size() <= index) machines_of_task.resize(index+1);
if(task_rank_in_machine.size() <= index) task_rank_in_machine.resize(index+1);
tasks_in_machine[j].push_back(index);
machines_of_task[index].push_back(j);
pair_ x(j, tasks_in_machine[j].size()-1);
task_rank_in_machine[index].push_back(x);
}
int Instance::getSetupTime(const int k, const int i, const int j) const {
// get the rank of task i in machine k
int ri = 0;
for(unsigned int x=0; x<task_rank_in_machine[i].size(); ++x)
if(task_rank_in_machine[i][x].element == k) {
ri = task_rank_in_machine[i][x].rank;
break;
}
int rj = 0;
for(unsigned int x=0; x<task_rank_in_machine[j].size(); ++x)
if(task_rank_in_machine[j][x].element == k) {
rj = task_rank_in_machine[j][x].rank;
break;
}
return setup_time[k][ri][rj];
}
std::ostream& Instance::print(std::ostream& os) {
os << "c " << (nJobs()) << " jobs, "
<< nMachines() << " machines ("
<< nTasks() << " tasks)" << std::endl;
for(int i=0; i<nJobs(); ++i) {
if(nTasksInJob(i) > 1) {
os << "c ";
for(int j=1; j<nTasksInJob(i); ++j)
os << " t" << tasks_in_job[i][j-1] << "+" << (duration[tasks_in_job[i][j-1]])
<< " <= t" << tasks_in_job[i][j];
os << std::endl;
}
}
for(int i=0; i<nMachines(); ++i) {
if(tasks_in_machine[i].size() > 0) {
os << "c machine" << i << ": t" << tasks_in_machine[i][0];
for(unsigned int j=1; j<tasks_in_machine[i].size(); ++j)
os << ", t" << tasks_in_machine[i][j];
os << std::endl;
}
}
// for(int i=0; i<task_rank_in_machine.size(); ++i) {
// std::cout << "task_" << i << " is";
// for(int j=0; j<task_rank_in_machine[i].size(); ++j) {
// pair_ p = task_rank_in_machine[i][j];
// std::cout << " the " << p.rank << "/" << getMachine(i,j) << "th in machine_" << p.element;
// if(task_rank_in_machine[i][j].element != machines_of_task[i][j]) {
// std::cout << "INCONSISTENCY" << std::endl;
// exit(1);
// }
// }
// std::cout << std::endl;
// }
return os;
}
int Instance::nDisjuncts() const {
int n_disjuncts = 0;
for(int i=0; i<nMachines(); ++i) {
n_disjuncts += (nTasksInMachine(i) * (nTasksInMachine(i)-1))/2;
}
return n_disjuncts;
}
int Instance::nPrecedences() const {
int n_precedences = 0;
for(int i=0; i<nJobs(); ++i) {
n_precedences += (nTasksInJob(i)-1);
}
if(hasTimeLag()) {
//n_precedences *= 2;
for(int i=0; i<nJobs(); ++i)
for(int j=1; j<nTasksInJob(i); ++j)
if(getMaxLag(i,j-1) >= 0)
++n_precedences;
}
return n_precedences;
}
double Instance::getNormalizer() const {
double normalizer=0.0, cost;
int i, j, job_dur;
for(i=0; i<nJobs(); ++i) {
job_dur = 0;
for(j=0; j<nTasksInJob(i); ++j) job_dur += getDuration(getJobTask(i,j));
if(hasFloatCost())
cost = getJobFloatCost(i);
else if(hasEarlyCost() || hasLateCost()) {
cost = 0.0;
if(hasEarlyCost()) cost += getJobEarlyCost(i);
if(hasLateCost()) cost += getJobLateCost(i);
} else cost = 1.0;
normalizer += ((double)job_dur * cost);
}
return normalizer;
}
std::ostream& Instance::printStats(std::ostream& os) {
os << "c ==================[ instance ]===================" << std::endl
<< "d " << std::left << std::setw(28) << "NUMTASKS " << std::right << std::setw(21) << nTasks() << std::endl
<< "d " << std::left << std::setw(28) << "NUMJOBS " << std::right << std::setw(21) << nJobs() << std::endl
<< "d " << std::left << std::setw(28) << "NUMMACHINES " << std::right << std::setw(21) << nMachines() << std::endl
<< "d " << std::left << std::setw(28) << "NUMDISJUNCTS " << std::right << std::setw(21) << nDisjuncts() << std::endl
<< "d " << std::left << std::setw(28) << "NUMPRECEDENCES "<< std::right << std::setw(21) << nPrecedences() << std::endl
//<< "d " << std::left << std::setw(28) << "LBMAKESPAN " << std::right << std::setw(21) << lb_C_max << std::endl
//<< "d " << std::left << std::setw(28) << "UBMAKESPAN " << std::right << std::setw(21) << ub_C_max << std::endl
<< "c ==================[ instance ]===================" << std::endl;
return os;
}
int Instance::getMakespanLowerBound() {
int mkp = 0, length;
for(int i=0; i<nJobs(); ++i) {
length = 0;
for(int j=0; j<nTasksInJob(i); ++j)
length += getDuration(getJobTask(i,j));
if(mkp < length) mkp = length;
}
for(int i=0; i<nMachines(); ++i) {
length = 0;
for(int j=0; j<nTasksInMachine(i); ++j)
length += getDuration(getMachineTask(i,j));
if(mkp < length) mkp = length;
}
DBG("Get instance's makespan lb (%d)\n", mkp);
return mkp;
}
int Instance::getMakespanUpperBound(const int iterations) {
int best_makespan = INFTY;
if(!hasTimeLag()) {
int current_job[nJobs()];
int current_job_bound[nJobs()];
int current_machine_bound[nMachines()];
int current_machine_task[nMachines()];
int random_jobs[nTasks()];
int m[nMachines()];
int k=0;
for(int i=0; i<nJobs(); ++i)
for(int j=0; j<nTasksInJob(i); ++j)
random_jobs[k++] = i;
int iter = iterations;
while(iter--) {
std::fill(current_job, current_job+nJobs(), 0);
std::fill(current_job_bound, current_job_bound+nJobs(), 0);
std::fill(current_machine_bound, current_machine_bound+nMachines(), 0);
std::fill(current_machine_task, current_machine_task+nMachines(), -1);
int makespan = 0;
for(int i=0; i<nTasks(); ++i) {
int j = randint(nTasks()-i);
int k = random_jobs[i];
random_jobs[i] = random_jobs[i+j];
random_jobs[i+j] = k;
}
for(int i=0; i<nTasks(); ++i) {
// pick the next job
int j = random_jobs[i];
// find out which task is that
int t = getJobTask(j, current_job[j]);
DBG("pick task t%d\n", t);
// find out which machine is that
for(int j=0; j<nMachines(t); ++j) {
m[j] = getMachine(t,j);
DBG(" -> uses machine%d\n", m[j]);
}
// find the current timepoint for this job
int j_mkp = current_job_bound[j];
// find the current timepoint for this machine
int m_mkp = current_machine_bound[m[0]];
DBG("m%d = %d\n", m[0], current_machine_bound[m[0]]);
for(int j=1; j<nMachines(t); ++j)
if(m_mkp < current_machine_bound[m[j]]) {
m_mkp = current_machine_bound[m[j]];
DBG("m%d = %d\n", m[j], current_machine_bound[m[j]]);
}
// get the start time for this task
int timepoint = (j_mkp < m_mkp ? m_mkp : j_mkp);
// check its release date
if(getReleaseDate(t) > timepoint) timepoint = getReleaseDate(t);
DBG("timepoint = %d\n", timepoint);
// add setup time, if any
if(hasSetupTime()) {
int setup = 0;
int setup_mj;
for(int j=0; j<nMachines(t); ++j) {
if(current_machine_task[m[j]] >= 0) {
setup_mj = getSetupTime(m[j], current_machine_task[m[j]], t);
if(setup < setup_mj) setup = setup_mj;
DBG("setup = %d\n", setup_mj);
}
}
timepoint += setup;
}
// get the finish time for this task
timepoint += getDuration(t);
// update machin and job bounds
for(int j=0; j<nMachines(t); ++j) {
current_machine_bound[m[j]] = timepoint;
current_machine_task[m[j]] = t;
}
//current_machine_bound[m] = timepoint;
current_job_bound[j] = timepoint;
// get the final makespan
if(makespan < timepoint) makespan = timepoint;
++current_job[j];
}
if(best_makespan > makespan) best_makespan = makespan;
}
} else {
best_makespan = 0;
for(int t=0; t<nTasks(); ++t) best_makespan += getDuration(t);
}
DBG("Get instance's makespan ub (%d)\n", best_makespan);
return best_makespan;
}
int Instance::getEarlinessTardinessLowerBound(const int c_max) {
return 0;
}
int Instance::getEarlinessTardinessUpperBound(const int c_max) {
int i, ti, sum_ub = 0;
if(hasEarlyCost())
for(i=0; i<nJobs(); ++i) {
ti = getLastTaskofJob(i);
sum_ub += ((getJobDueDate(i) - (getReleaseDate(ti) + getDuration(ti)))*getJobEarlyCost(i));
}
if(hasLateCost())
for(i=0; i<nJobs(); ++i) {
ti = getLastTaskofJob(i);
sum_ub += ((c_max - getJobDueDate(i))*getJobLateCost(i));
}
return sum_ub;
}
void Instance::osp_readData( const char* filename ) {
DBG("Read (osp)%s\n", "");
int opt, lb, i=0, j, k, nJobs, nMachines, dur, bufsize=1000;
char buf[bufsize];
std::ifstream infile( filename, std::ios_base::in );
do {
infile.getline( buf, bufsize, '\n' );
} while( buf[0] == '#' );
while( buf[i] != ' ' ) ++i;
buf[i] = '\0';
lb = atoi( buf );
while( buf[i] == '\0' || buf[i] == ' ' || buf[i] == '*' ) ++i;
j = i;
while( buf[i] != ' ' && buf[i] != '\n' && buf[i] != '\0' ) ++i;
buf[i] = '\0';
opt = atoi( &(buf[j]) );
do {
infile.get( buf[0] );
if( buf[0] != '#' ) break;
infile.getline( buf, bufsize, '\n' );
} while( true );
infile.unget();
infile >> nJobs;
infile >> nMachines;
infile.getline( buf, bufsize, '\n' );
do {
infile.get( buf[0] );
if( buf[0] != '#' ) break;
infile.getline( buf, bufsize, '\n' );
} while( true );
infile.unget();
k = 0;
for(i=0; i<nJobs; ++i) {
for(j=0; j<nMachines; ++j) {
infile >> dur;
addTask(dur, k, -1);
addTaskToMachine(k, i);
addTaskToMachine(k, nJobs+j);
++k;
}
}
}
void Instance::sds_readData( const char* filename ) {
DBG("Read (sds)%s\n", "");
int i, j, nJobs, nMachines, nFamilies, dur, mach;
std::string tag;
std::ifstream infile( filename, std::ios_base::in );
infile >> nMachines;
infile >> nJobs;
infile >> nFamilies;
int **family_matrix = new int*[nFamilies+1];
for(i=0; i<=nFamilies; ++i)
family_matrix[i] = new int[nFamilies];
setup_time = new int**[nMachines];
for(i=0; i<nMachines; ++i) {
setup_time[i] = new int*[nJobs];
for(j=0; j<nJobs; ++j) {
setup_time[i][j] = new int[nJobs];
}
}
int **family = new int*[nJobs];
for(i=0; i<nJobs; ++i)
family[i] = new int[nMachines];
for(i=0; i<nJobs; ++i) {
infile >> j;
assert(j==nMachines);
for(j=0; j<nMachines; ++j) {
infile >> dur;
infile >> mach;
--mach;
addTask(dur, i, mach);
//addTaskToMachine(k++, mach);
infile >> family[i][j];
--family[i][j];
}
}
for(i=0; i<=nFamilies; ++i)
for(j=0; j<nFamilies; ++j)
infile >> family_matrix[i][j];
for(int k=0; k<nMachines; ++k) {
for(i=0; i<nJobs; ++i)
for(j=0; j<nJobs; ++j) {
setup_time[k][i][j] = family_matrix[1+family[i][k]][family[j][k]] ;
}
}
int k=0;
for(i=0; i<nJobs; ++i) {
for(j=0; j<nMachines; ++j)
release_date[k++] = family_matrix[0][family[i][j]];
}
}
void Instance::jtl_readData( const char* filename ) {
DBG("Read (jtl)%s\n", "");
int i, j, dur, mach, nJobs, nMachines, opt;
std::string tag;
char c;
std::ifstream infile( filename, std::ios_base::in );
infile >> nJobs;
infile >> nMachines;
for(i=0; i<nJobs; ++i) {
for(j=0; j<nMachines; ++j) {
infile >> mach;
infile >> dur;
addTask(dur, i, mach);
}
}
infile >> tag;
infile >> opt;
infile.ignore( 100, '\n' );
infile.get(c);
assert( c == 'T' );
infile.get(c);
assert( c == 'L' );
infile.get(c);
assert( c == '=' );
time_lag[0] = new int*[nJobs];
time_lag[1] = new int*[nJobs];
for(i=0; i<nJobs; ++i) {
time_lag[0][i] = new int[nMachines];
time_lag[1][i] = new int[nMachines];
for(j=0; j<nMachines; ++j) {
infile >> time_lag[0][i][j];
infile >> time_lag[1][i][j];
}
}
}
void Instance::jla_readData( const char* filename ) {
DBG("Read (jla)%s\n", "");
int i, j, dur, mach, nJobs, nMachines;
std::ifstream infile( filename, std::ios_base::in );
infile >> nJobs;
infile >> nMachines;
for(i=0; i<nJobs; ++i) {
for(j=0; j<nMachines; ++j) {
infile >> mach;
infile >> dur;
addTask(dur, i, mach);
}
}
}
void Instance::tsp_readData( const char* filename ) {
DBG("Read (tsp)%s\n", "");
}
void Instance::fsp_readData( const char* filename ) {
DBG("Read (fsp)%s\n", "");
}
void Instance::jsp_readData( const char* filename ) {
DBG("Read (jsp)%s\n", "");
int i, j, k, dur, mach;
long int dump;
std::string tag;
std::ifstream infile( filename, std::ios_base::in );
int nJobs;
int nMachines;
infile >> nJobs;
infile >> nMachines;
infile >> dump;
infile >> dump;
infile >> dump;
infile >> dump;
infile >> tag;
assert( tag == "Times" );
for(i=0; i<nJobs; ++i) {
for(j=0; j<nMachines; ++j) {
infile >> dur;
addTask(dur, i, -1);
}
}
infile >> tag;
assert( tag == "Machines" );
k = 0;
for(i=0; i<nJobs; ++i)
for(j=0; j<nMachines; ++j) {
infile >> mach;
addTaskToMachine(k++, --mach);
}
}
void Instance::jet_readData( const char* filename ) {
DBG("Read (jet)%s\n", "");
int i, j, dur, mach, nJobs, nMachines;
std::string tag;
std::ifstream infile( filename, std::ios_base::in );
infile >> nJobs;
infile >> nMachines;
jsp_duedate = new int[nJobs];
jsp_earlycost = new int[nJobs];
jsp_latecost = new int[nJobs];
for(i=0; i<nJobs; ++i) {
for(j=0; j<nMachines; ++j) {
infile >> mach;
infile >> dur;
addTask(dur, i, mach);
}
infile >> jsp_duedate[i];
infile >> jsp_earlycost[i];
infile >> jsp_latecost[i];
}
}
void Instance::dyn_readData( const char* filename, const int precision ) {
DBG("Read (dyn)%s\n", "");
int i, j, k, dur, mach, nJobs, nMachines;
std::string tag;
std::ifstream infile( filename, std::ios_base::in );
infile >> nJobs;
infile >> nMachines;
jsp_duedate = new int[nJobs];
jsp_earlycost = new int[nJobs];
jsp_latecost = new int[nJobs];
jsp_floatcost = new double[nJobs];
for(i=0; i<nJobs; ++i) {
k = release_date.size();
for(j=0; j<nMachines; ++j) {
infile >> mach;
infile >> dur;
if(mach != -1 && dur != -1) addTask(dur, i, mach);
}
infile >> jsp_duedate[i];
infile >> j;
//infile >> jsp_latecost[i];
infile >> jsp_floatcost[i];
setReleaseDate(k, j);
//jsp_earlycost[i] = jsp_latecost[i];
}
double min_cost = jsp_floatcost[0];
double max_cost = jsp_floatcost[0];
for(i=1; i<nJobs; ++i) {
if(min_cost > jsp_floatcost[i]) min_cost = jsp_floatcost[i];
if(min_cost < jsp_floatcost[i]) max_cost = jsp_floatcost[i];
}
for(i=0; i<nJobs; ++i) {
int approx = (int)((jsp_floatcost[i]/max_cost)*precision);
jsp_earlycost[i] = jsp_latecost[i] = approx;
//std::cout << approx << std::endl;
}
}
SchedulingModel::SchedulingModel(Instance& inst, const int max_makespan) : CSP() {
setup(inst, max_makespan);
}
std::ostream& SchedulingModel::printStats(std::ostream& os) {
os << "c ====================[ model ]====================" << std::endl
<< "d " << std::left << std::setw(28) << "LBMAKESPAN " << std::right << std::setw(21) << lb_C_max << std::endl
<< "d " << std::left << std::setw(28) << "UBMAKESPAN " << std::right << std::setw(21) << ub_C_max << std::endl
<< "c ====================[ model ]====================" << std::endl;
return os;
}
void SchedulingModel::setup(Instance& inst, const int max_makespan) {
int i,j,k, lb, ub, ti, tj;
lb_C_max = inst.getMakespanLowerBound();
if(max_makespan < 0) ub_C_max = inst.getMakespanUpperBound(1);
else ub_C_max = max_makespan;
for(i=0; i<inst.nJobs(); ++i)
ub_C_max += inst.getDuration(inst.getLastTaskofJob(i));
lb_L_sum = inst.getEarlinessTardinessLowerBound(ub_C_max);
ub_L_sum = inst.getEarlinessTardinessUpperBound(ub_C_max);
data = &inst;
// create one variable per task
for(i=0; i<inst.nTasks(); ++i) {
lb = inst.getReleaseDate(i);
ub = std::min(ub_C_max, inst.getDueDate(i)) - inst.getDuration(i);
if(lb > ub) {
std::cout << "INCONSISTENT" << std::endl;
exit(1);
}
Variable t(lb, ub);
tasks.add(t);
}
// precedence constraints
for(i=0; i<inst.nJobs(); ++i)
for(j=1; j<inst.nTasksInJob(i); ++j) {
ti = inst.getJobTask(i,j-1);
tj = inst.getJobTask(i,j);
add( Precedence(tasks[ti],
(inst.getDuration(ti) +
(inst.hasTimeLag() ? inst.getMinLag(i,j-1) : 0)),
tasks[tj]) );
}
// time lags constraints
if(inst.hasTimeLag()) {
for(i=0; i<inst.nJobs(); ++i)
for(j=1; j<inst.nTasksInJob(i); ++j) if(inst.getMaxLag(i,j-1) >= 0) {
ti = inst.getJobTask(i,j-1);
tj = inst.getJobTask(i,j);
add( Precedence(tasks[tj],
-(inst.getDuration(ti)+inst.getMaxLag(i,j-1)),
tasks[ti]) );
}
}
// mutual exclusion constraints
for(k=0; k<inst.nMachines(); ++k)
for(i=0; i<inst.nTasksInMachine(k); ++i)
for(j=i+1; j<inst.nTasksInMachine(k); ++j) {
ti = inst.getMachineTask(k,i);
tj = inst.getMachineTask(k,j);
disjuncts.add( Disjunctive( tasks[ti],
inst.getDuration(ti)
+(inst.hasSetupTime() ? inst.getSetupTime(k,ti,tj) : 0),
tasks[tj],
inst.getDuration(tj)
+(inst.hasSetupTime() ? inst.getSetupTime(k,tj,ti) : 0) ) );
}
add( disjuncts );
Variable x_cmax(lb_C_max, ub_C_max);
C_max = x_cmax;
for(i=0; i<inst.nJobs(); ++i) {
ti = inst.getLastTaskofJob(i);
add(Precedence(tasks[ti], inst.getDuration(ti), C_max));
}
if(inst.hasJobDueDate()) {
// early/late bools - whether the last tasks are early or late
for(i=0; i<inst.nJobs(); ++i) {
ti = inst.getLastTaskofJob(i);
if(inst.hasEarlyCost())
earlybool.add(tasks[ti] < (inst.getJobDueDate(i) - inst.getDuration(ti)));
if(inst.hasLateCost())
latebool.add(tasks[ti] > (inst.getJobDueDate(i) - inst.getDuration(ti)));
}
//DG Added for calculating cost
VarArray sum_scope;
int weights[2*inst.nJobs()+1];
int sum_ub = 0;
int n_weights = 0;
k=0;
if(inst.hasEarlyCost()) {
for(i=0; i<inst.nJobs(); ++i) {
ti = inst.getLastTaskofJob(i);
Variable x(0, inst.getJobDueDate(i)-inst.getDuration(ti)); // amount of "earliness"
add(x == (earlybool[i]*((tasks[ti]*-1) - (inst.getDuration(ti) - inst.getJobDueDate(i)))));
sum_scope.add(x);
weights[k++] = inst.getJobEarlyCost(i);
sum_ub += ((inst.getJobDueDate(i) - (inst.getReleaseDate(ti) + inst.getDuration(ti)))*inst.getJobEarlyCost(i));
}
n_weights += inst.nJobs();
}
if(inst.hasLateCost()) {
for(i=0; i<inst.nJobs(); ++i) {
ti = inst.getLastTaskofJob(i);
Variable x(0, ub_C_max-inst.getJobDueDate(i));
add(x == (latebool[i]*(tasks[ti] + (inst.getDuration(ti) - inst.getJobDueDate(i)))));
sum_scope.add(x);
weights[k++] = inst.getJobLateCost(i);
sum_ub += ((ub_C_max - inst.getJobDueDate(i))*inst.getJobLateCost(i));
}
n_weights += inst.nJobs();
}
weights[n_weights] = 0;
Variable x_lsum(0, sum_ub);
L_sum = x_lsum;
add( L_sum == Sum(sum_scope, weights) );
}
// initialise last tasks
for(i=0; i<inst.nJobs(); ++i) last_tasks.add(tasks[inst.getLastTaskofJob(i)]);
// initialise searched vars
if(data->hasJobDueDate()) {
for(int i=0; i<earlybool.size(); ++i) SearchVars.add(earlybool[i]);
for(int i=0; i< latebool.size(); ++i) SearchVars.add(latebool [i]);
for(int i=0; i<data->nJobs(); ++i) SearchVars.add(tasks[data->getLastTaskofJob(i)]);
}
for(int i=0; i<disjuncts.size(); ++i) SearchVars.add(disjuncts[i]);
}
SchedulingModel::~SchedulingModel() {}
void No_wait_Model::setup(Instance& inst, const int max_makespan) {
int i,j,k, lb, ub, ti=0, tj=0;
std::vector<int> offset;
for(i=0; i<inst.nJobs(); ++i) {
offset.push_back(0);
for(j=0; j<inst.nTasksInJob(i)-1; ++j)
offset.push_back(offset.back() + inst.getDuration(inst.getJobTask(i,j)));
}
lb_C_max = inst.getMakespanLowerBound();
if(max_makespan < 0) {
ub_C_max = 0;
for(i=0; i<inst.nJobs(); ++i) {
ub_C_max += (offset[inst.getLastTaskofJob(i)] + inst.getDuration(inst.getLastTaskofJob(i)));
}
} else ub_C_max = max_makespan;
data = &inst;
// create one variable per task
for(i=0; i<inst.nJobs(); ++i) {
lb = inst.getReleaseDate(inst.getJobTask(i,0));
ub = std::min(ub_C_max, inst.getDueDate(inst.getLastTaskofJob(i)))
- (offset[inst.getLastTaskofJob(i)] + inst.getDuration(inst.getLastTaskofJob(i)));
if(lb > ub) {
std::cout << "INCONSISTENT" << std::endl;
exit(1);
}
Variable t(lb, ub);
tasks.add(t);
}
// mutual exclusion constraints
for(k=0; k<inst.nMachines(); ++k)
for(i=0; i<inst.nTasksInMachine(k); ++i)
for(j=i+1; j<inst.nTasksInMachine(k); ++j) {
ti = inst.getMachineTask(k,i);
tj = inst.getMachineTask(k,j);
disjuncts.add( Disjunctive( tasks[inst.getJob(ti,0)],
inst.getDuration(ti)
+(inst.hasSetupTime() ? inst.getSetupTime(k,ti,tj) : 0)
+offset[ti]
-offset[tj],
tasks[inst.getJob(tj,0)],
inst.getDuration(tj)
+(inst.hasSetupTime() ? inst.getSetupTime(k,tj,ti) : 0)
+offset[tj]
-offset[ti] ) );
}
add( disjuncts );
Variable x_cmax(lb_C_max, ub_C_max);
C_max = x_cmax;
for(i=0; i<inst.nJobs(); ++i) {
ti = inst.getLastTaskofJob(i);
k = inst.getDuration(ti) + offset[ti];
add(Precedence(tasks[i], k, C_max));
}
for(int i=0; i<disjuncts.size(); ++i) SearchVars.add(disjuncts[i]);
}
int L_sum_Model::get_lb() {
return lb_L_sum;
}
int L_sum_Model::get_ub() {
return ub_L_sum;
}
int C_max_Model::get_lb() {
return lb_C_max;
}
int C_max_Model::get_ub() {
return ub_C_max;
}
VariableInt* L_sum_Model::get_objective_var() {
return L_sum.getVariable();
}
VariableInt* C_max_Model::get_objective_var() {
return C_max.getVariable();
}
int L_sum_Model::set_objective(const int obj) {
//VariableInt *x_lsum = L_sum.getVariable();
return (L_sum.getVariable()->setMax(obj) ? UNKNOWN : UNSAT);
}
int C_max_Model::set_objective(const int obj) {
VariableInt *x_cmax = C_max.getVariable();
bool consistent = true;
if(x_cmax) {
consistent = x_cmax->setMax(obj);
} else {
int i, ti;
VariableInt *t;
for(i=0; consistent && i<data->nJobs(); ++i) {
ti = data->getLastTaskofJob(i);
t = tasks[ti].getVariable();
if(t) {
consistent &= t->setMax(obj - data->getDuration(ti));
} else {
if(tasks[ti].value() > (obj-data->getDuration(ti))) consistent = false;
}
}
}
return (consistent ? UNKNOWN : UNSAT);
}
int L_sum_Model::get_objective() {
// int total_cost = 0, cost;
// for(int i=0; i<latebool.size(); ++i) {
// cost = 0;
// if(earlybool[i].value()) {
// cost = (data->getJobDueDate(i) - (last_tasks[i].value()+data->getDuration(data->getLastTaskofJob(i))))*data->getJobEarlyCost(i);
// } else if(latebool[i].value()) {
// cost = ((last_tasks[i].value()+data->getDuration(data->getLastTaskofJob(i))) - data->getJobDueDate(i))*data->getJobLateCost(i);
// }
// total_cost += cost;
// }
return L_sum.value();
}
double L_sum_Model::get_normalized_objective() {
double total_cost = 0, cost;
for(int i=0; i<latebool.size(); ++i) {
cost = 0.0;
if(earlybool[i].value()) {
// std::cout << "E " << (data->getJobDueDate(i) - (last_tasks[i].value()+data->getDuration(data->getLastTaskofJob(i)))) << " * "
// << (data->hasFloatCost() ? data->getJobFloatCost(i) : data->getJobEarlyCost(i))
// << std::endl;
cost = (data->getJobDueDate(i) - (last_tasks[i].value()+data->getDuration(data->getLastTaskofJob(i))))*(data->hasFloatCost() ? data->getJobFloatCost(i) : data->getJobEarlyCost(i));
} else if(latebool[i].value()) {
// std::cout << "L " << ((last_tasks[i].value()+data->getDuration(data->getLastTaskofJob(i))) - data->getJobDueDate(i)) << " * "
// << (data->hasFloatCost() ? data->getJobFloatCost(i) : data->getJobLateCost(i))
// << std::endl;
cost = ((last_tasks[i].value()+data->getDuration(data->getLastTaskofJob(i))) - data->getJobDueDate(i))*(data->hasFloatCost() ? data->getJobFloatCost(i) : data->getJobLateCost(i));
}
total_cost += cost;
}
//std::cout << " => " << total_cost << "/" << data->getNormalizer();
total_cost /= data->getNormalizer();
//std::cout << " == " << total_cost << std::endl;
return total_cost;
}
int C_max_Model::get_objective() {
return C_max.value();
}
Solution::Solution(SchedulingModel *m, SchedulingSolver *s) {
model = m;
solver = s;
earlybool_value = NULL;
latebool_value = NULL;
task_min = NULL;
task_max = NULL;
ltask_value = NULL;
disjunct_value = NULL;
int i, n;
n = m->disjuncts.size();
if(n) {
disjunct_value = new int[n];
for(i=0; i<n; ++i) disjunct_value[i] = m->disjuncts[i].value();
}
if(model->data->hasJobDueDate()) {
n = m->earlybool.size();
if(n) {
earlybool_value = new int[n];
for(i=0; i<n; ++i) earlybool_value[i] = m->earlybool[i].value();
}
n = m->latebool.size();
if(n) {
latebool_value = new int[n];
for(i=0; i<n; ++i) latebool_value[i] = m->latebool[i].value();
}
n = m->tasks.size();
if(n) {
task_min = new int[n];
task_max = new int[n];
for(i=0; i<n; ++i) {
task_min[i] = m->tasks[i].min();
task_max[i] = m->tasks[i].max();
}
}
n = m->last_tasks.size();
if(n) {
ltask_value = new int[n];
for(i=0; i<n; ++i) {
ltask_value[i] = m->last_tasks[i].value();
}
}
}
}
Solution::~Solution() {
delete [] earlybool_value;
delete [] latebool_value;
delete [] task_min;
delete [] task_max;
delete [] ltask_value;
delete [] disjunct_value;
}
void Solution::guide_search() {
solver->setGuidedOrdering(model->disjuncts, disjunct_value);
if(model->data->hasJobDueDate()) {
solver->setGuidedOrdering(model->earlybool, earlybool_value);
solver->setGuidedOrdering(model->latebool, latebool_value);
solver->setGuidedOrdering(model->last_tasks, ltask_value, "nbd");
}
}
SchedulingSolver::SchedulingSolver(SchedulingModel* m,
ParameterList* p,
StatisticList* s)
: Solver(*m,m->SearchVars), stats(s)
{
model = m;
params = p;
stats = s;
//params.initialise(model);
//p.initialise(model);
params->initialise(model);
stats->lower_bound = m->get_lb();//lower_bound;
stats->upper_bound = m->get_ub();//upper_bound;
pool = new SolutionPool();
//s.normalizer = m->data->getNormalizer();
addHeuristic( params->Heuristic, params->Randomized, params->IValue, params->Hlimit );
}
std::ostream& SchedulingSolver::print_weights(std::ostream& os) {
int i, n=variables.size;
for(i=0; i<n; ++i) {
sequence[i]->print(os);
os << " " << std::setw(4) << heuristic->get_value(sequence[i]) << std::endl;
}
//os << std::endl;
n=constraints.size;
for(i=0; i<n; ++i) {
constraints[i]->print(os);
os << " " << std::setw(4) << constraints[i]->weight << std::endl;
}
//os << std::endl;
return os;
}
void SchedulingSolver::decay_weights(const double decay) {
int i, w, n=variables.size;
for(i=0; i<n; ++i) {
w = (int)(((double)(variables[i]->weight))*decay);
if(w > variables[i]->degree) variables[i]->weight = w;
else variables[i]->weight = variables[i]->degree;
}
n = constraints.size;
for(i=0; i<n; ++i) {
if(constraints[i]->arity < variables.size/2) {
w = (int)(((double)(constraints[i]->weight))*decay);
if(w > 1) constraints[i]->weight = w;
else constraints[i]->weight = 1;
//constraints[i]->oldweight = 0;
}
}
}
void SchedulingSolver::dichotomic_search()
{
int iteration = 0;
int minfsble = stats->lower_bound;
int maxfsble = stats->upper_bound;
int objective = -1;
int new_objective = -1;
int ngd_stamp = 0;
int lit_stamp = 0;
presolve();
setVerbosity(params->Verbose);
setTimeLimit(params->Cutoff);
setNodeLimit(params->NodeCutoff);
setRandomSeed( params->Seed );
if(params->Randomized) randomizeSequence();
WeighterRestartGenNogood *nogoods = NULL;
if(params->Rngd) nogoods = setRestartGenNogood();
////////// dichotomic search ///////////////
if(status == UNKNOWN) {
while( minfsble<maxfsble &&
iteration<params->Dichotomy
) {
double remaining_time = params->Optimise - stats->get_total_time();
if(remaining_time < (2*params->NodeBase)) break;
objective = (int)(floor(((double)minfsble + (double)maxfsble)/2));
//reorderSequence();
std::cout << "c ============[ start dichotomic step ]============" << std::endl;
std::cout << std::left << std::setw(30) << "c current dichotomic range" << ":"
<< std::right << std::setw(6) << " " << std::setw(5) << minfsble
<< " to " << std::setw(5) << maxfsble << std::endl;
std::cout << std::left << std::setw(30) << "c target objective" << ":"
<< std::right << std::setw(20) << objective << std::endl;
//std::cout << "c ===========[ start dichotomic search ]===========" << std::endl;
save();
status = model->set_objective(objective);
if(pool->size()) {
if(params->DValue == "guided") pool->getBestSolution()->guide_search();
}
if(nogoods) {
ngd_stamp = nogoods->base->nogood.size;
lit_stamp = sUnaryCons.size;
}
// if(verbosity == 4) heuristic->verbosity = 4;
// print_weights(std::cout);
// //heuristic->print_weights();
// ////std::cout << std::endl;
if(status == UNKNOWN) {
solve_and_restart(params->PolicyRestart, params->Base, params->Factor);
}
if( status == SAT ) {
new_objective = model->get_objective();
stats->normalized_objective = model->get_normalized_objective();
maxfsble = new_objective;
pool->add(new Solution(model, this));
std::cout << std::left << std::setw(30) << "c solutions's objective" << ":" << std::right << std::setw(20) << new_objective << std::endl;
} else {
new_objective = objective;
minfsble = objective+1;
if(nogoods) {
nogoods->forget(ngd_stamp);
nogoods->reinit();
}
// if( status != UNSAT ) {
// setVerbosity(4);
// was_unk = true;
// }
}
stats->add_info(this, new_objective);
printStatistics(std::cout, ((params->Verbose ? RUNTIME : 0) + ((params->Verbose || status != UNKNOWN) ? BTS + PPGS : 0) + OUTCOME) );
reset(true);
decay_weights(params->Decay);
if(pool->size() && (params->DValue != params->IValue)) {
addHeuristic( params->Heuristic, params->Randomized, params->DValue, params->Hlimit );
}
std::cout << "c =============[ end dichotomic step ]=============" << std::endl;
++iteration;
//if(status == SAT && was_unk) exit(1);
}
} else if( status == SAT ) {
std::cout << "c Solved during preprocessing!" << std::endl;
} else if( status == UNSAT ) {
std::cout << "c Found inconsistent during preprocessing!" << std::endl;
}
std::cout << std::endl;
}
void SchedulingSolver::branch_and_bound()
{
setNodeLimit(0);
save();
model->set_objective(stats->upper_bound-1);
addObjective();
setRandomSeed( params->Seed );
double time_limit = (params->Optimise - stats->get_total_time());
if(time_limit > 0) {
setTimeLimit( time_limit );
addHeuristic( params->Heuristic, params->Randomized, params->Value, params->Hlimit );
if(params->Value == "guided") {
function = new SolutionGuidedSearch( this, pool, stats );
if(pool->size()) pool->getBestSolution()->guide_search();
} else {
function = new StoreStats( this, stats );
}
std::cout << "c ============[ start branch & bound ]=============" << std::endl;
std::cout << std::left << std::setw(30) << "c current range" << ":"
<< std::right << std::setw(6) << " " << std::setw(5) << stats->lower_bound
<< " to " << std::setw(5) << goal->upper_bound << std::endl;
std::cout << std::left << std::setw(30) << "c run for " << ":"
<< std::right << std::setw(19) << (time_limit) << "s" << std::endl;
if(status == UNKNOWN) {
solve_and_restart(params->PolicyRestart, params->Base, params->Factor);
}
// std::cout << "c OUTCOME: " <<
// (status == UNKNOWN ? "UNKNOWN" : (status == SAT ? "SAT" : (status == OPT ? "OPT" : "UNSAT")))
// << " UB: " << goal->upper_bound << std::endl;
//if(SOLUTIONS)
//stats->normalized_objective = model->get_normalized_objective();
stats->add_info(this, goal->upper_bound, false);
printStatistics(std::cout, ((params->Verbose ? RUNTIME : 0) + (params->Verbose ? BTS + PPGS : 0) + OUTCOME) );
reset(true);
std::cout << "c =============[ end branch & bound ]==============" << std::endl;
}
}
void StoreStats::execute()
{
//stats->add_info((SchedulingSolver *)solver, solver->goal->upper_bound);
stats->normalized_objective = ss->model->get_normalized_objective();
}
|
2cb8dc2f25711a5624ca45723657e5973b3ae6b6
|
6491936374a34dcc8c20e1c68c175560afcf0fba
|
/Plugins/DlgSystem-4.23/Source/DlgSystem/Private/Nodes/DlgNode_Speech.cpp
|
f0d97d9ef71d0d836e4ad1bee1eb48078301b3d3
|
[
"MIT"
] |
permissive
|
gaypunkposer/CyberpunkUnreal
|
bce0c79af2098d06ad3245036b0e6a0b00cee6d2
|
5e9dac20eccc2ac0caff671b327ff21c61105f92
|
refs/heads/master
| 2023-02-15T22:38:16.982580
| 2021-01-13T17:08:23
| 2021-01-13T17:08:23
| 225,226,623
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,292
|
cpp
|
DlgNode_Speech.cpp
|
// Copyright 2017-2018 Csaba Molnar, Daniel Butum
#include "Nodes/DlgNode_Speech.h"
#include "DlgContextInternal.h"
#include "DlgSystemPrivatePCH.h"
#include "Logging/DlgLogger.h"
#include "DlgLocalizationHelper.h"
#if WITH_EDITOR
void UDlgNode_Speech::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
const FName PropertyName = PropertyChangedEvent.Property != nullptr ? PropertyChangedEvent.Property->GetFName() : NAME_None;
const bool bTextChanged = PropertyName == GetMemberNameText();
// rebuild text arguments
if (bTextChanged || PropertyName == GetMemberNameTextArguments())
{
RebuildTextArguments(true);
}
}
#endif
void UDlgNode_Speech::UpdateTextsValuesFromDefaultsAndRemappings(const UDlgSystemSettings* Settings, bool bEdges, bool bUpdateGraphNode)
{
FDlgLocalizationHelper::UpdateTextFromRemapping(Settings, Text);
Super::UpdateTextsValuesFromDefaultsAndRemappings(Settings, bEdges, bUpdateGraphNode);
}
void UDlgNode_Speech::UpdateTextsNamespacesAndKeys(const UDlgSystemSettings* Settings, bool bEdges, bool bUpdateGraphNode)
{
FDlgLocalizationHelper::UpdateTextNamespaceAndKey(GetOuter(), Settings, Text);
Super::UpdateTextsNamespacesAndKeys(Settings, bEdges, bUpdateGraphNode);
}
void UDlgNode_Speech::RebuildConstructedText(const UDlgContextInternal* DlgContext)
{
if (TextArguments.Num() <= 0)
{
return;
}
FFormatNamedArguments OrderedArguments;
for (const FDlgTextArgument& DlgArgument : TextArguments)
{
OrderedArguments.Add(DlgArgument.DisplayString, DlgArgument.ConstructFormatArgumentValue(DlgContext, OwnerName));
}
ConstructedText = FText::AsCultureInvariant(FText::Format(Text, OrderedArguments));
}
bool UDlgNode_Speech::HandleNodeEnter(UDlgContextInternal* DlgContext, TSet<const UDlgNode*> NodesEnteredWithThisStep)
{
RebuildConstructedText(DlgContext);
return Super::HandleNodeEnter(DlgContext, NodesEnteredWithThisStep);
}
bool UDlgNode_Speech::ReevaluateChildren(UDlgContextInternal* DlgContext, TSet<const UDlgNode*> AlreadyEvaluated)
{
if (bIsVirtualParent)
{
check(DlgContext != nullptr);
DlgContext->GetOptionArray().Empty();
DlgContext->GetAllOptionsArray().Empty();
// stop endless loop
if (AlreadyEvaluated.Contains(this))
{
FDlgLogger::Get().Warning(
TEXT("Endless loop detected in ReevaluateChildren call: a virtual parent became his own parent!"
"This is not supposed to happen, the dialogue is terminated!")
);
return false;
}
AlreadyEvaluated.Add(this);
for (const FDlgEdge& Edge : Children)
{
// Find first satisfied child
if (Edge.Evaluate(DlgContext, { this }))
{
UDlgNode* Node = DlgContext->GetNode(Edge.TargetIndex);
if (Node != nullptr)
{
// Get Grandchildren
return Node->ReevaluateChildren(DlgContext, AlreadyEvaluated);
}
}
}
return false;
}
// Normal speech node
return Super::ReevaluateChildren(DlgContext, AlreadyEvaluated);
}
void UDlgNode_Speech::GetAssociatedParticipants(TArray<FName>& OutArray) const
{
Super::GetAssociatedParticipants(OutArray);
for (const FDlgTextArgument& TextArgument : TextArguments)
{
if (TextArgument.ParticipantName != NAME_None)
{
OutArray.AddUnique(TextArgument.ParticipantName);
}
}
}
|
330608874ba7944655118146a9064078fd355462
|
6f150af94e52d9390eb0f1e0295d51440d7382db
|
/StringStack.cpp
|
643959c1f09bd424790eb40cc0f40b96a7cefb36
|
[] |
no_license
|
logm/TrueStack
|
8de68b470e984d5f0be2bfe1211477424acd43a4
|
e4dc95ed6f6728ab20e172a1407c927c2debe035
|
refs/heads/master
| 2021-08-23T11:49:21.141536
| 2017-12-04T19:47:34
| 2017-12-04T19:47:34
| 113,085,099
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 275
|
cpp
|
StringStack.cpp
|
#include "StringStack.h"
using namespace std;
string StringStack.pop() {
return stack.pop();
}
void StringStack.push(string x) {
stack.push(x);
}
bool StringStack.isEmpty() {
if (stack.isEmpty()) {
return true;
} else {
return false;
}
}
|
5f2fefe3f29236c8a7afb8ec045223b9c7cff460
|
8a1e2e354b716667857e6d4c632883c95196bf24
|
/PrototypeFactory/MazePrototypeFactory.h
|
1ab5575032f67fdcab6a6beb935d4e29dddf7e03
|
[] |
no_license
|
yyisgod/DesignPatterns
|
8c4a58e5a151181a11d76e496cf16efc63fbb253
|
2bbe0d2b1eac0c8606c959182a2ff1d240adacbc
|
refs/heads/master
| 2021-01-10T01:40:53.869214
| 2016-04-04T13:42:59
| 2016-04-04T13:42:59
| 54,208,995
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 459
|
h
|
MazePrototypeFactory.h
|
#ifndef __MAZEPROTOTYPEFACTORY__
#define __MAZEPROTOTYPEFACTORY__
#include "MazeFactory.h"
class MazePrototypeFactory : public MazeFactory {
public:
MazePrototypeFactory(Maze*, Wall*, Room*, Door*);
virtual Maze* MakeMaze() const;
virtual Room* MakeRoom(int) const;
virtual Wall* MakeWall() const;
virtual Door* MakeDoor(Room*, Room*) const;
private:
Maze* _protytypeMaze;
Room* _protytypeRoom;
Wall* _protytypeWall;
Door* _protytypeDoor;
};
#endif
|
34de9df327b6da6963293e60acdc32f809d7cba8
|
2a016f97e5bb82ce83a0d77bf625361fe9b2968c
|
/pr5/5.cpp
|
3824a8f2dac0b417bf59e8ec0e83093b34118fa4
|
[] |
no_license
|
JuliManhupli/Fundamental-of-Programming-II
|
1ba169590c7b112ad4578b3b34b05aea025ac59e
|
a1b6cebacdc5e30c3bd3eb222232c00458f8cc1f
|
refs/heads/main
| 2023-08-22T07:21:18.784383
| 2021-10-25T10:53:38
| 2021-10-25T10:53:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 266
|
cpp
|
5.cpp
|
#include<iostream>
#include<cstdlib>
using namespace std;
long mystrol(const char *start, char **end, int base = 10) {
return strtol(start, end, base);
}
int main() {
const char *str = "2543684287";
long c = mystrol(str, NULL);
cout << c << endl;
return 0;
}
|
1bf50047e114ba0ccf52b987aa843cd3e13abe05
|
a69661665c355426058c34a3ca1a01da4719b42f
|
/cpp/ccc.cpp
|
5d38dfdc92af48f3c14e4e4090bcf6fe08579a21
|
[] |
no_license
|
RezowanTalukder/SPL_1_0933
|
ee86af1a427ebbdfade6580a6b0aad240a9e5141
|
f928f355b57587d6a13a1d23ac9639e3e24bd2c6
|
refs/heads/master
| 2021-05-10T09:16:24.400105
| 2018-07-19T15:43:58
| 2018-07-19T15:43:58
| 118,921,818
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,545
|
cpp
|
ccc.cpp
|
#include<iostream>
using namespace std ;
int main()
{
int n ;
cin>>n ;
int arr[n] ;
for(int i=0 ;i<n ;i++)cin>>arr[i] ;
int sum1=0,sum2=0 ,ans = 0 ;
sum1+=arr[0];
sum2+=arr[n-1] ;
int cur ;
if(n%2==1){
for(int i=1,j=n-2 ;i!=j; ){
if(sum1==sum2){
if(sum1>ans){
ans = sum1 ;
}
sum1+=arr[i] ;
i++ ;
sum2+=arr[j] ;
j-- ;
}
else if(sum1>sum2){
sum2+=arr[j] ;
j-- ;
}
else {
sum1+=arr[i] ;
i++ ;
}
cur = i ;
}
if(sum1>sum2){
sum2+=arr[cur] ;
}
else sum1+=arr[cur] ;
if(sum1==sum2){
if(sum1>ans)ans = sum1 ;
}
cout<<ans<<endl ;
}
else{
for(int i=1,j=n-2 ;i!=j; ){
if(sum1==sum2){
if(sum1>ans){
ans = sum1 ;
}
sum1+=arr[i] ;
i++ ;
sum2+=arr[j] ;
j-- ;
}
else if(sum1>sum2){
sum2+=arr[j] ;
j-- ;
}
else {
sum1+=arr[i] ;
i++ ;
}
}
cout<<ans<<endl ;
}
return 0 ;
}
|
e5f9f47313c09e92a0ed5dba644023f23bc39181
|
39a971d68e4f81d980bc06ddc08f95d2465ba207
|
/Sources/CoveredCalc/UI/MainUIManager.cpp
|
9a3ac5f1066b532c7ad213c99dc43272342d824c
|
[
"MIT"
] |
permissive
|
HaikuArchives/CoveredCalc
|
7a3acb263732943952322729a711ff6a7462f6ce
|
b027e6e6a9bc0d3269769b5a7f67c044103859c9
|
refs/heads/master
| 2021-01-23T03:04:26.060946
| 2010-06-07T23:44:08
| 2010-06-07T23:44:08
| 40,125,175
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 42,737
|
cpp
|
MainUIManager.cpp
|
/*
* CoveredCalc
*
* Copyright (c) 2004-2009 CoveredCalc Project Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*!
@file MainUIManager.cpp
@brief Implementation of MainUIManager class
@author ICHIMIYA Hironori (Hiron)
@date 2003.12.27 created
*/
#include "Prefix.h"
#include "CoveredCalcApp.h"
#include "ColorCodedSkin.h"
#include "CoverManager.h"
#include "CoverDef.h"
#include "CoverInfo.h"
#include "CoverFontInfo.h"
#include "CoverButtonInfo.h"
#include "CoverMainWindowInfo.h"
#include "CoverDisplayInfo.h"
#include "MovingUITask.h"
#include "ButtonUITask.h"
#include "MouseHoverUITask.h"
#include "AppSettings.h"
#include "ExceptionMessageUtils.h"
#include "MainUIManager.h"
#include "UTF8Conv.h"
#include "CoverToolTipInfo.h"
#include "BMPFileStore.h"
#include "UITaskClass.h"
#include "MainUIController.h"
#include "StringID.h"
////////////////////////////////////////
#define base UIManager
////////////////////////////////////////
/// Index of state skins in generated main window skin object
enum SkinIndex
{
SkinIndex_BackgroundActive = 0, ///< active background
SkinIndex_BackgroundInactive, ///< inactive background
SkinIndex_Pressed, ///< pressed
SkinIndex_GrayedActive, ///< active grayed (disabled)
SkinIndex_GrayedInactive, ///< inactive grayed (disabled)
SkinIndex_CheckedActive, ///< active checked
SkinIndex_CheckedInactive, ///< inactive checked
SkinIndex_CheckedPressed, ///< checked and pressed
SkinIndex_HotActive, ///< active hot
SkinIndex_HotInactive, ///< inactive hot
SkinIndex_CheckedHotActive, ///< active checked and hot
SkinIndex_CheckedHotInactive, ///< inactive checked and hot
SkinIndexCount ///< number of SkinIndex enum value.
};
/// Index of other images in generated main window skin object
enum OtherImageIndex
{
OtherImageIndex_Font = 0, ///< font
OtherImageIndexCount ///< number of OtherImageIndex enum value.
};
// ---------------------------------------------------------------------
//! Constructor
// ---------------------------------------------------------------------
MainUIManager::MainUIManager()
{
mainUIController = NULL;
currentDigitForm = CalcCore::DigitForm_10;
}
// ---------------------------------------------------------------------
//! Destructor
// ---------------------------------------------------------------------
MainUIManager::~MainUIManager()
{
clearMembers();
}
// ---------------------------------------------------------------------
//! Clear all members
// ---------------------------------------------------------------------
void MainUIManager::clearMembers()
{
base::clearMembers();
}
// ---------------------------------------------------------------------
//! Initializes the object.
// ---------------------------------------------------------------------
/**
* @brief Initializes the object.
* @param[in] uiController UI controller object
* @param[in] mainUIController main UI controller object
* @param[in keyMappingManager key-mapping manager
*/
void MainUIManager::Init(UIController* uiController, MainUIController* mainUIController, const KeyMappingManager* keyMappingManager)
{
base::Init(uiController, keyMappingManager);
this->mainUIController = mainUIController;
}
// ---------------------------------------------------------------------
//! Readies user interface.
// ---------------------------------------------------------------------
void MainUIManager::Create()
{
clearMembers();
// read current skin
readSkin();
}
// ---------------------------------------------------------------------
//! Destroys user interface.
// ---------------------------------------------------------------------
void MainUIManager::Destroy()
{
CoveredCalcApp* app = CoveredCalcApp::GetInstance();
// save current location
Rect32 uiRect;
GetUIController()->GetUIRect(uiRect);
const Point32& basePoint = getBasePoint();
Point32 windowPos;
windowPos.x = uiRect.left + basePoint.x;
windowPos.y = uiRect.top + basePoint.y;
AppSettings* appSettings = app->GetAppSettings();
appSettings->SetLastMainWindowPos(windowPos);
try
{
appSettings->Save();
}
catch (Exception* ex)
{
ExceptionMessageUtils::DoExceptionMessageBoxWithText(app, ex, NSID_EMSG_SAVE_SETTING);
ex->Delete();
}
base::Destroy();
}
// ---------------------------------------------------------------------
//! Reads current skin and reflect it to user interface
// ---------------------------------------------------------------------
void MainUIManager::readSkin()
{
UIController* uiController = GetUIController();
if (uiController->IsUIMinimized())
{
uiController->Restore();
}
uiController->Hide();
try
{
const CoverManager* manager = CoveredCalcApp::GetInstance()->GetCoverManager();
ASSERT(NULL != manager);
SInt32 currentCover = manager->GetCurrentCover();
const CoverMainWindowInfo* mainWindowInfo = manager->GetCoverDef()->GetCoverInfo(currentCover)->GetMainWindowInfo();
ASSERT(NULL != mainWindowInfo);
// create skin object
ColorCodedSkin* skin = NULL;
ColorCodedSkinAppearance* appearance = NULL;
const Path& coverFilePath = manager->GetCoverDefFilePath();
const Path coverFileParent = coverFilePath.GetParent();
BMPFileStore* bmpFileStore = new BMPFileStore();
DIBitmap* mapBitmap = NULL;
ConstDIBitmapVector* stateSkins = NULL;
ConstDIBitmapVector* otherImages = NULL;
ColorAreaMap* colorAreas = NULL;
try
{
Path imagePath;
SInt32 index;
// map bitmap
imagePath = mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_ColorMap);
ASSERT(!imagePath.IsEmpty());
mapBitmap = bmpFileStore->Load(coverFileParent.Append(imagePath));
// state image bitmaps
stateSkins = new ConstDIBitmapVector();
for (index = 0; index < SkinIndexCount; index++)
{
imagePath = getImageFilePath(mainWindowInfo, index);
ASSERT(!imagePath.IsEmpty());
stateSkins->push_back(bmpFileStore->Load(coverFileParent.Append(imagePath)));
}
// other images
otherImages = new ConstDIBitmapVector();
for (index = 0; index < OtherImageIndexCount; index++)
{
switch (index)
{
case OtherImageIndex_Font:
imagePath = mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_Font);
break;
default:
ASSERT(false);
break;
}
ASSERT(!imagePath.IsEmpty());
otherImages->push_back(bmpFileStore->Load(coverFileParent.Append(imagePath)));
}
// color area map
ColorAreaMap* colorAreas = new ColorAreaMap();
SInt32 maxCount = mainWindowInfo->GetNumMapItems();
for (index = 0; index < maxCount; index++)
{
const ColorValue& color = mainWindowInfo->GetMapItem(index);
(*colorAreas)[color] = index;
}
// now create a skin object
skin = new ColorCodedSkin();
try
{
skin->Init(bmpFileStore, mapBitmap, stateSkins, otherImages, colorAreas);
}
catch (...)
{
delete skin;
throw;
}
}
catch (...)
{
delete bmpFileStore;
if (NULL != stateSkins)
delete stateSkins;
if (NULL != otherImages)
delete otherImages;
if (NULL != colorAreas)
delete colorAreas;
throw;
}
setSkinAppearance(NULL);
appearance = uiController->InitSkinAppearance();
skin->AttachAppearance(appearance);
setSkinAppearance(appearance);
setSkin(skin);
// set base point and move user interface
setBasePoint(mainWindowInfo->GetBasePoint());
// clip transparent region of the skin
SInt32 transparentIndex = mainWindowInfo->GetTransparentRegionIndex();
if (-1 != transparentIndex)
{
ColorValue transparentColor = mainWindowInfo->GetMapItem(transparentIndex);
skin->ClipSkinRegion(transparentColor);
}
else
{
skin->UnclipSkinRegion();
}
}
catch (...)
{
uiController->Show();
throw;
}
uiController->Show();
// make the first time draw
updateWholeAppearance();
// initialize calc engine
reinitCalcCore();
}
/**
* @brief paints whole UI
*/
void MainUIManager::updateWholeAppearance()
{
ColorCodedSkin* skin = GetSkin();
if (NULL != skin)
{
bool isUIActive = GetUIController()->IsUIActive();
SInt32 backgroundSkinIndex;
SInt32 grayedSkinIndex;
SInt32 checkedSkinIndex;
if (isUIActive)
{
backgroundSkinIndex = SkinIndex_BackgroundActive;
grayedSkinIndex = SkinIndex_GrayedActive;
checkedSkinIndex = SkinIndex_CheckedActive;
}
else
{
backgroundSkinIndex = SkinIndex_BackgroundInactive;
grayedSkinIndex = SkinIndex_GrayedInactive;
checkedSkinIndex = SkinIndex_CheckedInactive;
}
// background
skin->UpdateWholeAppearance(backgroundSkinIndex);
// each non-normal area
SInt32 commandId;
for (commandId = 0; commandId < CoverMainWindowInfo::ButtonClass_Max; commandId++)
{
UInt32 state = GetCommandState(commandId);
if (state & CommandState_Disabled)
{
SInt32 areaId = GetSkinAreaFromCommandId(commandId);
if (ColorCodedSkin::Area_None != areaId)
{
skin->UpdatePartAppearance(areaId, grayedSkinIndex);
}
}
else if (state & CommandState_Checked)
{
SInt32 areaId = GetSkinAreaFromCommandId(commandId);
if (ColorCodedSkin::Area_None != areaId)
{
skin->UpdatePartAppearance(areaId, checkedSkinIndex);
}
}
}
}
drawNumberStringOnDisplay(numberStringOnDisplay);
}
const Path& MainUIManager::getImageFilePath(const CoverMainWindowInfo* mainWindowInfo, SInt32 skinIndex)
{
const Path* imagePath = NULL;
switch (skinIndex)
{
case SkinIndex_BackgroundActive:
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_BackgroundActive));
break;
case SkinIndex_BackgroundInactive:
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_BackgroundInactive));
if (imagePath->IsEmpty())
{
imagePath = &(getImageFilePath(mainWindowInfo, SkinIndex_BackgroundActive));
}
break;
case SkinIndex_Pressed:
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_Pressed));
if (imagePath->IsEmpty())
{
imagePath = &(getImageFilePath(mainWindowInfo, SkinIndex_BackgroundActive));
}
break;
case SkinIndex_GrayedActive:
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_GrayedActive));
if (imagePath->IsEmpty())
{
imagePath = &(getImageFilePath(mainWindowInfo, SkinIndex_BackgroundActive));
}
break;
case SkinIndex_GrayedInactive:
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_GrayedInactive));
if (imagePath->IsEmpty())
{
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_GrayedActive));
}
if (imagePath->IsEmpty())
{
imagePath = &(getImageFilePath(mainWindowInfo, SkinIndex_BackgroundInactive));
}
break;
case SkinIndex_CheckedActive:
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_CheckedActive));
if (imagePath->IsEmpty())
{
imagePath = &(getImageFilePath(mainWindowInfo, SkinIndex_BackgroundActive));
}
break;
case SkinIndex_CheckedInactive:
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_CheckedInactive));
if (imagePath->IsEmpty())
{
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_CheckedActive));
}
if (imagePath->IsEmpty())
{
imagePath = &(getImageFilePath(mainWindowInfo, SkinIndex_BackgroundInactive));
}
break;
case SkinIndex_CheckedPressed:
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_CheckedPressed));
if (imagePath->IsEmpty())
{
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_CheckedActive));
}
if (imagePath->IsEmpty())
{
imagePath = &(getImageFilePath(mainWindowInfo, SkinIndex_Pressed));
}
break;
case SkinIndex_HotActive:
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_HotActive));
if (imagePath->IsEmpty())
{
imagePath = &(getImageFilePath(mainWindowInfo, SkinIndex_BackgroundActive));
}
break;
case SkinIndex_HotInactive:
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_HotInactive));
if (imagePath->IsEmpty())
{
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_HotActive));
}
if (imagePath->IsEmpty())
{
imagePath = &(getImageFilePath(mainWindowInfo, SkinIndex_BackgroundInactive));
}
break;
case SkinIndex_CheckedHotActive:
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_CheckedHotActive));
if (imagePath->IsEmpty())
{
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_CheckedActive));
}
if (imagePath->IsEmpty())
{
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_HotActive));
}
if (imagePath->IsEmpty())
{
imagePath = &(getImageFilePath(mainWindowInfo, SkinIndex_BackgroundActive));
}
break;
case SkinIndex_CheckedHotInactive:
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_CheckedHotInactive));
if (imagePath->IsEmpty())
{
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_CheckedHotActive));
}
if (imagePath->IsEmpty())
{
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_CheckedInactive));
}
if (imagePath->IsEmpty())
{
imagePath = &(mainWindowInfo->GetImageFilePath(CoverMainWindowInfo::ImageClass_CheckedActive));
}
if (imagePath->IsEmpty())
{
imagePath = &(getImageFilePath(mainWindowInfo, SkinIndex_HotInactive));
}
break;
default:
ASSERT(false);
break;
}
return *imagePath;
}
// ---------------------------------------------------------------------
//! Reinitializes calc's core object.
// ---------------------------------------------------------------------
void MainUIManager::reinitCalcCore()
{
const CoverMainWindowInfo* mainWindowInfo = getCurrentMainWindowInfo();
// get display length
UInt32 maxDispLength = 0;
const CoverFontInfo* fontInfo = mainWindowInfo->GetFontInfo();
SInt32 displayMapIndex = mainWindowInfo->GetDisplayInfo()->GetMapIndex();
Rect32 displayRect;
ColorCodedSkin* skin = getSkin();
skin->GetAreaRect(displayMapIndex, displayRect);
if (displayRect.bottom - displayRect.top + 1 >= fontInfo->GetHeight())
{
SInt32 drawPointX;
drawPointX = displayRect.right - fontInfo->GetWidth();
while (drawPointX >= displayRect.left)
{
maxDispLength++;
drawPointX -= fontInfo->GetWidth() + fontInfo->GetCharSpace();
}
}
// reinit
calcCore.Init(this, maxDispLength);
}
// ---------------------------------------------------------------------
//! Called when user interface is activated or deactivated.
// ---------------------------------------------------------------------
void MainUIManager::UIActivated()
{
ColorCodedSkin* skin = getSkin();
if (NULL != skin)
{
updateWholeAppearance();
}
base::UIActivated();
}
/**
* @brief Called when mouse cursor position is changed.
*/
void MainUIManager::MouseMove()
{
base::MouseMove();
bool doHoverTask;
#if defined(BEOS)
doHoverTask = GetUIController()->IsUIActive();
#else
doHoverTask = true;
#endif
if (doHoverTask)
{
UITaskManager* uiTaskManager = getTaskManager();
UITask* task = uiTaskManager->FindOneTask(UITaskClass::ButtonUITask);
if (NULL == task)
{
task = uiTaskManager->FindOneTask(UITaskClass::MovingUITask);
}
if (NULL == task)
{
Point32 startPoint = GetUIController()->GetMousePosition();
// hit test for button item
ColorCodedSkin* skin = getSkin();
SInt32 skinArea = skin->GetArea(startPoint);
if (ColorCodedSkin::Area_None != skinArea)
{
// checks if hover task is already exist.
bool isExist = false;
UITaskVector hoverTasks;
getTaskManager()->FindAllTask(UITaskClass::MouseHoverUITask, hoverTasks);
UITaskVector::const_iterator ite;
for (ite = hoverTasks.begin(); ite != hoverTasks.end(); ite++)
{
MouseHoverUITask* task = dynamic_cast<MouseHoverUITask*>(*ite);
if (task->GetTargetArea() == skinArea)
{
isExist = true;
break;
}
}
if (!isExist)
{
const CoverMainWindowInfo* mainWindowInfo = getCurrentMainWindowInfo();
CoverMainWindowInfo::ButtonClass command = mainWindowInfo->FindButton(skinArea);
if (CoverMainWindowInfo::ButtonClass_None != command)
{
UInt32 commandState = GetCommandState(command);
if (!(commandState & CommandState_Disabled))
{
SInt32 activeImageIndex = SkinIndex_BackgroundActive;
SInt32 inactiveImageIndex = SkinIndex_BackgroundInactive;
SInt32 hotActiveImageIndex = SkinIndex_HotActive;
SInt32 hotInactiveImageIndex = SkinIndex_HotInactive;
if (commandState & CommandState_Checked)
{
activeImageIndex = SkinIndex_CheckedActive;
inactiveImageIndex = SkinIndex_CheckedInactive;
hotActiveImageIndex = SkinIndex_CheckedHotActive;
hotInactiveImageIndex = SkinIndex_CheckedHotInactive;
}
MouseHoverUITask* newTask = new MouseHoverUITask();
newTask->Init(this);
newTask->SetImageIndex(activeImageIndex, inactiveImageIndex, hotActiveImageIndex, hotInactiveImageIndex);
newTask->SetInitialInformation(command, mainWindowInfo->GetHottingSteps());
StartTask(newTask);
}
}
}
}
}
}
}
// ---------------------------------------------------------------------
//! Called when mouse button 1 is pressed.
// ---------------------------------------------------------------------
void MainUIManager::Button1Down()
{
base::Button1Down();
UITaskManager* uiTaskManager = getTaskManager();
UITask* task = uiTaskManager->FindOneTask(UITaskClass::ButtonUITask);
if (NULL == task)
{
task = uiTaskManager->FindOneTask(UITaskClass::MovingUITask);
}
if (NULL == task)
{
Point32 startPoint = GetUIController()->GetMousePosition();
UITask* newTask = NULL;
// hit test for button item
ColorCodedSkin* skin = getSkin();
SInt32 skinArea = skin->GetArea(startPoint);
if (ColorCodedSkin::Area_None != skinArea)
{
const CoverMainWindowInfo* mainWindowInfo = getCurrentMainWindowInfo();
CoverMainWindowInfo::ButtonClass command = mainWindowInfo->FindButton(skinArea);
if (CoverMainWindowInfo::ButtonClass_None != command)
{
UInt32 commandState = GetCommandState(command);
if (!(commandState & CommandState_Disabled))
{
// cancels hover task of this button.
UITaskVector hoverTasks;
getTaskManager()->FindAllTask(UITaskClass::MouseHoverUITask, hoverTasks);
UITaskVector::iterator ite;
for (ite = hoverTasks.begin(); ite != hoverTasks.end(); ite++)
{
MouseHoverUITask* task = dynamic_cast<MouseHoverUITask*>(*ite);
if (task->GetTargetArea() == skinArea)
{
task->CancelTask();
}
}
ButtonUITask* buttonUITask = new ButtonUITask();
try
{
buttonUITask->Init(this);
buttonUITask->SetEventHandler(this);
SInt32 activeImageIndex = SkinIndex_BackgroundActive;
SInt32 inactiveImageIndex = SkinIndex_BackgroundInactive;
SInt32 pressedImageIndex = SkinIndex_Pressed;
if (commandState & CommandState_Checked)
{
activeImageIndex = SkinIndex_CheckedActive;
inactiveImageIndex = SkinIndex_CheckedInactive;
pressedImageIndex = SkinIndex_CheckedPressed;
}
buttonUITask->SetImageIndex( activeImageIndex,
inactiveImageIndex,
pressedImageIndex);
buttonUITask->SetInitialInformation(command);
}
catch (...)
{
delete buttonUITask;
throw;
}
newTask = buttonUITask;
}
}
}
if (NULL == newTask &&
!CoveredCalcApp::GetInstance()->GetAppSettings()->IsMainWindowLocked())
{
// moving task
MovingUITask* movingUITask = new MovingUITask();
try
{
movingUITask->Init(this);
}
catch (...)
{
delete movingUITask;
throw;
}
newTask = movingUITask;
}
if (NULL != newTask)
{
StartTask(newTask);
}
}
}
// ---------------------------------------------------------------------
//! Converts key event parameter to button class
// ---------------------------------------------------------------------
CoverMainWindowInfo::ButtonClass
MainUIManager::getButtonFromKeyFunc(
MainWindowKeyFunc::KeyFunc keyFunc
)
{
#define HANDLE_KEYFUNC(_keyFunc, _buttonClass) \
case _keyFunc: \
buttonClass = _buttonClass; \
break;
CoverMainWindowInfo::ButtonClass buttonClass;
switch (keyFunc)
{
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_0, CoverMainWindowInfo::ButtonClass_0)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_1, CoverMainWindowInfo::ButtonClass_1)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_2, CoverMainWindowInfo::ButtonClass_2)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_3, CoverMainWindowInfo::ButtonClass_3)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_4, CoverMainWindowInfo::ButtonClass_4)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_5, CoverMainWindowInfo::ButtonClass_5)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_6, CoverMainWindowInfo::ButtonClass_6)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_7, CoverMainWindowInfo::ButtonClass_7)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_8, CoverMainWindowInfo::ButtonClass_8)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_9, CoverMainWindowInfo::ButtonClass_9)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_A, CoverMainWindowInfo::ButtonClass_A)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_B, CoverMainWindowInfo::ButtonClass_B)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_C, CoverMainWindowInfo::ButtonClass_C)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_D, CoverMainWindowInfo::ButtonClass_D)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_E, CoverMainWindowInfo::ButtonClass_E)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_F, CoverMainWindowInfo::ButtonClass_F)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_Point, CoverMainWindowInfo::ButtonClass_Point)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_Clear, CoverMainWindowInfo::ButtonClass_Clear)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_BS, CoverMainWindowInfo::ButtonClass_BS)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_Equal, CoverMainWindowInfo::ButtonClass_Equal)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_Plus, CoverMainWindowInfo::ButtonClass_Plus)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_Minus, CoverMainWindowInfo::ButtonClass_Minus)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_Times, CoverMainWindowInfo::ButtonClass_Times)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_Div, CoverMainWindowInfo::ButtonClass_Div)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_Negate, CoverMainWindowInfo::ButtonClass_Negate)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_Hex, CoverMainWindowInfo::ButtonClass_Hex)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_Dec, CoverMainWindowInfo::ButtonClass_Dec)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_Oct, CoverMainWindowInfo::ButtonClass_Oct)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_Bin, CoverMainWindowInfo::ButtonClass_Bin)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_Minimize, CoverMainWindowInfo::ButtonClass_Minimize)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_Close, CoverMainWindowInfo::ButtonClass_Close)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_ShowHideCoverBrowser, CoverMainWindowInfo::ButtonClass_ShowHideCoverBrowser)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_ToggleAlwaysOnTop, CoverMainWindowInfo::ButtonClass_ToggleAlwaysOnTop)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_ToggleLockPos, CoverMainWindowInfo::ButtonClass_ToggleLockPos)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_ShowPreferencesDialog, CoverMainWindowInfo::ButtonClass_ShowPreferencesDialog)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_ShowCurrentCoverInfo, CoverMainWindowInfo::ButtonClass_ShowCurrentCoverInfo)
HANDLE_KEYFUNC(MainWindowKeyFunc::KeyFunc_About, CoverMainWindowInfo::ButtonClass_About)
default:
buttonClass = CoverMainWindowInfo::ButtonClass_None;
break;
}
return buttonClass;
#undef HANDLE_KEYFUNC
}
// ---------------------------------------------------------------------
//! Converts command id (on this UI) to area id on the skin.
/*!
@return area id on the skin
*/
// ---------------------------------------------------------------------
SInt32 MainUIManager::GetSkinAreaFromCommandId(
SInt32 commandId //!< command id on this UI
)
{
SInt32 retValue = ColorCodedSkin::Area_None;
if (commandId != CoverMainWindowInfo::ButtonClass_None)
{
const CoverButtonInfo* buttonInfo = getCurrentMainWindowInfo()->GetButtonInfo(static_cast<CoverMainWindowInfo::ButtonClass>(commandId));
if (NULL != buttonInfo)
{
retValue = buttonInfo->GetMapIndex();
}
}
return retValue;
}
/**
* @brief Returns state of specified command.
* @param[in] commandId command ID
* @return command state. it is a combination of UIManager::CommandState_xxx.
*/
UInt32 MainUIManager::GetCommandState(SInt32 commandId)
{
UInt32 state = UIManager::CommandState_None;
switch (commandId)
{
case CoverMainWindowInfo::ButtonClass_F:
case CoverMainWindowInfo::ButtonClass_E:
case CoverMainWindowInfo::ButtonClass_D:
case CoverMainWindowInfo::ButtonClass_C:
case CoverMainWindowInfo::ButtonClass_B:
case CoverMainWindowInfo::ButtonClass_A:
if (CalcCore::DigitForm_16 != currentDigitForm)
{
state |= UIManager::CommandState_Disabled;
}
break;
case CoverMainWindowInfo::ButtonClass_9:
case CoverMainWindowInfo::ButtonClass_8:
if (CalcCore::DigitForm_16 != currentDigitForm
&& CalcCore::DigitForm_10 != currentDigitForm)
{
state |= UIManager::CommandState_Disabled;
}
break;
case CoverMainWindowInfo::ButtonClass_7:
case CoverMainWindowInfo::ButtonClass_6:
case CoverMainWindowInfo::ButtonClass_5:
case CoverMainWindowInfo::ButtonClass_4:
case CoverMainWindowInfo::ButtonClass_3:
case CoverMainWindowInfo::ButtonClass_2:
if (CalcCore::DigitForm_16 != currentDigitForm
&& CalcCore::DigitForm_10 != currentDigitForm
&& CalcCore::DigitForm_8 != currentDigitForm)
{
state |= UIManager::CommandState_Disabled;
}
break;
case CoverMainWindowInfo::ButtonClass_Hex:
state |= UIManager::CommandState_Radio;
if (CalcCore::DigitForm_16 == currentDigitForm)
{
state |= UIManager::CommandState_Checked;
}
break;
case CoverMainWindowInfo::ButtonClass_Dec:
state |= UIManager::CommandState_Radio;
if (CalcCore::DigitForm_10 == currentDigitForm)
{
state |= UIManager::CommandState_Checked;
}
break;
case CoverMainWindowInfo::ButtonClass_Oct:
state |= UIManager::CommandState_Radio;
if (CalcCore::DigitForm_8 == currentDigitForm)
{
state |= UIManager::CommandState_Checked;
}
break;
case CoverMainWindowInfo::ButtonClass_Bin:
state |= UIManager::CommandState_Radio;
if (CalcCore::DigitForm_2 == currentDigitForm)
{
state |= UIManager::CommandState_Checked;
}
break;
case CoverMainWindowInfo::ButtonClass_ShowHideCoverBrowser:
if (CoveredCalcApp::GetInstance()->IsCoverBrowserVisible())
{
state |= UIManager::CommandState_Checked;
}
break;
case CoverMainWindowInfo::ButtonClass_ToggleAlwaysOnTop:
if (CoveredCalcApp::GetInstance()->GetAppSettings()->IsMainWindowAlwaysOnTop())
{
state |= UIManager::CommandState_Checked;
}
break;
case CoverMainWindowInfo::ButtonClass_ToggleLockPos:
if (CoveredCalcApp::GetInstance()->GetAppSettings()->IsMainWindowLocked())
{
state |= UIManager::CommandState_Checked;
}
break;
}
return state;
}
/**
* @brief Executes a command.
* @param[in] commandId command ID
*/
void MainUIManager::ExecuteCommand(SInt32 commandId)
{
CoverMainWindowInfo::ButtonClass button = static_cast<CoverMainWindowInfo::ButtonClass>(commandId);
ASSERT(CoverMainWindowInfo::ButtonClass_None != button);
#define HANDLE_CALCKEY(buttonClass, calcKey) \
case buttonClass: \
calcCore.Put(calcKey); \
break;
switch (button)
{
case CoverMainWindowInfo::ButtonClass_Close:
doCommandClose();
break;
case CoverMainWindowInfo::ButtonClass_Minimize:
doCommandMainMinimize();
break;
case CoverMainWindowInfo::ButtonClass_ShowHideCoverBrowser:
doCommandCoverBrowser();
break;
case CoverMainWindowInfo::ButtonClass_ToggleAlwaysOnTop:
doCommandMainWindowAlwaysOnTop();
break;
case CoverMainWindowInfo::ButtonClass_ToggleLockPos:
doCommandMainWindowLockPos();
break;
case CoverMainWindowInfo::ButtonClass_ShowPreferencesDialog:
doCommandPreferences();
break;
case CoverMainWindowInfo::ButtonClass_ShowCurrentCoverInfo:
doCommandAboutCurrentCover();
break;
case CoverMainWindowInfo::ButtonClass_About:
doCommandAbout();
break;
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_0, CalcCore::Key_0)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_1, CalcCore::Key_1)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_2, CalcCore::Key_2)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_3, CalcCore::Key_3)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_4, CalcCore::Key_4)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_5, CalcCore::Key_5)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_6, CalcCore::Key_6)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_7, CalcCore::Key_7)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_8, CalcCore::Key_8)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_9, CalcCore::Key_9)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_A, CalcCore::Key_A)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_B, CalcCore::Key_B)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_C, CalcCore::Key_C)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_D, CalcCore::Key_D)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_E, CalcCore::Key_E)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_F, CalcCore::Key_F)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_Point, CalcCore::Key_Point)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_Clear, CalcCore::Key_Clear)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_BS, CalcCore::Key_BS)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_Equal, CalcCore::Key_Equal)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_Plus, CalcCore::Key_Plus)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_Minus, CalcCore::Key_Minus)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_Times, CalcCore::Key_Times)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_Div, CalcCore::Key_Div)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_Negate, CalcCore::Key_Negate)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_Hex, CalcCore::Key_DigitForm16)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_Dec, CalcCore::Key_DigitForm10)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_Oct, CalcCore::Key_DigitForm8)
HANDLE_CALCKEY(CoverMainWindowInfo::ButtonClass_Bin, CalcCore::Key_DigitForm2)
default:
break;
}
#undef HANDLE_CALCKEY
}
/**
* @brief Called when a key is pressed.
* @return returns false to skip other behavior assigned to this key-event.
*/
bool MainUIManager::KeyDown(const KeyEventParameter& parameter)
{
bool ret = base::KeyDown(parameter);
SInt32 function = getKeyMappingManager()->GetFunction(parameter);
CoverMainWindowInfo::ButtonClass command = getButtonFromKeyFunc(static_cast<MainWindowKeyFunc::KeyFunc>(function));
if (CoverMainWindowInfo::ButtonClass_None != command)
{
UInt32 commandState = GetCommandState(command);
if (!(commandState & CommandState_Disabled))
{
ColorCodedSkin* skin = getSkin();
UIController* uiController = getUIController();
SInt32 skinArea = GetSkinAreaFromCommandId(command);
if (ColorCodedSkin::Area_None != skinArea)
{
// cancels hover task of this key.
UITaskVector hoverTasks;
getTaskManager()->FindAllTask(UITaskClass::MouseHoverUITask, hoverTasks);
UITaskVector::iterator ite;
for (ite = hoverTasks.begin(); ite != hoverTasks.end(); ite++)
{
MouseHoverUITask* task = dynamic_cast<MouseHoverUITask*>(*ite);
if (task->GetTargetArea() == skinArea)
{
task->CancelTask();
}
}
// update appearance
SInt32 pressedImageIndex;
SInt32 restoreImageIndex;
if (commandState & CommandState_Checked)
{
pressedImageIndex = SkinIndex_CheckedPressed;
if (uiController->IsUIActive())
restoreImageIndex = SkinIndex_CheckedActive;
else
restoreImageIndex = SkinIndex_CheckedInactive;
}
else
{
pressedImageIndex = SkinIndex_Pressed;
if (uiController->IsUIActive())
restoreImageIndex = SkinIndex_BackgroundActive;
else
restoreImageIndex = SkinIndex_BackgroundInactive;
}
skin->UpdatePartAppearance(skinArea, pressedImageIndex);
uiController->UpdateUI();
uiController->Wait(CoveredCalcApp::GetInstance()->GetAppSettings()->GetKeyAnimationWait());
skin->UpdatePartAppearance(skinArea, restoreImageIndex);
}
ButtonClicked(command);
}
}
else
{
// no button matches this key, but the function of this key can exsits.
}
if (ret)
{
ret = KeyFuncOperation::KeyFunc_None == function;
}
return ret;
}
// ---------------------------------------------------------------------
//! Called when mouse button 2 is pressed.
// ---------------------------------------------------------------------
void MainUIManager::Button2Down()
{
base::Button2Down();
UIController* uiController = GetUIController();
Point32 position = uiController->GetMouseScreenPosition();
GetMainUIController()->ShowMainUIContextMenu(position);
}
// ---------------------------------------------------------------------
//! Called when user execute "Cover Browser" command.
// ---------------------------------------------------------------------
void MainUIManager::doCommandCoverBrowser()
{
CoveredCalcApp* app = CoveredCalcApp::GetInstance();
bool isShown = app->IsCoverBrowserVisible();
app->ShowCoverBrowser(!isShown);
updateWholeAppearance();
}
/**
* @brief Called when user execute "Always on top" command.
*/
void MainUIManager::doCommandMainWindowAlwaysOnTop()
{
CoveredCalcApp* app = CoveredCalcApp::GetInstance();
AppSettings* appSettings = app->GetAppSettings();
bool isFlagOn = appSettings->IsMainWindowAlwaysOnTop();
GetUIController()->SetAlwaysOnTopFlag(!isFlagOn);
appSettings->SetMainWindowAlwaysOnTop(!isFlagOn);
updateWholeAppearance();
}
/**
* @brief Called when user execute "Lock position" command.
*/
void MainUIManager::doCommandMainWindowLockPos()
{
CoveredCalcApp* app = CoveredCalcApp::GetInstance();
AppSettings* appSettings = app->GetAppSettings();
bool isLocked = appSettings->IsMainWindowLocked();
appSettings->SetMainWindowLocked(!isLocked);
updateWholeAppearance();
}
/**
* @brief Called when user execute "Preferences" command.
*/
void MainUIManager::doCommandPreferences()
{
mainUIController->ShowPreferencesDialog();
}
// ---------------------------------------------------------------------
//! Called when user execute "About" command.
// ---------------------------------------------------------------------
void MainUIManager::doCommandAbout()
{
mainUIController->ShowAboutDialog();
}
// ---------------------------------------------------------------------
//! Called when user execute "About current cover" command.
// ---------------------------------------------------------------------
void MainUIManager::doCommandAboutCurrentCover()
{
mainUIController->ShowAboutCurrentCoverDialog();
}
// ---------------------------------------------------------------------
//! Called when user execute "Minimize" command.
// ---------------------------------------------------------------------
void MainUIManager::doCommandMainMinimize()
{
getUIController()->Minimize();
}
// ---------------------------------------------------------------------
//! Called when user execute "Close" command.
// ---------------------------------------------------------------------
void MainUIManager::doCommandClose()
{
GetUIController()->CloseUI();
}
// ---------------------------------------------------------------------
//! Called when button item is clicked
// ---------------------------------------------------------------------
void MainUIManager::ButtonClicked(
SInt32 buttonCommand //!< command of clicked button
)
{
ExecuteCommand(buttonCommand);
}
// ---------------------------------------------------------------------
//! Called when calculated value is displayed
// ---------------------------------------------------------------------
void MainUIManager::DisplayValue(
ConstAStr value //!< data to display
)
{
drawNumberStringOnDisplay(value);
numberStringOnDisplay = value;
}
/**
* @brief helper function for converting DigitForm to command id
*/
CoverMainWindowInfo::ButtonClass digitFormToCommandId(CalcCore::DigitForm form)
{
switch (form)
{
case CalcCore::DigitForm_16:
return CoverMainWindowInfo::ButtonClass_Hex;
case CalcCore::DigitForm_10:
return CoverMainWindowInfo::ButtonClass_Dec;
case CalcCore::DigitForm_8:
return CoverMainWindowInfo::ButtonClass_Oct;
case CalcCore::DigitForm_2:
return CoverMainWindowInfo::ButtonClass_Bin;
default:
ASSERT(false);
return CoverMainWindowInfo::ButtonClass_None;
}
}
/**
* @brief Displays digit form (radix)
*/
void MainUIManager::DisplayDigitForm(
CalcCore::DigitForm form ///< digit form
)
{
if (currentDigitForm != form)
{
currentDigitForm = form;
updateWholeAppearance();
}
}
// ---------------------------------------------------------------------
//! Displays the error.
// ---------------------------------------------------------------------
void MainUIManager::DisplayError(
CalcCore::Error error //!< error to display
)
{
if (CalcCore::Error_None == error)
return;
AChar value[CalcCore::MAX_VALUE_STR];
UInt32 maxLength = calcCore.GetMaxDispLength();
ASSERT(maxLength < CalcCore::MAX_VALUE_STR);
UInt32 index;
for (index=0; index<maxLength; index++)
{
value[index] = '-';
}
value[index] = '\0';
drawNumberStringOnDisplay(value);
numberStringOnDisplay = value;
}
// ---------------------------------------------------------------------
//! Draws number string
// ---------------------------------------------------------------------
void MainUIManager::drawNumberStringOnDisplay(
ConstAStr string //!< string to draw
)
{
const CoverMainWindowInfo* mainWindowInfo = getCurrentMainWindowInfo();
const CoverFontInfo* fontInfo = mainWindowInfo->GetFontInfo();
SInt32 displayMapIndex = mainWindowInfo->GetDisplayInfo()->GetMapIndex();
Rect32 displayRect;
ColorCodedSkin* skin = getSkin();
skin->GetAreaRect(displayMapIndex, displayRect);
// clear display
SInt32 skinIndex;
if (GetUIController()->IsUIActive())
{
skinIndex = SkinIndex_BackgroundActive;
}
else
{
skinIndex = SkinIndex_BackgroundInactive;
}
skin->UpdatePartAppearance(displayMapIndex, skinIndex);
// draw characters
if (displayRect.bottom - displayRect.top + 1 >= fontInfo->GetHeight())
{
const AChar* curChar = string + tcslen(string) - 1;
Point32 drawPoint;
drawPoint.y = displayRect.top;
drawPoint.x = displayRect.right - fontInfo->GetWidth();
while (curChar >= string && drawPoint.x >= displayRect.left)
{
switch (fontInfo->GetType())
{
case CoverFontInfo::Type_Number:
{
// The font on bitmap is located in order of the following: "0123456789ABCDEF.-"
Rect32 imageRect;
if ('.' == *curChar)
{
imageRect.left = fontInfo->GetWidth() * 16;
}
else if ('-' == *curChar)
{
imageRect.left = fontInfo->GetWidth() * 17;
}
else if ('0' <= *curChar && *curChar <= '9')
{
imageRect.left = fontInfo->GetWidth() * (*curChar - '0');
}
else if ('a' <= *curChar && *curChar <= 'f')
{
imageRect.left = fontInfo->GetWidth() * ((*curChar - 'a') + 10);
}
else if ('A' <= *curChar && *curChar <= 'F')
{
imageRect.left = fontInfo->GetWidth() * ((*curChar - 'A') + 10);
}
else
{
imageRect.left = -1;
}
if (-1 != imageRect.left)
{
imageRect.top = 0;
imageRect.bottom = fontInfo->GetHeight() - 1;
imageRect.right = imageRect.left + fontInfo->GetWidth() - 1;
skin->DrawImage(drawPoint, OtherImageIndex_Font, imageRect, fontInfo->GetTransparentColor());
}
}
break;
}
drawPoint.x -= fontInfo->GetWidth() + fontInfo->GetCharSpace();
curChar--;
}
}
}
// ---------------------------------------------------------------------
//! Returns main window information about current cover.
/*!
@return pointer to CoverMainWindowInfo object.
*/
// ---------------------------------------------------------------------
const CoverMainWindowInfo* MainUIManager::getCurrentMainWindowInfo() const
{
const CoverManager* manager = CoveredCalcApp::GetInstance()->GetCoverManager();
return manager->GetCoverDef()->GetCoverInfo(manager->GetCurrentCover())->GetMainWindowInfo();
}
/**
* @brief changes last skin area at the cursor position
*/
void MainUIManager::changeLastCursorSkinArea(
SInt32 area ///< new skin area
)
{
const CoverMainWindowInfo* mainWindowInfo = getCurrentMainWindowInfo();
if (NULL != mainWindowInfo)
{
const CoverToolTipInfo* toolTipInfo = mainWindowInfo->FindToolTipInfo(area);
if (NULL != toolTipInfo)
{
MBCString mbToolTipText;
UTF8Conv::ToMultiByteWithLineEnding(mbToolTipText, toolTipInfo->GetToolTipText());
GetUIController()->SetToolTipText(mbToolTipText);
}
else
{
GetUIController()->SetToolTipText(ALITERAL(""));
}
}
base::changeLastCursorSkinArea(area);
}
|
96e31aad3274c5429a80155b6ec9691af16ce0a7
|
7a71e006e0a8fd97f2ad2710c38d2e0db4d11f16
|
/test.cpp
|
7703ac188e09b1def2e7633ba44b63abfba723f5
|
[] |
no_license
|
lucasxsong/lab-07-iterator-hahaha
|
9ab73dac38e49b7caf85f0000626e944e9137da0
|
c7b1c574e4f0adb9038a54924dc294ecb4abac35
|
refs/heads/master
| 2020-04-10T02:25:41.371633
| 2018-12-07T01:39:26
| 2018-12-07T01:39:26
| 160,744,110
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,441
|
cpp
|
test.cpp
|
#include "gtest/gtest.h"
#include "composite.h"
#include "iterator.h"
#include "visitor.h"
TEST(PreOrdererIterator, testCaseOne){
Base* one = new Op(1);
Base* two = new Op(2);
Base* three = new Add(one,two);
Base* six = new Mult(three,two);
Base* root = new Root(six);
Iterator* i = new PreorderIterator(root);
i->first();
EXPECT_EQ(6,i->current()->evaluate());
}
TEST(PreOrdererIterator, testCaseTwo){
Base* one = new Op(2);
Base* two = new Op(4);
Base* three = new Add(one,two);
Base* six = new Mult(three,two);
Base* root = new Root(six);
Iterator* i = new PreorderIterator(root);
i->first();
EXPECT_EQ(24,i->current()->evaluate());
}
TEST(PreOrdererIterator, testCaseThree){
Base* one = new Op(1);
Base* two = new Op(2);
Base* three = new Add(one,two);
Base* six = new Mult(three,two);
Base* root = new Root(six);
Iterator* i = new PreorderIterator(root);
i->first();
i->next();
EXPECT_EQ(3,i->current()->evaluate());
i->next();
EXPECT_EQ(1,i->current()->evaluate());
i->next();
EXPECT_EQ(2,i->current()->evaluate());
i->next();
EXPECT_EQ(2,i->current()->evaluate());
}
TEST(unaryIterator, testCaseOne){
Base* two = new Op(2);
Base* four = new Sqr(two);
Base* root3 = new Root(four);
Iterator* i = new PreorderIterator(root3);
i->first();
EXPECT_EQ(4,i->current()->evaluate());
i->next();
EXPECT_EQ(2,i->current()->evaluate());
}
TEST(unaryIterator, testCaseTwo){
Base* two = new Op(2);
Base* four = new Sqr(two);
Base* root3 = new Root(four);
Iterator* i = new PreorderIterator(root3);
i->first();
EXPECT_EQ(4,i->current()->evaluate());
i->next();
EXPECT_EQ(2,i->current()->evaluate());
}
TEST(unaryIterator, testCaseThree){
Base* two = new Op(6);
Base* four = new Sqr(two);
Base* root3 = new Root(four);
Iterator* i = new PreorderIterator(root3);
i->first();
EXPECT_EQ(36,i->current()->evaluate());
i->next();
EXPECT_EQ(6,i->current()->evaluate());
}
TEST(Visitor, testCaseOne) {
Base* two = new Op(2);
Base* four = new Sqr(two);
Base* root3 = new Root(four);
Iterator* i = new PreorderIterator(root3);
Visitor* v = i->returnVisitor();
string s = v->returnOutput();
EXPECT_EQ("", s);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
1d2fb329fe5e4ea0ffe6af5a5fd06f27942fdb4d
|
e319e4db24538f8960eaf066e43067ca8a8afc96
|
/v2/Value/util/TestValue.cpp
|
9266d5350b32e2fc2adbcea3341a3be967ce92eb
|
[
"NCSA",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
arunkumarcea/ahir
|
5cf4327e387372882a1222997e7b8affec9737a5
|
3a242f4edb96b2916e697783f800037198df2361
|
refs/heads/master
| 2021-01-16T19:56:24.366786
| 2014-05-21T05:13:46
| 2014-05-21T05:13:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,739
|
cpp
|
TestValue.cpp
|
#include <Value.hpp>
using namespace std;
using namespace _base_value_;
int main()
{
Unsigned b(4,"_b1111");
Unsigned a(4,"_b0000");
cout << "Word-size is " << __WORD_SIZE__ << endl;
cout << a.To_String() << " a" << endl << b.To_String() << " b" << endl;
a.Add(b);
cout << a.To_String() << " a = a + b " << endl;
a.Subtract(b);
cout << a.To_String() << " a = a - b " << endl;
a.Multiply(b);
cout << a.To_String() << " a = a*b " << endl;
a.Divide(b);
cout << a.To_String() << " a = a/b " << endl;
a.Concatenate(b);
cout << a.To_String() << " a = Concatenate(a,b) " << endl;
a.Concatenate(b);
cout << a.To_String() << " a = Concatenate(a,b) " << endl;
a.Concatenate(b);
cout << a.To_String() <<" a = Concatenate(a,b) " << endl;
a.Concatenate(b);
cout << a.To_String() <<" a = Concatenate(a,b) " << endl;
a.Concatenate(b);
cout << a.To_String() <<" a = Concatenate(a,b) " << endl;
a.Concatenate(b);
cout << a.To_String() <<" a = Concatenate(a,b) " << endl;
a.Concatenate(b);
cout << a.To_String() <<" a = Concatenate(a,b) " << endl;
a.Concatenate(b);
cout << a.To_String() <<" a = Concatenate(a,b) " << endl;
a.Concatenate(b);
cout << a.To_String() <<" a = Concatenate(a,b) " << endl;
a.Concatenate(b);
cout << a.To_String() <<" a = Concatenate(a,b) " << endl;
a.Concatenate(b);
cout << a.To_String() <<" a = Concatenate(a,b) " << endl;
a.Concatenate(b);
cout << a.To_String() <<" a = Concatenate(a,b) " << endl;
a.Concatenate(b);
cout << a.To_String() <<" a = Concatenate(a,b) " << endl;
a.Concatenate(b);
cout << a.To_String() <<" a = Concatenate(a,b) " << " width " << a._width << endl;
a.Concatenate(b);
cout << a.To_String() <<" a = Concatenate(a,b) " << " width " << a._width << endl;
a.Concatenate(b);
cout << a.To_String() <<" a = Concatenate(a,b) " << " width " << a._width << endl;
Unsigned one_val(68);
one_val.Increment();
a.Add(one_val);
cout << a.To_String() << " a = a + 1" << endl;
a.Decrement();
cout << a.To_String() << " a = a - 1 " << endl;
a.Rotate_Left();
cout << a.To_String() << " a = ROL(a) " << endl;
a.Rotate_Right();
cout << a.To_String() << " a = ROR(a)" << endl;
a.Rotate_Right();
cout << a.To_String() << " a = ROR(a)" << endl;
Signed sa (a._width);
sa.Assign(a);
sa.Shift_Right();
cout << sa.To_String() << " sa = SHRA(a)" << endl;
Float c(8,23,"2.5");
Float d(8,23,"5.0");
c.Add(d);
cout << c.To_String() << endl;
c.Subtract(d);
cout << c.To_String() << endl;
c.Multiply(d);
cout << c.To_String() << endl;
c.Divide(d);
cout << c.To_String() << endl;
Float e(11,52,"247.5");
c.Assign(e);
cout << c.To_String() << endl;
return(1);
}
|
7a8a91d28bc567842483140848718c0943b66464
|
6d9cf8409a48d9b394d68ad731cd4af22dd5b671
|
/Classes/Base/POPTTonic2StrSingleton.h
|
42195efa1a42808a53aafbd2518497b32ffb3024
|
[] |
no_license
|
allen4z/poputar
|
cfe9b36698aa648438973d161cc4dd228ca85e2c
|
b8186eb6bdc8f2c10903dd28b5ba34bac2680c7a
|
refs/heads/master
| 2021-01-13T04:58:39.572594
| 2015-08-23T10:04:45
| 2015-08-23T10:04:45
| 32,199,098
| 1
| 0
| null | 2015-03-14T06:28:25
| 2015-03-14T06:28:25
| null |
UTF-8
|
C++
| false
| false
| 690
|
h
|
POPTTonic2StrSingleton.h
|
//
// POPTTonic2Str.h
// poputar
//
// Created by allen on 15-5-20.
//
//
#ifndef __poputar__POPTTonic2StrSingleton__
#define __poputar__POPTTonic2StrSingleton__
#include <stdio.h>
#include "Singleton.h"
using namespace std;
class POPTTonic2StrSingleton :public Singleton<POPTTonic2StrSingleton>{
private:
map<string,string> tonic2StrMap;
public:
POPTTonic2StrSingleton();
~POPTTonic2StrSingleton();
//加载主音弦位信息
void loadCurrentTonic(string type);
void unLoadTonic();
string getStrInfo(string note);
};
#define tonic2StrSingleton POPTTonic2StrSingleton::instance()
#endif /* defined(__poputar__POPTTonic2Str__) */
|
407e6774c2720f07984e0dcb375ae981ea8ecccc
|
b3ea96eb589d81ab9ceb21dbac9cd9b05db0dc2a
|
/All_sorting_algos.cpp
|
8da415bd1e77dc9df8106dde12f52293b20a616f
|
[] |
no_license
|
shivangisrivastava0408/Data-structures-and-Algorithms
|
11c2d4c349b4e76a8aa3dd769b6d9f9901a02f95
|
229b2a670e78b6dafbd806389d713de46c08bc2a
|
refs/heads/master
| 2021-06-30T21:36:41.172058
| 2020-10-01T12:42:48
| 2020-10-01T12:42:48
| 176,687,382
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,653
|
cpp
|
All_sorting_algos.cpp
|
#include <bits/stdc++.h>
using namespace std;
void bubblesort(int arr[], int n){
for(int i=0;i<n-1;i++){
for(int j=0;j<n-i-1;j++){
if(arr[j]>arr[j+1]){
swap(arr[j],arr[j+1]);
}
}
}
}
void selectionsort(int arr[], int n){
int min_ind;
for(int i=0;i<n-1;i++){
min_ind=i;
for(int j=i+1;j<n;j++){
if(arr[j]<arr[i])
min_ind=j;
}
swap(arr[i],arr[min_ind]);
}
}
void insertionsort(int arr[], int n){
int key,j;
for(int i=1;i<n;i++){
key=arr[i];
j=i-1;
while(j>=0 && arr[j]>key){
arr[j+1]=arr[j];
j-=1;
}
arr[j+1]=key;
}
}
void merge(int arr[], int l, int r, int mid){
int n1,n2;
n1=mid-l+1;
n2=r-mid;
int arr1[n1],arr2[n2];
int i,j;
for(i=0;i<n1;i++)
arr1[i]=arr[l+i];
for(i=0;i<n2;i++)
arr2[i]=arr[mid+1+i];
i=0,j=0;
int k=l;
while(i<n1 && j<n2){
if(arr1[i]<=arr2[j]){
arr[k]=arr1[i];
i++;
}
else{
arr[k]=arr2[j];
j++;
}
k++;
}
while(i<n1){
arr[k]=arr1[i];
i++;
k++;
}
while(j<n2){
arr[k]=arr2[j];
j++;
k++;
}
}
void mergesort(int arr[], int l, int r){
if(l<r){
int mid = l+(r-l)/2;
mergesort(arr,l,mid);
mergesort(arr,mid+1,r);
merge(arr,l,r, mid);
}
}
int partition(int arr[], int low, int high){
//ELEMENT AT THE LAST INDEX IS CHOSEN AS PIVOT
/*int pivot=arr[high];
int j=low-1;
for(int i=low;i<high;i++){
if(arr[i]<pivot){
j+=1;
swap(arr[i],arr[j]);
}
}
j+=1;
swap(arr[j],arr[high]);
return j;*/
//ELEMENT AT THE FIRST INDEX IS CHOSEN AS PIVOT
int pivot=arr[low];
int j=low+1;
for(int i=low+1;i<=high;i++){
if(arr[i]<pivot){
swap(arr[i],arr[j]);
j+=1;
}
}
j-=1;
swap(arr[j],arr[low]);
return j;
}
void quicksort(int arr[], int l,int r){
if(l<r){
int pi=partition(arr,l,r);
quicksort(arr,l,pi-1);
quicksort(arr,pi+1,r);
}
}
void heapify(int arr[], int n, int i){
int largest=i;
int l=2*i+1;
int r=2*i+2;
if(l<n && arr[largest]<arr[l]){
largest=l;
}
if(r<n && arr[largest]<arr[r]){
largest=r;
}
if(largest!=i){
swap(arr[largest],arr[i]);
heapify(arr,n,largest);
}
}
void heapsort(int arr[], int n){
int i;
for(i=n/2-1;i>=0;i--){
heapify(arr,n,i);
}
for(i=n-1;i>=0;i--){
swap(arr[i],arr[0]);
heapify(arr,i,0);
}
}
void printarr(int arr[], int n){
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
int main() {
int arr0[] = {55,44,3,2,12,65,77,48,37,56};
int n = sizeof(arr0)/sizeof(arr0[0]);
bubblesort(arr0,n);
printarr(arr0,n);
int arr1[] = {88,77,66,55,44,33,22,11,1};
int m = sizeof(arr1)/sizeof(arr1[0]);
selectionsort(arr1, m);
printarr(arr1,m);
int arr2[] = {30,27,24,21,18,15,12,9,6,3,1};
int p = sizeof(arr2)/sizeof(arr2[0]);
insertionsort(arr2,p);
printarr(arr2,p);
int arr3[] = {40,36,32,28,24,20,16,12,8,4,1};
int q = sizeof(arr3)/sizeof(arr3[0]);
mergesort(arr3,0,q-1);
printarr(arr3,q);
int arr4[] = {50,45,30,35,30,25,20,15,10,5,1};
int r = sizeof(arr4)/sizeof(arr4[0]);
quicksort(arr4,0,r-1);
printarr(arr4,r);
int arr5[] = {12,11,13,5,6,7};
int s = sizeof(arr5)/sizeof(arr5[0]);
heapsort(arr5,s);
printarr(arr5,s);
return 0;
}
|
ffc7a4138c6f95659c03c1aa49519fb538e14f4d
|
3a39b41a8f76d7d51b48be3c956a357cc183ffae
|
/Codeforces/EducationalRound/E69_D2/D.cpp
|
0c99d2af7f7bf57accdce82ecda76890a83cdddb
|
[] |
no_license
|
Acka1357/ProblemSolving
|
411facce03d6bf7fd4597dfe99ef58eb7724ac65
|
17ef7606af8386fbd8ecefcc490a336998a90b86
|
refs/heads/master
| 2020-05-05T10:27:43.356584
| 2019-11-07T06:23:11
| 2019-11-07T06:23:11
| 179,933,949
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 698
|
cpp
|
D.cpp
|
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cstring>
#include <queue>
#include <utility>
#include <functional>
#include <cstdlib>
#include <cmath>
#include <string>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
ll a[300001], vmin[300001];
int main()
{
ll N, M, K; scanf("%lld %lld %lld", &N, &M, &K);
for(int i = 1; i <= N; i++)
scanf("%lld", &a[i]);
memset(vmin, 0x3f, sizeof(vmin));
ll ans = 0, cum = 0;
for(int i = 1; i <= N; i++){
vmin[i % M] = min(vmin[i % M] + K, cum + K);
for(int j = 0; j < M; j++)
ans = max(ans, cum + a[i] - vmin[j]);
ans = max(ans, a[i] - K);
cum += a[i];
}
printf("%lld\n", ans);
return 0;
}
|
731236ec91fa21f09bf96ae00dfcc09f984292a8
|
ccf99275fbf55f743be8c8b67a82109ffdc030d0
|
/Game/Scenes/TestScene.cpp
|
cb8cdc4f06767f53f5566d3fbb69bba523162498
|
[] |
no_license
|
MrScottOliver/canned-engine
|
d4bb60af9d1f0127a31363f770fefa3c6bb8ab16
|
eefd7f29187ff597f494b0019cd5c1cc03548d60
|
refs/heads/master
| 2021-01-17T08:16:45.699384
| 2018-07-19T16:26:47
| 2018-07-19T16:26:47
| 11,161,613
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,518
|
cpp
|
TestScene.cpp
|
#include "Game/Scenes/TestScene.h"
#include "System/System.h"
bool regTestScene = RegisterScene<TestScene>( "TestScene" );
//Globals for scene variables?
//Would multiple instances of this scene share global variables?
TestScene::TestScene( System &s ) : IScene( s, "TestScene" ),
keys( input ),
logiMouse( input ),
player1( input ),
test1( input ),
transforms(),
meshes( s.graphics ),
sprites( s.graphics, transforms ),
animatedSprites( s.graphics, transforms ),
AddTransform( transforms ),
GetTransform( transforms ),
AddSprite( sprites ),
GetSprite( sprites ),
AddAnimatedSprite( animatedSprites ),
GetAnimatedSprite( animatedSprites )
{
test1.AddInput( std::bind( &Keyboard::IsPressed, &keys, Keyboard::Keys::LEFT_CONTROL ) );
test1.AddInput( std::bind( &Keyboard::WentUp, &keys, Keyboard::Keys::LEFT_ALT ) );
engine.AddProcess( &transforms, Priority::UPDATE );
engine.AddProcess( &meshes, Priority::RENDER );
engine.AddProcess( &sprites, Priority::RENDER );
engine.AddProcess( &animatedSprites, Priority::RENDER );
}
TestScene::~TestScene( void )
{
Unload();
}
void TestScene::Load( void )
{
TRACE( "Loading" );
sound.LoadSoundSample( "w:/game/sounds/drumloop.wav", "drumloop" );
graphics.LoadTexture( "w:/game/textures/qMark.bmp", "MarioQuestionBlockTexture" );
graphics.LoadTexture( "w:/game/textures/uvtemplate.bmp", "uvtest" );
graphics.LoadTexture( "w:/game/textures/transparency_test.png", "fucknope" );
//Always set state and report
State = SceneState::INIT;
loaded = true;
}
void TestScene::Start( void )
{
TRACE( "TestScene Start method!" );
Entity& qMark = entityManager.New( "qMark" );
//TODO: Need to add delete* methods to remove components
AddTransform( qMark );
AddSprite( qMark, "MarioQuestionBlockTexture");
GetTransform( qMark ).translation.z = 5;
GetTransform( qMark ).scale.x = 512;
GetTransform( qMark ).scale.y = 512;
GetSprite( qMark ).TextureDimensions.right = 2.0f;
GetSprite( qMark ).TextureDimensions.bottom = 2.0f;
//TESTING ANIMATED SPRITES//
Entity& animTest = entityManager.New( "animTest" );
AddTransform( animTest );
AddAnimatedSprite( animTest );
Transform& animTransform = GetTransform( animTest );
animTransform.translation.x = -300;
animTransform.translation.y = -200;
animTransform.translation.z = 6;
animTransform.scale.x = 100;
animTransform.scale.y = 100;
Animation2D testAnimation( "test" );
Frame one = animatedSprites.NewFrame( EngineDuration( std::chrono::seconds( 1 ) ), "uvtest" );
Frame two = animatedSprites.NewFrame( EngineDuration( std::chrono::seconds( 1 ) ), "uvtest" );
Frame three = animatedSprites.NewFrame( EngineDuration( std::chrono::seconds( 1 ) ), "uvtest" );
one.TextureDimensions.right = 0.1f;
one.TextureDimensions.bottom = 0.1f;
two.TextureDimensions.left = 0.1f;
two.TextureDimensions.right = 0.2f;
two.TextureDimensions.bottom = 0.1f;
three.TextureDimensions.left = 0.2f;
three.TextureDimensions.right = 0.3f;
three.TextureDimensions.bottom = 0.1f;
testAnimation.AddFrame( one );
testAnimation.AddFrame( two );
testAnimation.AddFrame( three );
GetAnimatedSprite( animTest ).AddAnimation( testAnimation );
GetAnimatedSprite( animTest ).PlayAnimation( "test", Animation2D::PlaybackMode::LOOP );
//TRANSPARENCY TEST//
Entity& tTest = entityManager.New( "tTest" );
AddTransform( tTest );
AddSprite( tTest, "fucknope" );
GetTransform( tTest ).scale.x = 79;
GetTransform( tTest ).scale.y = 103;
GetTransform( tTest ).translation.z = 4;
State = SceneState::UPDATE;
}
void TestScene::OnLost( void )
{
if( !lost )
{
TRACE( "Lost, releasing resources" );
lost = true;
}
}
void TestScene::OnRecover( void )
{
if( lost )
{
TRACE( "Reloading" );
lost = false;
}
}
void TestScene::Unload( void )
{
bool Playing = true;
if( channel )
{
channel->isPlaying( &Playing );
if( Playing ){ sound.ErrorCheck( channel->setLoopCount( 0 ), "Main: Stopping sound" ); }
}
//Always set state and report
loaded = false;
}
//TODO: Add "Start" init method to iScene - This will hold init code separate to Load method, which could be called asynchronously
//TODO: Add "End" clean-up method(?)
void TestScene::Update( void )
{
engine.UpdateProcesses( system.time.DeltaTimeActual(), Priority::UPDATE );
//TODO: Add overload that accepts just string, that will then do the lookup for you?
GetTransform( entityManager["qMark"] ).localRotation.z -= ( 0.01 );
if( test1.IsChordPressed() )
{
TRACE("Chord Pressed");
// bool Playing = false;
// bool Paused = false;
// if( channel )
// {
// channel->isPlaying( &Playing );
// channel->getPaused( &Paused );
// if( Playing ){ sound.ErrorCheck( channel->setLoopCount( 0 ), "Main: Stopping sound" ); }
// else{ sound.ErrorCheck( channel->setLoopCount( 1 ), "Main: Starting sound" ); }
// }
}
}
void TestScene::PreRender( void )
{
graphics.Device()->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB( 150, 150, 150 ), 1.0f, 0 );
graphics.Device()->BeginScene();
//Should this be called before the scene begins?
engine.UpdateProcesses( system.time.DeltaTimeActual(), Priority::PRE_RENDER );
}
void TestScene::PostRender( void )
{
engine.UpdateProcesses( system.time.DeltaTimeActual(), Priority::POST_RENDER );
graphics.Device()->EndScene();
graphics.Device()->Present( NULL, NULL, NULL, NULL );
}
void TestScene::End( void )
{
}
|
66a76aeb247ab0dfce1a196929e3032d8a7653af
|
aad28fa1140e713c8591db5a383ac5f6605f743b
|
/192 Кто получит автомат/Кто получит автомат.cpp
|
9696da0c5cc5205303ad41c3baa100c4f9f0ed1f
|
[] |
no_license
|
DaniilMuntyan/Solutions_e-olymp
|
d7ad45357d4f999c853efefcd47c39bc17e33664
|
7a318572e13f2e6103a2ade49c8ce9c5210caad9
|
refs/heads/master
| 2021-02-28T15:22:58.506994
| 2020-03-07T21:42:50
| 2020-03-07T21:42:50
| 245,708,666
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 388
|
cpp
|
Кто получит автомат.cpp
|
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n;
cin >> n;
int a[10000];
int sum = 0;
int i;
double av;
for(i = 0; i < n; i++)
{
cin >> a[i];
sum += a[i];
}
int k = 0;
av = sum / i;
for(i = 0; i < n; i++)
{
if(a[i] > av)
{
k++;
}
}
cout << k << endl;
return 0;
}
|
49de38f6c6f9d5f4bb78b0ebbb2f6b6d44986e09
|
8a1512191c8f213fa1055cd1b12a28c834d17466
|
/game/midistre.cpp
|
59f167305e50b9b0883fc0e97cd20571090cc0d3
|
[] |
no_license
|
jstasiak/polanie-src
|
882721a6896ba67731e84e488a0252de3ca7e92a
|
dc679cbd1add67ba7f3da59ba24ba9d6c560ed1b
|
refs/heads/master
| 2023-05-31T22:18:28.362896
| 2020-02-18T16:26:25
| 2020-02-18T16:26:25
| 169,010,720
| 10
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,657
|
cpp
|
midistre.cpp
|
#include "midistre.h"
void MIDIstream::SetData(BYTE *data, WORD len)
// ustawia adres i długość bufora z danymi MIDI
{
databuf = data;
datalen = len;
datapos = 0;
}
long MIDIstream::ReadVarLen()
// odczytuje liczbę w postaci o zmiennej długości
{
long value;
BYTE c;
if ((value = databuf[datapos++]) & 0x80) {
value &= 0x7F;
do {
value = (value << 7) + ((c = databuf[datapos++]) & 0x7F);
} while (c & 0x80);
}
return value;
}
BYTE MIDIstream::GetAndSkip()
// pobiera kolejny bajt danych omijając
// ew. komunikaty czasowe
{
while (databuf[datapos++] >= 0xF8)
;
return databuf[datapos - 1];
}
void MIDIstream::DoMessage()
// pobiera kolejny komunikat i wywołuje
// odpowiednią dla niego funkcję
{
BYTE B, C, D;
WORD len;
if (datapos >= datalen) {
TheEnd();
return;
}
B = databuf[datapos++];
if (B < 0x80) // running status byte; B>=0 zawsze bo jest unsigned
{
B = lastmsg;
datapos--;
}
lastmsg = B;
switch (B >> 4) {
case 0x8: // wyłącz nutę
C = GetAndSkip();
D = GetAndSkip();
Msg8(B & 15, C, D);
break;
case 0x9: // włącz nutę
C = GetAndSkip();
D = GetAndSkip();
Msg9(B & 15, C, D);
break;
case 0xA: // nacisk klawisza
C = GetAndSkip();
D = GetAndSkip();
MsgA(B & 15, C, D);
break;
case 0xB: // ustawienie kontrolera
C = GetAndSkip();
D = GetAndSkip();
MsgB(B & 15, C, D);
break;
case 0xE: // zmiana wys. dźwięku
C = GetAndSkip();
D = GetAndSkip();
MsgE(B & 15, C, D);
break;
case 0xC: // zmiana programu
MsgC(B & 15, GetAndSkip());
break;
case 0xD: // głośność
MsgD(B & 15, GetAndSkip());
break;
default:
switch (B) {
case 0xF0: // system exclusive F0
len = ReadVarLen();
SysExF0(databuf + datapos, len);
datapos += len;
break;
case 0xF1:
case 0xF3: // komunikaty F1 i F3
Common1Byte(B, GetAndSkip());
break;
case 0xF2: // pozycja melodii
C = GetAndSkip();
D = GetAndSkip();
Common2Bytes(B, C, D);
break;
case 0xF4:
case 0xF5:
case 0xF6:
Common0Bytes(B);
break;
case 0xF7: // system exclusive F7
len = ReadVarLen();
SysExF7(databuf + datapos, len);
datapos += len;
break;
case 0xFF: // metazdarzenie
C = databuf[datapos++];
len = ReadVarLen();
MetaEvent(C, databuf + datapos, len);
datapos += len;
break;
default: // komunikaty czasowe
RealTimeMsg(B);
}
}
}
void MIDIstream::MetaEvent(BYTE type, BYTE *data, WORD len) {
if (type == 0x2F)
TheEnd();
}
|
fac4e77616f2a7dd5938b93d38124fb4ee2df8da
|
0f054d3440d94f27bc61c2b69c46d250fd1400a8
|
/cpp/mempool/pool.h
|
9d78dadcee5e22da2e21082fbbc17d9f2d2a5dc7
|
[] |
no_license
|
Tomerder/Cpp
|
db73f34e58ff36e145af619f03c2f4d19d44dc5d
|
18bfef5a571a74ea44e480bd085b4b789839f90d
|
refs/heads/master
| 2020-04-13T21:37:06.400580
| 2018-12-29T02:35:50
| 2018-12-29T02:35:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,532
|
h
|
pool.h
|
/**************************************************************************************
Author : Tomer Dery
Creation date : 31.12.13
Date last modified : 31.12.13 - 1.1.14
Description : memory pool
***************************************************************************************/
#ifndef __MEM_POOL_H__
#define __MEM_POOL_H__
#include<list>
#include "mem.h"
#include "page.h"
using namespace std;
class MemPool_t : public Memory_t {
private:
list<MemPage_t*> m_pages;
//int m_pagesCapacity; // managed by static default size at page class
//will never be use
MemPool_t(const MemPool_t& _pool);
MemPool_t& operator=(const MemPool_t& _pool);
/*----------------------private methods----------------*/
/*creates new page add it to list and returns it*/
MemPage_t* PageCreate();
/*return page and pos in age acording to pool pos*/
MemPage_t* GetPageOfPos(int _pos ,int* _posCounter);
/*returns next on list*/
MemPage_t* getNextPage(MemPage_t* _memPage);
/*returns next page to write to - if next page is STUB - creates new page add it to list and return it*/
MemPage_t* getNextPageToWriteTo(MemPage_t* _memPage);
/*recursively write to next page - creates new pages when out of space */
void writeRec(const void* _dataToWrite, int _lenLeftToWrite , int _lenWriten , MemPage_t* _pageToWrtTo );
/*recursively read from next pages*/
void readRec(void* _dataToRead, int _lenLeftToRead , int _lenWasRead , MemPage_t* _pageToReadFrom );
public:
MemPool_t();
virtual ~MemPool_t();
/*writes _len bytes from _dataToWrite to cur position of pool , cur position advances by _len, and inc size of pool if nessesery*/
virtual bool write(const void* _dataToWrite, int _len) ;
virtual bool write(const void* _dataToWrite, int _len, int _pos) ;
/*will read _len bytes from _pos into _buffer ,advances to the point after the part that has been read*/
virtual bool read(void* _buffer, int _len ) ;
virtual bool read(void* _buffer, int _len, int _pos) ;
void setDefaultPageCapcity(int _newDefaultCapacity) const { MemPage_t::setDefaultPageCapcity(_newDefaultCapacity); }
int getDefaultPageCapcity() const { return MemPage_t::getDefaultPageCapcity(); }
/*disabled - pages will be created on default size only(static DM of page)*/
//MemPool_t(int _defaultPageSize);
//int getPagesCapacity() const {return m_pagesCapacity;}
//void setPagesCapacity(int _newPagesCapacity) { m_pagesCapacity = _newPagesCapacity; }
};
#endif /*__MEM_POOL_H__*/
|
41468b00d915e45de2583ad64eb765607f62a51d
|
aa045c238793aa63a2db016bace61e12171a035c
|
/src/groups/md/mdmem/mdmem_testallocator.cpp
|
d3b79390dda0044a4e198331346ab17a2a08d4db
|
[] |
no_license
|
mvdsanden/mdev
|
ae5bc29f9af52615d9d60daeb49ba3dde9d8f527
|
e8b15baa1961f5ca65eabdd977b9259061a18ae4
|
refs/heads/master
| 2020-05-02T07:04:50.870566
| 2019-03-26T15:30:50
| 2019-03-26T15:30:50
| 177,809,125
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 115
|
cpp
|
mdmem_testallocator.cpp
|
// mdmem_testallocator.cpp -*-c++-*-
#include <mdmem_testallocator.h>
|
407c0428d2e6a5eb47c8132c30ab34557956ed3d
|
fbfd3ec0f89101f4e7403854b0ebbeade1d06c1d
|
/Unreal Engine Full C++/ShootTheMap/Source/ShootTheMap/Public/Weapons/STMProjectile.h
|
fb396442969ab62762437b882218e034cd7bb55f
|
[] |
no_license
|
markveligod/CoursesUnrealEngine
|
b1a14692f2d74d15a3911df4933b6f7588149f3d
|
3939882f35a81a47a7f8b8dd324f566a141e16dd
|
refs/heads/main
| 2023-05-30T23:24:02.200425
| 2021-06-16T16:19:20
| 2021-06-16T16:19:20
| 320,260,105
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,345
|
h
|
STMProjectile.h
|
// ShootTheMap
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "STMProjectile.generated.h"
class USphereComponent;
class UProjectileMovementComponent;
class USTMWeaponVFXComponent;
UCLASS()
class SHOOTTHEMAP_API ASTMProjectile : public AActor
{
GENERATED_BODY()
public:
ASTMProjectile();
void SetShotDirection(const FVector Direction);
protected:
UPROPERTY(VisibleDefaultsOnly, Category = "Weapon")
USphereComponent *CollisionComponent;
UPROPERTY(VisibleDefaultsOnly, Category = "Weapon")
UProjectileMovementComponent *MovementComponent;
UPROPERTY(EditDefaultsOnly, Category = "Weapon")
float DamageRadius = 200.f;
UPROPERTY(EditDefaultsOnly, Category = "Weapon")
float DamageAmount = 50.f;
UPROPERTY(EditDefaultsOnly, Category = "Weapon")
float LifeSeconds = 5.f;
UPROPERTY(EditDefaultsOnly, Category = "Weapon")
bool DoFullDamage = false;
UPROPERTY(VisibleAnyWhere, Category = "VFX")
USTMWeaponVFXComponent *WeaponVFXComponent;
virtual void BeginPlay() override;
private:
FVector ShootDirection;
UFUNCTION()
void OnProjectileHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit);
AController *GetController() const;
};
|
e6869b61754663f375904a062c91a8be70702bfe
|
6db9478ab57690420b2aa98b450d346f7a9f3b7d
|
/z_unclassified/2953.cpp
|
da515c87bd13c914feb4e2d17d9cf237ed052a61
|
[] |
no_license
|
siosio34/AlgorithmStudy
|
d23266e0d4576a3aab123aee7b571021ec619009
|
b5626a0e4eb14f9553fe48aacacb1696a927c740
|
refs/heads/master
| 2020-03-19T09:15:13.167353
| 2019-05-22T13:50:41
| 2019-05-22T13:50:41
| 136,272,154
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 353
|
cpp
|
2953.cpp
|
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int maxPoint = 0;
int winIndex = 0;
int tmp;
for(int i = 0 ; i <5 ; i++) {
int sum = 0;
for(int j = 0 ; j < 4 ; j++) {
cin >> tmp;
sum += tmp;
if(maxPoint < sum ) {
maxPoint = sum;
winIndex = i;
}
}
}
cout << winIndex + 1 << " " << maxPoint;
}
|
cca0c3a6e70be09c89542f72f525391b28db759a
|
102988c689f70b66878049ebe695930ba1f4041e
|
/real/src/Cluster.cpp
|
090bf1ed0668157aed273486811535bfcad75b6f
|
[] |
no_license
|
ElitCoder/Kobla-2D-Server
|
cb80471d14a1fb3d00ddf54952bc6b2d1292c513
|
586dc08589d7749fc203ea774f73cfbbb9b9032a
|
refs/heads/master
| 2021-04-15T04:48:09.094422
| 2020-03-01T20:29:34
| 2020-03-01T20:29:34
| 126,654,041
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,420
|
cpp
|
Cluster.cpp
|
#include <fstream>
#include "Main.h"
#include "Cluster.h"
#include "Handle.h"
#include "Item.h"
#include "BufferCheck.h"
using namespace std;
extern vector<Player*> pvector;
extern vector<NPC*> npcs;
extern bool debugs;
int playPuhId = 1;
void Client::CharacterList()
{
if(this->online)
{
std::vector<Player*> te = this->GetCharacterVector();
Packet pak = Packet();
pak.addHeader(0x6);
if(te.size() > 0)
{
pak.addInt(te.size());
for(unsigned int i = 0; i < te.size(); i++)
{
pak.addLongInt(te.at(i)->level);
pak.addLongInt(te.at(i)->power);
pak.addLongInt(te.at(i)->magic);
pak.addLongInt(te.at(i)->agility);
pak.addLongInt(te.at(i)->intt);
pak.addInt(te.at(i)->job);
pak.addString(te.at(i)->name);
pak.addInt(2);
pak.addInt(te.at(i)->slot);
}
}
else
pak.addInt(0);
pak.ready();
this->AddPacket(pak, 0);
if(debugs)
log(DEBUG, "Character list: %s %d.\n", this->username.c_str(), te.size());
LD(LOGIN, "Requesting character list: [%s] [%s] [%d].\n", this->username.c_str(), this->password.c_str(), te.size());
}
}
bool Client::SlotFree(int slot)
{
for(unsigned int i = 0; i < pvector.size(); i++)
{
if(strcmp(this->username.c_str(), pvector.at(i)->owner.c_str()) == 0)
{
if(pvector.at(i)->slot == slot)
return false;
}
}
return true;
}
int Client::GetFirstFreeCharacterSlot()
{
int i1 = 0;
int i2 = 0;
int i3 = 0;
for(unsigned int i = 0; i < pvector.size(); i++)
{
if(strcmp(this->username.c_str(), pvector.at(i)->owner.c_str()) == 0)
{
switch(pvector.at(i)->slot)
{
case 1: i1 = 1;
break;
case 2: i2 = 1;
break;
case 3: i3 = 1;
break;
}
}
}
if(i1 == 0)
return 1;
else if(i2 == 0)
return 2;
else if(i3 == 0)
return 3;
return 4;
}
std::vector<Player*> Client::GetCharacterVector()
{
vector<Player*> cp;
Player *p1 = new Player();
Player *p2 = new Player();
Player *p3 = new Player();
for(unsigned int i = 0; i < pvector.size(); i++)
{
if(strcmp(this->username.c_str(), pvector.at(i)->owner.c_str()) == 0)
{
switch(pvector.at(i)->slot)
{
case 1: p1 = pvector.at(i);
break;
case 2: p2 = pvector.at(i);
break;
case 3: p3 = pvector.at(i);
break;
}
}
}
if(strcmp(p1->name.c_str(), "") != 0)
cp.push_back(p1);
else
delete p1;
if(strcmp(p2->name.c_str(), "") != 0)
cp.push_back(p2);
else
delete p2;
if(strcmp(p3->name.c_str(), "") != 0)
cp.push_back(p3);
else
delete p3;
return cp;
}
Player *Client::GetThisPlayer(int id)
{
Player *ret = NULL;
for(unsigned int i = 0; i < pvector.size(); i++)
{
if(strcmp(this->username.c_str(), pvector.at(i)->owner.c_str()) == 0 && pvector.at(i)->slot == id)
{
ret = pvector.at(i);
break;
}
}
return ret;
}
void Client::EditCharacter(int b, char *paks)
{
if(this->online)
{
if(b == 1)
{
int pos = 4;
int res = 3;
string cname = getString(paks, 5, (int)paks[4]);
pos += ((int)paks[4] + 1);
int slots = paks[pos];
pos++;
int job = paks[pos];
pos++;
Class *gc = GetClass(job);
bool doClass = true;
if(gc == NULL)
doClass = false;
else
{
if(gc->disabled)
doClass = false;
}
if(doClass)
{
if(this->GetCharacterVector().size() < 3)
{
if(slots > 0 && slots <= 3)
{
if(CreateOK(cname))
{
if(AllowLetters(cname))
{
if(cname.length() <= 16)
{
if(cname.length() >= 3)
{
ofstream r;
r.open("Data/Character/CharacterIndex.txt", fstream::app);
if(!r)
{
log(ERR, "[void Client::EditCharacter(int,char*)] [Can not open file] [%s]\n", "Data/Character/CharacterIndex.txt");
r.close();
}
else
{
int kslot = slots;
if(!this->SlotFree(slots))
kslot = this->GetFirstFreeCharacterSlot();
r << this->username.c_str() << " " << kslot << endl;
r.close();
Player *play = new Player();
play->power = 2;
play->x = (float)mPlayerStartX;
play->y = (float)mPlayerStartY;
play->exp = 0;
play->magic = 2;
play->powerpoints = 0;
play->pkpoints = 0;
play->access = 50;
play->mapId = GetMap(mPlayerStartMap);
play->level = 1;
play->slot = kslot;
play->agility = 2;
play->job = job;
play->owner = this->username;
play->name = cname;
//strcpy(play->owner, this->username.c_str());
//strcpy(play->name, cname.c_str());
play->setId(playPuhId);
playPuhId += 1;
if(play->x > play->mapId->xSize || play->x < 0)
play->x = (float)(play->mapId->xSize / 2);
if(play->y > play->mapId->ySize || play->y < 0)
play->y = (float)(play->mapId->ySize / 2);
for(unsigned int i = 0; i < gc->items.size(); i++)
{
Item *stru = GetItemById(gc->items.at(i).id);
if(stru != NULL)
{
Item *item = new Item();
*item = *stru;
item->stack = gc->items.at(i).stack;
item->id = gc->items.at(i).id;
if(gc->items.at(i).eq)
play->eq[gc->items.at(i).slot - 1] = item;
else
play->inv[gc->items.at(i).slot - 1] = item;
}
else
log(ERR, "[void Client::EditCharacter(int,char*)] [Could not find item] [%d]\n", 3);
}
CheckSkills(play);
CheckClassSkills(play);
pvector.push_back(play);
//char slots[10];
//_itoa_s(play->slot, slots, 10);
string charp = "Data/Character/";
charp += play->owner;
charp += to_string(play->slot);
charp += ".txt";
ofstream o(charp.c_str());
o << play->name << endl << play->level << endl << play->power << endl << play->agility << endl << play->x << endl << play->y << endl << play->mapId->id << endl << play->exp << endl << play->magic << endl << play->powerpoints << endl << play->pkpoints << endl << play->access << endl;
/*<< 1 << endl << "2 0 0" << endl << 0 << endl << 0 << endl << 3 << endl << "1 91 1 0" << endl << "12 92 1 0" << endl << "13 92 1 0" << endl;*//* << 1 << endl;*/
int num = 1;
for(int i = 0; i < 25; i++)
{
if(play->inv[i] != NULL)
num++;
}
o << num << endl;
o << "2 0 0" << endl;
for(int i = 0; i < 25; i++)
{
if(play->inv[i] != NULL)
o << play->inv[i]->id << " " << (i + 1) << " " << play->inv[i]->stack << endl;
}
o << 0 << endl << 0 << endl << 0 << endl;
num = 0;
for(int i = 0; i < 4; i++)
{
if(play->eq[i] != NULL)
num++;
}
o << num << endl;
for(int i = 0; i < 4; i++)
{
if(play->eq[i] != NULL)
o << play->eq[i]->id << " " << (i + 1) << endl;
}
o << "2" << endl << "0" << endl << play->job << endl;
/*"3 1" << endl << "2" << endl << "0" << endl;*/
o.close();
res = 1;
LD(LOGIN, "Create character: [%s] [%s] [Name: %s].\n", this->username.c_str(), this->password.c_str(), play->name);
}
}
else
res = 6;
}
else
res = 5;
}
else
res = 4;
}
else
res = 2;
}
}
}
else
res = 7;
switch(res)
{
case 1: PlayerLog("[Create character] [%s] [Accepted] [%d]\n", cname.c_str(), slots);
break;
case 2: PlayerLog("[Create character] [%s] [Name already taken]\n", cname.c_str());
break;
case 3: PlayerLog("[Create character] [%s] [Already got 3 characters]\n", cname.c_str());
break;
case 4: PlayerLog("[Create character] [%s] [Not allowed letters]\n", cname.c_str());
break;
case 5: PlayerLog("[Create character] [%s] [Name too long]\n", cname.c_str());
break;
case 6: PlayerLog("[Create character] [%s] [Name too short]\n", cname.c_str());
break;
case 7: PlayerLog("[Create character] [%s] [Class disabled] [%d]\n", cname.c_str(), job);
}
Packet pak = Packet();
pak.addHeader(0x7);
pak.addInt(res);
pak.ready();
this->AddPacket(pak, 0);
}
else if(b == 2)
{
int res = 2;
int pos = 4;
string dname = getString(paks, (pos + 1), (int)paks[pos]);
pos += ((int)paks[pos] + 1);
string passn = getString(paks, (pos + 1), (int)paks[pos]);
if(this->GetCharacterVector().size() > 0)
{
if(strcmp(passn.c_str(), this->password.c_str()) == 0)
{
if(!CreateOK(dname))
{
string slots = to_string(DeleteSlot((char*)dname.c_str()));
//char slots[10];
//_itoa_s(DeleteSlot((char*)dname.c_str()), slots, 10, 10);
for(unsigned int i = 0; i < pvector.size(); i++)
{
if(strcmp(pvector.at(i)->name.c_str(), dname.c_str()) == 0)
{
for(unsigned int y = 0; y < pvector.size(); y++)
{
if(pvector.at(y)->getId() == pvector.at(i)->getId())
continue;
for(unsigned int z = 0; z < pvector.at(y)->friends.size(); z++)
{
if(strcmp(pvector.at(y)->friends.at(z).name.c_str(), pvector.at(i)->name.c_str()) == 0)
{
Client *plas = GetClientByPlayerName(pvector.at(y)->name.c_str());
if(plas == NULL)
pvector.at(y)->friends.erase(pvector.at(y)->friends.begin() + z);
else
{
plas->p->friends.erase(plas->p->friends.begin() + z);
Packet pak2 = Packet();
pak2.addHeader(0x0D);
pak2.addInt(2);
pak2.addString(pvector.at(i)->name);
pak2.ready();
plas->AddPacket(pak2, 0);
}
break;
}
}
}
delete pvector.at(i);
pvector.erase((pvector.begin() + i));
break;
}
}
string ds = "Data/Character/CharacterIndex.txt";
ofstream o(ds.c_str());
if(!o)
log(ERR, "[void Client::EditCharacter(int,char*)] [Unable to open file] [%s]\n", ds.c_str());
else
{
for(unsigned int i = 0; i < pvector.size(); i++)
o << pvector.at(i)->owner << " " << pvector.at(i)->slot << endl;
}
o.close();
string charp = "Data/Character/";
charp += this->username.c_str();
charp += slots;
charp += ".txt";
remove(charp.c_str());
res = 1;
LD(LOGIN, "Remove character: [%s] [%s] [Name: %s].\n", this->username.c_str(), this->password.c_str(), dname.c_str());
}
else
res = 3;
}
else
res = 4;
}
switch(res)
{
case 1: PlayerLog("[Delete character] [%s] [Accepted]\n", dname.c_str());
break;
case 2: PlayerLog("[Delete character] [%s] [Access violation]\n", dname.c_str());
break;
case 3: PlayerLog("[Delete character] [%s] [Character does not exist]\n", dname.c_str());
break;
case 4: PlayerLog("[Delete character] [%s] [Password is wrong] [%s]\n", dname.c_str(), passn.c_str());
break;
}
Packet pak = Packet();
pak.addHeader(0x7);
pak.addInt(res);
pak.ready();
this->AddPacket(pak, 0);
}
}
}
bool AllowLetters(std::string name)
{
std::string al = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
unsigned int len = al.length();
bool found = false;
for(unsigned int i = 0; i < name.length(); i++)
{
found = false;
for(unsigned int u = 0; u < len; u++)
{
if(name[i] == al[u])
{
found = true;
break;
}
}
if(!found)
return false;
}
return true;
}
bool CreateOK(std::string name)
{
bool val = true;
for(unsigned int i = 0; i < pvector.size(); i++)
{
if(strcmp(name.c_str(), pvector.at(i)->name.c_str()) == 0)
{
val = false;
break;
}
}
if(val)
{
for(unsigned int i = 0; i < npcs.size(); i++)
{
if(strcmp(name.c_str(), npcs.at(i)->name.c_str()) == 0)
{
val = false;
break;
}
}
}
if(val)
{
if(strcmp("System", name.c_str()) == 0)
val = false;
else if(strcmp("Notice", name.c_str()) == 0)
val = false;
}
return val;
}
int DeleteSlot(char *name)
{
int slot = 0;
for(unsigned int i = 0; i < pvector.size(); i++)
{
if(strcmp(name, pvector.at(i)->name.c_str()) == 0)
{
slot = pvector.at(i)->slot;
break;
}
}
return slot;
}
|
d948c7ae57226fb9fb8a800658f8a607690fa6e5
|
c62435fe44f7a0c9df746f530dbdd4edba5dc262
|
/main/test/test0000.cpp
|
444ce344dc13651e2a73428b4787efbfd984e352
|
[] |
no_license
|
mrverdant13/esp-idf-vscode-makefile-template
|
0943872a24bd1a114c286eac35aeffbd4e3d2a77
|
611936a9dad0562a80cbbc3e7a99104fedebfdc8
|
refs/heads/master
| 2022-02-15T07:47:33.457263
| 2019-08-04T22:33:33
| 2019-08-04T22:33:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 238
|
cpp
|
test0000.cpp
|
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
extern "C"
{
void app_main();
}
static const char *TAG = "TEST_0000";
void app_main(void)
{
for (;;)
{
ESP_LOGI(TAG, "Loop");
vTaskDelay(1000);
}
}
|
2a7ed9a483adc23b61286a59dbfc34e20feb6da2
|
179783204e6d145e0db1fef21a7439c018995323
|
/src/lib/util/util_string.cpp
|
0a6ad529203f40e5384f890961124fdf110079b4
|
[
"BSD-3-Clause"
] |
permissive
|
r9y9/sinsy
|
aa65652565ad469db09e4250c58e7d6cff3f5317
|
6a5be094f49285fdf704fdea5083caabdc6a62eb
|
refs/heads/master
| 2022-02-12T19:58:51.586873
| 2022-02-06T01:44:49
| 2022-02-06T01:44:49
| 244,630,165
| 61
| 13
| null | 2022-02-06T01:44:49
| 2020-03-03T12:27:27
|
C++
|
UTF-8
|
C++
| false
| false
| 4,110
|
cpp
|
util_string.cpp
|
/* ----------------------------------------------------------------- */
/* The HMM-Based Singing Voice Synthesis System "Sinsy" */
/* developed by Sinsy Working Group */
/* http://sinsy.sourceforge.net/ */
/* ----------------------------------------------------------------- */
/* */
/* Copyright (c) 2009-2015 Nagoya Institute of Technology */
/* Department of Computer Science */
/* */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or */
/* without modification, are permitted provided that the following */
/* conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright */
/* notice, this list of conditions and the following disclaimer. */
/* - Redistributions in binary form must reproduce the above */
/* copyright notice, this list of conditions and the following */
/* disclaimer in the documentation and/or other materials provided */
/* with the distribution. */
/* - Neither the name of the Sinsy working group nor the names of */
/* its contributors may be used to endorse or promote products */
/* derived from this software without specific prior written */
/* permission. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND */
/* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, */
/* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */
/* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS */
/* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, */
/* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED */
/* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, */
/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY */
/* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */
/* POSSIBILITY OF SUCH DAMAGE. */
/* ----------------------------------------------------------------- */
#include <algorithm>
#include "util_string.h"
namespace sinsy
{
/*!
c is blank character or not
*/
bool isBlank(char c)
{
size_t idx(BLANK_STR.find(c));
if (std::string::npos == idx) {
return false;
}
return true;
}
/*!
cut left and right blanks
*/
std::string& cutBlanks(std::string& str)
{
size_t start(str.find_first_not_of(BLANK_STR));
if (std::string::npos == start) {
str.clear();
return str;
}
size_t end(str.find_last_not_of(BLANK_STR));
size_t sz(end - start + 1);
if ((0 == start) && (str.size() == sz)) {
return str;
}
str = str.substr(start, sz);
return str;
}
/*!
find first blank character
*/
size_t findFirstOfBlank(const std::string& str)
{
return str.find_first_of(BLANK_STR);
}
/*!
find first not blank character
*/
size_t findFirstNotOfBlank(const std::string& str, size_t index)
{
return str.find_first_not_of(BLANK_STR, index);
}
/*!
convert str to lower-case
*/
void toLower(std::string& str)
{
std::transform(str.begin(), str.end(), str.begin(), tolower);
}
/*!
convert str to lower-case
*/
void toUpper(std::string& str)
{
std::transform(str.begin(), str.end(), str.begin(), toupper);
}
}; // namespace sinsy
|
9d61745b26a1b418dc1dd99803feee7f8a24a6ec
|
d05e3f019cce75cde70262774218dbdc2db61281
|
/smallest_string_with_swaps.cpp
|
1bdcf2d00ea9b054f1dc2fe27c1c2c8824138eea
|
[
"MIT"
] |
permissive
|
kshitijanand36/Important-programs
|
a586f89fb0622d49e6f73f2a838a4957b3ed04a8
|
6b5867896d64ab16453248e0f8c1ca0ba54036e3
|
refs/heads/master
| 2021-07-14T01:32:33.492131
| 2021-07-13T16:26:41
| 2021-07-13T16:26:41
| 250,024,326
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,591
|
cpp
|
smallest_string_with_swaps.cpp
|
//using dsu
class Solution {
public:
int *super_parent;
int find_parent(int ele){
if(super_parent[ele] == ele)return ele;
super_parent[ele] = find_parent(super_parent[ele]);
return super_parent[ele];
}
void make_union(int a , int b){
int parent1 = find_parent(a);
int parent2 = find_parent(b);
if(parent1 != parent2){
super_parent[parent1] = parent2;
}
}
string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
int n = s.size();
super_parent = new int[n];
for(int i= 0 ;i<n; i++){
super_parent[i] = i;
}
for(int i = 0 ; i< pairs.size() ; i++){
int val1 = pairs[i][0] , val2 = pairs[i][1];
make_union(val1 , val2);
}
unordered_map<int , vector<int>>mp;
for(int i= 0 ;i<n ; i++){
mp[find_parent(i)].push_back(i);
}
for(auto &curr_vec : mp){
string temp;
for(auto &x : curr_vec.second){
temp += s[x];
}
sort(temp.begin() , temp.end());
int ptr = 0;
for(auto &x : curr_vec.second){
s[x] = temp[ptr++];
}
}
return s;
}
};
|
8e7c113e7ea34f752625ce897f122f69fcb75450
|
3ff6cd06dacc43eb232c9d21f0eaee3151719ef6
|
/src/Weibull.cpp
|
362e33ee71dd8eb95593e4dfa2e15477805e2bb2
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
marcizhu/PyStats
|
fd9585ac214ed5bd11dd80d829ec33ae2636bb88
|
94fde5042930de60979b3bc7b07ecb4ea757bb3c
|
refs/heads/master
| 2023-06-02T07:32:41.673951
| 2021-06-17T09:29:26
| 2021-06-17T09:29:26
| 362,223,330
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,476
|
cpp
|
Weibull.cpp
|
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"
#define STATS_ENABLE_STDVEC_WRAPPERS
#include "stats.hpp"
namespace py = pybind11;
void Weibull(py::module& m)
{
// Scalar input
m.def("dweibull", static_cast<double(*)(double, double, double, bool)>(&stats::dweibull),
py::arg("x"), py::arg("alpha") = 1.0, py::arg("sigma") = 1.0, py::arg("log") = false,
"Density function of the Weibull distribution.\n\n"
"Example:\n"
" >>> pystats.dweibull(1.0, 2.0, 3.0)\n"
" 0.19885318151430437\n\n"
"Args:\n"
" x (float): A real-valued input.\n"
" alpha (float): The shape parameter, a real-valued input.\n"
" sigma (float): The scale parameter, a real-valued input.\n"
" log (bool): Return the log-density or the true form.\n\n"
"Returns:\n"
" The density function evaluated at `x`.");
m.def("pweibull", static_cast<double(*)(double, double, double, bool)>(&stats::pweibull),
py::arg("p"), py::arg("alpha") = 1.0, py::arg("sigma") = 1.0, py::arg("log") = false,
"Distribution function of the Weibull distribution.\n\n"
"Example:\n"
" >>> pystats.pweibull(1.0, 2.0, 3.0)\n"
" 0.1051606831856301\n\n"
"Args:\n"
" p (float): A real-valued input.\n"
" alpha (float): The shape parameter, a real-valued input.\n"
" sigma (float): The scale parameter, a real-valued input.\n"
" log (bool): Return the log-density or the true form.\n\n"
"Returns:\n"
" The cumulative distribution function evaluated at `p`.");
m.def("qweibull", static_cast<double(*)(double, double, double)>(&stats::qweibull),
py::arg("q"), py::arg("alpha") = 1.0, py::arg("sigma") = 1.0,
"Quantile function of the Weibull distribution.\n\n"
"Example:\n"
" >>> pystats.qweibull(0.5, 2.0, 3.0)\n"
" 2.497663833473093\n\n"
"Args:\n"
" q (float): A real-valued input.\n"
" alpha (float): The shape parameter, a real-valued input.\n"
" sigma (float): The scale parameter, a real-valued input.\n\n"
"Returns:\n"
" The quantile function evaluated at `q`.");
m.def("rweibull", [](double alpha, double sigma) { return stats::rweibull(alpha, sigma); },
py::arg("alpha") = 1.0, py::arg("sigma") = 1.0,
"Random sampling function for the Weibull distribution.\n\n"
"Example:\n"
" >>> pystats.rweibull(2.0, 3.0)\n"
" 2.7238639049596536\n\n"
"Args:\n"
" alpha (float): The shape parameter, a real-valued input.\n"
" sigma (float): The scale parameter, a real-valued input.\n\n"
"Returns:\n"
" A pseudo-random draw from the Weibull distribution.");
m.def("rweibull", [](size_t n, double alpha, double sigma) { return stats::rweibull<std::vector<double>>(1, n, alpha, sigma); },
py::arg("n"), py::arg("alpha") = 1.0, py::arg("sigma") = 1.0,
"Random sampling function for the Weibull distribution.\n\n"
"Example:\n"
" >>> pystats.rweibull(3, 2.0, 3.0)\n"
" [0.563858221268503, 1.10144762159266, 2.0484747373540606]\n\n"
"Args:\n"
" n (int): The number of output values.\n"
" alpha (float): The shape parameter, a real-valued input.\n"
" sigma (float): The scale parameter, a real-valued input.\n\n"
"Returns:\n"
" A list of pseudo-random draws from the Weibull distribution.");
// Vector input
m.def("dweibull", static_cast<std::vector<double>(*)(const std::vector<double>&, double, double, bool)>(&stats::dweibull),
py::arg("x"), py::arg("alpha") = 1.0, py::arg("sigma") = 1.0, py::arg("log") = false,
"Density function of the Weibull distribution.\n\n"
"Example:\n"
" >>> pystats.dweibull([1.8, 0.7, 4.2], 2.0, 3.0)\n"
" [0.27907053042841234, 0.14731284075281734, 0.1314678595263087]\n\n"
"Args:\n"
" x (List[float]): A standard list input.\n"
" alpha (float): The shape parameter, a real-valued input.\n"
" sigma (float): The scale parameter, a real-valued input.\n"
" log (bool): Return the log-density or the true form.\n\n"
"Returns:\n"
" A list of density values corresponding to the elements of `x`.");
m.def("pweibull", static_cast<std::vector<double>(*)(const std::vector<double>&, double, double, bool)>(&stats::pweibull),
py::arg("p"), py::arg("alpha") = 1.0, py::arg("sigma") = 1.0, py::arg("log") = false,
"Distribution function of the Weibull distribution.\n\n"
"Example:\n"
" >>> pystats.pweibull([1.8, 0.7, 4.2], 2.0, 3.0)\n"
" [0.302323673928969, 0.052988880874744404, 0.859141579078955]\n\n"
"Args:\n"
" p (List[float]): A standard list input.\n"
" alpha (float): The shape parameter, a real-valued input.\n"
" sigma (float): The scale parameter, a real-valued input.\n"
" log (bool): Return the log-density or the true form.\n\n"
"Returns:\n"
" A list of CDF values corresponding to the elements of `p`.");
m.def("qweibull", static_cast<std::vector<double>(*)(const std::vector<double>&, double, double)>(&stats::qweibull),
py::arg("q"), py::arg("alpha") = 1.0, py::arg("sigma") = 1.0,
"Quantile function of the Weibull distribution.\n\n"
"Example:\n"
" >>> pystats.qweibull([0.3, 0.5, 0.9], 2.0, 3.0)\n"
" [1.7916680762486648, 2.497663833473093, 4.552281388155439]\n\n"
"Args:\n"
" q (List[float]): A standard list input.\n"
" alpha (float): The shape parameter, a real-valued input.\n"
" sigma (float): The scale parameter, a real-valued input.\n\n"
"Returns:\n"
" A list of quantiles values corresponding to the elements of `q`.");
}
|
22140e0ece907398dee88dd8c592f75729902553
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_1482494_1/C++/fidels/B.cpp
|
e99e7f4dc4c595410c7ae79fbb38749db066ea27
|
[] |
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,256
|
cpp
|
B.cpp
|
#include <iostream>
using namespace std;
#define MAXN 1024
struct level {
int a, b;
bool va, vb;
} n[MAXN];
int main() {
int N, i, S, maxb, RES, t, T;
bool flag;
cin >> T;
for (t=1; t<=T; t++) {
cin >> N;
for (i=0; i<N; i++) {
cin >> n[i].a;
cin >> n[i].b;
n[i].va = n[i].vb = true;
}
S = RES = 0;
do {
flag = false; maxb = -1;
for (i=0; i<N && !flag; i++) {
if (n[i].vb == true && n[i].b <= S) {
if (n[i].va == true) {n[i].va = false; S++;}
n[i].vb = false; S++;
flag = true;
RES++;
}
if (n[i].va == true && n[i].a <= S && (maxb == -1 || n[i].b > n[maxb].b)) maxb = i;
}
if (!flag && maxb!=-1) {n[maxb].va = false; S++; flag = true; RES++;}
} while (flag);
flag = true;
for (i=0; i<N && flag; i++) if (n[i].va == true || n[i].vb == true) flag = false;
cout << "Case #" << t << ": ";
if (!flag) cout << "Too Bad" << endl;
else cout << RES << endl;
}
return 0;
}
|
26f5e524f3542624282237fdcc7e4fd633cb7d90
|
16e2f8a1d64d10e5d99595e2bff2d70d9e0efb03
|
/Matrix/Source.cpp
|
4465a05499237a1e0da5ac89a757f5dc1bf97154
|
[] |
no_license
|
shablov/Matrix
|
6cb5c53dcc81da900e1f0ec008830a786e14fd50
|
9748474dab90f4b4ccc4b0bc21caf9555d8399bc
|
refs/heads/master
| 2020-04-01T00:29:38.842544
| 2018-10-13T10:01:45
| 2018-10-13T10:01:45
| 152,699,424
| 0
| 0
| null | 2018-10-12T05:41:02
| 2018-10-12T05:41:02
| null |
UTF-8
|
C++
| false
| false
| 692
|
cpp
|
Source.cpp
|
#include <cstdio> //Library for files(read from files, write to files)
#include <chrono>
#include <fstream>
#include "Matrix.h" // Library for matrix (need to be in folder of project)
const size_t NumberOfTests = 10;
const bool DispalayResult = false;
int main()
{
std::cout << std::fixed << Matrix<int>::indentity(3) << std::endl;
std::ifstream input("StressIn.txt");
std::ofstream output("StressOut.txt");
auto t_start = std::chrono::steady_clock::now();
for (int i = 0; i < NumberOfTests; i++)
{
Matrix<double> x;
input >> x;
output << x.transpose();
}
auto t_end = std::chrono::steady_clock::now();
output << "\n\nDURATION - " << (t_end - t_start).count();
return 0;
}
|
1886440f8ff2befe86e47a23e1493d435ef7c691
|
847e3adca9968f1048ccd3bde509b82dfac153cf
|
/Patterns_In_Cpp/floyds_traingle.cpp
|
7257f4e07fd027bc623be392b0cc15b735a000bd
|
[] |
no_license
|
gedaprems/datastructure_cpp_practice
|
b675b38a4e063936d506f4e34e6d522dc18cdc81
|
8330ee489e08d8f69419c14d96f31fd6d9295355
|
refs/heads/master
| 2023-05-08T22:11:32.530115
| 2021-05-19T08:13:53
| 2021-05-19T08:13:53
| 368,793,502
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 340
|
cpp
|
floyds_traingle.cpp
|
// output:
// 1
// 23
// 456
// 78910
#include <iostream>
using namespace std;
int main(){
int n,sum=0;
cin>>n;
for (int i = 1; i <= n; i++)
{
for (int j = 0; j < i; j++)
{
sum=sum+1;
cout<<sum;
}
cout<<endl;
}
return 0;
}
|
c9bdbbe6bfc024734ac52a3cf6f988c25c2b39b8
|
319bc7012894c6135785802bdc73cc9f8fc429b7
|
/src/LP.h
|
1a27872635dc8e9a920a62a3c0cad0d2b5c6216c
|
[] |
no_license
|
krofna/dagmatch
|
6dcc02fb44e2ffc822789583bd2a99c1e78631a2
|
49cb3a7769edddba148a5520d5695b0e9f5cdf1b
|
refs/heads/master
| 2022-12-16T04:41:48.148012
| 2020-07-30T23:38:27
| 2020-07-30T23:38:27
| 283,037,701
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,809
|
h
|
LP.h
|
/*
Copyright (C) 2018-2020 Mislav Blažević
This file is part of dagmatch.
dagmatch 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.
*/
#ifndef LP_H
#define LP_H
#include "Graph.h"
#include "Geno.h"
#include "IndependentSetConstraint.h"
#include "AntichainConstraint.h"
#include "CrossingConstraint.h"
typedef tuple<int, int> ii;
class LP
{
public:
LP(Graph& t1, Graph& t2, vector<vd>& matrix);
void Solve(string filename, bool ilp);
void SolvePairwise(string filename, bool ilp);
void SolveInt(string filename);
void WriteSolution(string fileName);
private:
template<class T> int Add();
template<int N> int Add();
void SolveLP();
void SolveILP();
void MatchingConstraints();
bool IsNotInConflict(int i, int j, int x, int y) const;
void AddConstraint(const ii& a, const ii& b);
vector<ET> Triplets;
// backup x->warm_x and y->warm_y for two consecutive iterations
Vector warm_x, warm_y;
Vector x, y;
vector<vi> K;
Vector c;
int nr_rows, nr_cols;
int cnt;
bool dag;
Graph &t1, &t2;
vector<vd> matrix;
};
template<class T>
int LP::Add()
{
int row_old = nr_rows;
T c12(Triplets, t1, t2, K, x, false);
nr_rows += c12.AddTriplets(nr_rows);
T c21(Triplets, t2, t1, K, x, true);
nr_rows += c21.AddTriplets(nr_rows);
return nr_rows - row_old;
}
template<int N>
int LP::Add()
{
static_assert(N == 1 || N == 2, "invalid constraint");
if (N == 1)
return Add<CrossingConstraint>();
return (dag ? Add<AntichainConstraint>() : Add<IndependentSetConstraint>());
}
#endif
|
184041a41b5f4d05050c97d5fca4293eec399191
|
544e77e04e49545cfd37ae512f09bf3e399fe53c
|
/build/cmr_msgs/rosidl_generator_cpp/cmr_msgs/msg/detail/maxon_status__struct.hpp
|
c50b960caaeda659fe25a2ec7e6f6c0ed6479b6a
|
[] |
no_license
|
LiWeiAn/map_fuse
|
e7338bd15bd88b15ebcea24d5222e28d41c68707
|
58641cc15012c70049cce98f23f0efd8dd3623e1
|
refs/heads/master
| 2023-05-26T11:47:10.932447
| 2021-06-03T21:29:06
| 2021-06-03T21:29:06
| 373,645,597
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,545
|
hpp
|
maxon_status__struct.hpp
|
// generated from rosidl_generator_cpp/resource/idl__struct.hpp.em
// with input from cmr_msgs:msg/MaxonStatus.idl
// generated code does not contain a copyright notice
#ifndef CMR_MSGS__MSG__DETAIL__MAXON_STATUS__STRUCT_HPP_
#define CMR_MSGS__MSG__DETAIL__MAXON_STATUS__STRUCT_HPP_
#include <rosidl_runtime_cpp/bounded_vector.hpp>
#include <rosidl_runtime_cpp/message_initialization.hpp>
#include <algorithm>
#include <array>
#include <memory>
#include <string>
#include <vector>
// Include directives for member types
// Member 'header'
#include "std_msgs/msg/detail/header__struct.hpp"
#ifndef _WIN32
# define DEPRECATED__cmr_msgs__msg__MaxonStatus __attribute__((deprecated))
#else
# define DEPRECATED__cmr_msgs__msg__MaxonStatus __declspec(deprecated)
#endif
namespace cmr_msgs
{
namespace msg
{
// message struct
template<class ContainerAllocator>
struct MaxonStatus_
{
using Type = MaxonStatus_<ContainerAllocator>;
explicit MaxonStatus_(rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL)
: header(_init)
{
(void)_init;
}
explicit MaxonStatus_(const ContainerAllocator & _alloc, rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL)
: header(_alloc, _init)
{
(void)_init;
}
// field types and members
using _header_type =
std_msgs::msg::Header_<ContainerAllocator>;
_header_type header;
using _device_state_type =
std::vector<uint8_t, typename ContainerAllocator::template rebind<uint8_t>::other>;
_device_state_type device_state;
using _velocity_dem_type =
std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other>;
_velocity_dem_type velocity_dem;
using _velocity_act_type =
std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other>;
_velocity_act_type velocity_act;
using _torque_act_avg_type =
std::vector<int16_t, typename ContainerAllocator::template rebind<int16_t>::other>;
_torque_act_avg_type torque_act_avg;
using _voltage_type =
std::vector<uint16_t, typename ContainerAllocator::template rebind<uint16_t>::other>;
_voltage_type voltage;
using _i2t_level_cont_type =
std::vector<uint16_t, typename ContainerAllocator::template rebind<uint16_t>::other>;
_i2t_level_cont_type i2t_level_cont;
using _i2t_level_motor_type =
std::vector<uint16_t, typename ContainerAllocator::template rebind<uint16_t>::other>;
_i2t_level_motor_type i2t_level_motor;
using _current_dem_type =
std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other>;
_current_dem_type current_dem;
using _current_act_type =
std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other>;
_current_act_type current_act;
using _current_act_avg_type =
std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other>;
_current_act_avg_type current_act_avg;
using _sense_vel_act_type =
std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other>;
_sense_vel_act_type sense_vel_act;
using _sense_vel_avg_type =
std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other>;
_sense_vel_avg_type sense_vel_avg;
using _error_type =
std::vector<uint8_t, typename ContainerAllocator::template rebind<uint8_t>::other>;
_error_type error;
using _error_history_type =
std::vector<uint16_t, typename ContainerAllocator::template rebind<uint16_t>::other>;
_error_history_type error_history;
// setters for named parameter idiom
Type & set__header(
const std_msgs::msg::Header_<ContainerAllocator> & _arg)
{
this->header = _arg;
return *this;
}
Type & set__device_state(
const std::vector<uint8_t, typename ContainerAllocator::template rebind<uint8_t>::other> & _arg)
{
this->device_state = _arg;
return *this;
}
Type & set__velocity_dem(
const std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other> & _arg)
{
this->velocity_dem = _arg;
return *this;
}
Type & set__velocity_act(
const std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other> & _arg)
{
this->velocity_act = _arg;
return *this;
}
Type & set__torque_act_avg(
const std::vector<int16_t, typename ContainerAllocator::template rebind<int16_t>::other> & _arg)
{
this->torque_act_avg = _arg;
return *this;
}
Type & set__voltage(
const std::vector<uint16_t, typename ContainerAllocator::template rebind<uint16_t>::other> & _arg)
{
this->voltage = _arg;
return *this;
}
Type & set__i2t_level_cont(
const std::vector<uint16_t, typename ContainerAllocator::template rebind<uint16_t>::other> & _arg)
{
this->i2t_level_cont = _arg;
return *this;
}
Type & set__i2t_level_motor(
const std::vector<uint16_t, typename ContainerAllocator::template rebind<uint16_t>::other> & _arg)
{
this->i2t_level_motor = _arg;
return *this;
}
Type & set__current_dem(
const std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other> & _arg)
{
this->current_dem = _arg;
return *this;
}
Type & set__current_act(
const std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other> & _arg)
{
this->current_act = _arg;
return *this;
}
Type & set__current_act_avg(
const std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other> & _arg)
{
this->current_act_avg = _arg;
return *this;
}
Type & set__sense_vel_act(
const std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other> & _arg)
{
this->sense_vel_act = _arg;
return *this;
}
Type & set__sense_vel_avg(
const std::vector<int32_t, typename ContainerAllocator::template rebind<int32_t>::other> & _arg)
{
this->sense_vel_avg = _arg;
return *this;
}
Type & set__error(
const std::vector<uint8_t, typename ContainerAllocator::template rebind<uint8_t>::other> & _arg)
{
this->error = _arg;
return *this;
}
Type & set__error_history(
const std::vector<uint16_t, typename ContainerAllocator::template rebind<uint16_t>::other> & _arg)
{
this->error_history = _arg;
return *this;
}
// constant declarations
// pointer types
using RawPtr =
cmr_msgs::msg::MaxonStatus_<ContainerAllocator> *;
using ConstRawPtr =
const cmr_msgs::msg::MaxonStatus_<ContainerAllocator> *;
using SharedPtr =
std::shared_ptr<cmr_msgs::msg::MaxonStatus_<ContainerAllocator>>;
using ConstSharedPtr =
std::shared_ptr<cmr_msgs::msg::MaxonStatus_<ContainerAllocator> const>;
template<typename Deleter = std::default_delete<
cmr_msgs::msg::MaxonStatus_<ContainerAllocator>>>
using UniquePtrWithDeleter =
std::unique_ptr<cmr_msgs::msg::MaxonStatus_<ContainerAllocator>, Deleter>;
using UniquePtr = UniquePtrWithDeleter<>;
template<typename Deleter = std::default_delete<
cmr_msgs::msg::MaxonStatus_<ContainerAllocator>>>
using ConstUniquePtrWithDeleter =
std::unique_ptr<cmr_msgs::msg::MaxonStatus_<ContainerAllocator> const, Deleter>;
using ConstUniquePtr = ConstUniquePtrWithDeleter<>;
using WeakPtr =
std::weak_ptr<cmr_msgs::msg::MaxonStatus_<ContainerAllocator>>;
using ConstWeakPtr =
std::weak_ptr<cmr_msgs::msg::MaxonStatus_<ContainerAllocator> const>;
// pointer types similar to ROS 1, use SharedPtr / ConstSharedPtr instead
// NOTE: Can't use 'using' here because GNU C++ can't parse attributes properly
typedef DEPRECATED__cmr_msgs__msg__MaxonStatus
std::shared_ptr<cmr_msgs::msg::MaxonStatus_<ContainerAllocator>>
Ptr;
typedef DEPRECATED__cmr_msgs__msg__MaxonStatus
std::shared_ptr<cmr_msgs::msg::MaxonStatus_<ContainerAllocator> const>
ConstPtr;
// comparison operators
bool operator==(const MaxonStatus_ & other) const
{
if (this->header != other.header) {
return false;
}
if (this->device_state != other.device_state) {
return false;
}
if (this->velocity_dem != other.velocity_dem) {
return false;
}
if (this->velocity_act != other.velocity_act) {
return false;
}
if (this->torque_act_avg != other.torque_act_avg) {
return false;
}
if (this->voltage != other.voltage) {
return false;
}
if (this->i2t_level_cont != other.i2t_level_cont) {
return false;
}
if (this->i2t_level_motor != other.i2t_level_motor) {
return false;
}
if (this->current_dem != other.current_dem) {
return false;
}
if (this->current_act != other.current_act) {
return false;
}
if (this->current_act_avg != other.current_act_avg) {
return false;
}
if (this->sense_vel_act != other.sense_vel_act) {
return false;
}
if (this->sense_vel_avg != other.sense_vel_avg) {
return false;
}
if (this->error != other.error) {
return false;
}
if (this->error_history != other.error_history) {
return false;
}
return true;
}
bool operator!=(const MaxonStatus_ & other) const
{
return !this->operator==(other);
}
}; // struct MaxonStatus_
// alias to use template instance with default allocator
using MaxonStatus =
cmr_msgs::msg::MaxonStatus_<std::allocator<void>>;
// constant definitions
} // namespace msg
} // namespace cmr_msgs
#endif // CMR_MSGS__MSG__DETAIL__MAXON_STATUS__STRUCT_HPP_
|
5235e409d87d70ff4e7c72b2b551998164c274a6
|
ef1e794906d7caa41e2d2b70a763ff2adcc2ea3f
|
/Source/GamedevNosatov3dP/Public/Core/Actors/MaterialActor.h
|
35497253a4eda119cd9dacbf314d9634bc03a24c
|
[] |
no_license
|
Synoecium/GamedevNosatov3dP
|
139d9d4627d855f1c85e84d65d11dd36d4a89d9d
|
41075a56dbf9082f658265e48ca2bfea7965858d
|
refs/heads/main
| 2023-06-03T05:01:58.722922
| 2021-06-22T04:58:48
| 2021-06-22T04:58:48
| 344,588,367
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 999
|
h
|
MaterialActor.h
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Curves/CurveVector.h"
#include "GameFramework/Actor.h"
#include "MaterialActor.generated.h"
UCLASS()
class GAMEDEVNOSATOV3DP_API AMaterialActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AMaterialActor();
UPROPERTY(VisibleAnywhere)
UStaticMeshComponent* StaticMesh;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
UCurveVector* ColorCurve;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
UCurveFloat* MetallicCurve;
UPROPERTY(EditAnywhere)
float AnimationTime = 1.f;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
private:
float _startTimeColor, _endTimeColor;
float _startTimeMet, _endTimeMet;
float _elapsedTime = 0.f;
UMaterialInstanceDynamic* _DynamicMatInstance;
};
|
bfa662d5f15aecf081095062b5d5b971911407bd
|
15cec5616a1c10924ebfd7d1db2134dbcc4e5598
|
/atcoder.jp/abc042/abc042_b/Main.cpp
|
240783ee4a7d2a84a4394fde8d1a1b945cd283a8
|
[] |
no_license
|
shuto1441/atcoder_archive
|
2c474a379b6b3df8783504335cc678b3e45fc0e8
|
8c3cc31ebe39746e26f8fdef4f6ac289d34f91a0
|
refs/heads/main
| 2023-07-11T00:03:38.661106
| 2021-08-21T11:16:28
| 2021-08-21T11:16:28
| 397,816,573
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 250
|
cpp
|
Main.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int N,L;
cin >> N>>L;
vector<string>vec(N);
for (int i = 0;i < N;++i)
cin>>vec[i];
sort(vec.begin(),vec.end());
for (int i = 0;i < N;++i)
cout<<vec[i];
cout<<endl;
}
|
127a3b135f76376c7960348d95fc3c4bed0226d4
|
904441a3953ee970325bdb4ead916a01fcc2bacd
|
/src/apps/topology/topology/polygon_topology.cpp
|
26aad962944e4c2ea8ffe573ae6f11ed45f8ebd6
|
[
"MIT"
] |
permissive
|
itm/shawn
|
5a75053bc490f338e35ea05310cdbde50401fb50
|
49cb715d0044a20a01a19bc4d7b62f9f209df83c
|
refs/heads/master
| 2020-05-30T02:56:44.820211
| 2013-05-29T13:34:51
| 2013-05-29T13:34:51
| 5,994,638
| 16
| 4
| null | 2014-06-29T05:29:00
| 2012-09-28T08:33:42
|
C++
|
UTF-8
|
C++
| false
| false
| 5,142
|
cpp
|
polygon_topology.cpp
|
/************************************************************************
** This file is part of the network simulator Shawn. **
** Copyright (C) 2004-2007 by the SwarmNet (www.swarmnet.de) project **
** Shawn is free software; you can redistribute it and/or modify it **
** under the terms of the BSD License. Refer to the shawn-licence.txt **
** file in the root of the Shawn source tree for further details. **
************************************************************************/
#include "_apps_enable_cmake.h"
#ifdef ENABLE_TOPOLOGY
#include "shawn_config.h"
#include "apps/topology/topology/polygon_topology.h"
#include <iostream>
using namespace shawn;
namespace topology
{
// ----------------------------------------------------------------------
PolygonTopology::
PolygonTopology()
: outer_( NULL ),
name_ ("")
{}
// ----------------------------------------------------------------------
PolygonTopology::
~PolygonTopology()
{
if( outer_ != NULL )
delete outer_;
//Delete the tags
for(PolygonTagMap::iterator it = tags_.begin(), endit = tags_.end(); it != endit; ++it)
delete it->second;
//Delete the polygons
for(PolygonVector::iterator it = holes_.begin(), endit = holes_.end(); it != endit; ++it )
delete *it;
}
// ----------------------------------------------------------------------
bool
PolygonTopology::
value( const Vec& p )
const throw()
{
assert( outer_ != NULL );
// we take the boundary of holes to be inside the area, i.e.,
// the topological closure is considered "inside".
//cout<<"pos = "<<p<<" : ";
if(outer_->bounded_side(p)||outer_->on_boundary(p)){
for( PolygonVector::const_iterator it = holes_.begin(); it != holes_.end(); it++ ){
if(((*it)->bounded_side(p))){
if(!((*it)->on_boundary(p))){
//cout<<"hole->bounded_side"<<endl;
return false;
}
//cout<<"hole->boundary"<<endl;
}
}
return true;
}
return false;
}
// ----------------------------------------------------------------------
shawn::Box
PolygonTopology::
domain( void )
const throw()
{
assert( outer_!=NULL );
Box bb = outer_->getBoundingBox();
Vec lower = bb.lower();
Vec upper = bb.upper();
return Box(lower,upper);
}
// ----------------------------------------------------------------------
Box
PolygonTopology::
get_outer_bbox( void )
const throw()
{
assert( outer_!=NULL );
return outer_->getBoundingBox();
}
// ----------------------------------------------------------------------
void
PolygonTopology::
set_outer_polygon( Polygon& p )
throw()
{
assert( p.is_simple() );
assert( outer_ == NULL );
outer_ = &p;
}
// ----------------------------------------------------------------------
void
PolygonTopology::
add_hole_polygon( Polygon& p )
throw()
{
assert( p.is_simple() );
holes_.push_back(&p);
}
// ----------------------------------------------------------------------
const shawn::TagContainer*
PolygonTopology::
tags(Polygon& polygon)
const
{
if(tags_.find(&polygon) == tags_.end() ){
std::cerr << "No tags found for polygon!" << std::endl;
return NULL;
}
PolygonTagMap& m = *((PolygonTagMap*)(&tags_));//Fieser Hack...
return m[&(Polygon&)polygon];
}
// ----------------------------------------------------------------------
shawn::TagContainer&
PolygonTopology::
tags_w(Polygon& polygon)
{
if(tags_.find(&polygon) == tags_.end() )
tags_[&polygon] = new TagContainer();
assert( tags_.find(&polygon) != tags_.end() );
return *tags_[&polygon];
}
// ----------------------------------------------------------------------
std::string
PolygonTopology::
name( void )
const throw()
{
return name_;
}
// ----------------------------------------------------------------------
std::string
PolygonTopology::
description( void )
const throw()
{
return std::string("2-dimensional polygonal area");
}
// ----------------------------------------------------------------------
void
PolygonTopology::
set_name( const std::string& s )
throw()
{
name_ = s;
}
// ----------------------------------------------------------------------
polygon::Polygon&
PolygonTopology::
outer_w()
const
{
assert (outer_ != NULL);
return *outer_;
}
// ----------------------------------------------------------------------
PolygonTopology::ConstPolygonVector&
PolygonTopology::
holes()
const
{
return holes_;
}
// ----------------------------------------------------------------------
PolygonTopology::PolygonVector&
PolygonTopology::
holes_w()
{
return holes_;
}
}
#endif
/*-----------------------------------------------------------------------
* Source $Source: /cvs/shawn/shawn/apps/topology/topology/polygon_topology.cpp,v $
* Version $Revision: 197 $
* Date $Date: 2008-04-29 17:40:51 +0200 (Tue, 29 Apr 2008) $
*-----------------------------------------------------------------------
* $Log: polygon_topology.cpp,v $
*-----------------------------------------------------------------------*/
|
cc950730910e7fa4289bb1622ac753ed1cf6b8c0
|
63b11528f60ad5570f9da678b20e682dc29bed5b
|
/CrazyTanks v.2/src/Class Diagram/DrawEnemyStrategy.cpp
|
2ff75d959c33caeede38cdc4267421f5f491747f
|
[] |
no_license
|
Dheinamar/Luxoft
|
235ae0e4bc72b8c2abe3ebe04c42825f0dab9917
|
24afcb52035e67fab64b9786e794dc03276ccf54
|
refs/heads/master
| 2021-03-30T21:03:18.353948
| 2018-04-03T22:00:26
| 2018-04-03T22:00:26
| 125,091,859
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,905
|
cpp
|
DrawEnemyStrategy.cpp
|
/**
* Project CrazyTanks
*/
#include "DrawEnemyStrategy.h"
/**
* DrawEnemyStrategy implementation
*/
DrawEnemyStrategy::DrawEnemyStrategy () :SIZE (pair<int, int> (30, 30)),
TURRET_SIZE (pair<int, int> (10, 15)),
BLACK (Color (0, 0, 0))
{}
void
DrawEnemyStrategy::drawObject (const pair<int, int> coordinates, Way way,
Graphics & graphics, const Pen & pen)
{
const auto TURRET_SIDE_INDENT = (SIZE.first - TURRET_SIZE.first) / 2,
TURRET_BACK_INDENT = SIZE.second / 2;
graphics.DrawRectangle (&pen, coordinates.first, coordinates.second,
SIZE.first, SIZE.second);
switch (way) {
case UP:
graphics.DrawRectangle (&BLACK,
coordinates.first + TURRET_SIDE_INDENT,
coordinates.second,
TURRET_SIZE.first,
TURRET_SIZE.second);
break;
case LEFT:
graphics.DrawRectangle (&BLACK,
coordinates.first,
coordinates.second + TURRET_SIDE_INDENT,
TURRET_SIZE.second,
TURRET_SIZE.first);
break;
case DOWN:
graphics.DrawRectangle (&BLACK,
coordinates.first + TURRET_SIDE_INDENT,
coordinates.second + TURRET_BACK_INDENT,
TURRET_SIZE.first,
TURRET_SIZE.second);
break;
case RIGHT:
graphics.DrawRectangle (&BLACK,
coordinates.first + TURRET_BACK_INDENT,
coordinates.second + TURRET_SIDE_INDENT,
TURRET_SIZE.second,
TURRET_SIZE.first);
break;
default:
break;
}
}
|
734a84e586888661928dc737561614a31427eb9e
|
3a6b7fd1aaf14ed529a1735b3f503cc361afec73
|
/src/right-master.cpp
|
9058d3df953d792cd7f1498c3c825788ede8b45f
|
[
"MIT"
] |
permissive
|
vexchow/FreiKey
|
f051b281231e7d5fa809243db9b1514dcad04379
|
f2abdf86f2308b40330422e2369d8a96eba3c80d
|
refs/heads/master
| 2020-04-15T00:50:51.398288
| 2018-10-13T19:54:47
| 2018-10-13T19:54:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,090
|
cpp
|
right-master.cpp
|
#include "sysstuff.h"
#include "boardio.h"
#include "callbacks.h"
#include "dbgcfg.h"
#include "globals.h"
#include "hardware.h"
#include "helpers.h"
#include "keystate.h"
#include "led_states.h"
#include "scanner.h"
#include "sleepstate.h"
#include "status_dump.h"
// I'm going to update this to keep track of additional state.
// Each key 'previously' pressed should have a 'time last pressed'
// Maybe keep track of whether other keys have been pressed since?
// Perhaps have a flag for something that's a "Normal" key?
// The core idea:
// I want to be able to trigger something off of both the "key pressed"
// as well as the "key released". In addition, I want to do things that
// 'cancel out' the key state if something specific occurs
// Kind of things I want to do:
// #1: Better, intentional debouncing
// #2: Key-up triggering
// #3: Cancellation
// #4: Key-state back & forth (caps as a real cmd/ctrl, instead of a layer
// shift)
// These numbers correspond to the *port pin* numbers in the nRF52 documentation
// not the physical pin numbers...
constexpr BoardIO RightBoard = {
{29, 16, 15, 7, 27, 11, 30}, {13, 4, 2, 3, 5, 12}, 28};
state::hw leftSide{};
state::hw rightSide{};
// The are the top left & right keys, plus the lowest 'outer' key
const BoardIO::bits status_clear_bonds_left{
{1, 2, 3, 4, 5}}; // 0x10000000042ULL;
const BoardIO::bits status_clear_bonds_right{
{1, 2, 3, 4, 5}}; // 0x1000000021ULL;
// This is called when the LHS connects, disconnects, and when the system is
// initialized. The idea is that it should just wipe everything clean.
void resetTheWorld() {
layer_pos = 0;
layer_stack[0] = 0;
memset(&leftSide, 0, sizeof(leftSide));
memset(&rightSide, 0, sizeof(rightSide));
memset(keyStates, 0xff, sizeof(keyStates));
hid.keyRelease();
}
const state::led* curState = nullptr;
uint32_t stateTime = 0;
// Check to see if we should update the battery level and if so, do so
void updateBatteryLevel(const state::hw& downLeft, const state::hw& downRight) {
if (downRight.battery_level != rightSide.battery_level ||
downLeft.battery_level != leftSide.battery_level) {
// We only get the battery level from the left side once you hit a key, so
// only report it if we have something to actually report
if (downLeft.battery_level) {
battery.notify((downRight.battery_level + downLeft.battery_level) / 2);
DBG(dumpVal((downRight.battery_level + downLeft.battery_level) / 2,
"battery avg: "));
} else {
DBG(dumpVal(downRight.battery_level, "right only battery: "));
battery.notify(downRight.battery_level);
}
rightSide.battery_level = downRight.battery_level;
leftSide.battery_level = downLeft.battery_level;
}
}
SleepState sleepState = {0, false, true};
void loop() {
uint32_t now = millis();
// Get the hardware state for the two sides...
state::hw downRight{now, rightSide, RightBoard};
state::hw downLeft{clientUart, leftSide};
// For sleeping, look at both sides of the keyboard
bool down = downRight.switches.any() || downLeft.switches.any();
if (sleepState.CheckForSleeping(down, now, RightBoard)) {
// I'm assuming this saves power. If it doesn't, there's no point...
delay(250);
waitForEvent();
return;
}
// Update the combined battery level
updateBatteryLevel(downLeft, downRight);
// Get the before & after of each side into a 64 bit value
BoardIO::bits beforeLeft = leftSide.switches;
BoardIO::bits afterLeft = downLeft.switches;
BoardIO::bits beforeRight = rightSide.switches;
BoardIO::bits afterRight = downRight.switches;
// Pseudo-code for what I'm looking to clean up:
#if 0
std::vector<scancode_t> scanCodes = GetScanCodesForSwitchStates(
beforeLeft, afterLeft, beforeRight, afterRight);
PerformActionsForScanCodes(scanCodes);
#endif
BoardIO::bits deltaLeft = beforeLeft.delta(afterLeft);
BoardIO::bits deltaRight = beforeRight.delta(afterRight);
bool keysChanged = deltaLeft.any() || deltaRight.any();
if (deltaRight.any() && !curState) {
// if we're not already in a state, check to see if we're transitioning
// into one
curState = state::led::get(downRight, layer_pos + 1);
if (curState) {
stateTime = now;
}
}
if (curState) {
// We're in some random LED display state. Do something...
if (now - curState->time < stateTime) {
RightBoard.setLED(curState->get_led_value(downRight, now - stateTime));
} else {
RightBoard.setLED(0);
curState = nullptr;
}
}
while (deltaLeft.any() || deltaRight.any()) {
scancode_t sc;
bool pressed;
if (deltaLeft.any()) {
sc = getNextScanCode(deltaLeft, afterLeft, pressed);
} else {
// Add offset to the right scan code...
sc = getNextScanCode(deltaRight, afterRight, pressed) +
BoardIO::matrix_size;
}
preprocessScanCode(sc, pressed, now);
}
if (keysChanged) {
usb_report r = getUSBData(now);
#if defined(DEBUG) && DEBUG > 1
Serial.print("mods=");
Serial.print(r.mods, HEX);
Serial.print(" repsize=");
Serial.print(r.repsize);
for (int i = 0; i < r.repsize; i++) {
Serial.print(" ");
Serial.print(r.report[i], HEX);
}
dumpHex(r.consumer, "Consumer:");
#endif
// Update the hardware previous state
rightSide = downRight;
leftSide = downLeft;
// Handle the consumer stuff:
if (r.consumer) {
if (r.consumer > 0) {
DBG2(dumpHex(r.consumer, "Consumer key press: "));
hid.consumerKeyPress(r.consumer);
} else {
DBG2(dumpHex(r.consumer, "Consumer key release: "));
hid.consumerKeyRelease();
}
}
#if defined(STATUS_DUMP)
// If we do a status dump, don't pass the keys pressed on to the computer...
if (!status_dump_check(rightSide, leftSide))
#endif
hid.keyboardReport(r.mods, r.report);
DBG2(Serial.println("============================="));
DBG2(Serial.print("Left side "));
DBG2(downLeft.dump());
DBG2(Serial.print("Right side "));
DBG2(downRight.dump());
if (rightSide.switches == status_clear_bonds_right &&
leftSide.switches == status_clear_bonds_left) {
DBG(Serial.println("CLEARING BLUETOOTH BONDS!"));
Bluefruit.clearBonds();
}
}
waitForEvent(); // Request CPU enter low-power mode until an event occurs
}
// In Arduino world the 'setup' function is called to initialize the device.
// The 'loop' function is called over & over again, after setup completes.
void setup() {
DBG(Serial.begin(115200));
RightBoard.Configure();
resetTheWorld();
// Central and peripheral
Bluefruit.begin(true, true);
// Bluefruit.clearBonds();
Bluefruit.autoConnLed(true);
battery.begin();
// I'm assuming that by dropping this power down, I'll save some battery life.
// I should experiment to see how low I can get it and still communicate with
// both my Mac and my PC reliably. They're each within a meter of the
// keyboard... Acceptable values: -40, -30, -20, -16, -12, -8, -4, 0, 4
Bluefruit.setTxPower(4);
Bluefruit.setName(BT_NAME);
Bluefruit.Central.setConnectCallback(callback::cent_connect);
Bluefruit.Central.setDisconnectCallback(callback::cent_disconnect);
dis.setManufacturer(MANUFACTURER);
dis.setModel(MODEL);
dis.setHardwareRev(HW_REV);
dis.setSoftwareRev(__DATE__);
dis.begin();
clientUart.begin();
Bluefruit.setConnectCallback(callback::core_connect);
Bluefruit.setDisconnectCallback(callback::core_disconnect);
// clientUart.setRxCallback(cent_bleuart_rx_callback);
/* Start Central Scanning
* - Enable auto scan if disconnected
* - Interval = 100 ms, window = 80 ms
* - Filter only accept bleuart service
* - Don't use active scan
* - Start(timeout) with timeout = 0 will scan forever (until connected)
*/
Bluefruit.Scanner.setRxCallback(callback::scan);
Bluefruit.Scanner.restartOnDisconnect(true);
Bluefruit.Scanner.setInterval(160, 80); // in unit of 0.625 ms
Bluefruit.Scanner.filterUuid(BLEUART_UUID_SERVICE);
Bluefruit.Scanner.useActiveScan(false);
// I should probably stop advertising after a while if that's possible. I have
// switches now, so if I need it to advertise, I can just punch the power.
Bluefruit.Scanner.start(0); // 0 = Don't stop scanning after n seconds
hid.begin();
// delay(5000);
// Bluefruit.printInfo();
// This gets Advertising going...
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
Bluefruit.Advertising.addTxPower();
Bluefruit.Advertising.addAppearance(BLE_APPEARANCE_HID_KEYBOARD);
Bluefruit.Advertising.addService(hid);
Bluefruit.ScanResponse.addService(battery); // This doesn't seem to work :(
Bluefruit.Advertising.addName();
Bluefruit.Advertising.restartOnDisconnect(true);
Bluefruit.Advertising.setInterval(32, 244); // in unit of 0.625 ms
Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode
Bluefruit.Advertising.start(0); // 0 = Don't stop advertising after n seconds
}
|
01653e0496b8d1d1b71400297ccc64764da3d26b
|
c971c89e25d9acf44ddbc70522a6e8f618625d6a
|
/Dragon Fight/Priest.h
|
29238ea43a040550694d842419e7de98567cf2b4
|
[] |
no_license
|
AustynM1994/DragonFight
|
07a571c3091a65a6f98551930537445d007edf38
|
951c38793aea89290d24f3b66dc78c4672d70cd8
|
refs/heads/main
| 2023-01-12T06:49:30.074884
| 2020-11-15T23:50:02
| 2020-11-15T23:50:02
| 313,146,502
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 413
|
h
|
Priest.h
|
/*
This class has the Priests health and abilities
*/
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
//Priest Class Definition
class Priest:public Character
{
public:
//Member Functions for ability rolls
int getSmiteDamage()
{
return rand() % 6 + 5;
}
int getHealAmount()
{
return rand() % 6 + 20;
}
};//End of Priest Class
|
4e4f37f4298282b2a8e0a3fc53023ce72646ff83
|
21cd33416c6f47454591eed9ea7d02f5a6f65395
|
/tail.cpp
|
ed63f49a7c7fa8fa08d2def6bcec3981b4c46091
|
[] |
no_license
|
forcha/algorithm
|
87bb3020c2fd2583af522412783e6726e8308db4
|
6086924cf913f27259ca0f64872d987d067bb2d7
|
refs/heads/master
| 2021-01-19T02:33:23.158972
| 2016-08-08T20:25:56
| 2016-08-08T20:25:56
| 64,073,266
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,292
|
cpp
|
tail.cpp
|
#include <iostream>
#include <string>
#include <utility>
#include <vector>
#include <fstream>
#include <algorithm>
#include <exception>
const unsigned long kDefaultLines = 10;
std::pair<std::string, unsigned long> parse_args(int argc, char const *argv[]) {
unsigned long lines = kDefaultLines;
if (argc == 2) {
return std::make_pair(std::string(argv[1]), lines);
} else {
lines = std::stoul(argv[1]);
return std::make_pair(std::string(argv[2]), lines);
}
}
void print_last_n_lines(const std::string &filename, const unsigned long lines) {
std::vector<std::string> buffer(lines);
unsigned long size = 0;
std::ifstream file(filename);
while (file.peek() != EOF) {
getline(file, buffer[size % lines]);
size++;
}
unsigned long start = size > lines ? (size % lines) : 0;
unsigned long count = std::min(lines, size);
for (unsigned long i = 0; i < count; ++i) {
std::cout << buffer[(start + i) % lines] << std::endl;
}
}
int main(int argc, char const *argv[])
{
try {
unsigned long lines;
std::string filename;
std::tie(filename, lines) = parse_args(argc, argv);
print_last_n_lines(filename, lines);
return 0;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
}
|
fa31c93bf0443b1aaba5b1224da2cbecf92a481e
|
6fee31ef3f6c3707de20a5956b2d96575fdf0aac
|
/znd/dev/src/gui/3rdparty/Charts/2.0/Src/src/charts/xychart/qvxymodelmapper.cpp
|
32d61f6a6906488260bd0584afc0304a76a55bb1
|
[] |
no_license
|
hilockman/cim2ddl
|
605b05e5c67acde1f9b0c93e6b0a227dd27519a6
|
78ec9a3b4136710ac659fa40e3da28c9bb57c10f
|
refs/heads/master
| 2021-01-01T17:50:55.311126
| 2019-01-03T05:35:47
| 2019-01-03T05:35:47
| 98,163,859
| 3
| 6
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,646
|
cpp
|
qvxymodelmapper.cpp
|
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc
** All rights reserved.
** For any questions to Digia, please use contact form at http://qt.io
**
** This file is part of the Qt Charts module.
**
** Licensees holding valid commercial license for Qt may use this file in
** accordance with the Qt License Agreement provided with the Software
** or, alternatively, in accordance with the terms contained in a written
** agreement between you and Digia.
**
** If you have questions regarding the use of this file, please use
** contact form at http://qt.io
**
****************************************************************************/
#include <QtCharts/QVXYModelMapper>
QT_CHARTS_BEGIN_NAMESPACE
/*!
\class QVXYModelMapper
\inmodule Qt Charts
\brief Vertical model mapper for QXYSeries.
\mainclass
Model mappers allow you to use QAbstractItemModel derived models as a data source for a chart series.
Vertical model mapper is used to create a connection between QXYSeries and QAbstractItemModel derived model object.
It is possible to use both QAbstractItemModel and QXYSeries model API. QXYModelMapper makes sure that QXYSeries and the model are kept in sync.
Note: used model has to support adding/removing rows/columns and modifying the data of the cells.
*/
/*!
\qmltype VXYModelMapper
\instantiates QVXYModelMapper
\inqmlmodule QtCharts
\brief Vertical model mapper for QXYSeries.
VXYModelMapper allows you to use your own QAbstractItemModel derived model with data in columns
as a data source for XYSeries based series. It is possible to use both QAbstractItemModel and
XYSeries data API to manipulate data. VXYModelMapper keeps the series and the model in sync.
*/
/*!
\property QVXYModelMapper::series
\brief Defines the QXYSeries object that is used by the mapper.
All the data in the series is discarded when it is set to the mapper.
When new series is specified the old series is disconnected (it preserves its data)
*/
/*!
\qmlproperty XYSeries VXYModelMapper::series
Defines the XYSeries object that is used by the mapper. All the data in the series is discarded when it is set to
the mapper. When new series is specified the old series is disconnected (it preserves its data).
*/
/*!
\property QVXYModelMapper::model
\brief Defines the model that is used by the mapper.
*/
/*!
\qmlproperty SomeModel VXYModelMapper::model
The QAbstractItemModel based model that is used by the mapper. You need to implement the model
and expose it to QML. Note: the model has to support adding/removing rows/columns and modifying
the data of the cells.
*/
/*!
\property QVXYModelMapper::xColumn
\brief Defines which column of the model is kept in sync with the x values of QXYSeries.
Default value is: -1 (invalid mapping)
*/
/*!
\qmlproperty int VXYModelMapper::xColumn
Defines which column of the model is kept in sync with the x values of the series. Default value is -1 (invalid
mapping).
*/
/*!
\property QVXYModelMapper::yColumn
\brief Defines which column of the model is kept in sync with the y values of QXYSeries.
Default value is: -1 (invalid mapping)
*/
/*!
\qmlproperty int VXYModelMapper::yColumn
Defines which column of the model is kept in sync with the y values of the series. Default value is -1 (invalid
mapping).
*/
/*!
\property QVXYModelMapper::firstRow
\brief Defines which row of the model contains the data for the first point of the series.
Minimal and default value is: 0
*/
/*!
\qmlproperty int VXYModelMapper::firstRow
Defines which row of the model contains the data for the first point of the series.
The default value is 0.
*/
/*!
\property QVXYModelMapper::rowCount
\brief Defines the number of rows of the model that are mapped as the data for series.
Minimal and default value is: -1 (count limited by the number of rows in the model)
*/
/*!
\qmlproperty int VXYModelMapper::columnCount
Defines the number of rows of the model that are mapped as the data for series. The default value is
-1 (count limited by the number of rows in the model).
*/
/*!
\fn void QVXYModelMapper::seriesReplaced()
Emitted when the series to which mapper is connected to has changed.
*/
/*!
\fn void QVXYModelMapper::modelReplaced()
Emitted when the model to which mapper is connected to has changed.
*/
/*!
\fn void QVXYModelMapper::xColumnChanged()
Emitted when the xColumn has changed.
*/
/*!
\fn void QVXYModelMapper::yColumnChanged()
Emitted when the yColumn has changed.
*/
/*!
\fn void QVXYModelMapper::firstRowChanged()
Emitted when the firstRow has changed.
*/
/*!
\fn void QVXYModelMapper::rowCountChanged()
Emitted when the rowCount has changed.
*/
/*!
Constructs a mapper object which is a child of \a parent.
*/
QVXYModelMapper::QVXYModelMapper(QObject *parent) :
QXYModelMapper(parent)
{
QXYModelMapper::setOrientation(Qt::Vertical);
}
QAbstractItemModel *QVXYModelMapper::model() const
{
return QXYModelMapper::model();
}
void QVXYModelMapper::setModel(QAbstractItemModel *model)
{
if (model != QXYModelMapper::model()) {
QXYModelMapper::setModel(model);
emit modelReplaced();
}
}
QXYSeries *QVXYModelMapper::series() const
{
return QXYModelMapper::series();
}
void QVXYModelMapper::setSeries(QXYSeries *series)
{
if (series != QXYModelMapper::series()) {
QXYModelMapper::setSeries(series);
emit seriesReplaced();
}
}
int QVXYModelMapper::xColumn() const
{
return QXYModelMapper::xSection();
}
void QVXYModelMapper::setXColumn(int xColumn)
{
if (xColumn != xSection()) {
QXYModelMapper::setXSection(xColumn);
emit xColumnChanged();
}
}
int QVXYModelMapper::yColumn() const
{
return QXYModelMapper::ySection();
}
void QVXYModelMapper::setYColumn(int yColumn)
{
if (yColumn != ySection()) {
QXYModelMapper::setYSection(yColumn);
emit yColumnChanged();
}
}
int QVXYModelMapper::firstRow() const
{
return first();
}
void QVXYModelMapper::setFirstRow(int firstRow)
{
if (firstRow != first()) {
setFirst(firstRow);
emit firstRowChanged();
}
}
int QVXYModelMapper::rowCount() const
{
return count();
}
void QVXYModelMapper::setRowCount(int rowCount)
{
if (rowCount != count()) {
setCount(rowCount);
emit rowCountChanged();
}
}
#include "moc_qvxymodelmapper.cpp"
QT_CHARTS_END_NAMESPACE
|
e6353c7b2d10aac7bc139a0e4f31b5c2b486adcd
|
4be1ffed57db4628a64593388e03467dcfcda571
|
/proto/main.cpp
|
b852711a7de78f17b1dc33e0aa2c8af8807d6aae
|
[] |
no_license
|
Carbohz/PythonCppInteraction
|
80dca76e5858a190246350242e7362712dd9eeb1
|
afa053fcb29931e81661fb433640d70075ba0830
|
refs/heads/main
| 2023-05-04T14:28:54.209480
| 2021-05-30T17:05:58
| 2021-05-30T17:05:58
| 372,271,299
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,473
|
cpp
|
main.cpp
|
#include <google/protobuf/service.h>
#include <grpcpp/ext/proto_server_reflection_plugin.h>
#include <grpcpp/grpcpp.h>
#include <grpcpp/health_check_service_interface.h>
#include "file.grpc.pb.h"
#include "file.pb.h"
#include "sum.h"
class SummatorImpl final : public example::Summator::Service {
public:
grpc::Status Sum(grpc::ServerContext* context, const example::InputData* request, example::Result* response) override {
response->set_res(::Sum(request->a(), request->b()));
return grpc::Status::OK;
}
};
void RunServer() {
// This parts is taken from the "hello world" gRPC sample.
using namespace std::string_literals;
const std::string server_address = "0.0.0.0:50051"s;
SummatorImpl service;
grpc::ServerBuilder builder;
// Listen on the given address without any authentication mechanism.
builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
// Register "service" as the instance through which we'll communicate with
// clients. In this case it corresponds to an *synchronous* service.
builder.RegisterService(&service);
// Finally assemble the server.
std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << server_address << std::endl;
// Wait for the server to shutdown. Note that some other thread must be
// responsible for shutting down the server for this call to ever return.
server->Wait();
}
int main() {
RunServer();
return 0;
}
|
4f15f06dc2740110c9d8d8c77dc59dc8d95722cc
|
f07bb4f7232c27bdb90af6a02459754e89f040c0
|
/include/TrickHLA/SyncPntList.hh
|
9697c4180324064c4db3e39d3fb34d1d64c66ecc
|
[
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-us-govt-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
nasa/TrickHLA
|
14cb5c2a396301dc2ce43dbf2ecc0659597ba99c
|
94d60042997da82afe708e71cf15dfa3d8be10a5
|
refs/heads/master
| 2023-09-03T01:12:27.784573
| 2023-08-29T00:12:26
| 2023-08-29T00:12:26
| 244,526,923
| 31
| 10
|
NOASSERTION
| 2023-09-10T18:26:54
| 2020-03-03T02:53:06
|
C++
|
UTF-8
|
C++
| false
| false
| 2,961
|
hh
|
SyncPntList.hh
|
/*!
@file TrickHLA/SyncPntList.hh
@ingroup TrickHLA
@brief This class extends the TrickHLA::SyncPntListBase class and provides an
instantiable implementation for storing and managing HLA synchronization points
for TrickHLA.
@copyright Copyright 2019 United States Government as represented by the
Administrator of the National Aeronautics and Space Administration.
No copyright is claimed in the United States under Title 17, U.S. Code.
All Other Rights Reserved.
\par<b>Responsible Organization</b>
Simulation and Graphics Branch, Mail Code ER7\n
Software, Robotics & Simulation Division\n
NASA, Johnson Space Center\n
2101 NASA Parkway, Houston, TX 77058
@trick_parse{everything}
@python_module{TrickHLA}
@tldh
@trick_link_dependency{../source/TrickHLA/SyncPntListBase.cpp}
@revs_title
@revs_begin
@rev_entry{Dan Dexter, NASA ER7, TrickHLA, March 2019, --, Version 2 origin.}
@rev_entry{Edwin Z. Crues, NASA ER7, TrickHLA, March 2019, --, Version 3 rewrite.}
@revs_end
*/
#ifndef TRICKHLA_SYNC_PNT_LIST_HH
#define TRICKHLA_SYNC_PNT_LIST_HH
// System includes.
// Trick include files.
// TrickHLA include files.
#include "TrickHLA/StandardsSupport.hh"
#include "TrickHLA/SyncPntListBase.hh"
// C++11 deprecated dynamic exception specifications for a function so we need
// to silence the warnings coming from the IEEE 1516 declared functions.
// This should work for both GCC and Clang.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
// HLA include files.
#include RTI1516_HEADER
#pragma GCC diagnostic pop
namespace TrickHLA
{
class SyncPntList : public TrickHLA::SyncPntListBase
{
// Let the Trick input processor access protected and private data.
// InputProcessor is really just a marker class (does not really
// exists - at least yet). This friend statement just tells Trick
// to go ahead and process the protected and private data as well
// as the usual public data.
friend class InputProcessor;
// IMPORTANT Note: you must have the following line too.
// Syntax: friend void init_attr<namespace>__<class name>();
friend void init_attrTrickHLA__SyncPntList();
public:
//
// Public constructors and destructor.
//
/*! @brief Default constructor for the TrickHLA SyncPntList class. */
SyncPntList()
{
return;
}
/*! @brief Pure virtual destructor for the TrickHLA SyncPntList class. */
virtual ~SyncPntList()
{
return;
}
private:
// Do not allow the copy constructor or assignment operator.
/*! @brief Copy constructor for SyncPntList class.
* @details This constructor is private to prevent inadvertent copies. */
SyncPntList( SyncPntList const &rhs );
/*! @brief Assignment operator for SyncPntList class.
* @details This assignment operator is private to prevent inadvertent copies. */
SyncPntList &operator=( SyncPntList const &rhs );
};
} // namespace TrickHLA
#endif /* TRICKHLA_SYNC_PNT_LIST_HH */
|
eecedec2b89b5913e77d3db2a5226d4f87313e9d
|
9fe2b7394d8246fcf87439f560ff935f3d898e72
|
/EmrClient/EMR/obj/view/input/ImageMouseInput.h
|
b4cb1fdc34468bf4048f630e97597f356d7a4c28
|
[] |
no_license
|
sky-tree/emr
|
a04d5e3a66eea8ce0faf1ed1297f2d9de1533e05
|
468bb25b97959627730ed277fdfa72f9a6736013
|
refs/heads/master
| 2021-01-24T03:37:13.566997
| 2018-02-26T01:19:21
| 2018-02-26T01:19:21
| 122,894,442
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 518
|
h
|
ImageMouseInput.h
|
#ifndef _IMAGE_MOUSE_INPUT_H_
#define _IMAGE_MOUSE_INPUT_H_
#pragma once
#include "BaseMouse.h"
#include "ViewObj.h"
class ImageMouseInput :public BaseMouse
{
public:
ImageMouseInput(ViewObj * owner);
ImageMouseInput(ViewObj * owner, BaseMouse * scoure);
~ImageMouseInput();
public:
int mousePress(int type, int x, int y);
int mouseRelease(int type, int x, int y);
int mouseDrag(int type, int x, int y);
int mouseDoublePress(int type, int x, int y);
private:
void doDoublePress(bool isAction);
};
#endif
|
e59b8eb0ecb08cec4c05ce6656e3e14e3b1b2ee2
|
627ddc63ba0ef8978f7cbae23cb0a1f1cb979e9a
|
/Include/Kernel/Drivers/STM32/TLV493DDriver.h
|
705353bc0d59ac599cf68189e4426eb17171b116
|
[] |
no_license
|
kavionic/PadOS
|
4190ef764b146de6b756e97d3859d6d0fec3e2ec
|
64acab418038ddcf7306c77ffbabc1c6880591d4
|
refs/heads/master
| 2023-07-04T09:58:57.316342
| 2023-06-26T23:46:39
| 2023-06-26T23:46:39
| 125,652,980
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,095
|
h
|
TLV493DDriver.h
|
// This file is part of PadOS.
//
// Copyright (C) 2020 Kurt Skauen <http://kavionic.com/>
//
// PadOS 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.
//
// PadOS 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 PadOS. If not, see <http://www.gnu.org/licenses/>.
///////////////////////////////////////////////////////////////////////////////
// Created: 04.03.2020 21:59:38
#pragma once
#include <cmath>
#include "Kernel/HAL/DigitalPort.h"
#include "Kernel/VFS/KDeviceNode.h"
#include "Kernel/KMutex.h"
#include "Kernel/KConditionVariable.h"
#include "DeviceControl/TLV493D.h"
#include "Utils/Utils.h"
#include "Threads/Thread.h"
namespace kernel
{
// I2C addresses
#define TLV493D_I2C_ADDR_PRIM 0xbc
#define TLV493D_I2C_ADDR_SEC 0x3e
struct tlv493d_read_registers
{
uint8_t BXH;
uint8_t BYH;
uint8_t BZH;
uint8_t TempHFrmCh;
uint8_t BXYL;
uint8_t FlagsBZL;
uint8_t TempL;
uint8_t DefaultCfg1;
uint8_t DefaultCfg2;
uint8_t DefaultCfg3;
};
// Fields in tlv493d_read_registers::TempHFrmCh
static const uint8_t TLV493D_CHANNEL_Pos = 0;
static const uint8_t TLV493D_CHANNEL = 0x03;
static const uint8_t TLV493D_FRAME_Pos = 2;
static const uint8_t TLV493D_FRAME = 0x0c;
// Fields in tlv493d_read_registers::FlagsBZL
static const uint8_t TLV493D_POWER_DOWN = 0x10;
static const uint8_t TLV493D_BZL_Pos = 0;
static const uint8_t TLV493D_BZL = 0xf;
struct tlv493d_write_registers
{
uint8_t Reserved1;
uint8_t Mode1;
uint8_t Reserved2;
uint8_t Mode2;
};
static const uint8_t TLV493D_MODE1_LOW = 0x01;
static const uint8_t TLV493D_MODE1_FAST = 0x02;
static const uint8_t TLV493D_MODE1_INT = 0x04;
static const uint8_t TLV493D_MODE1_IICADDR1 = 0x20;
static const uint8_t TLV493D_MODE1_IICADDR2 = 0x40;
static const uint8_t TLV493D_MODE1_PARITY = 0x80;
constexpr int32_t TLV493D_MAX_FRAMERATE = 2475; // 3.3kHz - 25%
constexpr TimeValMicros TLV493D_CONVERSION_TIME = TimeValMicros::FromMicroseconds(TimeValMicros::TicksPerSecond / TLV493D_MAX_FRAMERATE);
class TLV493DDriver : public PtrTarget, public os::Thread, public SignalTarget, public KFilesystemFileOps
{
public:
IFLASHC TLV493DDriver();
IFLASHC ~TLV493DDriver();
IFLASHC bool Setup(const char* devicePath, const char* i2cPath, DigitalPinID powerPin);
IFLASHC virtual int Run() override;
IFLASHC virtual int DeviceControl(Ptr<KFileNode> file, int request, const void* inData, size_t inDataLength, void* outData, size_t outDataLength) override;
IFLASHC virtual ssize_t Read(Ptr<KFileNode> file, off64_t position, void* buffer, size_t length) override;
private:
enum class State_e
{
Initializing,
Idle,
ReadingTempPressCalibration,
ReadingHumidityCalibration,
ReadingRegister,
ProcessingRegister
};
IFLASHC void ResetSensor();
IFLASHC void ConfigChanged();
IFLASHC void UpdateParity();
KMutex m_Mutex;
KConditionVariable m_NewFrameCondition;
KConditionVariable m_NewConfigCondition;
State_e m_State = State_e::Initializing;
TimeValMicros m_LastUpdateTime;
TimeValMicros m_PeriodTime;
float m_AveragingScale = 1.0f;
DigitalPin m_PowerPin;
int m_I2CDevice = -1;
uint8_t m_DeviceAddress = TLV493D_I2C_ADDR_PRIM;
tlv493d_config m_Config;
tlv493d_read_registers m_ReadRegisters;
tlv493d_write_registers m_WriteRegisters;
tlv493d_data m_CurrentValues;
TLV493DDriver(const TLV493DDriver &) = delete;
TLV493DDriver& operator=(const TLV493DDriver &) = delete;
};
} // namespace
|
db1a277b0fb15e987801ac6d932ce1d6639deeca
|
586de0d5a2f83c05ec0669f7261c125a7efd553c
|
/mcc/HUD/cfgFunctions.hpp
|
6c56b02ea90913d8715d7ac0ac81324b87013fe6
|
[] |
no_license
|
Razatop/MCC_sandbox_modDev
|
91fc39c9a2df5d930e11c47b1b98212a470c94e9
|
b9ec8a780a1e2fd7b14e08c9f4b68562dddf552f
|
refs/heads/master
| 2023-07-18T18:17:51.252303
| 2021-08-26T06:48:12
| 2021-08-26T06:48:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 377
|
hpp
|
cfgFunctions.hpp
|
class HUD {
#ifdef MCCMODE
file = "\mcc_sandbox_mod\mcc\HUD\fnc";
#else
file = "mcc\HUD\fnc";
#endif
class initCompassHUD {};
class initHUD {postInit = 1;};
class supressionInit {};
class supressionFiredEH {};
class supressionEffects {};
class forceCamera {description = "Force first person camera";};
class PvPInterface {description = "Enable PvP interface";};
};
|
6bbc373a8f1de24ba04b95c4d989c3172318f722
|
b69c6e4e3144c15360a73cdfcc32678ee04ea380
|
/src/ParserCalc/ParserCalc.h
|
24f1538e2f85f425f07cad57fc5b6f4d16a8972b
|
[] |
no_license
|
yet-another-average-joe/WorkShop_Calculator
|
ad13082a8df7bc1a526a7d8d0016a8737e1ee9a8
|
a0c6bc470bfd1925f7e9d29f7a5a0a093260adf2
|
refs/heads/master
| 2020-08-09T02:01:14.842256
| 2019-10-11T00:10:57
| 2019-10-11T00:10:57
| 213,972,598
| 1
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 467
|
h
|
ParserCalc.h
|
// ParserCalc.h : fichier d'en-tête principal pour l'application PROJECT_NAME
//
#pragma once
#include "AppSheet.h"
#include "resourceppc.h"
// CParserCalcApp:
// Consultez ParserCalc.cpp pour l'implémentation de cette classe
//
class CParserCalcApp : public CAppSheet
{
public:
CParserCalcApp();
// Substitutions
public:
virtual BOOL InitInstance();
// Implémentation
DECLARE_MESSAGE_MAP()
};
extern CParserCalcApp theApp;
|
b6983160658e39babcd84b234e07f3379a49af1d
|
28deae191271bc80344aa266aa71856a0a558dd4
|
/Project/befc/smi/calls/svi/SviProcGetBlkReply.hpp
|
5842d4e070bf9c6727c170723e75b27455a1a87d
|
[] |
no_license
|
ruudstaal/myproject
|
fb15d2da87523edccd86c3450cb01c16c76ce61b
|
483dff59824a39508c1f8c6df5d37c60fbd84429
|
refs/heads/main
| 2023-03-16T10:21:19.198456
| 2021-02-26T10:31:11
| 2021-02-26T10:31:11
| 342,539,312
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,037
|
hpp
|
SviProcGetBlkReply.hpp
|
/*
* SviProcGetBlkReply.hpp
*
* Created on: Mar 13, 2017
* Author: madsen
*/
#ifndef BEFC_SMI_CALLS_SVI_SVIPROCGETBLKREPLY_HPP_
#define BEFC_SMI_CALLS_SVI_SVIPROCGETBLKREPLY_HPP_
#include <SmiCallReply.hpp>
#include "ParametrizedObject.hpp"
class SviProcGetBlkReply: public SmiCallReply, public ParametrizedObject
{
public:
SviProcGetBlkReply();
virtual ~SviProcGetBlkReply();
void readReply(SmiStream *pStream);
void callFailed(UINT32 reason);
SINT32 getReturnCode();
UINT32 getDataLength();
int getReplySize();
UINT8* getData();
//In case reply states that BLK should be read with MultiBLK calls.
bool useMultiBlk(){return isMultiBlk;}
UINT32 getBufferId(){return bufferId;}
UINT32 getBufferlength(){return bufferlength;}
private:
SINT32 returnCode;
UINT32 dataLength;
UINT8* data;
//In case value should be set with MultiBLK
bool isMultiBlk;
UINT32 bufferId;
UINT32 bufferlength;
};
#endif /* BEFC_SMI_CALLS_SVI_SVIPROCGETBLKREPLY_HPP_ */
|
9d567cfb9133cba7bcba914ec79eda3b54bc0f5c
|
713895f4545dc65f9ca467e48708e4a93c8bfdf2
|
/ProcessInfo.h
|
851be21d770a9c91147547e31a0d5d4c3813a25c
|
[] |
no_license
|
AndreyFlyAway/ProcessesInfo
|
51bfd61fddaf784dea0443b74d3e9f3e9af0f0eb
|
a4a1cf1fc34d3441ebbf7a744f7163a04be7b510
|
refs/heads/master
| 2020-04-24T23:13:09.551176
| 2019-03-10T12:41:05
| 2019-03-10T12:41:05
| 172,336,468
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,355
|
h
|
ProcessInfo.h
|
#include <string.h>
#include <dirent.h>
#include <dirent.h>
#include <unistd.h>
#include <string>
#include <sstream>
#include <vector>
#include <iostream>
#include <fstream>
//#include <INIReader.cpp>
#include "cpp/INIReader.h"
//#include "ini.h"
//#include "/home/user/opt/inih/cpp/INIReader.h"
#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>
#include <log4cplus/configurator.h>
#include <log4cplus/initializer.h>
#include <log4cplus/helpers/fileinfo.h>
#include <log4cplus/syslogappender.h>
#include <log4cplus/consoleappender.h>
#include <log4cplus/fileappender.h>
#include <log4cplus/asyncappender.h>
using namespace log4cplus;
using namespace log4cplus::helpers;
#ifndef PROCESSINFO__H_
#define PROCESSINFO__H_
namespace process_info
{
#define MAXLEN 1000
#define MAXPIDLEN 1000
#define PID_LEN 6
#define PROC_FOLDER "/proc/"
#define PROC_NAME "/comm"
#define PROC_STAT_FOLDER "/proc/stat"
#define MEMINFO_FOLDER "/proc/meminfo"
#define N_FREQ 5
#define SLEEP_DISCR_MC 200000 // для ожидания во время сбора инофрмации о процессе
#define SLEEP_PID_ERROR_MC 300000 // время оиждания между попытками найти PID,
#define LOGGER_NAME "log"
#define STATUS_FILE_LINES 41
#define SYS_FILE_NUM 4
/* list of file in /proc/sys/kernel/, they are used for reading information about distributive */
const std::string sys_info_list[SYS_FILE_NUM] = {"/proc/sys/kernel/ostype",
"/proc/sys/kernel/hostname",
"/proc/sys/kernel/osrelease",
"/proc/sys/kernel/version", };
const std::string DEFAULT_CONFIG_FILE_PATH {"config_processes.ini"};
static long int g_n_freq {}; // количество интервалов
static long int g_sleep_discr {}; // время между интервалами
static long int g_average_n = {}; // количество интервалов, которые будет учитываться для вычисления среднего значение
static int average_counter {}; // для подсчте среднего значения
static float cpu_load {1.1};
static long g_total_mem {}; /* для хранения количества памяти на машине */
/* структура для хранения памят иданных о процессе */
struct proc_info
{
// std::string name[MAXLEN];
char name[MAXLEN];
char pid[PID_LEN];
float cur_CPU_usage = 0;
float max_CPU_usage = 0;
float average_CPU = 0;
float sum_CPU_values = 0;
int virt_mem = -1;
int rss_mem = -1;
float mem_in_percent;
};
struct process_info_t
{
// std::string name[MAXLEN];
std::string name {};
std::string pid {};
float cur_CPU_usage = 0;
float max_CPU_usage = 0;
float average_CPU = 0;
float sum_CPU_values = 0;
int virt_mem = -1;
int rss_mem = -1;
float mem_in_percent;
};
std::string get_pid(const std::string & proc_name);
int process_cpu(const std::string &pid_c);
int resources_usage(std::vector <process_info_t> &config, const int n_freq, const int sleep_t_ms);
void get_cpu_section(std::vector <process_info_t> &config, int out_arr[]);
void get_mem_section(std::vector <process_info_t> &config, int o_virt_arr[], int o_rss_arr[], float o_rss_perc_arr[]);
int MEM_usage(const std::string & pid, int & virt_out, int & rss_out, float & rss_percentage);
std::string get_num_frm_str(const std::string & str);
int load_config(std::vector <process_info_t> &config, const std::string & conf_file_path);
int copy_word(char * str_in, char * str_out);
long get_total_mem(void);
int get_system_info(char * str_out);
int & proc_stat(int &cpu_total, int &idle);
std::vector <std::string> & split_string(const std::string & str,
std::vector <std::string> & buf,
const std::string & sp_str=" ");
//int check_process(void);
}
#endif
|
5b9e3e1a4fc180bdb6b8793a06d31d1a886b13a7
|
c30d1183ed353065828f1249613ac2c7ace6c1a9
|
/BigQ.h
|
b61e1fc248b19b4482dd2554720e8f04d8b6b65c
|
[] |
no_license
|
siyuan808/DBI-Final-Proj
|
2c38e8be938565e1c293d76f6c78cd423ae311ad
|
a68c248479d88a0c76817cf177fd58cb013d0836
|
refs/heads/master
| 2020-12-24T13:20:41.230042
| 2013-05-16T13:55:46
| 2013-05-16T13:55:46
| 10,037,347
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,910
|
h
|
BigQ.h
|
#ifndef BIGQ_H
#define BIGQ_H
#include <pthread.h>
#include <iostream>
#include "Pipe.h"
#include "File.h"
#include "Record.h"
#include <vector>
#include <sstream>
#include <sys/time.h>
#include <string.h>
//#include <queue>
using namespace std;
//class CompareRecord {
//private:
// OrderMaker *orderMaker;
// ComparisonEngine cmp;
//public:
// CompareRecord(OrderMaker *order);
// ~CompareRecord();
// bool operator()(Record *r1, Record *r2) {
// if(cmp.Compare(r1, r2, orderMaker) != 1)
// return true;
// else return false;
// }
//};
//typedef priority_queue<Record, vector<Record>, CompareRecord> PQ;
//PQ pq;
class BigQ {
struct Util{
Pipe *in;
Pipe *out;
OrderMaker *sortorder;
int runlen;
Util(Pipe *i, Pipe *o, OrderMaker *s, int l){
in = i;
out = o;
sortorder = s;
runlen = l;
}
~Util();
};
private:
Util *util;
Page *runPages;
char *fileName;
char *phaseIIfilename;
File *tmpFile;
int runNum;
struct CompareRecords
{
OrderMaker *pSortOrder;
CompareRecords(OrderMaker *pOM): pSortOrder(pOM) {}
bool operator()(Record* const& r1, Record* const& r2)
{
Record* r11 = const_cast<Record*>(r1);
Record* r22 = const_cast<Record*>(r2);
ComparisonEngine ce;
//sort in a descending order, 'cause we fetch it reversely
if (ce.Compare(r11, r22, pSortOrder) ==1)
return true;
else
return false;
}
};
private:
static void *workerHelper(void *);
void *worker();
void mergeOut();
// int sort(int rcdNum);
void appendRunToFile(vector<Record*>* aRun, bool);
// //auxiliary methods for sort
// void quickSort(Record *record, int *result, int start,
// int end, OrderMaker *sortorder);
// int partition(Record *record, int *result, int start,
// int end, OrderMaker *sortorder);
bool lessThan(Record &, Record &, OrderMaker &);
public:
BigQ (Pipe &in, Pipe &out, OrderMaker &sortorder, int runlen);
~BigQ ();
};
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.