text
stringlengths 8
6.88M
|
|---|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef WINDOWS_OPMESSAGE_LOOP_H
#define WINDOWS_OPMESSAGE_LOOP_H
#ifndef NS4P_COMPONENT_PLUGINS
# include "platforms/windows/pi/WindowsOpMessageLoopLegacy.h"
#else // NS4P_COMPONENT_PLUGINS
#include "adjunct/quick/managers/sleepmanager.h"
#include "platforms/windows/IPC/WindowsOpComponentPlatform.h"
/** Maximum number of unprocessed WM_KEYDOWN entries recorded. */
#define MAX_KEYDOWN_QUEUE_LENGTH 128
/** Maximum number of non-standard virtual key => WM_CHAR character value
* mappings recorded. */
#define MAX_KEYUP_TABLE_LENGTH 32
#include "platforms/windows/pi/WindowsOpWindow.h"
#include "platforms/windows/utils/sync_primitives.h"
class WindowsOpMessageLoop
: public WindowsOpComponentPlatform
, public StayAwakeListener
, private WindowsOpComponentPlatform::WMListener
{
public:
WindowsOpMessageLoop();
~WindowsOpMessageLoop();
OP_STATUS Init();
OP_STATUS Run() {return Run(NULL);}
OpKey::Code ConvertKey_VK_To_OP(UINT32 vk_key);
BOOL TranslateOperaMessage(MSG *pMsg, BOOL &called_translate);
inline void SSLSeedFromMessageLoop(const MSG *msg);
OP_STATUS Run(WindowsOpWindow* wait_for_this_dialog_to_close);
void EndDialog(WindowsOpWindow* window) {m_dialog_hash_table.Remove(window);}
BOOL OnAppCommand(UINT32 lParam);
void DispatchAllPostedMessagesNow();
// implementing OpComponentPlatform
virtual OP_STATUS RequestPeer(int& peer, OpMessageAddress requester, OpComponentType type);
virtual OP_STATUS RequestPeerThread(int& peer, OpMessageAddress requester, OpComponentType type) { return OpStatus::ERR_NOT_SUPPORTED; }
//implementing StayAwakeListener
virtual void OnStayAwakeStatusChanged(BOOL stay_awake);
private:
// Internal class.
class AppCommandInfo
{
public:
AppCommandInfo(OpInputAction::Action action, OpInputContext* input_context, INTPTR action_data)
: m_action(action),
m_action_data(action_data),
m_input_context(input_context)
{
}
OpInputAction::Action m_action;
OpInputContext* m_input_context;
INTPTR m_action_data;
};
//Used to store information about processes started by RequestPeer
struct ProcessDetails
{
~ProcessDetails()
{
if (!pid)
UnregisterWait(process_wait);
else
UnregisterWaitEx(process_wait, INVALID_HANDLE_VALUE);
CloseHandle(process_handle);
}
HANDLE process_handle;
INT32 pid;
HANDLE process_wait;
WindowsOpMessageLoop* message_loop;
};
// Methods.
static VOID CALLBACK ReportDeadPeer(PVOID process_details, BOOLEAN timeout);
virtual void HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam);
OP_STATUS ProcessMessage(MSG &msg);
OP_STATUS DoLoopContent(BOOL ran_core);
// Members.
OpCriticalSection m_known_processes_list_access;
/* List of initialized ProcessDetails structures. Used to make sure we
don't leak them on exit. */
OpVector<ProcessDetails> m_known_processes_list;
BOOL m_destructing;
OpPointerSet<WindowsOpWindow> m_dialog_hash_table;
WindowsOpWindow* m_wait_for_this_dialog_to_close;
BOOL m_use_RTL_shortcut;
UINT GetRShiftScancode() { return m_rshift_scancode; }
/** Determine if the virtual_key and modifiers will produce a character value.
* If TRUE, the reporting of a keydown must wait until the translation
* of the key has occurred. If FALSE, the key does not produce a character
* value and its keydown event may be reported right away. */
BOOL HasCharacterValue(OpKey::Code virtual_key, ShiftKeyState shiftkeys, WPARAM wParam, LPARAM lParam);
/** Insert a mapping from a WM_KEYDOWN's wParam to the wParam
* that its corresponding WM_CHAR produced. If a mapping already
* exists, it's value will be overwritten/updated. */
void AddKeyValue(WPARAM wParamDown, WPARAM wParamChar);
/** Return the character value that virtual_key has been
* recorded as producing. Returns TRUE if found, and wParamChar
* is updated with its value. FALSE if no mapping known. */
BOOL LookupKeyCharValue(WPARAM virtual_key, WPARAM &wParamChar);
/** Clear out any queued character values kept. */
void ClearKeyValues();
AppCommandInfo* m_pending_app_command;
/** Scancode for the right Shift key; used to disambiguate location of
the VK_SHIFT virtual key. */
UINT m_rshift_scancode;
/** Associating the WPARAM from a WM_KEYDOWN with the translated character
* it produces in a WM_CHAR.
*
* Used when processing WM_KEYUP, having to affix the character value that
* its key produces/d. @see m_keyvalue_table. */
class KeyValuePair
{
public:
/** The WPARAM of the WM_KEYDOWN that initiated the key event. */
WPARAM keydown_wParam;
/** The WPARAM that the WM_CHAR reported for the WM_KEYDOWN
* corresponding to keydown_wParam. */
WPARAM char_wParam;
};
/** The delivery of keyup events must include the character value
* of the virtual key. The WM_KEYUP only supplies the virtual key,
* hence a table is kept of virtual keys and the character values
* they produced on WM_CHAR. If a valid match is found for the virtual
* key, that entry's character will be included. If not, no character
* value will be included. For function and modifier keys that do
* not produce character values, that is expected.
*
* To handle this, keep a mapping table for all standard VKs together
* with a fixed size one for non-standard ones that somehow are generated
* (its size controlled by MAX_KEYUP_TABLE LENGTH.) Should the user
* be able to hold down more non-standard keys than that without
* first releasing any, keyup events for these won't have correct
* character value information attached. Given that it is unclear
* if any virtual key map into this range, the risk of information
* loss is on the low side. KeyValuePair encodes the association
* for these non-standard keys. */
WPARAM* m_keyvalue_vk_table;
KeyValuePair* m_keyvalue_table;
/** Index of next available slot in the m_keyvalue_table table. */
unsigned int m_keyvalue_table_index;
};
extern WindowsOpMessageLoop* g_windows_message_loop;
#endif // NS4P_COMPONENT_PLUGINS
#endif // WINDOWS_OPMESSAGE_LOOP_H
|
#ifndef EDITORWIDGET_H
#define EDITORWIDGET_H
#include <QWidget>
#include <QLabel>
#include <QHBoxLayout>
#include <QDoubleSpinBox>
#include <QFormLayout>
#include <QComboBox>
#include "Editor.h"
#include "EditorView.h"
class EditorView;
/**
* @brief Widget that allow ModifierGroup edition and modification of edition parameters
*/
class EditorWidget : public QWidget
{
Q_OBJECT
public:
explicit EditorWidget(Editor *editor, QWidget *parent = 0);
void refresh(void);
void enable_modifier_add(bool on);
private:
Editor *editor_;
EditorView *editor_view_;
QComboBox *combo_box_modifier_;
QPushButton *add_modifier_button_;
QDoubleSpinBox *displacement_val_;
Editor *editor(void);
EditorView *editor_view(void);
void editor(Editor *editor);
void editor_view(EditorView *editor_view);
signals:
void signal_refresh_modifiers_widget();
void signal_refresh_trajectory_widget();
private slots:
void add_modifier(void);
void precise_value_displacement(double value);
void enable_precise_edit(bool on);
};
#endif // EDITORWIDGET_H
|
/* BEGIN LICENSE */
/*****************************************************************************
* SKCore : the SK core library
* Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr>
* $Id: textfile.cpp,v 1.11.2.2 2005/02/17 15:29:21 krys Exp $
*
* Authors: Alexis Seigneurin <seigneurin @at@ idm .dot. fr>
* Arnaud de Bossoreille de Ribou <debossoreille @at@ idm .dot. fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Alternatively you can contact IDM <skcontact @at@ idm> for other license
* contracts concerning parts of the code owned by IDM.
*
*****************************************************************************/
/* END LICENSE */
#include <nspr/nspr.h>
#include <nspr/plstr.h>
#include "../skcoreconfig.h"
#include "../machine.h"
#include "../error.h"
#include "../refcount.h"
#include "../skptr.h"
#include "skfopen.h"
#include "file.h"
#include "textfile.h"
#include "inifile.h"
#define DEFAULT_BUFFER_SIZE 4096
SKTextFile::SKTextFile() : m_bReady(PR_FALSE),
m_pFileDesc(NULL),
m_pszBuffer(NULL),
m_iBufferSize(0),
m_iFileSize(0),
m_pDelegate(NULL)
{
}
SKTextFile::~SKTextFile()
{
if(m_pFileDesc)
PR_Close(m_pFileDesc);
if(m_pszBuffer)
PR_Free(m_pszBuffer);
}
SKERR SKTextFile::SetFileName(const char *pszFileName,
const char *pszDefaultFileName)
{
if(pszFileName)
{
SKERR err = SKFile::SetFileName(pszFileName, pszDefaultFileName);
if(err != noErr)
return err;
m_pFileDesc = skPR_Open(m_pszFileName, PR_RDONLY, 0);
if(!m_pFileDesc)
return err_failure;
PRFileInfo Info;
if (PR_GetOpenFileInfo(m_pFileDesc, &Info)!= PR_SUCCESS)
return err_failure;
m_iFileSize = Info.size;
}
else
{
return err_failure;
}
return PostInitialize();
}
SKERR SKTextFile::SetFileDesc(PRFileDesc *pFd)
{
m_pFileDesc = pFd;
m_iFileSize = 0;
return PostInitialize();
}
SKERR SKTextFile::PostInitialize()
{
m_pszBuffer = (char *)PR_Malloc((DEFAULT_BUFFER_SIZE + 1) * sizeof(char));
if(!m_pszBuffer)
return err_memory;
m_iBufferSize = DEFAULT_BUFFER_SIZE;
m_iDeadLength = 0;
m_iReadLength = 0;
m_bReady = PR_TRUE;
m_bFinished = PR_FALSE;
return noErr;
}
PRUint32 SKTextFile::GetFilePosition ()
{
PRInt32 iPos = PR_Seek (m_pFileDesc, 0, PR_SEEK_CUR);
// PR_Seek returns -1 if the call failed
return (PRUint32) iPos;
}
PRUint32 SKTextFile::GetFileSize()
{
return m_iFileSize;
}
SKERR SKTextFile::GetLine(char **ppszLine)
{
if(!m_bReady)
return err_failure;
if(!ppszLine)
return err_invalid;
// are we done ?
if(m_bFinished && m_iDeadLength == m_iReadLength)
{
*ppszLine = 0;
PR_Free(m_pszBuffer);
m_pszBuffer = 0;
m_iDeadLength = 0;
m_iReadLength = 0;
m_iBufferSize = 0;
return noErr;
}
PRUint32 iStart = m_iDeadLength;
PRUint32 iEnd = iStart;
while(iEnd < m_iReadLength && m_pszBuffer[iEnd] != '\n')
iEnd++;
// do we have a full line ?
if(iEnd < m_iReadLength || m_bFinished)
{
if(iEnd < m_iReadLength)
{
m_pszBuffer[iEnd] = '\0';
if ((iEnd > iStart) && (m_pszBuffer[iEnd-1] == '\r'))
m_pszBuffer[iEnd-1] = '\0';
}
else
{
// this is the last line
SK_ASSERT(iEnd == m_iReadLength && m_bFinished);
m_pszBuffer[iEnd--] = '\0';
}
m_iDeadLength = iEnd + 1;
*ppszLine = m_pszBuffer + iStart;
return noErr;
}
// recopy the still living part of the buffer at the beginning
if(m_iDeadLength)
{
for(PRUint32 i = 0; i < m_iReadLength - m_iDeadLength; i++)
m_pszBuffer[i] = m_pszBuffer[i+m_iDeadLength];
m_iReadLength -= m_iDeadLength;
m_iDeadLength = 0;
}
// can we read more stuff in our buffer ?
if(m_iReadLength == m_iBufferSize)
{
m_iBufferSize = 2 * m_iBufferSize;
m_pszBuffer = (char*) PR_Realloc(m_pszBuffer,
(m_iBufferSize + 1) * sizeof(char));
}
// read more data
PRInt32 iRead = PR_Read(m_pFileDesc,
m_pszBuffer + m_iReadLength,
m_iBufferSize - m_iReadLength);
if(iRead < 0)
return err_failure;
if(iRead == 0)
m_bFinished = PR_TRUE;
m_iReadLength += iRead;
return GetLine(ppszLine);
}
SKERR SKTextFile::ParseConfiguration()
{
IniParser parser(this);
SKERR err = noErr;
char* pszSection = NULL;
char* pszName = NULL;
char* pszValue = NULL;
PushEnvir();
PRUint32 line = 0;
while ( (err == noErr)
&& parser.readIniLine(&pszSection, &pszName, &pszValue, &line))
{
err = ConfigureItem(pszSection, pszName, pszValue);
if(err != noErr)
SKError(err_failure, "[SKTextFile::ParseConfiguration] "
"Stops parsing. Error %d on line %d of %s : %s/%s=%s",
err, line, GetSharedFileName(),
pszSection, pszName, pszValue);
}
PopEnvir();
return err;
}
SKERR SKTextFile::ConfigureItem(char *pszSection, char *pszName, char *pszValue)
{
SKERR err = err_not_handled;
if(!pszName)
return noErr;
#ifdef DEBUG_CONFIG
SKDebugLog("SKFile:: [%s] %s=%s", pszSection, pszName, pszValue);
#endif
if(m_pDelegate)
err = m_pDelegate->ConfigureItem(pszSection, pszName, pszValue);
if(err != err_not_handled)
return err;
// nobody knows about this configuration option
return SKError(err_cnf_invalid, "[SKTextFile::Configure] "
"Invalid configuration option [%s] %s=%s",
pszSection, pszName, pszValue);
}
|
/*
Copyright (c) 2014 Mircea Daniel Ispas
This file is part of "Push Game Engine" released under zlib license
For conditions of distribution and use, see copyright notice in Push.hpp
*/
#pragma once
#include <type_traits>
namespace Push
{
template<typename T>
typename std::enable_if<std::is_integral<T>::value && std::is_unsigned<T>::value, T>::type MakeNumber(const char*& begin, const char* end)
{
T value = 0;
while(begin != end && std::isdigit(*begin))
{
value = value * 10 + static_cast<T>(*begin++) - '0';
}
return value;
}
template<typename T>
typename std::enable_if<std::is_integral<T>::value && std::is_signed<T>::value, T>::type MakeNumber(const char*& begin, const char* end)
{
return begin != end && *begin == '-' ? -static_cast<T>(MakeNumber<typename std::make_unsigned<T>::type>(++begin, end)) : static_cast<T>(MakeNumber<typename std::make_unsigned<T>::type>(begin, end));
}
template<typename T>
typename std::enable_if<std::is_floating_point<T>::value, T>::type MakeNumber(const char*& begin, const char* end)
{
T sign = T(1);
T integral = 0;
if(begin != end && *begin == '-')
{
begin += 1;
sign = T(-1);
}
while(begin != end && std::isdigit(*begin))
{
integral = integral * 10 + *begin++ - '0';
}
if(begin != end && *begin == '.')
{
T exponent = 1;
T fractional = 0;
begin += 1;
while(begin != end && std::isdigit(*begin))
{
exponent *= 10;
fractional = fractional * 10 + *begin++ - '0';
}
return sign * (integral + fractional / exponent);
}
return sign * integral;
}
}
|
// --- This file is distributed under the MIT Open Source License, as detailed
// by the file "LICENSE.TXT" in the root of this repository ---
#include "hurchalla/util/traits/extensible_make_signed.h"
#include "hurchalla/util/compiler_macros.h"
#include "gtest/gtest.h"
#include <cstdint>
#include <type_traits>
namespace {
template <typename T, typename S>
void check_type_conversion()
{
namespace ut = hurchalla::util;
static_assert(std::is_same<S, typename
ut::extensible_make_signed<T>::type>::value, "");
static_assert(std::is_same<const S, typename
ut::extensible_make_signed<const T>::type>::value, "");
static_assert(std::is_same<volatile S, typename
ut::extensible_make_signed<volatile T>::type>::value, "");
static_assert(std::is_same<const volatile S, typename
ut::extensible_make_signed<const volatile T>::type>::value, "");
}
TEST(HurchallaUtil, extensible_make_signed) {
#if HURCHALLA_COMPILER_HAS_UINT128_T()
check_type_conversion<__int128_t, __int128_t>();
check_type_conversion<__uint128_t, __int128_t>();
#endif
check_type_conversion<std::int64_t, std::int64_t>();
check_type_conversion<std::uint64_t, std::int64_t>();
check_type_conversion<std::int32_t, std::int32_t>();
check_type_conversion<std::uint32_t, std::int32_t>();
check_type_conversion<std::int16_t, std::int16_t>();
check_type_conversion<std::uint16_t, std::int16_t>();
check_type_conversion<std::int8_t, std::int8_t>();
check_type_conversion<std::uint8_t, std::int8_t>();
// the following statement should cause a static_assert compile error within
// extensible_make_signed, if it is enabled:
#if 0
using T = hurchalla::util::extensible_make_signed<float>::type;
#endif
}
} // end namespace
|
/**********************************************************************************
camera.h
This file contains the class definition, attributes, and methods For the camera.
The Pixy2 camera uses the Arduino library that can be downloaded from the pixy
website (https://pixycam.com/downloads-pixy2/). The camera settings (such as the
signature setting, brightness, etc.) are set through the PixyMon software that is
also a free download at the same website. The code is a modified version of the
"cc_i2c_uart" example given in the Pixy2 library.
Last Edited by Ethan Lauer 3/29/20
*********************************************************************************/
#include <Arduino.h>
#include <Pixy2I2C.h> // include the Pixy iibrary available for download
class Camera {
private:
Pixy2I2C pixy; // create the pixy camerea object
public:
// Maximum Pixel Values - these are public so they can be called in the
// followHand() function in head.h.
// Directions are assuming you are looking from the camera's point of view.
// (0,0) point is in the top left corner of the camera's field of view.
// X axis
const int pixMaxLeft = 0;
const int pixMaxRight = 316;
//Y axis
const int pixMaxUp = 0;
const int pixMaxDown = 208;
//************************************************INITIALIZE********************************
// Define the camera
Camera () {
}
/*
setUp - run the init() function that is abstracted back into the pixy library
print a statement so the user can see where in the setup the program is
*/
void setUp() {
Serial.println("Initializing Camera");
pixy.init();
}
//**************************************** GET INFORMATION ************************************
/*
getBlockInfo - get any information from the detected blocks since (for now) HAL is only following
a single hand or block, only get the information if there was one block detected.
Note: this should be adjusted in the PixyMon software also so the camera is only
detecting one block maximum
int state - an integer that corresponds to the requested information which can equal the following
0 = x (0-316) and y (0-208) coordinates
1= width (1 to 316)and height (1 to 208)
2= angle (used for color code)(-180 to 180).
3= index - tracking inted of block
4= age- number of frames the bblock has been tracked about 61 frames/sec (could be transfered to time)
5= signature - what color block, what identified object (1-7)
return array of integers result - if input state is not 0 or 1: the value is only in the first index[0] of the arrray
see function for details
*/
int *getBlockInfo(int state) {
// create variables under a new name so it is easier
// to read & understand in the switch case
int requestedInfo = state;
const int Coord = 0;
const int Size = 1;
const int Angle = 2;
const int Index = 3;
const int Age = 4;
const int Signature = 5;
static int result[2]; // result array
pixy.ccc.getBlocks(); // get the block information
if (pixy.ccc.numBlocks) { // If there are detected blocks
Serial.println("Detected ");
if (pixy.ccc.numBlocks > 1) { // check that maximum of 1 block is detected otherwise print an error
Serial.println("Too Many Blocks! Adjust Camera Settings or Eliminate Exessive Background");
} else {
switch (requestedInfo) { // store the needed info in the result array
case Coord: // format: [x_position, y_position]
result[0] = pixy.ccc.blocks[0].m_x;
result[1] = pixy.ccc.blocks[0].m_y;
break;
case Size:// not used for this application. included only for future work.
// format: [width, height] Note: can be used to determine how close a standardized object is.
result[0] = pixy.ccc.blocks[0].m_width;
result[1] = pixy.ccc.blocks[0].m_height;
break;
case Angle: // not used for this application. included only for future work.
result[0] = pixy.ccc.blocks[0].m_angle;
result[1] = 0;
break;
case Index: // not used for this application. included only for future work.
result[0] = pixy.ccc.blocks[0].m_index;
result[1] = 0;
break;
case Age: // used to determine if the block is not longer detected - format: [age, 0]
result[0] = pixy.ccc.blocks[0].m_age;
result[1] = 0;
break;
case Signature: //not used for this application. included only for future work.
// format: [signature, 0] - can be used to distinguish between
// two different colored object (ex. blue gloved hand or a red
// patch on a lab coat)
result[0] = pixy.ccc.blocks[0].m_signature;
result[1] = 0;
break;
}
}
}
return result; // return the array
}
};
|
#include "RGB.h"
#include <Arduino.h>
RGB::RGB()
{
this->_r = 0;
this->_g = 0;
this->_b = 0;
this->_l = 0;
}
RGB::RGB(byte *__rgb)
{
this->_r = __rgb[0];
this->_g = __rgb[1];
this->_b = __rgb[2];
this->_l = 50;
}
RGB::RGB(byte r, byte g, byte b)
{
this->_r = r;
this->_g = g;
this->_b = b;
this->_l = 50;
}
RGB::RGB(byte r, byte g, byte b, byte l)
{
this->_r = r;
this->_g = g;
this->_b = b;
this->_l = l;
}
RGB RGB::hex2rgb(uint32_t rgbInt)
{
RGB _rgb = RGB();
_rgb.set_r(rgbInt >> 16);
_rgb.set_g((rgbInt & 0x00ff00) >> 8);
_rgb.set_b(rgbInt & 0x0000ff);
return _rgb;
}
RGB RGB::hsl2rgb(uint16_t ih, uint8_t is, uint8_t il)
{
/*
H is HUE range(0,360)
S i stu
*/
float h, s, l, t1, t2, tr, tg, tb;
uint8_t r, g, b;
h = (ih % 360) / 360.0;
s = constrain(is, 0, 100) / 100.0;
l = constrain(il, 0, 100) / 100.0;
if (s == 0)
{
r = g = b = 255 * l;
//return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
return RGB(r, g, b);
}
if (l < 0.5)
t1 = l * (1.0 + s);
else
t1 = l + s - l * s;
t2 = 2 * l - t1;
tr = h + 1 / 3.0;
tg = h;
tb = h - 1 / 3.0;
r = hsl_convert(tr, t1, t2);
g = hsl_convert(tg, t1, t2);
b = hsl_convert(tb, t1, t2);
// NeoPixel packed RGB color
//return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
return RGB(r, g, b);
}
void RGB::rgb2hsl_convert()
{
float h, s, l;
float r, g, b;
r = (float)_r / 255.0f;
g = (float)_g / 255.0f;
b = (float)_b / 255.0f;
float _min = min(min(r, g), b);
float _max = max(max(r, g), b);
float _delta = _max - _min;
h = 0.0f;
s = 0.0f;
l = (_max + _min) / 2.0f;
if (_delta != 0.0f)
{
s = (l <= 0.5f) ? (_delta / (_max + _min)) : (_delta / (2.0f - _max - _min));
if (r == _max)
{
h = ((g - b) / _delta) + (g < b ? 6.0f : 0.0f);
}
else if (g == _max)
{
h = (b - r) / _delta + 2.0f;
}
else
{
h = (r - g) / _delta + 4.0f;
}
}
_hue = (uint16_t)(h * 360.0f);
_stu = (uint8_t)(s * 100.0);
_lua = (uint8_t)(l * 100.0);
// Serial.print(r);
// Serial.print(" ");
// Serial.print(g);
// Serial.print(" ");
// Serial.print(b);
// Serial.print("/");
// Serial.print(_r);
// Serial.print(" ");
// Serial.print(_g);
// Serial.print(" ");
// Serial.print(_b);
// Serial.print("/");
// Serial.print(h);
// Serial.print(" ");
// Serial.print(_hue);
// Serial.print(" ");
// Serial.print(_stu);
// Serial.print(" ");
// Serial.println(_lua);
}
/**
HSL Convert
Helper function
*/
uint8_t RGB::hsl_convert(float c, float t1, float t2)
{
if (c < 0)
c += 1;
else if (c > 1)
c -= 1;
if (6 * c < 1)
c = t2 + (t1 - t2) * 6 * c;
else if (2 * c < 1)
c = t1;
else if (3 * c < 2)
c = t2 + (t1 - t2) * (2 / 3.0 - c) * 6;
else
c = t2;
return (uint8_t)(c * 255);
}
uint32_t RGB::toInt32()
{
return (_r << 16) | (_g << 8) | _b;
}
|
class Category_629 {
class FoodCanBakedBeans {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanFrankBeans {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanPasta {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanSardines {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanBeef {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanPotatoes {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanGriff {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanBadguy {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanBoneboy {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanCorn {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanCurgon {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanDemon {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanFraggleos {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanHerpy {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanDerpy {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanOrlok {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanPowell {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanTylers {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanUnlabeled {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanRusUnlabeled {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanRusStew {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanRusPork {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanRusPeas {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanRusMilk {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCanRusCorn {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodChipsSulahoops {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodChipsMysticales {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodChipsChocolate {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCandyChubby {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCandyAnders {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCandyLegacys {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCakeCremeCakeClean {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodCandyMintception {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodPistachio {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodNutmix {
type = "trade_items";
buy[] = {2,"ItemSilverBar"};
sell[] = {1,"ItemSilverBar"};
};
class FoodMRE {
type = "trade_items";
buy[] = {1,"ItemSilverBar10oz"};
sell[] = {5,"ItemSilverBar"};
};
};
class Category_692 {
duplicate = 629;
};
|
#include <string>
#include <cstring>
#include <iostream>
using namespace std;
#define MAX 1000002
int N, p[MAX];
string s;
void kmp()
{
s = " " + s;
p[1] = 0;
int j = 0;
for(int i=2; i<=N; ++i)
{
while(s[j+1]!=s[i] && j)
j = p[j];
if(s[j+1] == s[i])
++j;
p[i] = j;
}
}
void process()
{
for(int i=2;i<=N;++i)
{
if(!p[i])
continue;
int k = i-p[i];
if( !(i%k) )
cout << i << ' ' << i/k << endl;
}
}
int main()
{
int cnt = 0;
while(cin >> N)
{
++cnt;
if(!N)
break;
if(cnt!=1)
cout << endl;
cin >> s;
cout << "Test case #" << cnt << endl;
kmp();
process();
}
}
|
#include <iostream>
#include <vector>
#include <stdio.h>
using namespace std;
const int N = 1000111;
const int INF = 1e9;
int a[N];
int n, k;
int order[N + N];
int PS[N*2];
vector<int> st;
int* pos = PS + N;
int nexto[N], nextc[N];
int main() {
freopen("brackets.in", "r", stdin);
freopen("brackets.out", "w", stdout);
int T;
scanf("%d", &T);
while (T--) {
scanf("%d%d", &n, &k);
for (int i = 0; i < k + k; ++i) {
scanf("%d", order + i);
pos[ order[i] ] = i;
}
nexto[k + k - 1] = INF;
nextc[k + k - 1] = INF;
for (int i = k + k - 2; i >= 0; --i) {
if (order[i + 1] > 0) {
nexto[i] = i + 1;
nextc[i] = nextc[i + 1];
} else {
nextc[i] = i + 1;
nexto[i] = nexto[i + 1];
}
}
for (int i = 0; i < n + n; ++i) {
scanf("%d", a + i);
}
st.clear();
int where = -1;
int who = -1;
for (int i = 0; i < n + n; ++i) {
int balance = st.size();
int len = n + n - i -1;
int position = pos[ a[i] ];
if (a[i] < 0) {
if (nexto[position] != INF) {
if (balance + 1 <= len && !( (len - 1 - balance) & 1 )) {
where = i;
who = order[nexto[position]];
}
}
} else {
if (nexto[position] != INF) {
where = i;
who = order[nexto[position]];
}
if (balance > 0) {
if (!( (len + 1 - balance) & 1) && pos[-st.back()] > position) {
if (where < i || pos[-st.back()] < pos[who]) {
where = i;
who = -st.back();
}
}
}
}
if (a[i] < 0) {
st.pop_back();
} else {
st.push_back(a[i]);
}
}
int coolo = nexto[0] == INF? order[0] : order[nexto[0]];
if (order[0] > 0) coolo = order[0];
st.clear();
if (where != -1) a[where] = who;
for (int i = 0; i <= where; ++i) {
if (a[i] > 0) st.push_back(a[i]);
else st.pop_back();
}
for (int i = where + 1; i < n + n; ++i) {
int balance = st.size();
int len = n + n - 1 - i;
if (st.size() == 0) {
a[i] = coolo;
st.push_back(coolo);
continue;
}
if (len < balance + 1) {
a[i] = -st.back();
st.pop_back();
continue;
}
if (pos[coolo] < pos[-st.back()]) {
a[i] = coolo;
st.push_back(a[i]);
} else {
a[i] = -st.back();
st.pop_back();
}
}
for (int i = 0; i < n + n; ++i) printf("%d ", a[i]);
puts("");
}
return 0;
}
|
// Created on: 1997-05-13
// Created by: Alexander BRIVIN
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _VrmlConverter_WFRestrictedFace_HeaderFile
#define _VrmlConverter_WFRestrictedFace_HeaderFile
#include <BRepAdaptor_Surface.hxx>
#include <Standard_OStream.hxx>
class VrmlConverter_Drawer;
//! WFRestrictedFace - computes the wireframe
//! presentation of faces with restrictions by
//! displaying a given number of U and/or V
//! isoparametric curves, converts this one into VRML
//! objects and writes (adds) into anOStream.
//! All requested properties of the representation
//! are specify in aDrawer.
//! This kind of the presentation is converted into
//! IndexedLineSet ( VRML ).
class VrmlConverter_WFRestrictedFace
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT static void Add (Standard_OStream& anOStream, const Handle(BRepAdaptor_Surface)& aFace, const Handle(VrmlConverter_Drawer)& aDrawer);
Standard_EXPORT static void AddUIso (Standard_OStream& anOStream, const Handle(BRepAdaptor_Surface)& aFace, const Handle(VrmlConverter_Drawer)& aDrawer);
Standard_EXPORT static void AddVIso (Standard_OStream& anOStream, const Handle(BRepAdaptor_Surface)& aFace, const Handle(VrmlConverter_Drawer)& aDrawer);
Standard_EXPORT static void Add (Standard_OStream& anOStream, const Handle(BRepAdaptor_Surface)& aFace, const Standard_Boolean DrawUIso, const Standard_Boolean DrawVIso, const Standard_Integer NBUiso, const Standard_Integer NBViso, const Handle(VrmlConverter_Drawer)& aDrawer);
protected:
private:
};
#endif // _VrmlConverter_WFRestrictedFace_HeaderFile
|
#include <iostream>
#include <fstream>
struct Point {
int x,y,z;
constexpr Point up(int d) const { return {x, y, z+d}; }
constexpr Point move(int dx, int dy) const { return {x+dx, y+dy}; }
friend std::ostream& operator<<(std::ostream& os, Point const& p) {
return (os << p.x << " " << p.y << " " << p.z << "\n");
}
};
void test(double d) {
char a = d;
// error: type 'double' cannot be narrowed to 'char' in initializer list [-Wc++11-narrowing]
// if w/o static_cast
char b {static_cast<char>(d)};
}
int main() {
constexpr Point origin {0,0,0};
constexpr int z = origin.x;
constexpr Point a[] = {
origin, Point{1,1}, Point{2,2}, origin.move(2,3)
};
std::cout << origin << std::endl;
std::cout << a[0] << a[1] << a[2] << std::endl;
}
|
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
string scheme(string s){
size_t found;
found = s.find("://");
if (found == string::npos) return s;
cout<<"scheme:"<<s.substr(0,found)<<endl;
return s.substr(found+3);
}
string domain(string s){
size_t found;
if (s=="") return s;
found = s.find(":");
if (found == string::npos) found = s.find("/");
if (found == string::npos){
cout<<"domain:"<<s<<endl;
return "";
} else {
cout<<"domain:"<<s.substr(0,found)<<endl;
return s.substr(found);
}
}
void remain(string s){
size_t found[] = {s.find(':'),s.find('/'),s.find('?'),s.find('#')};
size_t small;
if (found[0] != string::npos){
small = *min_element(found+1,found+4);
cout<<"port:"<<s.substr(found[0]+1, small==string::npos?small:small-found[0]-1)<<endl;
}
if (found[1] != string::npos){
small = *min_element(found+2,found+4);
cout<<"path:"<<s.substr(found[1]+1, small==string::npos?small:small-found[1]-1)<<endl;
}
if (found[2] != string::npos){
small = *min_element(found+3,found+4);
cout<<"query_string:"<<s.substr(found[2]+1, small==string::npos?small:small-found[2]-1)<<endl;
}
if(found[3] != string::npos){
cout<<"fragment_id:"<<s.substr(found[3]+1)<<endl;
}
}
int main(){
string input;
do{
getline(cin, input);
input = scheme(input);
if (input=="") continue;
input = domain(input);
if (input=="") continue;
remain(input);
cout<<endl;
}while (cin.peek()!=EOF);
return 0;
}
|
#include "CCivilianPed.h"
|
#include <iostream>
export module solid;
class Shape
{
public:
virtual ~Shape() noexcept = default;
virtual double getArea() const = 0;
//virtual void draw() const = 0; // Violate ISP, and maybe SRP
};
class Drawable
{
public:
virtual ~Drawable() noexcept = default;
virtual void draw() const = 0;
//virtual void draw(const Circle& c) const // Violate SRP
//{
// std::cout << "Circle\n";
//}
};
/* Circle *************************************************************************************************/
class Circle;
class DrawCircle : public Drawable
{
public:
virtual ~DrawCircle() noexcept = default;
virtual void draw() const override
{
std::cout << "Circle\n";
}
};
class Circle : public Shape
{
public:
virtual ~Circle() noexcept = default;
explicit Circle(double radius) : _radius{ radius }
{}
virtual double getArea() const override
{
return 3.14 * _radius;
}
void draw() const
{
_painter.draw();
}
private:
double _radius;
DrawCircle _painter;
};
/* Rectangle ***********************************************************************************************/
class Rectangle : public Shape
{
public:
Rectangle() noexcept = default;
virtual ~Rectangle() noexcept = default;
explicit Rectangle(double w, double h) :
_width{ w }, _height { h }
{}
virtual void setw(double w) { _width = w; }
virtual void seth(double h) { _width = h; }
virtual double getArea() const override
{
return _width * _height;
}
//virtual void draw() const override // I don't use draw
//{
//}
private:
double _width;
double _height;
};
/* Square ***********************************************************************************************/
class Square : public Rectangle // Violent LSP
{
public:
virtual ~Square() noexcept {}
explicit Square(double w)
{
setw(w);
seth(w);
}
virtual void setw(double w) override { Rectangle::setw(w); Rectangle::seth(w); } // Work arround to fix LSP violent
virtual void seth(double h) override { Rectangle::setw(h); Rectangle::seth(h); } // Work arround to fix LSP violent
};
|
#include "stdafx.h"
#include "feature.h"
#include "utils.h"
double descr_dist_sq(struct feature* f1, struct feature* f2)
{
double sum = 0;
double diff = 0;
for (int i = 0; i < f1->n; i++)
{
diff = f1->x[i] - f2->x[i];
sum += diff * diff;
}
return sum;
}
|
#include "thirdmonster.h"
#include <cmath>
#include <ctime>
int ThirdMonster::Num = 0;
ThirdMonster::ThirdMonster(QObject *parent) : Monster(parent)
{}
ThirdMonster::ThirdMonster(int x, int y, int width, int height, QObject *parent)
: Monster(x,
y,
width,
height,
":/images/monster/images/monster/monster3.png",
1,
Up,
1,
parent),
Launcher(1500 + rand() % 1000), _num(Num++), _originMoveSpeed(_moveSpeed),
_launchTimer(this)
{
connect(&_launchTimer, SIGNAL(timeout()), this, SLOT(launchOver()));
}
void ThirdMonster::updatePos(int judge_unit)
{
srand(time(nullptr) + _num);
directio_n = rand() % 8;
_moveSpeed = _originMoveSpeed - 75 + rand() % 150;
_launchInteval = 1500 + rand() % 1000;
switch (directio_n) {
case Up:
_tempPos.moveTo(x(), y() - judge_unit);
break;
case UpRight:
_tempPos.moveTo(x() + judge_unit, y() - judge_unit);
break;
case Right:
_tempPos.moveTo(x() + judge_unit, y());
break;
case DownRight:
_tempPos.moveTo(x() + judge_unit, y() + judge_unit);
break;
case Down:
_tempPos.moveTo(x(), y() + judge_unit);
break;
case DownLeft:
_tempPos.moveTo(x() - judge_unit, y() + judge_unit);
break;
case Left:
_tempPos.moveTo(x() - judge_unit, y());
break;
case UpLeft:
_tempPos.moveTo(x() - judge_unit, y() - judge_unit - judge_unit);
break;
default:
break;
}
}
FlyingProp * ThirdMonster::launchFlyingProp()
{
if (!canLaunch() || !isShow()) {
return nullptr;
}
launch();
_launchTimer.setInterval(_launchInteval);
_launchTimer.start();
int flyingPropWidth = 0.6 * width();
int flyingPropHeight = 0.6 * width();
int posX = 0;
int posY = 0;
switch (directio_n) {
case Up:
posX = x() + width() / 2 - flyingPropWidth / 2;
posY = y() - flyingPropHeight;
break;
case UpRight:
posX = x() + width();
posY = y() - flyingPropHeight;
break;
case Right:
posX = x() + width();
posY = y() + height() / 2 - flyingPropHeight / 2;
break;
case DownRight:
posX = x() + width();
posY = y() + height();
break;
case Down:
posX = x() + width() / 2 - flyingPropWidth / 2;
posY = y() + height();
break;
case DownLeft:
posX = x() - flyingPropWidth;
posY = y() + height();
break;
case Left:
posX = x() - flyingPropWidth;
posY = y() + height() / 2 - flyingPropHeight / 2;
break;
case UpLeft:
posX = x() - flyingPropWidth;
posY = y() - flyingPropHeight;
break;
default:
break;
}
return new FireBall(posX,
posY,
flyingPropWidth,
flyingPropHeight,
directio_n,
this);
}
void ThirdMonster::launchOver()
{
ready();
_launchTimer.stop();
}
|
// C headers
extern "C" {
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <sys/wait.h>
#include <signal.h>
#include <libgen.h>
}
// C++ headers
#include <iostream>
#include <system_error>
#include "util.h"
using namespace std;
using namespace util;
bool util::PathExists(string path)
{
struct stat s;
int r = lstat(path.c_str(), &s);
if (r < 0)
{
if (errno != ENOENT)
{
throw system_error(errno, system_category(), "PathExists, lstat() failed");
}
return false;
}
return true;
}
bool util::IsRegularFile(string path)
{
struct stat s;
int r = lstat(path.c_str(), &s);
if (r < 0)
{
if (errno != ENOENT)
{
throw system_error(errno, system_category(), "IsRegularFile, lstat() failed");
}
return false; // Does not exist
}
return S_ISREG(s.st_mode);
}
bool util::IsDirectory(string path)
{
struct stat s;
int r = lstat(path.c_str(), &s);
if (r < 0)
{
if (errno != ENOENT)
{
throw system_error(errno, system_category(), "IsDirectory, lstat() failed");
}
return false; // Does not exist
}
return S_ISDIR(s.st_mode);
}
string util::BaseName(string path)
{
char* copy = strdup(path.c_str());
string bn = basename(copy);
free(copy);
return bn;
}
void util::DeleteFile(string path)
{
if (unlink(path.c_str()) < 0)
{
throw system_error(errno, system_category(), "DeleteFile, unlink() failed");
}
}
void util::DeleteFolder(string path)
{
if (rmdir(path.c_str()) < 0)
{
throw system_error(errno, system_category(), "DeleteFolder, rmdir() failed");
}
}
void util::ChangeMode(string path, unsigned short mode)
{
mode_t old_mask = umask(0);
if (chmod(path.c_str(), mode) < 0)
{
umask(old_mask); // umask does not change errno
throw system_error(errno, system_category(), "ChangeMode, chmod() failed");
}
umask(old_mask);
}
string util::CreateTempFolder(string path_prefix)
{
char buffer[256];
const char* X = "XXXXXX";
if ((path_prefix.size() + strlen(X) + 1) > sizeof(buffer))
{
throw runtime_error("path prefix is too long!");
}
snprintf(buffer, sizeof(buffer), "%s%s", path_prefix.c_str(), X);
if (mkdtemp(buffer) == NULL)
{
throw system_error(errno, system_category(), "CreateTempFolder, mkdtemp() failed");
}
return string(buffer);
}
void util::CreateFolder(string path, unsigned short mode)
{
mode_t old_mask = umask(0);
if (mkdir(path.c_str(), mode) < 0)
{
umask(old_mask); // umask does not change errno
throw system_error(errno, system_category(), "CreateFolder, mkdir() failed");
}
umask(old_mask);
}
void util::BindMount(string source, string dest)
{
if (mount(source.c_str(), dest.c_str(), "", MS_BIND | MS_REC, "") < 0)
{
throw system_error(errno, system_category(), "BindMount, 1st mount() failed");
}
if (mount(source.c_str(), dest.c_str(), "", MS_BIND | MS_REMOUNT | MS_RDONLY | MS_PRIVATE, "") < 0)
{
throw system_error(errno, system_category(), "BindMount, 2nd mount() failed");
}
}
void util::Unmount(string dest)
{
if (umount(dest.c_str()) < 0)
{
throw system_error(errno, system_category(), "Unmount, umount() failed");
}
}
void util::MarkMountPointPrivate(string path)
{
if (mount(path.c_str(), path.c_str(), "", MS_REMOUNT | MS_PRIVATE, "") < 0)
{
throw system_error(errno, system_category(), "MarkMountPointPrivate, mount() failed");
}
}
void util::CreatePrivateMount(string path)
{
if (mount(path.c_str(), path.c_str(), "", MS_BIND | MS_REC, "") < 0)
{
throw system_error(errno, system_category(), "CreatePrivateMount, mount() failed");
}
MarkMountPointPrivate(path);
}
void util::MountSpecialFileSystem(string path, string fs)
{
if (mount(fs.c_str(), path.c_str(), fs.c_str(), 0, "") < 0)
{
throw system_error(errno, system_category(), "MountSpecialFileSystem, mount() failed");
}
}
void util::Chroot(string new_root)
{
if (chroot(new_root.c_str()) < 0)
{
throw system_error(errno, system_category(), "Chroot, chroot() failed");
}
}
void util::Chdir(string path)
{
if (chdir(path.c_str()) < 0)
{
throw system_error(errno, system_category(), "Chdir, chdir() failed");
}
}
void util::ForkExecWait(char* args[], Task beforeExec)
{
pid_t pid = fork();
if (pid == 0)
{
// Child
beforeExec();
execv(args[0], args);
cerr << "Error in execv: " << strerror(errno) << endl;
exit(EXIT_FAILURE);
}
else if (pid > 0)
{
// Parent
if (waitpid(pid, NULL, 0) < 0)
{
throw system_error(errno, system_category(), "ForkExecWait, waitpid() failed");
}
}
else
{
// Error, in parent
throw system_error(errno, system_category(), "ForkExecWait, fork() failed");
}
}
void util::ForkExecWaitTimeout(char* args[], Task beforeExec, unsigned int timeout_ms)
{
pid_t timer_pid = fork();
if (timer_pid == 0)
{
struct timespec req;
req.tv_sec = timeout_ms / 1000;
req.tv_nsec = (timeout_ms % 1000) * 1000000;
// Sleep for the amount of timeout
nanosleep(&req, NULL);
_exit(0);
}
else if (timer_pid < 0)
{
throw system_error(errno, system_category(), "ForkExecWaitTimeout, failed to fork() timer process");
}
pid_t child_pid = fork();
if (child_pid == 0)
{
// Child
beforeExec();
execv(args[0], args);
cerr << "Error in execv: " << strerror(errno) << endl;
exit(EXIT_FAILURE);
}
else if (child_pid < 0)
{
// Error, in parent
throw system_error(errno, system_category(), "ForkExecWaitTimeout, failed to fork() child process");
}
// Parent: wait
pid_t x = waitpid(-1, NULL, 0);
if (x == child_pid)
{
kill(timer_pid, SIGKILL);
waitpid(-1, NULL, 0);
}
else if (x == timer_pid)
{
kill(child_pid, SIGKILL);
waitpid(-1, NULL, 0);
}
else
{
throw runtime_error("ForkExecWaitTimeout, Could not determine which child process exitted");
}
}
void util::ForkCallWait(Task task)
{
pid_t pid = fork();
if (pid == 0)
{
// Child
task();
exit(EXIT_SUCCESS);
}
else if (pid > 0)
{
// Parent
if (waitpid(pid, NULL, 0) < 0)
{
throw system_error(errno, system_category(), "ForkCallWait, waitpid() failed");
}
}
else
{
// Error, in parent
throw system_error(errno, system_category(), "ForkCallWait, fork() failed");
}
}
void util::Unshare(int flags)
{
if (unshare(flags) < 0)
{
throw system_error(errno, system_category(), "Unshare, unshare() failed");
}
}
|
#include <chuffed/core/propagator.h>
#include <iostream>
class BoolArgMax : public Propagator {
public:
int const sz;
BoolView* const x;
IntView<> const y;
int offset;
BoolArgMax(vec<BoolView> _x, int _offset, IntView<> _y)
: sz(_x.size()), x(_x.release()), y(_y), offset(_offset) {
priority = 1;
for (int i = 0; i < sz; i++) {
x[i].attach(this, i, EVENT_LU);
}
y.attach(this, sz, EVENT_C);
}
bool propagate() override {
// l = index of first x that can be true
// y >= l because not x[i] forall i<l
// u = index of first x that must be true
// y <= u because x[u]
int ol = y.getMin();
for (int i = 0; i < ol - offset; i++) {
if (x[i].setValNotR(false)) {
Clause* r = nullptr;
if (so.lazy) {
r = Reason_new(2);
(*r)[1] = y.getFMinLit(ol);
}
if (!x[i].setVal(false, r)) {
return false;
}
}
}
if (y.isFixed()) {
int yl = y.getVal() - offset;
if (x[yl].setValNotR(true)) {
Clause* r = nullptr;
if (so.lazy) {
r = Reason_new(2);
(*r)[1] = y.getValLit();
}
if (!x[yl].setVal(true, r)) {
return false;
}
}
}
int l = sz;
int u = 0;
vec<int> toFix;
for (typename IntView<>::iterator yi = y.begin(); yi != y.end(); ++yi) {
int i = *yi - offset;
if (l == sz && (!x[i].isFixed() || x[i].isTrue())) {
l = i;
}
if (x[i].isFixed() && x[i].isFalse()) {
if (y.remValNotR(i + offset)) {
toFix.push(i);
}
}
u = i;
if (x[i].isFixed() && x[i].isTrue()) {
break;
}
}
for (int i = 0; i < toFix.size(); i++) {
Clause* r = nullptr;
if (so.lazy) {
r = Reason_new(2);
(*r)[1] = x[toFix[i]];
}
if (!y.remVal(toFix[i] + offset, r)) {
return false;
}
}
if (y.setMinNotR(l + offset)) {
Clause* r = nullptr;
if (so.lazy) {
r = Reason_new(l + 1);
for (int i = 0; i < l; i++) {
(*r)[i + 1] = x[i];
}
}
if (!y.setMin(l + offset, r)) {
return false;
}
}
if (y.setMaxNotR(u + offset)) {
Clause* r = nullptr;
if (so.lazy) {
r = Reason_new(2);
(*r)[1] = ~x[u];
}
if (!y.setMax(u + offset, r)) {
return false;
}
}
if (y.isFixed()) {
int yl = y.getVal() - offset;
if (x[yl].setValNotR(true)) {
Clause* r = nullptr;
if (so.lazy) {
r = Reason_new(2);
(*r)[1] = y.getValLit();
}
if (!x[yl].setVal(true, r)) {
return false;
}
}
}
int nl = y.getMin();
for (int i = ol - offset; i < nl - offset; i++) {
if (x[i].setValNotR(false)) {
Clause* r = nullptr;
if (so.lazy) {
r = Reason_new(2);
(*r)[1] = y.getFMinLit(nl);
}
if (!x[i].setVal(false, r)) {
return false;
}
}
}
return true;
}
};
void bool_arg_max(vec<BoolView>& x, int offset, IntVar* y) {
vec<BoolView> w;
for (int i = 0; i < x.size(); i++) {
w.push(BoolView(x[i]));
}
new BoolArgMax(w, offset, IntView<>(y));
}
|
// Created on: 1994-11-08
// Created by: Jean Yves LEBEY
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TopOpeBRepDS_EdgeInterferenceTool_HeaderFile
#define _TopOpeBRepDS_EdgeInterferenceTool_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TopAbs_Orientation.hxx>
#include <Standard_Integer.hxx>
#include <TopTrans_CurveTransition.hxx>
class TopoDS_Shape;
class TopOpeBRepDS_Interference;
class TopOpeBRepDS_Point;
//! a tool computing complex transition on Edge.
class TopOpeBRepDS_EdgeInterferenceTool
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT TopOpeBRepDS_EdgeInterferenceTool();
Standard_EXPORT void Init (const TopoDS_Shape& E, const Handle(TopOpeBRepDS_Interference)& I);
Standard_EXPORT void Add (const TopoDS_Shape& E, const TopoDS_Shape& V, const Handle(TopOpeBRepDS_Interference)& I);
Standard_EXPORT void Add (const TopoDS_Shape& E, const TopOpeBRepDS_Point& P, const Handle(TopOpeBRepDS_Interference)& I);
Standard_EXPORT void Transition (const Handle(TopOpeBRepDS_Interference)& I) const;
protected:
private:
TopAbs_Orientation myEdgeOrientation;
Standard_Integer myEdgeOriented;
TopTrans_CurveTransition myTool;
};
#endif // _TopOpeBRepDS_EdgeInterferenceTool_HeaderFile
|
/*
===========================================================================
Copyright (C) 2017 waYne (CAM)
===========================================================================
*/
#pragma once
#ifndef ELYSIUM_CORE_LOGGING_LOGLEVEL
#define ELYSIUM_CORE_LOGGING_LOGLEVEL
namespace Elysium
{
namespace Core
{
namespace Logging
{
enum class LogLevel : int
{
Trace = 1,
Information = 2,
Debug = 3,
Warning = 4,
Error = 5,
Fatal = 6,
None = 0,
All = LogLevel::Fatal,
};
}
}
}
#endif
|
// Created on: 1996-11-14
// Created by: Philippe MANGIN
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _AdvApprox_PrefAndRec_HeaderFile
#define _AdvApprox_PrefAndRec_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TColStd_Array1OfReal.hxx>
#include <AdvApprox_Cutting.hxx>
#include <Standard_Boolean.hxx>
//! inherits class Cutting; contains a list of preferential points (pi)i
//! and a list of Recommended points used in cutting management.
//! if Cutting is necessary in [a,b], we cut at the di nearest from (a+b)/2
class AdvApprox_PrefAndRec : public AdvApprox_Cutting
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT AdvApprox_PrefAndRec(const TColStd_Array1OfReal& RecomendedCut, const TColStd_Array1OfReal& PrefferedCut, const Standard_Real Weight = 5);
//! cuting value is
//! - the recommended point nerest of (a+b)/2
//! if pi is in ]a,b[ or else
//! - the preferential point nearest of (a+b) / 2
//! if pi is in ](r*a+b)/(r+1) , (a+r*b)/(r+1)[ where r = Weight
//! - or (a+b)/2 else.
Standard_EXPORT virtual Standard_Boolean Value (const Standard_Real a, const Standard_Real b, Standard_Real& cuttingvalue) const Standard_OVERRIDE;
protected:
private:
TColStd_Array1OfReal myRecCutting;
TColStd_Array1OfReal myPrefCutting;
Standard_Real myWeight;
};
#endif // _AdvApprox_PrefAndRec_HeaderFile
|
#include<stdio.h>
int a,s=0;
main()
{
scanf("%d",&a);
for(int b=1; b<=10; b++)
{
printf("%d*%d=%d\n",a,b,s=a*b);
}
}
|
#include "platform/i_platform.h"
#include "item_loader_repo.h"
#include "property_loader.h"
#include "item.h"
#include "plasma_gun.h"
#include "pistol.h"
#include "shotgun.h"
#include "rocket_launcher.h"
#include "ion_gun.h"
#include "gatling_gun.h"
#include "gauss_gun.h"
#include "lucky_rocket.h"
#include "rusty_reaper.h"
using platform::AutoId;
DefaultItemLoader const ItemLoaderRepo::mDefault;
ItemLoaderRepo::ItemLoaderRepo()
: Repository<PropertyLoaderBase<Item> >( mDefault )
{
int32_t id = AutoId( "plasma_gun" );
mElements.insert( id, new PlasmaGunLoader() );
id = AutoId( "guard_plasma_gun" );
mElements.insert( id, new PlasmaGunLoader() );
id = AutoId( "pistol" );
mElements.insert( id, new PistolLoader() );
id = AutoId( "shotgun" );
mElements.insert( id, new ShotgunLoader() );
id = AutoId( "rocket_launcher" );
mElements.insert( id, new RocketLauncherLoader() );
id = AutoId( "ion_gun" );
mElements.insert( id, new IonGunLoader() );
id = AutoId( "gatling_gun" );
mElements.insert( id, new GatlingGunLoader() );
id = AutoId( "gauss_gun" );
mElements.insert( id, new GaussGunLoader() );
id = AutoId( "lucky_rocket" );
mElements.insert( id, new LuckyRocketLoader() );
id = AutoId( "rusty_reaper");
mElements.insert(id, new RustyReaperLoader());
Init();
}
void ItemLoaderRepo::Init()
{
PathVect_t Paths;
Filesys& FSys = Filesys::Get();
FSys.GetFileNames( Paths, "actors" );
for( PathVect_t::const_iterator i = Paths.begin(), e = Paths.end(); i != e; ++i )
{
boost::filesystem::path const& Path = *i;
if( Path.extension().string() != ".item" )
{
continue;
}
AutoFile JsonFile = FSys.Open( *i );
if( !JsonFile.get() )
{
continue;
}
JsonReader Reader( *JsonFile );
if( !Reader.IsValid() )
{
continue;
}
Json::Value Root = Reader.GetRoot();
if( !Root.isArray() )
{
continue;
}
for( Json::Value::iterator i = Root.begin(), e = Root.end(); i != e; ++i )
{
Json::Value& ItemDesc = *i;
if( !LoadItemFromOneDesc( ItemDesc ) )
{
return;
}
}
}
}
bool ItemLoaderRepo::LoadItemFromOneDesc( Json::Value& ItemDesc )
{
std::string nameStr;
if( !Json::GetStr( ItemDesc["name"], nameStr ) )
{
return false;
}
PropertyLoaderBase<Item>& itemLoader = operator()( AutoId( nameStr ) );
Json::Value& setters = ItemDesc["set"];
if ( !setters.isArray() )
{
return false;
}
if ( setters.empty() )
{
return true;
}
L1( "Load item_loader: %s\n", nameStr.c_str() );
itemLoader.Load( *setters.begin() );
return true;
}
|
#include <iostream>
#include <tuple>
#include <vector>
using namespace std;
using ll = long long;
const ll MOD = 1000000007;
template <typename T, typename U>
T mypow(T b, U n) {
if (n == 0) return 1;
if (n == 1) return b % MOD;
if (n % 2 == 0) {
return mypow(b * b % MOD, n / 2);
} else {
return mypow(b, n - 1) * b % MOD;
}
}
vector<pair<ll, ll>> factor(ll N) {
vector<pair<ll, ll>> ret;
ll M = N;
for (ll i = 2; i * i <= M; ++i) {
if (N % i > 0) continue;
ll cnt = 0;
while (N % i == 0) {
++cnt;
N /= i;
}
ret.push_back(make_pair(i, cnt));
}
if (N > 1) ret.push_back(make_pair(N, 1));
return ret;
}
int main() {
ll inv[100];
for (ll i = 0; i < 100; ++i) {
inv[i] = mypow(i, MOD - 2);
}
ll N;
int K;
cin >> N >> K;
vector<pair<ll, ll>> facts = factor(N);
ll ans = 1;
for (auto q : facts) {
ll p, a;
tie(p, a) = q;
ll dp[K + 1][a + 1];
fill(dp[0], dp[K + 1], 0);
dp[0][a] = 1;
for (ll k = 1; k <= K; ++k) {
for (ll i = 0; i <= a; ++i) {
for (ll j = 0; j <= i; ++j) {
dp[k][j] += dp[k - 1][i] * inv[i + 1] % MOD;
dp[k][j] %= MOD;
}
}
}
ll part = 0;
for (ll i = 0; i <= a; ++i) {
part += dp[K][i] * mypow(p, i);
part %= MOD;
}
ans *= part;
ans %= MOD;
}
cout << ans << endl;
return 0;
}
|
#include "PortManager.hh"
#include "Defines.hh"
#include "Format.hpp"
#include <regex>
#include <iostream>
#include <iomanip>
//Initialization of the ressources and properties of Port Manager command
PortManager::PortManager()
: ACommand()
{
this->_minArg = 1;
this->_command = "-port";
this->_mandatory = true;
this->_argFormat = FORMAT_PORT;
this->_description = "Port of reception";
}
PortManager::~PortManager()
{
}
//Check the syntax of the command Port Manager
bool PortManager::checkSyntax(std::vector<std::string> &args)
{
std::string port(args.at(1));
if ((args.size() - 1) < this->_minArg)
return (false);
//Check syntax of the port
if (!std::regex_match(port, std::regex("[0-9]+")))
return (false);
this->_port = std::stoi(port);
this->_used = true;
args.erase(args.begin(), args.begin() + 2);
return (true);
}
//Accessor method for the port attribute
int PortManager::getPort() const
{
return (this->_port);
}
//Accessor method for format of the command Port Manager
std::string PortManager::getFormat() const
{
return (std::string(this->_command + " " + this->_argFormat));
}
//Display the usage of the Port Manager
void PortManager::displayUsage() const
{
std::cout << "You must to provide the reception port with the command below:" << std::endl;
Format::displayUsageWithFormat(this->_command, this->_argFormat, this->_description);
}
|
class Solution {
public:
bool canConvertString(string s, string t, int k) {
int n = s.size();
vector <int> v;
unordered_map <int, int> m;
if(s.size() != t.size()) return false;
for(int i=0; i<n; i++) {
if(s[i] != t[i]) {
int diff = s[i] < t[i] ? t[i] - s[i] : 26 + t[i]-s[i];
if(diff > k ) return false;
if(m.find(diff) != m.end()) {
m[diff] += 26;
if(m[diff] > k) return false;
}
else {
m[diff] = diff;
if(m[diff] > k) return false;
}
}
}
return true;
}
};
|
#pragma once
#include "../NetIOCP/ISession.h"
using namespace NetIOCP;
class CSession {
public:
CSession(ISession* session);
~CSession() = default;
public:
void recv();
private:
ISession* mpSession;
};
|
#include<stdio.h>
#include<conio.h>
using namespace std;
int kadanes(int arr[],int n)
{
int m1=0,m2=0;
for(int i=0;i<n;i++)
{
m1 = m1+arr[i];
if(m1 <0)
m1 = 0;
if(m2<m1)
m2=m1;
}
return m2;
}
int main()
{
int arr[] = {11,10,-20,5,-3,-5,8,-13,-10};
int size = sizeof(arr)/sizeof(arr[0]);
int ans = kadanes(arr,size);
printf("%d",ans);
getch();
}
|
#include<iostream>
using namespace std;
/* viet chuong trinh nhap vao 1 phan so.cho biet phan so do am hay duong hay bang 0
*/
class phanso
{
private:
int tuso,mauso;
public:
void nhap()
{
cout<<"\n nhap vao tu so:\t";
cin>>this->tuso;
cout<<"\n nhap vao mau so:\t";
cin>>mauso;
}
void xet()
{
if(tuso==0||mauso==0)
{
cout<<"\n phan so bang 0";
}
else if(tuso<0||mauso<0)
{
cout<<"\n phan so am!";
}
else
{
cout<<"\n phan so duong!";
}
}
void xuat()
{
cout<<"\n phan so:\t"<<tuso<<"/"<<mauso<<endl;
xet();
}
};
int main()
{
phanso ps;
ps.nhap();
ps.xuat();
return 0;
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "qpainter.h"
#include <QThread>
#include <QLabel>
#include <QMovie>
#include <QTime>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
movie = new QMovie("source/dice.gif");
ui->gif->setPixmap(QPixmap("source/6.png"));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_begin_clicked()
{
QString numberstr=ui->input->text();
if(numberstr.isEmpty())
{
return; //若输入框为空则直接返回
}
//否则开始进行游戏
Head=new Node;
Head->num=0;
Head->next=nullptr;
number=numberstr.toInt();
if(number>=100)
{
ui->input->clear();
return;
}
init(Head,number);
Now=Head->next;
begin_tag=1;
int sum=number;
for(int i=0;i<sum;i++)//一共要掷number次骰子
{
draw_tag=1;//只画圆圈和节点
update();
ui->gif->setMovie(movie);
movie->start();
sleep(1500);
movie->stop();
rand_tag=random();//产生掷出的数字
switch(rand_tag)
{
case 1:ui->gif->setPixmap(QPixmap("source/1.png"));break;
case 2:ui->gif->setPixmap(QPixmap("source/2.png"));break;
case 3:ui->gif->setPixmap(QPixmap("source/3.png"));break;
case 4:ui->gif->setPixmap(QPixmap("source/4.png"));break;
case 5:ui->gif->setPixmap(QPixmap("source/5.png"));break;
case 6:ui->gif->setPixmap(QPixmap("source/6.png"));break;
}
sleep(1500);
for(int i=1;i<=rand_tag;i++)
{
str=QString::number(i);
draw_tag=3;
update();
sleep(1000);
Now=Now->next;
}
sleep(500);
dice(Head,rand_tag,number);
Now=Head->next;
draw_tag=1;//画骰子和节点
update();
sleep(1000);
}
draw_tag=4;
update();
}
void MainWindow::paintEvent(QPaintEvent * event)
{
Q_UNUSED(event);
QPainter painter(this);//在Widget部件内部绘制
if(begin_tag==0)return;
//设置画笔风格
QPen draw(Qt::green,5,Qt::SolidLine,Qt::RoundCap,Qt::BevelJoin);
QPen circle(Qt::darkYellow,3,Qt::SolidLine,Qt::RoundCap,Qt::BevelJoin);
QPen num(Qt::black,5,Qt::SolidLine,Qt::RoundCap,Qt::BevelJoin);
QPen fail(Qt::red,4,Qt::SolidLine,Qt::RoundCap,Qt::BevelJoin);
int x0 = 476;
int y0 = 236;
int length;
int halflen;
length = 360;
halflen = int(0.5*length);
painter.setPen(draw);
painter.drawEllipse(x0-halflen,y0-halflen,length,length);//画中心圆
length = 450;
halflen=int(0.5*length);
painter.drawEllipse(x0-halflen,y0-halflen,length,length);//画外侧中心圆
if(draw_tag==1||draw_tag==2||draw_tag==3)
{
length = 360;
halflen = int(0.5*length);
painter.setPen(draw);
painter.drawEllipse(x0-halflen,y0-halflen,length,length);//画中心圆
length = 450;
halflen=int(0.5*length);
painter.drawEllipse(x0-halflen,y0-halflen,length,length);//画外侧中心圆
Node*p=Head->next;
for(int i=1;i<=number;i++)//画每个节点
{
int a=p->num;
if(xyz[0][a]==1)
{
painter.setPen(circle);
painter.drawEllipse(xyz[1][a]-15,xyz[2][a]-15,30,30);
painter.setPen(num);
QRectF ff(xyz[1][a]-7,xyz[2][a]-7,15,15);
QString s=QString::number(a);
painter.drawText(ff,Qt::AlignCenter,s);//写出节点内数字
}
p=p->next;
}
}
if(draw_tag==3)
{
//画出位置框图
Node*p=Now;
int a=p->num;
painter.setPen(fail);
QRectF ff(xyz[1][a]-20,xyz[2][a]-20,40,40);
QRectF FF(660,20,30,30);
painter.drawRect(ff);
painter.drawRect(FF);
painter.drawText(FF,Qt::AlignCenter,str);
}
if(draw_tag==4)
{
//游戏结束
QFont font("仿宋",30,QFont::Bold,false);
//设置字体的类型,大小,加粗,非斜体
font.setLetterSpacing(QFont::AbsoluteSpacing,7);
//设置间距
painter.setFont(font);
//添加字体
QRectF ff(476-150,236-100,300,200);
painter.drawRect(ff);
painter.setPen(QColor(Qt::black));
painter.drawText(ff,Qt::AlignCenter,"游戏结束!");
}
}
//构建一个循环链表用于存游戏中的人
void init(Node*&Head,int n)
{
if (n <= 0)return;
int x0 = 476;
int y0 = 236;
int length = 202;
double divide = double(n);
double degree = 2 * 3.1415926535 / divide;
Node* p = new Node;
p->num=1;
p->next=nullptr;
Head->next=p;
Node* T=p;
xyz[0][1] = 1;
xyz[1][1] = x0;
xyz[2][1] = y0 - length;
double deg = degree;
for (int i = 2; i <= n; i++)
{
Node*q=new Node;
q->num=i;
q->next=nullptr;
p->next=q;
p=q;
xyz[0][i] = 1;
xyz[1][i] = int(x0 + length * sin(deg));
xyz[2][i] = int(y0 - length * cos(deg));
deg += degree;
}
p->next = T;
return;
}
//产生随机数
int random()
{
srand((unsigned int)time(nullptr));
int num = rand() % 6 + 1;
return num;
}
//开始掷骰子
void dice(Node*&Head,int n,int &num)//n为掷出的骰子点数,num为剩余节点数
{
if (num > 1)
{
Node*p = Head->next;
Node*pre=p;
for(int i=0;i<num-1;i++)
{
pre=pre->next;
}
for (int i = 0; i < n-1; i++)
{
pre = p;
p = p->next;
}
pre->next = p->next;
xyz[0][p->num] = 0;
delete p;
Head->next = pre->next;
num--;
}
else if(num==1)
{
delete Head->next;
Head->next = nullptr;
num--;
}
else
{
return;
}
}
void sleep(int msec)
{
QTime reachTime = QTime::currentTime().addMSecs(msec);
while(QTime::currentTime()<reachTime)
QCoreApplication::processEvents(QEventLoop::AllEvents,100);
}
|
// Created on: 2002-11-18
// Created by: Vladimir ANIKIN
// Copyright (c) 2002-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TDocStd_MultiTransactionManager_HeaderFile
#define _TDocStd_MultiTransactionManager_HeaderFile
#include <Standard.hxx>
#include <TDocStd_SequenceOfApplicationDelta.hxx>
#include <Standard_Integer.hxx>
#include <Standard_Boolean.hxx>
#include <Standard_Transient.hxx>
#include <Standard_OStream.hxx>
class TCollection_ExtendedString;
class TDocStd_Document;
class TDocStd_MultiTransactionManager;
DEFINE_STANDARD_HANDLE(TDocStd_MultiTransactionManager, Standard_Transient)
//! Class for synchronization of transactions within multiple documents.
//! Each transaction of this class involvess one transaction in each modified document.
//!
//! The documents to be synchronized should be added explicitly to
//! the manager; then its interface is used to ensure that all transactions
//! (Open/Commit, Undo/Redo) are performed synchronously in all managed documents.
//!
//! The current implementation does not support nested transactions
//! on multitransaction manager level. It only sets the flag enabling
//! or disabling nested transactions in all its documents, so that
//! a nested transaction can be opened for each particular document
//! with TDocStd_Document class interface.
//!
//! NOTE: When you invoke CommitTransaction of multi transaction
//! manager, all nested transaction of its documents will be closed (committed).
class TDocStd_MultiTransactionManager : public Standard_Transient
{
public:
//! Constructor
Standard_EXPORT TDocStd_MultiTransactionManager();
//! Sets undo limit for the manager and all documents.
Standard_EXPORT void SetUndoLimit (const Standard_Integer theLimit);
//! Returns undo limit for the manager.
Standard_Integer GetUndoLimit() const;
//! Undoes the current transaction of the manager.
//! It calls the Undo () method of the document being
//! on top of the manager list of undos (list.First())
//! and moves the list item to the top of the list of manager
//! redos (list.Prepend(item)).
Standard_EXPORT void Undo();
//! Redoes the current transaction of the application. It calls
//! the Redo () method of the document being on top of the
//! manager list of redos (list.First()) and moves the list
//! item to the top of the list of manager undos (list.Prepend(item)).
Standard_EXPORT void Redo();
//! Returns available manager undos.
const TDocStd_SequenceOfApplicationDelta& GetAvailableUndos() const;
//! Returns available manager redos.
const TDocStd_SequenceOfApplicationDelta& GetAvailableRedos() const;
//! Opens transaction in each document and sets the flag that
//! transaction is opened. If there are already opened transactions in the documents,
//! these transactions will be aborted before opening new ones.
Standard_EXPORT void OpenCommand();
//! Unsets the flag of started manager transaction and aborts
//! transaction in each document.
Standard_EXPORT void AbortCommand();
//! Commits transaction in all documents and fills the transaction manager
//! with the documents that have been changed during the transaction.
//! Returns True if new data has been added to myUndos.
//! NOTE: All nested transactions in the documents will be committed.
Standard_EXPORT Standard_Boolean CommitCommand();
//! Makes the same steps as the previous function but defines the name for transaction.
//! Returns True if new data has been added to myUndos.
Standard_EXPORT Standard_Boolean CommitCommand (const TCollection_ExtendedString& theName);
//! Returns true if a transaction is opened.
Standard_Boolean HasOpenCommand() const;
//! Removes undo information from the list of undos of the manager and
//! all documents which have been modified during the transaction.
Standard_EXPORT void RemoveLastUndo();
//! Dumps transactions in undos and redos
Standard_EXPORT void DumpTransaction (Standard_OStream& theOS) const;
//! Adds the document to the transaction manager and
//! checks if it has been already added
Standard_EXPORT void AddDocument (const Handle(TDocStd_Document)& theDoc);
//! Removes the document from the transaction manager.
Standard_EXPORT void RemoveDocument (const Handle(TDocStd_Document)& theDoc);
//! Returns the added documents to the transaction manager.
const TDocStd_SequenceOfDocument& Documents() const;
//! Sets nested transaction mode if isAllowed == Standard_True
//! NOTE: field myIsNestedTransactionMode exists only for synchronization
//! between several documents and has no effect on transactions
//! of multitransaction manager.
Standard_EXPORT void SetNestedTransactionMode (const Standard_Boolean isAllowed = Standard_True);
//! Returns Standard_True if NestedTransaction mode is set.
//! Methods for protection of changes outside transactions
Standard_Boolean IsNestedTransactionMode() const;
//! If theTransactionOnly is True, denies all changes outside transactions.
Standard_EXPORT void SetModificationMode (const Standard_Boolean theTransactionOnly);
//! Returns True if changes are allowed only inside transactions.
Standard_Boolean ModificationMode() const;
//! Clears undos in the manager and in documents.
Standard_EXPORT void ClearUndos();
//! Clears redos in the manager and in documents.
Standard_EXPORT void ClearRedos();
DEFINE_STANDARD_RTTIEXT(TDocStd_MultiTransactionManager,Standard_Transient)
protected:
private:
TDocStd_SequenceOfDocument myDocuments;
TDocStd_SequenceOfApplicationDelta myUndos;
TDocStd_SequenceOfApplicationDelta myRedos;
Standard_Integer myUndoLimit;
Standard_Boolean myOpenTransaction;
Standard_Boolean myIsNestedTransactionMode;
Standard_Boolean myOnlyTransactionModification;
};
#include <TDocStd_MultiTransactionManager.lxx>
#endif // _TDocStd_MultiTransactionManager_HeaderFile
|
int trigPin = 8;
int echoPin = 7;
int led = 13;
int buz = 5;
int motion = 2;
int button = 3;
int servoPin = 9;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led, OUTPUT);
pinMode(buz, OUTPUT);
pinMode(motion, INPUT);
pinMode(button, INPUT);
digitalWrite(button, HIGH);
pinMode(servoPin, OUTPUT);
}
void pulseServo(int pin, int pulse) {
for (int i = 0; i < 30; i++) {
digitalWrite(pin, HIGH);
delayMicroseconds(pulse);
digitalWrite(pin, LOW);
delay(15);
}
}
void servoTest()
{
pulseServo(servoPin, 1000);
delay(100);
pulseServo(servoPin, 2500);
delay(500);
}
void loop() {
// put your main code here, to run repeatedly:
int d = distanceM(trigPin, echoPin) * 100;
Serial.println(d, DEC); // debug log
if (d < 100) { // distance near
pinOnOff(led);
buzPlay(buz);
}
int m = motionIR(motion);
if (m > 0) {
buzPlay(buz);
}
if (digitalRead(button) == LOW) {
buzPlay(buz);
}
servoTest();
delay(10);
}
|
#include "quat.hh"
using namespace Eigen;
// Constructor
Quat::Quat() {
qs = 1.0;
Vector3d v;
v << 0.0, 0.0, 0.0;
qv = v;
}
Quat::Quat(double s, double x, double y, double z) {
qs = s;
Vector3d v;
v << x, y, z;
qv = v;
}
Quat::Quat(double s, Vector3d v) {
qs = s;
qv = v;
}
// Destructor
Quat::~Quat() {
}
// Accessors
double Quat::getS(){
return qs;
}
Vector3d Quat::getV() {
return qv;
}
// Operations
Quat Quat::add(Quat &q) {
double ns = qs + q.getS();
Vector3d nv = qv + q.getV();
Quat n(ns, nv);
return n;
}
Quat Quat::sub(Quat &q) {
double ns = qs - q.getS();
Vector3d nv = qv - q.getV();
Quat n(ns, nv);
return n;
}
Quat Quat::prod(Quat &q) {
double sa = qs;
double sb = q.getS();
Vector3d va = qv;
Vector3d vb = q.getV();
double sn = (sa * sb) - va.dot(vb);
Vector3d nv = sa*vb + sb*va + va.cross(vb);
Quat n(sn, nv);
return n;
}
void Quat::normalize(void) {
double norm = sqrt(qs*qs + qv(0)*qv(0) + qv(1)*qv(1) + qv(2)*qv(2));
qs = qs/norm;
qv = qv/norm;
return;
}
// Functions
Matrix4d Quat::rotation_matrix(void) {
double qx = qv(0), qy = qv(1), qz = qv(2);
double yy = qy * qy, xx = qx * qx, zz = qz *qz;
double xy = qx * qy, xz = qx * qz, xs = qx*qs;
double yz = qy * qz, ys = qy * qs, zs = qz * qs;
Matrix4d m;
m << 1 - 2 * yy - 2 * zz, 2 * (xy - zs), 2 * (xz + ys), 0.0,
2 * (xy + zs) , 1 - 2 * xx - 2 * zz , 2 * (yz - xs) , 0.0,
2 * (xz - ys) , 2 * (yz + xs) , 1 - 2 * xx - 2 * yy, 0.0,
0.0, 0.0, 0.0, 1.0;
return m;
}
|
// 2 The Edge - Team 8: Liam Hall, Dan Powell, Louis Mills, Mo Patel, Ethan Gangotra, Hencraft, keasibanda
#pragma once
#include "CoreMinimal.h"
#include "Components/TextRenderComponent.h"
#include "GameFramework/Actor.h"
#include "PlayerNameHeader.generated.h"
UCLASS()
class TWOTHEEDGE_API APlayerNameHeader : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
APlayerNameHeader();
UPROPERTY(EditAnywhere, BlueprintReadWrite)
UTextRenderComponent* TextRenderComponent;
AActor* ActorToFollow;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
APlayerCameraManager* CameraManager;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
void Initialise(FString PlayerName, FColor Colour, AActor* Follow);
UFUNCTION(BlueprintImplementableEvent)
void OnTick();
};
|
/*
* @Description: 订阅激光点云信息,并解析数据
* @Author: Ren Qian
* @Date: 2020-02-05 02:27:30
*/
#ifndef LIDAR_LOCALIZATION_SUBSCRIBER_CLOUD_SUBSCRIBER_HPP_
#define LIDAR_LOCALIZATION_SUBSCRIBER_CLOUD_SUBSCRIBER_HPP_
#include <deque>
#include <mutex>
#include <thread>
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl_conversions/pcl_conversions.h>
#include "lidar_localization/sensor_data/cloud_data.hpp"
namespace lidar_localization {
class CloudSubscriber {
public:
CloudSubscriber(ros::NodeHandle& nh, std::string topic_name, size_t buff_size);
CloudSubscriber() = default;
void ParseData(std::deque<CloudData>& deque_cloud_data);
private:
void msg_callback(const sensor_msgs::PointCloud2::ConstPtr& cloud_msg_ptr);
private:
ros::NodeHandle nh_;
ros::Subscriber subscriber_;
std::deque<CloudData> new_cloud_data_;
std::mutex buff_mutex_;
};
}
#endif
|
#include "MySound.h"
void JigsawSound::loadSounds()
{
SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic("backgound1.mp3");
SimpleAudioEngine::sharedEngine()->preloadEffect("sound1.mp3");
SimpleAudioEngine::sharedEngine()->preloadEffect("sound2.mp3");
SimpleAudioEngine::sharedEngine()->preloadEffect("sound3.mp3");
SimpleAudioEngine::sharedEngine()->preloadEffect("sound4.mp3");
}
void JigsawSound::playBackGround()
{
SimpleAudioEngine::sharedEngine()->playBackgroundMusic("backgound1.mp3", true);
}
void JigsawSound::playTouch()
{
//SimpleAudioEngine::sharedEngine()->playEffect("sound1.mp3");
}
void JigsawSound::playMerge()
{
SimpleAudioEngine::sharedEngine()->playEffect("sound4.mp3");
}
void JigsawSound::playFinish()
{
SimpleAudioEngine::sharedEngine()->playEffect("sound2.mp3");
}
void JigsawSound::stopAll()
{
SimpleAudioEngine::sharedEngine()->stopBackgroundMusic();
SimpleAudioEngine::sharedEngine()->stopAllEffects();
}
void JigsawSound::pauseMusic()
{
SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
}
void JigsawSound::resumeMusic()
{
SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
}
|
#include "stdafx.h"
#include <string>
void printMePCH()
{
std::string v = "PCH";
std::cout << v << ":" << v << std::endl;
}
|
// mesh.h: interface for the mesh class.
//
//////////////////////////////////////////////////////////////////////
#ifndef AFX_MESH_H_
#define AFX_MESH_H_
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <vector>
#include <string>
class Material
{
public:
float Ka[4]; //ambient coefficient
float Kd[4]; //diffuse coefficient
float Ks[4]; //specular coefficient
float Ns; //shiness
float Tr; //Transpant (or d)
std::string map_Ka; //ambient texture
std::string map_Kd; //diffuse texture
std::string map_Ks; //specular texture
//This mtl loader is still incomplete
//Please see http://en.wikipedia.org/wiki/Wavefront_.objFile#Material_template_library
Material()
{
for (size_t i=0;i<4;i++)
Ka[i] = Kd[i] = Ks[i] = 1.0f;
Ns = 0.0f;
Tr = 0.0f;
}
};
class Mesh
{
class Vertex // store the property of a basic vertex
{
public:
size_t v; // vertex (index of vList_)
size_t n; // normal (index of nList_)
size_t t; // texture (index of tList_)
Vertex() {};
Vertex(size_t v_index, size_t n_index, size_t t_index=0)
{
v = v_index;
n = n_index;
t = t_index;
}
};
class Vec3 // structure for vList_, nList_, tList_
{
public:
float ptr[3];
Vec3 (float *v)
{
for (size_t i=0;i<3;i++)
ptr[i] = v[i];
}
inline float& operator[](size_t index)
{
return ptr[index];
}
};
class Face // structure for faceList_
{
public:
Vertex v[3]; // 3 vertex for each face
int m; // Material (index of Material)
Face (Vertex &v1, Vertex &v2, Vertex &v3, int m_index)
{
v[0] = v1;
v[1] = v2;
v[2] = v3;
m = m_index;
}
inline Vertex& operator[](size_t index)
{
return v[index];
}
};
void loadMtl(std::string tex_file);
public:
/////////////////////////////////////////////////////////////////////////////
// Loading Object
/////////////////////////////////////////////////////////////////////////////
std::string objFile_;
std::string matFile_;
size_t mTotal_; // total Material
std::map<std::string,size_t>matMap_; // matMap_[Material_name] = Material_ID
std::vector<Material> mList_; // Material ID (every Mesh has at most 100 Materials)
std::vector<Vec3> vList_; // Vertex List (Position) - world cord.
std::vector<Vec3> nList_; // Normal List
std::vector<Vec3> tList_; // Texture List
std::vector<Face> faceList_; // Face List
size_t vTotal_, tTotal_, nTotal_, fTotal_; // number of total vertice, faces, texture coord., normal vecters, and faces
void loadMesh(std::string objFile);
Mesh();
Mesh(const char* objFile);
virtual ~Mesh();
void init(const char* objFile);
private:
FILE *mtlFilePtr_;
};
#endif
|
#ifndef MACOPDRAGMANAGER_H
#define MACOPDRAGMANAGER_h
#include "modules/pi/OpDragManager.h"
class MacOpDragManager : public OpDragManager
{
public:
MacOpDragManager();
virtual ~MacOpDragManager();
virtual OP_STATUS StartDrag(DesktopDragObject* drag_object);
virtual void StopDrag();
virtual BOOL IsDragging();
static pascal OSErr SaveDragFile(FlavorType flavorType, void *refcon, ItemReference itemRef, DragReference dragRef);
void AddDragImage(OpBitmap* bitmap);
DesktopDragObject* GetDragObject() { return m_drag_object; }
private:
Boolean mIsDragging;
DesktopDragObject* m_drag_object;
DragReference mDragRef;
Boolean mImageSet;
OpBitmap* mBitmap;
};
#endif
|
#ifndef BIG_INTEGER_H
#define BIG_INTEGER_H
#include <array>
#include <cstring>
#include <mpc.h>
#include <vector>
namespace rsa {
struct big {
big();
big(int i);
big(big const& other);
explicit big(std::vector<unsigned char> const& str);
explicit big(std::string const& str);
big& operator*=(big const& o);
big& operator-=(big const& o);
big& operator+=(big const& o);
big& operator%=(big const& o);
big& operator/=(big const& o);
template <size_t N>
friend big generate_prime();
friend bool operator<(big const& a, big const& b);
friend bool operator==(big const& a, big const& b);
friend big powm(big const& a, big const& b, big const& m);
friend size_t size(big const& a);
template <size_t SIZE>
friend std::string to_string(big const& a);
// ~big();
private:
mpz_t mpz;
};
big operator*(big a, big const& b);
big operator-(big a, big const& b);
big operator+(big a, big const& b);
big operator%(big a, big const& b);
big operator/(big a, big const& b);
bool operator<(big const& a, big const& b);
bool operator==(big const& a, big const& b);
big powm(big const& a, big const& b, big const& m);
template <size_t SIZE>
std::string to_string(const rsa::big& a) {
if constexpr (SIZE == 0) {
char* tmp = mpz_get_str(nullptr, 16, a.mpz);
std::string res = tmp;
void (*freefunc)(void*, size_t);
mp_get_memory_functions(nullptr, nullptr, &freefunc);
freefunc(tmp, std::strlen(tmp) + 1);
return res;
} else {
std::vector<unsigned char> res(SIZE);
size_t written = 0;
mpz_export(res.data(), &written, 1, sizeof(unsigned char), 0, 0, a.mpz);
res.resize(written);
return std::string(res.begin(), res.end());
}
}
std::ostream& operator<<(std::ostream& o, big const& a);
size_t size(big const& a);
} // namespace rsa
#endif // BIG_INTEGER_H
|
//
// EPITECH PROJECT, 2018
// nanotekspice
// File description:
// simulate chipsets
//
#ifndef __C4071_HPP__
# define __C4071_HPP__
# include "AComponent.hpp"
# include "Gate.hpp"
# include <vector>
namespace nts {
class C4071 : public nts::IComponent
{
const int nb_in;
const int nb_out;
std::string _name;
std::vector<nts::Tristate> _pins;
public:
C4071(const std::string &name);
virtual ~C4071() {};
public:
virtual nts::Tristate compute(std::size_t pin = 1);
virtual void setLink(std::size_t pin, nts::IComponent &other, std::size_t otherPin);
virtual void dump() const;
virtual std::string getName() const;
virtual void setState(nts::Tristate, size_t);
virtual nts::Tristate getPinAddr(size_t);
};
};
#endif /* __C4071_HPP__ */
|
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#include "ActionCue_editor.h"
#include "ActionCue_editorStyle.h"
#include "ActionCue_editorCommands.h"
#include "AudioUtills.h"
#include "LevelEditor.h"
#include "Editor.h"
#include "Engine.h"
#include "Engine/Selection.h"
#include "Widgets/Docking/SDockTab.h"
#include "Widgets/Layout/SBox.h"
#include "Widgets/Text/STextBlock.h"
#include "Widgets/Input/SButton.h"
#include "Widgets/SBoxPanel.h" //used ??
#include "Framework/MultiBox/MultiBoxBuilder.h"
#include "SeekButton.h"
#include "CueSelectButton.h"
#include "BaseAudioActor.h"
static const FName ActionCue_editorTabName("ActionCue_editor");
//TSharedPtr<SDockTab> FActionCue_editorModule::main__t;
#define LOCTEXT_NAMESPACE "FActionCue_editorModule"
void FActionCue_editorModule::StartupModule()
{
// This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module
FActionCue_editorStyle::Initialize();
FActionCue_editorStyle::ReloadTextures();
FActionCue_editorCommands::Register();
PluginCommands = MakeShareable(new FUICommandList);
PluginCommands->MapAction(
FActionCue_editorCommands::Get().OpenPluginWindow,
FExecuteAction::CreateRaw(this, &FActionCue_editorModule::PluginButtonClicked),
FCanExecuteAction());
FLevelEditorModule& LevelEditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");
{
TSharedPtr<FExtender> MenuExtender = MakeShareable(new FExtender());
MenuExtender->AddMenuExtension("WindowLayout", EExtensionHook::After, PluginCommands, FMenuExtensionDelegate::CreateRaw(this, &FActionCue_editorModule::AddMenuExtension));
LevelEditorModule.GetMenuExtensibilityManager()->AddExtender(MenuExtender);
}
{
TSharedPtr<FExtender> ToolbarExtender = MakeShareable(new FExtender);
ToolbarExtender->AddToolBarExtension("Settings", EExtensionHook::After, PluginCommands, FToolBarExtensionDelegate::CreateRaw(this, &FActionCue_editorModule::AddToolbarExtension));
LevelEditorModule.GetToolBarExtensibilityManager()->AddExtender(ToolbarExtender);
}
FTabSpawnerEntry tse = FGlobalTabmanager::Get()->RegisterNomadTabSpawner( ActionCue_editorTabName, FOnSpawnTab::CreateRaw( this, &FActionCue_editorModule::OnSpawnPluginTab ) )
.SetDisplayName( LOCTEXT( "FActionCue_editorTabTitle", "ActionCue_editor" ) )
.SetMenuType( ETabSpawnerMenuType::Hidden );
}
void FActionCue_editorModule::ShutdownModule()
{
// This function may be called during shutdown to clean up your module. For modules that support dynamic reloading,
// we call this function before unloading the module.
FActionCue_editorStyle::Shutdown();
FActionCue_editorCommands::Unregister();
FGlobalTabmanager::Get()->UnregisterNomadTabSpawner(ActionCue_editorTabName);
}
TSharedRef<SDockTab> FActionCue_editorModule::OnSpawnPluginTab(const FSpawnTabArgs& SpawnTabArgs)
{
FirstRun();
// Create the basic button data
Update_ButtonsData( ButtonTypes::Seek );
Update_ButtonsData( ButtonTypes::Select );
// Build all content
Build_SeekContent();
Build_CueSelectContent();
Build_DetailsContent();
Build_ToolbarContent();
return SNew( SDockTab )
.TabRole( ETabRole::NomadTab )
[
// Put your tab content here!
BuildContent_Display()
];
}
void FActionCue_editorModule::FirstRun()
{
if ( hadFirstRun ) return;
audioData = new AudioUtills();
Setup_Buttons();
// Register delegates
USelection::SelectionChangedEvent.AddRaw( this, &FActionCue_editorModule::SelectionChanged );
hadFirstRun = true;
}
void FActionCue_editorModule::PluginButtonClicked()
{
activeTabManager = FGlobalTabmanager::Get()->InvokeTab( ActionCue_editorTabName )->GetTabManager();
}
void FActionCue_editorModule::AddMenuExtension(FMenuBuilder& Builder)
{
Builder.AddMenuEntry(FActionCue_editorCommands::Get().OpenPluginWindow);
}
void FActionCue_editorModule::AddToolbarExtension(FToolBarBuilder& Builder)
{
Builder.AddToolBarButton(FActionCue_editorCommands::Get().OpenPluginWindow);
}
TSharedRef<SDockTab> FActionCue_editorModule::GetTab()
{
//A bit of a work around to return the tab instance, its just that the tab blinks when ever we need to make an update :|
//I've done it like this because if i store the tab in a var the window will NOT reopen once its been closed.
//There must be a better way! //Like the function after sounds good but does not return the correct window! hmmm...
//Have a look at InvokeTab!!
//return FGlobalTabmanager::Get()->InvokeTab( ActionCue_editorTabName ); //FGlobalTabmanager::Get()->FindExistingLiveTab( ActionCue_editorTabName ).ToSharedRef();
//Check there is a valid tab manager
if ( !activeTabManager.IsValid() )
PluginButtonClicked();
//This is How, it only took me 5hrs to find!
return activeTabManager.ToSharedRef()->FindExistingLiveTab( ActionCue_editorTabName ).ToSharedRef();
}
void FActionCue_editorModule::SelectionChanged( UObject* obj )
{
//Check that there is at least one actor selected in the scene
if ( GEditor->GetSelectedActorCount() == 0 ) return;
//Get the last object that was selected that inherits form ABaseAudioActor
ABaseAudioActor* selectedAudio = GEditor->GetSelectedActors()->GetBottom<ABaseAudioActor>();
if ( selectedAudio == selectedAudioActor ) return; // Nothing has really changed.
// Flag that we need to refresh the amp data
hasSeekAmpData = false;
hasSelectAmpData = false;
selectedAudioActor = selectedAudio;
USoundWave* audioClip = ( !selectedAudio ? nullptr : selectedAudioActor->audioClip ); // prevent crash if selectedAudio is null
audioData->SetAudioClip( audioClip );
/*
** Rebuild data and repaint tab
** Todo. this all needs its own function??
*/
// reset the select range.
currentSelectedRange_start = currentSelectedRange_end = -1;
//update the max sample value
SetMaxSampleValue();
// refresh button data
Update_ButtonsData( ButtonTypes::Seek );
Update_ButtonsData( ButtonTypes::Select );
// Build content
Build_SeekContent();
Build_ToolbarContent();
Build_CueSelectContent();
Build_DetailsContent();
RepaintTab();
FString audioActorName = ( !selectedAudio ? "None" : selectedAudioActor->GetName() );
FString msg = "Selection Changed: " + audioActorName;// GetFullName();
UE_LOG( LogTemp, Warning, TEXT( "%s" ), *msg );
}
void FActionCue_editorModule::SetMaxSampleValue()
{
if ( selectedAudioActor == nullptr )
return;
maxSampleValue = 1;
// start at sample 1 so we dont go over the total samples
for ( int i = 1; i < audioData->totalSamples; i++ )
{
float sampleValue = audioData->GetAmplitudeData( i - 1, i ); //Check a single sample
if ( sampleValue > maxSampleValue )
maxSampleValue = FMath::CeilToInt(sampleValue);
}
FString s = "New Max Sample: " + FString::FromInt( maxSampleValue );
UE_LOG( LogTemp, Log, TEXT( "%s" ), *s );
}
void FActionCue_editorModule::RepaintTab()
{
GetTab()->SetContent( BuildContent_Display() );
GetTab()->CacheVolatility();
}
TSharedRef<SBox> FActionCue_editorModule::BuildContent_Display()
{
/* Window layout
|---------------------------------------------|
|<| Seek Bar / zoom |>| Details |
|-------------------------------| |
| Seek | |
| | |
|---------------------------------------------|
| Cue Tool bar |
|---------------------------------------------|
| Cue Select |
| |
| |
|---------------------------------------------|
*/
float audioTopPadding = (maxButtonSize - minButtonSize) + 45.0f;
//Create the main content hold
TSharedRef<SBox> content = SNew( SBox )
.VAlign( VAlign_Fill )
.HAlign( HAlign_Fill )
.Padding(15.0f)
[
//Split the window with 3 rows
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.MaxHeight( 75.0f )
.Padding( 15.0f, 25.0f, 15.0f, -25.0f )
[
SNew( STextBlock )
.Text( FText::FromString( TEXT( "Action Cue BETA v0.4 By Ashley Sands" ) ) )
]
+SVerticalBox::Slot()
.MaxHeight(625.0f)
.Padding( 15.0f, audioTopPadding, 15.0f, 10.0f )
[
//Split the first row into 2 columns
SNew(SHorizontalBox)
+SHorizontalBox::Slot()
.VAlign(VAlign_Fill)
.HAlign(HAlign_Left)
.MaxWidth(1320.0f)
.Padding(0.0f, 0.0f, 0.0f, 0.0f)
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.MaxHeight( 25.0f )
.VAlign( VAlign_Top )
.Padding( 0.0f, -audioTopPadding-15.0f, 0.0f, 0.0f )
[
// Seek bar
SNew( STextBlock )
.Text( FText::FromString( GetSamplesToButtonRatio( "Seek Zoom", audioData->totalSamples, seekButtonsToDisplay ) ) )
]
+ SVerticalBox::Slot()
.MaxHeight( 550.0f )
.VAlign( VAlign_Bottom )
.Padding( 0.0f, 0.0f, 0.0f, 0.0f )
[
//Sample Seek content
seekContent.ToSharedRef()
]
]
+SHorizontalBox::Slot()
.VAlign( VAlign_Top )
.HAlign( HAlign_Fill )
.Padding(0.0f, -(audioTopPadding+25.0f), 0.0f, 0.0f)
.MaxWidth(1000.0f)
[
//Details Content
detailsContent.ToSharedRef()
]
]
+SVerticalBox::Slot()
.MaxHeight(40.0f)
.Padding( 0.0f, 50.0f, 0.0f, 20.0f )
[
//Cue Tools
toolbarContent.ToSharedRef()
]
+SVerticalBox::Slot()
.MaxHeight(325.0f)
.Padding( 15.0f, audioTopPadding, 15.0f, 25.0f)
.VAlign(VAlign_Fill)
[
//Action Cue Select
cueSelectContent.ToSharedRef()
]
];
return content;
}
void FActionCue_editorModule::Setup_Buttons()
{
//Only update the arrays if the amount of buttons has changed
if(seekButtons.Num() != seekButtonsToDisplay )
{
seekButtons.Empty();
for ( int i = 0; i < seekButtonsToDisplay; i++ )
{
seekButtons.Add( new SeekButton( i ) );
seekButtons[i]->OnButtonPressed.AddRaw( this, &FActionCue_editorModule::ButtonPressed_Seek);
}
//seekButtons.AddDefaulted( seekButtonsToDisplay );
FString mes = "Seek Button Count: " + FString::FromInt( seekButtons.Num() );
UE_LOG( LogTemp, Warning, TEXT( "%s" ), *mes );
}
if ( cueSelectButtons.Num() != cueSelectButtonsToDisplay )
{
cueSelectButtons.Empty();
for ( int i = 0; i < cueSelectButtonsToDisplay; i++ )
{
cueSelectButtons.Add( new CueSelectButton( i ) );
cueSelectButtons[i]->OnButtonPressed.AddRaw( this, &FActionCue_editorModule::ButtonPressed_Select );
}
FString mes = "Cue Select Button Count: " + FString::FromInt( cueSelectButtons.Num() );
UE_LOG( LogTemp, Warning, TEXT( "%s" ), *mes );
}
}
int FActionCue_editorModule::GetButtonsToDisplay( ButtonTypes buttonTypes )
{
switch ( buttonTypes )
{
case Seek:
return seekButtonsToDisplay;
case Select:
return cueSelectButtonsToDisplay;
}
return 0;
}
void FActionCue_editorModule::Update_ButtonsData( ButtonTypes buttonType )
{
int buttonCount = GetButtonsToDisplay( buttonType );
BaseButton* button;
int nextActionCueId = -1; //used when updating the cue select to update the selected buttons
//Extract the button from the array of button type
for ( int i = 0; i < buttonCount; i++ )
{
switch ( buttonType )
{
case ButtonTypes::Seek:
{
int endSample = seekButtons[seekButtons.Num() - 1]->GetSample( BaseButton::SampleRangeType::End );
button = seekButtons[i];
if ( !hasSeekAmpData )
{
endSample = audioData->totalSamples - 1;
if(!hasSelectAmpData) //deselect buttons if a rebuild of the select amp data is also required.
Update_ButtonIsSet( button, -2, 0, endSample ); //action cue id is always -2 to force deselect.
}
Update_buttonData( button, i, buttonCount, 0, endSample );
}
break;
case ButtonTypes::Select:
{
button = cueSelectButtons[i];
//transform the button id's into sample range
int selectedStartRange = GetSeekSampleValue( BaseButton::SampleRangeType::Start );
int selectedEndRange = GetSeekSampleValue( BaseButton::SampleRangeType::End );
if ( !hasSelectAmpData )
{
selectedStartRange = 0;
selectedEndRange = audioData->totalSamples - 1;
}
Update_buttonData( button, i, buttonCount, selectedStartRange, selectedEndRange );
nextActionCueId = Update_ButtonIsSet( button, nextActionCueId, selectedStartRange, selectedEndRange );
}
break;
}
}
//we must set hasSeekAmpData at the end so they all get set
if ( buttonType == ButtonTypes::Seek )
hasSeekAmpData = true;
else if ( buttonType == ButtonTypes::Select )
hasSelectAmpData = true;
}
int FActionCue_editorModule::GetSeekSampleValue( BaseButton::SampleRangeType rangeType )
{
int selectedStart = currentSelectedRange_start;
int selectedEnd = currentSelectedRange_end;
switch ( rangeType )
{
case BaseButton::SampleRangeType::Start:
if ( selectedStart < 0 && selectedEnd >= 0 )
selectedStart = selectedEnd;
else if ( selectedStart < 0 )
selectedStart = 0;
return seekButtons[selectedStart]->GetSample( BaseButton::SampleRangeType::Start );
case BaseButton::SampleRangeType::End:
if ( selectedStart > 0 && selectedEnd < 0 )
selectedEnd = selectedStart;
else if ( selectedEnd < 0 )
selectedEnd = seekButtons.Num() - 1;
return seekButtons[selectedEnd]->GetSample( BaseButton::SampleRangeType::End );
default:
return 0;
}
}
void FActionCue_editorModule::Update_buttonData( BaseButton* button, int currentButtonId, int maxButtonId, int startSampleRange, int endSampleRange )
{
//make shore that the start and end samples are in range.
if ( startSampleRange >= audioData->totalSamples )
startSampleRange = audioData->totalSamples - 1;
if ( endSampleRange < startSampleRange )
endSampleRange = startSampleRange;
if ( endSampleRange >= audioData->totalSamples )
endSampleRange = audioData->totalSamples - 1;
//find the sample range
int totalSamplesInRange = endSampleRange - startSampleRange;
int samplesRange = FMath::CeilToInt( totalSamplesInRange / maxButtonId );
int startSample = startSampleRange + (samplesRange * currentButtonId);
int endSample = startSample + samplesRange;
// Make shore the start and end samples do not go out of range of the audio samples
if ( startSample >= audioData->totalSamples )
startSample = endSample = audioData->totalSamples - 1; //End sample is alway more than start sample
else if ( endSample >= audioData->totalSamples )
endSample = audioData->totalSamples - 1;
//FString s = "StartSamp: " + FString::FromInt( startSampleRange ) + " EndSamp: " + FString::FromInt( endSampleRange ) + " TotalSamp: "+FString::FromInt(audioData->totalSamples);
//UE_LOG(LogTemp, Warning, TEXT("%s"), *s)
button->SetSampleRange( startSample, endSample );
button->SetValue( audioData->GetAmplitudeData( startSample, endSample ) / maxSampleValue );
}
int FActionCue_editorModule::Update_ButtonIsSet( BaseButton* button, int actionCueId, int startSample, int endSample )
{
// if theres is nothing selected there no point looking for cue data (plus it will crash)
// so just override it so it just deselects all the buttons :)
if ( !selectedAudioActor ) actionCueId = -2;
FString s = ""; //debugging
//find the first action key
if ( actionCueId == -1 )
{
bool found = false; // so we can return if no action is found to be in range.
//find which action if any is in range
for ( int i = 0; i < selectedAudioActor->actionCues.Num(); i++ )
{
int actionCueSample = audioData->SecondsToSamples( selectedAudioActor->actionCues[i] );
if ( actionCueSample >= startSample && actionCueSample <= endSample )
{
actionCueId = i;
found = true;
break;
}
}
if(!found)
{
actionCueId = -2;
}
s = ( found ? "true" : "false");
}
//s = "<<>> " + FString::FromInt( actionCueId ) + " :: " + s;
//UE_LOG( LogTemp, Log, TEXT( "%s" ), *s );
// Set the button to its correct state.
if ( actionCueId >= 0 )
{
int actionCueSample = audioData->SecondsToSamples( selectedAudioActor->actionCues[actionCueId] );
if ( button->IsSampleInRange( actionCueSample ) )
{
button->Set( true );
actionCueId++;
// check that the action cue is still in range
if ( actionCueId >= selectedAudioActor->actionCues.Num() )
actionCueId = 0;
}
else
{
button->Set( false );
}
}
else
{
button->Set( false );
}
return actionCueId;
}
void FActionCue_editorModule::DrawButtons( TSharedRef<SHorizontalBox> buttonHold, ButtonTypes buttonType )
{
int buttonCount = GetButtonsToDisplay( buttonType );
BaseButton* button;
//Extract the button from the array of button type
for ( int i = 0; i < buttonCount; i++ )
{
switch(buttonType)
{
case ButtonTypes::Seek:
button = seekButtons[ i ];
DrawButton( buttonHold, button );
break;
case ButtonTypes::Select:
button = cueSelectButtons[ i ];
DrawButton( buttonHold, button );
break;
}
}
}
void FActionCue_editorModule::DrawButton( TSharedRef< SHorizontalBox > buttonHold, BaseButton* button )
{
// Todo: For the min width issue i think the padding should be set via a delegate
// so that the padding does not got below the HBox max width.
// Create a vertical box so the button is the correct height
// we do this for each button as there all different heights
float sizeDif = maxButtonSize - minButtonSize;
TSharedRef< SVerticalBox > buttonHeightBox = SNew( SVerticalBox );
SVerticalBox::FSlot& vSlot = buttonHeightBox->AddSlot()
.MaxHeight( minButtonSize + ( sizeDif * button->GetValue() ) )
.Padding( 0.0f, (minButtonSize + ( sizeDif * ( 1.0f - button->GetValue() ) ) ) / 2.0f )
[
button->GetButton()
];
// Create a new horizontal slot in the button hold so all the buttons have the same width and horizontal spacing
// and insert the vertical box holding the button
SHorizontalBox::FSlot& hSlot = buttonHold->AddSlot()
//.MaxWidth( 250.0f )
.VAlign(VAlign_Fill)
.Padding( 3.0f, -sizeDif )
[
buttonHeightBox
];
}
FString FActionCue_editorModule::GetSamplesToButtonRatio( FString lable, int sampleRange, int buttonCount )
{
lable += " 1:" + FString::FromInt( FMath::FloorToInt( sampleRange / buttonCount ) );
return lable;
}
void FActionCue_editorModule::ButtonPressed_Seek( int buttonId )
{
// Get the range so we can work out which end to move.
int buttonSelectRangeMidPoint = (currentSelectedRange_end - currentSelectedRange_start) / 2.0f;
// Find if its the start or end button that has been changed.
if ( buttonId == currentSelectedRange_start )
{
currentSelectedRange_start = -1;
}
else if ( buttonId == currentSelectedRange_end )
{
if ( currentSelectedRange_start >= 0 )
{
currentSelectedRange_end = currentSelectedRange_start;
currentSelectedRange_start = -1;
}
else
{
currentSelectedRange_end = -1;
}
}// Move the start point if select before the start point or if we are closer to start than end
else if ( buttonId < currentSelectedRange_start
|| (buttonId < currentSelectedRange_end && buttonId - currentSelectedRange_start <= FMath::CeilToInt( buttonSelectRangeMidPoint ) )
|| (currentSelectedRange_start < 0 && buttonId < currentSelectedRange_end) )
{
if(currentSelectedRange_start >= 0)
seekButtons[currentSelectedRange_start]->Set( false );
currentSelectedRange_start = buttonId;
}// Move the end point if select after the end point or if we are closer to the end than the start
else if ( buttonId > currentSelectedRange_end || currentSelectedRange_end - buttonId <= FMath::FloorToInt( buttonSelectRangeMidPoint ) )
{
if ( currentSelectedRange_start < 0 ) //if there is no start set start to end
currentSelectedRange_start = currentSelectedRange_end;
else if ( currentSelectedRange_end >= 0 )
seekButtons[currentSelectedRange_end]->Set( false );
currentSelectedRange_end = buttonId;
}
FString s = "Seek button pressed: " + FString::FromInt( buttonId ) + " || Current selected start: "+FString::FromInt(currentSelectedRange_start)+" Current Selected end:"+FString::FromInt(currentSelectedRange_end);
UE_LOG( LogTemp, Log, TEXT( "%s" ), *s );
}
void FActionCue_editorModule::ButtonPressed_Select( int buttonId )
{
if ( !selectedAudioActor ) return;
//Find the time position of the selected button.
int sample = cueSelectButtons[buttonId]->GetAvgSample();
float time = audioData->SamplesToSeconds(sample);
bool addKey = cueSelectButtons[buttonId]->IsSet();
Update_SelectedAudioActorActions( time, addKey, buttonId );
FString s = "Select button pressed: " + FString::FromInt( buttonId ) +" Sample: "+FString::FromInt(sample)+" Time: "+FString::SanitizeFloat(time);
UE_LOG( LogTemp, Log, TEXT( "%s" ), *s );
}
void FActionCue_editorModule::Update_SelectedAudioActorActions( float time, bool addKey, int buttonId )
{
//Error: nothing to remove
if ( !addKey && selectedAudioActor->actionCues.Num() == 0 )
{
FString s = "Selected audio actor has no actions to remove";
UE_LOG( LogTemp, Error, TEXT( "%s" ), *s );
return;
}
//Add the first element to the array of actions
if ( addKey && selectedAudioActor->actionCues.Num() == 0 )
{
selectedAudioActor->actionCues.Add( time );
return;
}
// So theres actions, find where to add or what to remove
//Todo. Add undo step. See the unreal plugin base script that is after standalone for more info.
bool done = false; //so we can print a message if it fails to add or remove.
for ( int i = 0; i < selectedAudioActor->actionCues.Num(); i++ )
{
if ( addKey && (time < selectedAudioActor->actionCues[ i ] || i == selectedAudioActor->actionCues.Num()-1) )
{
//Add it to the end if its after time
if( time > selectedAudioActor->actionCues[i] )
selectedAudioActor->actionCues.Add( time );
else
selectedAudioActor->actionCues.Insert( time, i );
done = true;
break;
}
else if ( !addKey && cueSelectButtons[buttonId]->IsSampleInRange( audioData->SecondsToSamples( selectedAudioActor->actionCues[i] ) ) )
{
selectedAudioActor->actionCues.RemoveAt( i );
done = true;
break;
}
}
if ( !done )
{
FString s = ( addKey ? "add" : "remove" );
s = "Failed to " + s + " key at time: " + FString::SanitizeFloat( time );
UE_LOG( LogTemp, Error, TEXT( "%s" ), *s );
}
}
void FActionCue_editorModule::Build_SeekContent()
{
// Create a new seek content hold and generate its contents
seekContent = SNew( SHorizontalBox );
DrawButtons( seekContent.ToSharedRef(), ButtonTypes::Seek );
}
void FActionCue_editorModule::Build_CueSelectContent()
{
// Create a new cue select content hold and generate its contents.
cueSelectContent = SNew( SHorizontalBox );
DrawButtons( cueSelectContent.ToSharedRef(), ButtonTypes::Select );
}
void FActionCue_editorModule::Build_DetailsContent()
{
// Create a new cue select content hold and generate its contents.
detailsContent = SNew( SVerticalBox )
+ SVerticalBox::Slot()
.Padding( 50.0f, 5.0f, 5.0f, 5.0f )
[
DetailsRow( "Object Name", GetDetailsValues( DetailsContentTypes::ObjName ) )
];
// don't display any audio data if theres no BaseAudioActor selected
if ( selectedAudioActor == nullptr) return;
detailsContent->AddSlot()
.Padding(50.0f, 5.0f, 5.0f, 5.0f)
[
DetailsRow("Clip Name", GetDetailsValues( DetailsContentTypes::ClipName ) )
];
// Only display audio data if there is an audio clip
if ( selectedAudioActor->audioClip == nullptr ) return;
detailsContent->AddSlot()
.Padding(50.0f, 5.0f, 5.0f, 5.0f)
[
DetailsRow("Clip Length", GetDetailsValues( DetailsContentTypes::ClipLength ) )
];
detailsContent->AddSlot()
.Padding(50.0f, 5.0f, 5.0f, 5.0f)
[
DetailsRow("Clip Channels", GetDetailsValues( DetailsContentTypes::ClipChannels ) )
];
detailsContent->AddSlot()
.Padding( 50.0f, 5.0f, 5.0f, 5.0f )
[
DetailsRow( "Clip Sample Rate", GetDetailsValues( DetailsContentTypes::ClipSampleRate ) )
];
detailsContent->AddSlot()
.Padding( 50.0f, 5.0f, 5.0f, 5.0f )
[
DetailsRow( "Clip Total Samples", GetDetailsValues( DetailsContentTypes::ClipTotalSamples ) )
];
detailsContent->AddSlot()
.Padding(50.0f, 5.0f, 5.0f, 5.0f)
[
DetailsRow("Cue Count", GetDetailsValues(DetailsContentTypes::CueCount))
];
}
TSharedRef<SHorizontalBox> FActionCue_editorModule::DetailsRow( FString lable, FString value )
{
TSharedRef<SHorizontalBox> row = SNew( SHorizontalBox )
+SHorizontalBox::Slot()
.HAlign(HAlign_Left)
.MaxWidth(175.0f)
[
SNew( STextBlock )
.Text( FText::FromString( lable ) )
]
+SHorizontalBox::Slot()
.HAlign( HAlign_Left )
.MaxWidth( 1800.0f )
[
SNew( STextBlock )
.Text( FText::FromString( value ) )
];
return row;
}
void FActionCue_editorModule::Build_ToolbarContent()
{
int sampleRange = GetSeekSampleValue( BaseButton::SampleRangeType::End ) - GetSeekSampleValue( BaseButton::SampleRangeType::Start );
FString buttonLengthSec = FString::SanitizeFloat( audioData->SamplesToSeconds( FMath::FloorToInt( sampleRange / cueSelectButtonsToDisplay ) ) );
toolbarContent = SNew( SHorizontalBox )
+ SHorizontalBox::Slot()
.MaxWidth( 55.0f )
.Padding( 5.0f, 5.0f )
[
SNew( SButton )
.OnClicked_Raw( this, &FActionCue_editorModule::TEMP_ButtonAction )
.Text( FText::FromString( FString( "Load" ) ) )
]
+ SHorizontalBox::Slot()
.MaxWidth( 155.0f )
.Padding( 5.0f, 5.0f )
[
SNew( SButton )
.OnClicked_Raw( this, &FActionCue_editorModule::RefreshContent_select )
[
SNew( STextBlock )
.Text( FText::FromString( "Refresh Action Select" ) )
]
]
+ SHorizontalBox::Slot()
.MaxWidth( 210.0f )
.Padding( 5.0f, 5.0f )
[
SNew( STextBlock )
.Text( FText::FromString( GetSamplesToButtonRatio( "Select Zoom", sampleRange, cueSelectButtonsToDisplay ) + "\nButton length " + buttonLengthSec + " Seconds" ) )
];
}
FString FActionCue_editorModule::GetDetailsValues( DetailsContentTypes dcType )
{
// return our default values for none selected or no audio clip
if ( selectedAudioActor == nullptr )
return "None Selected";
else if ( selectedAudioActor->audioClip == nullptr && dcType != DetailsContentTypes::ObjName )
return "None";
switch ( dcType )
{
case DetailsContentTypes::ObjName:
return selectedAudioActor->GetName();
case DetailsContentTypes::ClipName:
return selectedAudioActor->audioClip->GetName();
case DetailsContentTypes::ClipLength:
return FString::SanitizeFloat( selectedAudioActor->audioClip->GetDuration(), 0) + " seconds";
case DetailsContentTypes::ClipChannels:
return FString::FromInt( selectedAudioActor->audioClip->NumChannels );
case DetailsContentTypes::ClipSampleRate:
return FString::FromInt( audioData->sampleRate );
case DetailsContentTypes::ClipTotalSamples:
return FString::FromInt( audioData->totalSamples );
case DetailsContentTypes::CueCount:
return "0"; //Todo: implement cue.
}
return "Error: Details content not found.";
}
FReply FActionCue_editorModule::RefreshContent_select()
{
Update_ButtonsData( ButtonTypes::Select );
Build_ToolbarContent();
Build_CueSelectContent();
RepaintTab();
return FReply::Handled();
}
FReply FActionCue_editorModule::TEMP_ButtonAction()
{
//Update data
Update_ButtonsData( ButtonTypes::Seek );
Update_ButtonsData( ButtonTypes::Select );
//Build all content
Build_SeekContent();
Build_CueSelectContent();
Build_DetailsContent();
Build_ToolbarContent();
//Repaint the tab
RepaintTab();
return FReply::Handled();
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FActionCue_editorModule, ActionCue_editor)
|
#ifndef HEADER_CURL_MD5_H
#define HEADER_CURL_MD5_H
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2010, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#ifndef CURL_DISABLE_CRYPTO_AUTH
#include "curl_hmac.h"
namespace youmecommon
{
#define MD5_DIGEST_LEN 16
typedef void(*Curl_MD5_init_func)(void *context);
typedef void(*Curl_MD5_update_func)(void *context,
const unsigned char *data,
unsigned int len);
typedef void(*Curl_MD5_final_func)(unsigned char *result, void *context);
typedef struct {
Curl_MD5_init_func md5_init_func; /* Initialize context procedure */
Curl_MD5_update_func md5_update_func; /* Update context with data */
Curl_MD5_final_func md5_final_func; /* Get final result procedure */
unsigned int md5_ctxtsize; /* Context structure size */
unsigned int md5_resultlen; /* Result length (bytes) */
} MD5_params;
typedef struct {
const MD5_params *md5_hash; /* Hash function definition */
void *md5_hashctx; /* Hash function context */
} MD5_context;
extern const MD5_params Curl_DIGEST_MD5[1];
extern const HMAC_params Curl_HMAC_MD5[1];
void Curl_md5it(unsigned char *output,
const unsigned char *input);
MD5_context * Curl_MD5_init(const MD5_params *md5params);
int Curl_MD5_update(MD5_context *context,
const unsigned char *data,
unsigned int len);
int Curl_MD5_final(MD5_context *context, unsigned char *result);
}
#endif
#endif /* HEADER_CURL_MD5_H */
|
#pragma once
#include "texture.hpp"
namespace leaves { namespace pipeline
{
template <>
struct texture_traits<texture_1d_array> : texture_traits_base
{
static constexpr bool is_texture_1d() noexcept
{
return true;
}
static constexpr object_type type() noexcept
{
return object_type::texture_1d;
}
static constexpr bool is_texture_array() noexcept
{
return true;
}
// meta structure
struct meta
{
pixel_format format;
uint16_t width;
uint16_t array_size;
bool has_mipmap;
texture_meta to_tex_meta() const noexcept
{
return{ format, width, uint16_t{1}, uint16_t{1}, array_size, has_mipmap };
}
};
};
class texture_1d_array : public texture<texture_1d_array>
{
public:
// base class type
using base_type = texture<texture_1d_array>;
using meta = texture_traits<texture_1d_array>::meta;
public:
// constructor
texture_1d_array(string name, meta const& meta_data_spec)
: base_type(std::move(name), meta_data_spec.to_tex_meta(), device_access::none, device_access::read)
{
}
};
} }
|
#include <MsTimer2.h>
#include <Adafruit_NeoPixel.h>
#define PIN 6
#define LEDNUM 35
double bpm = 90.0;
double interval = 60.0/bpm;
double tt = interval*1000;
double half_tt = tt/2;
double pre_time = 0;
double cal_time = 0; // for calculating accuracy
double start_time = 0;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(LEDNUM, PIN, NEO_GRB + NEO_KHZ800);
int threshold=4;
int a[1];
int pattern[16]={1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0};
int i = 0;
int j = 0;
void setup() {
Serial.begin(9600);
strip.begin();
MsTimer2::set(tt,check_tempo);
strip.setBrightness(10);
strip.clear();
strip.show();
for(int k = 4; k > 0 ; k--){
for(j = 0; j <= LEDNUM; j++){
strip.setPixelColor(j,0,255,255);
}
strip.setBrightness(10);
strip.show();
delay(half_tt);
strip.clear();
strip.show();
delay(half_tt);
}
MsTimer2::start();
}
void loop(){
}
void check_tempo(){
double start_time = millis();
strip.clear();
strip.show();
delay(half_tt);
int sensorValue = analogRead(A5);
a[0] = sensorValue;
i = i%16;
if(sensorValue>threshold){
double check_time = millis();
double cal_time = check_time - start_time;
if(tt-700<cal_time||cal_time< tt+700){
if(pattern[i] == 1){ //Good
Serial.println(a[0]);
for(j = 0 ; j <= LEDNUM ; j++){
strip.setPixelColor(j,0,0,255);
}
}
else{
Serial.println(a[0]); //Wrong note
for(j = 0 ; j <= LEDNUM ; j++){
strip.setPixelColor(j,255,255,255);
}
}
}
else{
Serial.println(a[0]); //Miss
for(j = 0 ; j <= LEDNUM ; j++){
strip.setPixelColor(j,0,255,0);
}
}
}
else{
Serial.println(a[0]); //Failed
for(j = 0 ; j <= LEDNUM ; j++){
strip.setPixelColor(j,255,0,0);
}
}
strip.show();
delay(half_tt);
i++;
}
|
#ifndef INTEGER_H
#define INTEGER_H
#include "Data.hpp"
namespace uipf{
// Integer which is a specification of Data
class Integer : public Data {
public:
typedef SMARTPOINTER<Integer> ptr;
typedef const SMARTPOINTER<Integer> c_ptr;
public:
// default constructor
Integer() : i_(0) {};
// constructor
Integer(int i) : i_(i) {};
// copy constructor
Integer(const Integer& i) : i_(i.i_) {};
// destructor
~Integer(void){};
// returns the value of the integer
int getContent() const;
// sets the value of the integer
void setContent(int);
// returns the data type of this data object: in this case: INTEGER
Type getType() const override;
private:
// value of the integer
int i_;
};
} // namespace
#endif
|
#include "hotelwindow.h"
#include <QApplication>
#include "lde.h"
#include "les.h"
#include "no.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
HotelWindow w;
w.show();
return a.exec();
}
|
//
// Table.h
// Project 4
//
// Created by Hender Lin on 6/5/21.
//
#ifndef Table_h
#define Table_h
#include <string>
#include <vector>
#include <list>
class Table
{
public:
Table(std::string keyColumn, const std::vector<std::string>& columns);
~Table();
bool good() const;
bool insert(const std::string& recordString);
void find(std::string key, std::vector<std::vector<std::string>>& records) const;
int select(std::string query, std::vector<std::vector<std::string>>& records) const;
// We prevent a Table object from being copied or assigned by
// making the copy constructor and assignment operator unavailable.
Table(const Table&) = delete;
Table& operator=(const Table&) = delete;
private:
int m_key = -1;
int buckets = 0;
std::vector<std::string> fields;
std::list<std::vector<std::string>> *m_table;
bool validRecord(const std::string& recordString);
bool validQuery(std::string query) const;
};
#endif /* Table_h */
|
#include "componentprovider.h"
using namespace std;
namespace sbg {
template <int n>
ComponentProvider<n>::ComponentProvider(Provider<Vector<n, double>> position, Provider<Vector<freedom(n), double>> orientation) :
_orientation{move(orientation)},
_position{move(position)}
{}
template <int n>
Vector <freedom(n), double> ComponentProvider<n>::getOrientation() const
{
return _orientation();
}
template<int n>
Vector<n, double> ComponentProvider<n>::getPosition() const
{
return _position();
}
template struct ComponentProvider<2>;
template struct ComponentProvider<3>;
}
|
// MIT License
// Copyright (c) 2020 Marnix van den Berg <m.a.vdberg88@gmail.com>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "Reader.h"
#include "ErrorLogger.h"
#include "InputData.h"
#include <iostream>
#include <fstream>
#include "rapidjson/document.h"
#include "rapidjson/filereadstream.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
struct DocumentObject
{
DocumentObject()
{
m_document.SetNull();
}
rapidjson::Document m_document;
};
namespace
{
bool readDoubleFromObj(const rapidjson::Value& obj, std::string member, double* val)
{
if (!obj.IsObject())
{
ErrLog::log("Error: input to readDoubleFromObj is not an object.");
return false;
}
if (!obj.HasMember(member.c_str()))
{
ErrLog::log("Error: member " + member + "not found in object.");
return false;
}
if (!(obj[member.c_str()].IsDouble() || obj[member.c_str()].IsInt64()))
{
ErrLog::log("Error: member " + member + "is not a double.");
return false;
}
*val = obj[member.c_str()].GetDouble();
return true;
}
bool readIntFromObj(const rapidjson::Value& obj, std::string member, int* val)
{
if (!obj.IsObject())
{
ErrLog::log("Error: input to readDoubleFromObj is not an object.");
return false;
}
if (!obj.HasMember(member.c_str()))
{
ErrLog::log("Error: member " + member + "not found in object.");
return false;
}
if (!(obj[member.c_str()].IsDouble() || obj[member.c_str()].IsInt64()))
{
ErrLog::log("Error: member " + member + "is not an int or double.");
return false;
}
*val = obj[member.c_str()].GetInt64();
return true;
}
}
Reader::Reader()
{
m_doc = std::make_unique<DocumentObject>();
}
Reader::~Reader() = default;
bool Reader::readInputData(std::string fileName, InputData* inputData)
{
if (!parseFile(fileName))
{
return false;
}
if (!readSettings(&inputData->settings)) return false;
if (m_doc->m_document.HasMember("concentration"))
{
if (m_doc->m_document["concentration"].IsDouble() || m_doc->m_document["concentration"].IsInt64())
{
inputData->concentration = m_doc->m_document["concentration"].GetDouble();
}
}
if (m_doc->m_document.HasMember("domainSize"))
{
if (m_doc->m_document["domainSize"].IsArray())
{
const rapidjson::Value& sizeArr = m_doc->m_document["domainSize"];
if (sizeArr.Size() != 2)
{
return false;
}
int i0(0), i1(1);
inputData->domainSize[0] = sizeArr[i0].GetDouble();
inputData->domainSize[1] = sizeArr[i1].GetDouble();
}
}
if (!readBodyPoints(&inputData->bodyPointsVec))
{
ErrLog::log("Failed to read body points");
return false;
}
int stop = 1;
return true;
}
bool Reader::readSettings(Settings* settings)
{
if (!m_doc->m_document.HasMember("settings"))
{
ErrLog::log("Reading error: Could not find settings.");
return false;
}
if (!m_doc->m_document["settings"].IsObject())
{
ErrLog::log("Reading error: Expected settings object.");
return false;
}
const rapidjson::Value& settingsObj = m_doc->m_document["settings"];
if (!readDoubleFromObj(settingsObj, "maxCollisionMargin", &settings->maxCollisionMargin)) return false;
if (!readDoubleFromObj(settingsObj, "maxResidualPenetration", &settings->maxResidualPenetration)) return false;
if (!readIntFromObj(settingsObj, "maxSolverIterations", &settings->maxSolverIterations)) return false;
return true;
}
bool Reader::parseFile(std::string fileName)
{
m_doc->m_document.SetNull();
FILE* file;
fopen_s(&file, fileName.c_str(), "r");
if (file == NULL)
{
ErrLog::log("Error: Could not open input file.");
return false;
}
char readBuffer[16384];
rapidjson::FileReadStream inStream(file, readBuffer, sizeof(readBuffer));
// Default template parameter uses UTF8 and MemoryPoolAllocator.
m_doc->m_document.ParseStream<0>(inStream);
if (m_doc->m_document.HasParseError())
{
ErrLog::log("Error: Failed to parse input file. " + fileName);
fclose(file);
return false;
}
fclose(file);
return true;
}
bool Reader::readBodyPoints(std::vector<std::vector<Vector2>>* bodyPointsVec)
{
if (m_doc->m_document.IsNull())
return false;
if (m_doc->m_document.HasMember("bodies"))
{
if (m_doc->m_document["bodies"].IsArray())
{
const rapidjson::Value& bodyArray = m_doc->m_document["bodies"];
for (rapidjson::SizeType i = 0; i < bodyArray.Size(); i++)
{
if (bodyArray[i].IsObject())
{
if (!bodyArray[i].HasMember("points"))
{
ErrLog::log("Reading error: No points in body.");
}
const rapidjson::Value& pointsArray = bodyArray[i]["points"];
if (pointsArray.Size() % 2 != 0) return false;
std::vector<Vector2> points;
for (rapidjson::SizeType j = 0; j < pointsArray.Size()/2; j++)
{
int idx = j * 2;
int idy = j * 2 + 1;
Vector2 p;
if (pointsArray[idx].IsDouble() || pointsArray[idx].IsInt64())
{
p.setX(pointsArray[idx].GetDouble());
}
if (pointsArray[idy].IsDouble() || pointsArray[idx].IsInt64())
{
p.setY(pointsArray[idy].GetDouble());
}
points.push_back(p);
}
bodyPointsVec->push_back(points);
}
}
return true;
}
}
ErrLog::log("Warning: Failed to parse body points from the input file");
return false;
}
|
char* menu1[]={"Search&Destroy","Sabotage","Domination" };
char* menu2[]={"Game Config","Sound Config", "Mosfet Test", "Auto Test" };
char* GAME_TIME="Game Time:";
char* BOMB_TIME="Bomb Time:";
char* ZERO_MINUTES="00 minutes";
char* ARM_TIME="Arm Time:";
char* ZERO_SECS="00 seconds";
char* ENABLE_SOUND="Enable Sound?";
char* YES_OR_NOT="A : Yes B : No";
char* ENABLE_MOSFET="Enable Mosfet?";
char* ENABLE_CODE="Enable Code Arm?";
char* GAME_TIME_TOP="GAME TIME";
char* ARMING_BOMB = "ARMING BOMB";
char* ENTER_CODE = "Enter Code";
char* CODE_ERROR = "Code Error!";
char* BOMB_ARMED = "BOMB ARMED";
char* DETONATION_IN = "DETONATION IN";
char* DISARMING = "DISARMING BOMB" ;
char* DISARM = "DISARMING";
char* GAME_OVER = " GAME OVER! ";
char* DEFENDERS_WIN = " DEFENDERS WIN ";
|
/*
* Academic License - for use in teaching, academic research, and meeting
* course requirements at degree granting institutions only. Not for
* government, commercial, or other organizational use.
* File: rtwtypes.h
*
* MATLAB Coder version : 3.3
* C/C++ source code generated on : 24-Apr-2018 18:23:19
*/
#ifndef RTWTYPES_H
#define RTWTYPES_H
#ifndef __TMWTYPES__
#define __TMWTYPES__
namespace matlabautogen
{
/*=======================================================================*
* Target hardware information
* Device type: Generic->MATLAB Host Computer
* Number of bits: char: 8 short: 16 int: 32
* long: 32 long long: 64
* native word size: 64
* Byte ordering: LittleEndian
* Signed integer division rounds to: Zero
* Shift right on a signed integer as arithmetic shift: on
*=======================================================================*/
/*=======================================================================*
* Fixed width word size data types: *
* int8_T, int16_T, int32_T - signed 8, 16, or 32 bit integers *
* uint8_T, uint16_T, uint32_T - unsigned 8, 16, or 32 bit integers *
* real32_T, real64_T - 32 and 64 bit floating point numbers *
*=======================================================================*/
typedef signed char int8_T;
typedef unsigned char uint8_T;
typedef short int16_T;
typedef unsigned short uint16_T;
typedef int int32_T;
typedef unsigned int uint32_T;
typedef long long int64_T;
typedef unsigned long long uint64_T;
typedef float real32_T;
typedef double real64_T;
/*===========================================================================*
* Generic type definitions: real_T, time_T, boolean_T, int_T, uint_T, *
* ulong_T, ulonglong_T, char_T and byte_T. *
*===========================================================================*/
typedef double real_T;
typedef double time_T;
typedef unsigned char boolean_T;
typedef int int_T;
typedef unsigned int uint_T;
typedef unsigned long ulong_T;
typedef unsigned long long ulonglong_T;
typedef char char_T;
typedef char_T byte_T;
/*===========================================================================*
* Complex number type definitions *
*===========================================================================*/
#define CREAL_T
typedef struct {
real32_T re;
real32_T im;
} creal32_T;
typedef struct {
real64_T re;
real64_T im;
} creal64_T;
typedef struct {
real_T re;
real_T im;
} creal_T;
typedef struct {
int8_T re;
int8_T im;
} cint8_T;
typedef struct {
uint8_T re;
uint8_T im;
} cuint8_T;
typedef struct {
int16_T re;
int16_T im;
} cint16_T;
typedef struct {
uint16_T re;
uint16_T im;
} cuint16_T;
typedef struct {
int32_T re;
int32_T im;
} cint32_T;
typedef struct {
uint32_T re;
uint32_T im;
} cuint32_T;
typedef struct {
int64_T re;
int64_T im;
} cint64_T;
typedef struct {
uint64_T re;
uint64_T im;
} cuint64_T;
/*=======================================================================*
* Min and Max: *
* int8_T, int16_T, int32_T - signed 8, 16, or 32 bit integers *
* uint8_T, uint16_T, uint32_T - unsigned 8, 16, or 32 bit integers *
*=======================================================================*/
#define MAX_int8_T ((int8_T)(127))
#define MIN_int8_T ((int8_T)(-128))
#define MAX_uint8_T ((uint8_T)(255))
#define MIN_uint8_T ((uint8_T)(0))
#define MAX_int16_T ((int16_T)(32767))
#define MIN_int16_T ((int16_T)(-32768))
#define MAX_uint16_T ((uint16_T)(65535))
#define MIN_uint16_T ((uint16_T)(0))
#define MAX_int32_T ((int32_T)(2147483647))
#define MIN_int32_T ((int32_T)(-2147483647-1))
#define MAX_uint32_T ((uint32_T)(0xFFFFFFFFU))
#define MIN_uint32_T ((uint32_T)(0))
#define MAX_int64_T ((int64_T)(9223372036854775807LL))
#define MIN_int64_T ((int64_T)(-9223372036854775807LL-1LL))
#define MAX_uint64_T ((uint64_T)(0xFFFFFFFFFFFFFFFFULL))
#define MIN_uint64_T ((uint64_T)(0ULL))
/* Logical type definitions */
#if !defined(__cplusplus) && !defined(__true_false_are_keywords)
# ifndef false
# define false (0U)
# endif
# ifndef true
# define true (1U)
# endif
#endif
/*
* Maximum length of a MATLAB identifier (function/variable)
* including the null-termination character. Referenced by
* rt_logging.c and rt_matrx.c.
*/
#define TMW_NAME_LENGTH_MAX 64
}
#endif
#endif
/*
* File trailer for rtwtypes.h
*
* [EOF]
*/
|
#include "Task.h"
#include <algorithm>
#include <string>
Task::Task() {
//
}
Task::Task(int task_id, int period, int execution_time)
: task_id(task_id), period(period) {
//
}
double Task::utilization() const {
if (period != 0) {
return (double)execution_time / period;
}
return 0;
}
std::string Task::to_string() const {
return "T" + std::to_string(task_id) + ": (" + std::to_string(period) +
", " + std::to_string(execution_time) + ")";
}
|
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int ws[5] = {3, 4, 1, 2, 3};
int ps[5] = {2, 3, 2, 3, 6};
int maxw = 10;
// dp[x][y] ... x: x番目の価値, y: 重さ
int dp[6][11];
int ret = 0;
// 初期化
for (int i = 0; i <= maxw; i++) dp[0][i] = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j <= maxw; j++) {
if (j >= ws[i]) {
dp[i + 1][j] = max(dp[i][j - ws[i]] + ps[i], dp[i][j]);
} else {
dp[i + 1][j] = dp[i][j];
}
}
}
cout << dp[5][10] << endl;
return 0;
}
|
#include "GameCmd.h"
#include "CDLReactor.h"
#include "Despatch.h"
#include "HallHandler.h"
#include "Logger.h"
#include "Despatch.h"
#include "PlayerManager.h"
using namespace std;
static InputPacket pPacket;
//=================HallHandler=========================
HallHandler::HallHandler()
{
uid = -1;
}
HallHandler::~HallHandler( )
{
//this->_decode = NULL;
uid = -1;
}
int HallHandler::OnConnected()
{
LOGGER(E_LOG_INFO) << "Success Connect netfd=" << netfd;
return 0;
}
int HallHandler::OnClose()
{
LOGGER(E_LOG_INFO) << "Success Connect Close fd=" << netfd;
PlayerManager::getInstance().delPlayer(this->uid, true);
return 0;
}
int HallHandler::OnPacketComplete(const char* data, int len)
{
pPacket.Copy(data,len);
return Despatch::getInstance().doBackResponse(this, &pPacket);
}
|
/* Author: Puttichai Lertkultanon */
#ifndef SUPERBOT_SETUP_
#define SUPERBOT_SETUP_
#include <openrave-core.h>
#include <openrave/openrave.h>
#include <ompl/control/SimpleSetup.h>
namespace ob = ompl::base;
namespace oc = ompl::control;
class SuperBotSetup : public oc::SimpleSetup {
public:
SuperBotSetup(RobotBasePtr probot);
private:
void initialize(RobotBasePtr probot);
};
#endif
|
#include "ObjectManager.h"
void ObjectManager::Exit()
{
}
|
// Copyright 2012 Yandex
#include <cmath>
#include <stdexcept>
#include "logog/logog.h"
#include "ltr/learners/decision_tree/classification_result.h"
namespace ltr {
ClassificationResult::ClassificationResult(int n) {
INFO("Resizing probability_ vector to %d elements.", n);
probability_.resize(n, 0.0);
}
ClassificationResult::ClassificationResult(const vector<double>& probability) {
probability_ = probability;
}
double& ClassificationResult::operator[](int id) {
INFO("Geting element of probability with index %d.", id);
return probability_[id];
}
const double& ClassificationResult::operator[](int id) const {
INFO("Geting element of probability with index %d.", id);
return probability_[id];
}
int ClassificationResult::size() const {
INFO("Geting size of probability_ vector.");
return probability_.size();
}
void ClassificationResult::normalize() {
INFO("Normalizing classification result.");
double sum = 0;
for (int i = 0; i < size(); i++) {
sum += std::fabs(probability_[i]);
}
if (sum == 0) {
INFO("Sum of all probabilities is equal to zero.");
for (int i = 0; i < size(); i++) {
probability_[i] = 1.0 / size();
}
return;
}
for (int i = 0; i < size(); i++) {
probability_[i] = std::fabs(probability_[i]) / sum;
}
}
ClassificationResult operator+(
const ClassificationResult& left, const ClassificationResult& right) {
INFO("Finding sum of two classification results.");
if (left.size() != right.size()) {
throw std::logic_error("can't add: different number of classes");
}
ClassificationResult result(left.size());
for (int i = 0; i < (int)result.size(); i++) {
result[i] = left[i] + right[i];
}
return result;
}
ClassificationResult operator*(
const ClassificationResult& left, double right) {
INFO("Multiplying classification result by %lf", right);
ClassificationResult result(left.size());
for (int i = 0; i < (int)result.size(); i++) {
result[i] = right * left[i];
}
return result;
}
ClassificationResult operator*(
double left, const ClassificationResult& right) {
INFO("Multiplying classification result by %lf", left);
return right * left;
}
ClassificationResult operator/(
const ClassificationResult& left, double right) {
INFO("Dividing classification result by %lf", right);
return left * (1.0 / right);
}
};
|
#ifndef __HEAP_H__
#define __HEAP_H__
/*
===============================================================================
Memory Management
This is a replacement for the compiler heap code (i.e. "C" malloc() and
free() calls). On average 2.5-3.0 times faster than MSVC malloc()/free().
Worst case performance is 1.65 times faster and best case > 70 times.
===============================================================================
*/
// RAVEN BEGIN
// jsinger: attempt to eliminate cross-DLL allocation issues
#ifdef RV_UNIFIED_ALLOCATOR
class Memory
{
public:
static void *Allocate(size_t size)
{
if(mAllocator)
{
return mAllocator(size);
}
else
{
#ifndef _LOAD_DLL
// allocations from the exe are safe no matter what, but allocations from a DLL through
// this path will be unsafe, so we warn about them. Adding a breakpoint here will allow
// allow locating of the specific offending allocation
Error("Unprotected allocations are not allowed. Make sure you've initialized Memory before allocating dynamic memory");
#endif
return malloc(size);
}
}
static void Free(void *ptr)
{
if(mDeallocator)
{
mDeallocator(ptr);
}
else
{
#ifndef _LOAD_DLL
// allocations from the exe are safe no matter what, but allocations from a DLL through
// this path will be unsafe, so we warn about them. Adding a breakpoint here will allow
// allow locating of the specific offending allocation
Error("Unprotected allocations are not allowed. Make sure you've initialized Memory before allocating dynamic memory");
#endif
return free(ptr);
}
}
static size_t MSize(void *ptr)
{
if(mMSize)
{
return mMSize(ptr);
}
else
{
#ifndef _LOAD_DLL
// allocations from the exe are safe no matter what, but allocations from a DLL through
// this path will be unsafe, so we warn about them. Adding a breakpoint here will allow
// allow locating of the specific offending allocation
Error("Unprotected allocations are not allowed. Make sure you've initialized Memory before allocating dynamic memory");
#endif
return _msize(ptr);
}
}
static void InitAllocator(void *(*allocator)(size_t size), void (*deallocator)(void *), size_t (*msize)(void *ptr))
{
// check for errors prior to initialization
if(!sOK)
{
Error("Unprotected allocation in DLL detected prior to initialization of memory system");
}
mAllocator = allocator;
mDeallocator = deallocator;
mMSize = msize;
}
static void DeinitAllocator()
{
mAllocator = NULL;
mDeallocator = NULL;
mMSize = NULL;
}
static void Error(const char *errStr);
private:
static void *(*mAllocator)(size_t size);
static void (*mDeallocator)(void *ptr);
static size_t (*mMSize)(void *ptr);
static bool sOK;
};
#endif
// RAVEN END
typedef struct {
int num;
int minSize;
int maxSize;
int totalSize;
} memoryStats_t;
// RAVEN BEGIN
// amccarthy: tags for memory allocation tracking. When updating this list please update the
// list of discriptions in Heap.cpp as well.
typedef enum {
MA_NONE = 0,
MA_OPNEW,
MA_DEFAULT,
MA_LEXER,
MA_PARSER,
MA_AAS,
MA_CLASS,
MA_SCRIPT,
MA_CM,
MA_CVAR,
MA_DECL,
MA_FILESYS,
MA_IMAGES,
MA_MATERIAL,
MA_MODEL,
MA_FONT,
MA_RENDER,
MA_VERTEX,
MA_SOUND,
MA_WINDOW,
MA_EVENT,
MA_MATH,
MA_ANIM,
MA_DYNAMICBLOCK,
MA_STRING,
MA_GUI,
MA_EFFECT,
MA_ENTITY,
MA_PHYSICS,
MA_AI,
MA_NETWORK,
MA_DO_NOT_USE, // neither of the two remaining enumerated values should be used (no use of MA_DO_NOT_USE prevents the second dword in a memory block from getting the value 0xFFFFFFFF)
MA_MAX // <- this enumerated value is a count and cannot exceed 32 (5 bits are used to encode tag within memory block with rvHeap.cpp)
} Mem_Alloc_Types_t;
#if defined(_DEBUG) || defined(_RV_MEM_SYS_SUPPORT)
const char *GetMemAllocStats(int tag, int &num, int &size, int &peak);
#endif
// RAVEN END
void Mem_Init( void );
void Mem_Shutdown( void );
void Mem_EnableLeakTest( const char *name );
void Mem_ClearFrameStats( void );
void Mem_GetFrameStats( memoryStats_t &allocs, memoryStats_t &frees );
void Mem_GetStats( memoryStats_t &stats );
void Mem_Dump_f( const class idCmdArgs &args );
void Mem_DumpCompressed_f( const class idCmdArgs &args );
void Mem_AllocDefragBlock( void );
// RAVEN BEGIN
// amccarthy command for printing tagged mem_alloc info
void Mem_ShowMemAlloc_f( const idCmdArgs &args );
// jnewquist: Add Mem_Size to query memory allocation size
int Mem_Size( void *ptr );
// jnewquist: memory tag stack for new/delete
#if (defined(_DEBUG) || defined(_RV_MEM_SYS_SUPPORT)) && !defined(ENABLE_INTEL_SMP)
class MemScopedTag {
byte mTag;
MemScopedTag *mPrev;
static MemScopedTag *mTop;
public:
MemScopedTag( byte tag ) {
mTag = tag;
mPrev = mTop;
mTop = this;
}
~MemScopedTag() {
assert( mTop != NULL );
mTop = mTop->mPrev;
}
void SetTag( byte tag ) {
mTag = tag;
}
static byte GetTopTag( void ) {
if ( mTop ) {
return mTop->mTag;
} else {
return MA_OPNEW;
}
}
};
#define MemScopedTag_GetTopTag() MemScopedTag::GetTopTag()
#define MEM_SCOPED_TAG(var, tag) MemScopedTag var(tag)
#define MEM_SCOPED_TAG_SET(var, tag) var.SetTag(tag)
#else
#define MemScopedTag_GetTopTag() MA_OPNEW
#define MEM_SCOPED_TAG(var, tag)
#define MEM_SCOPED_TAG_SET(var, tag)
#endif
// RAVEN END
#ifndef ID_DEBUG_MEMORY
// RAVEN BEGIN
// amccarthy: added tags from memory allocation tracking.
void * Mem_Alloc( const int size, byte tag = MA_DEFAULT );
void * Mem_ClearedAlloc( const int size, byte tag = MA_DEFAULT );
void Mem_Free( void *ptr );
char * Mem_CopyString( const char *in );
void * Mem_Alloc16( const int size, byte tag=MA_DEFAULT );
void Mem_Free16( void *ptr );
// jscott: standardised stack allocation
inline void *Mem_StackAlloc( const int size ) { return( _alloca( size ) ); }
inline void *Mem_StackAlloc16( const int size ) {
byte *addr = ( byte * )_alloca( size + 15 );
addr = ( byte * )( ( int )( addr + 15 ) & 0xfffffff0 );
return( ( void * )addr );
}
// dluetscher: moved the inline new/delete operators to sys_local.cpp and Game_local.cpp so that
// Tools.dll will link.
#if defined(_XBOX) || defined(ID_REDIRECT_NEWDELETE) || defined(_RV_MEM_SYS_SUPPORT)
void *operator new( size_t s );
void operator delete( void *p );
void *operator new[]( size_t s );
void operator delete[]( void *p );
#endif
// RAVEN END
#else /* ID_DEBUG_MEMORY */
// RAVEN BEGIN
// amccarthy: added tags from memory allocation tracking.
void * Mem_Alloc( const int size, const char *fileName, const int lineNumber, byte tag = MA_DEFAULT );
void * Mem_ClearedAlloc( const int size, const char *fileName, const int lineNumber, byte tag = MA_DEFAULT );
void Mem_Free( void *ptr, const char *fileName, const int lineNumber );
char * Mem_CopyString( const char *in, const char *fileName, const int lineNumber );
void * Mem_Alloc16( const int size, const char *fileName, const int lineNumber, byte tag = MA_DEFAULT);
void Mem_Free16( void *ptr, const char *fileName, const int lineNumber );
// jscott: standardised stack allocation
inline void *Mem_StackAlloc( const int size ) { return( _alloca( size ) ); }
inline void *Mem_StackAlloc16( const int size ) {
byte *addr = ( byte * )_alloca( size + 15 );
addr = ( byte * )( ( int )( addr + 15 ) & 0xfffffff0 );
return( ( void * )addr );
}
// dluetscher: moved the inline new/delete operators to sys_local.cpp and Game_local.cpp so that
// the Tools.dll will link.
#if defined(_XBOX) || defined(ID_REDIRECT_NEWDELETE) || defined(_RV_MEM_SYS_SUPPORT)
void *operator new( size_t s, int t1, int t2, char *fileName, int lineNumber );
void operator delete( void *p, int t1, int t2, char *fileName, int lineNumber );
void *operator new[]( size_t s, int t1, int t2, char *fileName, int lineNumber );
void operator delete[]( void *p, int t1, int t2, char *fileName, int lineNumber );
void *operator new( size_t s );
void operator delete( void *p );
void *operator new[]( size_t s );
void operator delete[]( void *p );
// RAVEN END
#define ID_DEBUG_NEW new( 0, 0, __FILE__, __LINE__ )
#undef new
#define new ID_DEBUG_NEW
#endif
#define Mem_Alloc( size, tag ) Mem_Alloc( size, __FILE__, __LINE__ )
#define Mem_ClearedAlloc( size, tag ) Mem_ClearedAlloc( size, __FILE__, __LINE__ )
#define Mem_Free( ptr ) Mem_Free( ptr, __FILE__, __LINE__ )
#define Mem_CopyString( s ) Mem_CopyString( s, __FILE__, __LINE__ )
#define Mem_Alloc16( size, tag ) Mem_Alloc16( size, __FILE__, __LINE__ )
#define Mem_Free16( ptr ) Mem_Free16( ptr, __FILE__, __LINE__ )
// RAVEN END
#endif /* ID_DEBUG_MEMORY */
/*
===============================================================================
Block based allocator for fixed size objects.
All objects of the 'type' are properly constructed.
However, the constructor is not called for re-used objects.
===============================================================================
*/
// RAVEN BEGIN
// jnewquist: Mark memory tags for idBlockAlloc
template<class type, int blockSize, byte memoryTag>
class idBlockAlloc {
public:
idBlockAlloc( void );
~idBlockAlloc( void );
void Shutdown( void );
type * Alloc( void );
void Free( type *element );
int GetTotalCount( void ) const { return total; }
int GetAllocCount( void ) const { return active; }
int GetFreeCount( void ) const { return total - active; }
// RAVEN BEGIN
// jscott: get the amount of memory used
size_t Allocated( void ) const { return( total * sizeof( type ) ); }
// RAVEN END
private:
typedef struct element_s {
struct element_s * next;
type t;
} element_t;
typedef struct block_s {
element_t elements[blockSize];
struct block_s * next;
} block_t;
block_t * blocks;
element_t * free;
int total;
int active;
};
template<class type, int blockSize, byte memoryTag>
idBlockAlloc<type,blockSize,memoryTag>::idBlockAlloc( void ) {
blocks = NULL;
free = NULL;
total = active = 0;
}
template<class type, int blockSize, byte memoryTag>
idBlockAlloc<type,blockSize,memoryTag>::~idBlockAlloc( void ) {
Shutdown();
}
template<class type, int blockSize, byte memoryTag>
type *idBlockAlloc<type,blockSize,memoryTag>::Alloc( void ) {
if ( !free ) {
MEM_SCOPED_TAG(tag, memoryTag);
block_t *block = new block_t;
block->next = blocks;
blocks = block;
for ( int i = 0; i < blockSize; i++ ) {
block->elements[i].next = free;
free = &block->elements[i];
}
total += blockSize;
}
active++;
element_t *element = free;
free = free->next;
element->next = NULL;
return &element->t;
}
template<class type, int blockSize, byte memoryTag>
void idBlockAlloc<type,blockSize,memoryTag>::Free( type *t ) {
element_t *element = (element_t *)( ( (unsigned char *) t ) - ( (int) &((element_t *)0)->t ) );
element->next = free;
free = element;
active--;
}
template<class type, int blockSize, byte memoryTag>
void idBlockAlloc<type,blockSize,memoryTag>::Shutdown( void ) {
while( blocks ) {
block_t *block = blocks;
blocks = blocks->next;
delete block;
}
blocks = NULL;
free = NULL;
total = active = 0;
}
// RAVEN END
/*
==============================================================================
Dynamic allocator, simple wrapper for normal allocations which can
be interchanged with idDynamicBlockAlloc.
No constructor is called for the 'type'.
Allocated blocks are always 16 byte aligned.
==============================================================================
*/
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
class idDynamicAlloc {
public:
idDynamicAlloc( void );
~idDynamicAlloc( void );
void Init( void );
void Shutdown( void );
void SetFixedBlocks( int numBlocks ) {}
void SetLockMemory( bool lock ) {}
void FreeEmptyBaseBlocks( void ) {}
type * Alloc( const int num );
type * Resize( type *ptr, const int num );
void Free( type *ptr );
const char * CheckMemory( const type *ptr ) const;
int GetNumBaseBlocks( void ) const { return 0; }
int GetBaseBlockMemory( void ) const { return 0; }
int GetNumUsedBlocks( void ) const { return numUsedBlocks; }
int GetUsedBlockMemory( void ) const { return usedBlockMemory; }
int GetNumFreeBlocks( void ) const { return 0; }
int GetFreeBlockMemory( void ) const { return 0; }
int GetNumEmptyBaseBlocks( void ) const { return 0; }
private:
int numUsedBlocks; // number of used blocks
int usedBlockMemory; // total memory in used blocks
int numAllocs;
int numResizes;
int numFrees;
void Clear( void );
};
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
idDynamicAlloc<type, baseBlockSize, minBlockSize, memoryTag>::idDynamicAlloc( void ) {
Clear();
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
idDynamicAlloc<type, baseBlockSize, minBlockSize, memoryTag>::~idDynamicAlloc( void ) {
Shutdown();
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
void idDynamicAlloc<type, baseBlockSize, minBlockSize, memoryTag>::Init( void ) {
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
void idDynamicAlloc<type, baseBlockSize, minBlockSize, memoryTag>::Shutdown( void ) {
Clear();
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
type *idDynamicAlloc<type, baseBlockSize, minBlockSize, memoryTag>::Alloc( const int num ) {
numAllocs++;
if ( num <= 0 ) {
return NULL;
}
numUsedBlocks++;
usedBlockMemory += num * sizeof( type );
// RAVEN BEGIN
// jscott: to make it build
// mwhitlock: to make it build on Xenon
return (type *) ( (byte *) Mem_Alloc16( num * sizeof( type ), memoryTag ) );
// RAVEN BEGIN
}
#include "math/Simd.h"
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
type *idDynamicAlloc<type, baseBlockSize, minBlockSize, memoryTag>::Resize( type *ptr, const int num ) {
numResizes++;
// RAVEN BEGIN
// jnewquist: provide a real implementation of resize
if ( num <= 0 ) {
Free( ptr );
return NULL;
}
type *newptr = Alloc( num );
if ( ptr != NULL ) {
const int oldSize = Mem_Size(ptr);
const int newSize = num*sizeof(type);
SIMDProcessor->Memcpy( newptr, ptr, (newSize<oldSize)?newSize:oldSize );
Free(ptr);
}
return newptr;
// RAVEN END
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
void idDynamicAlloc<type, baseBlockSize, minBlockSize, memoryTag>::Free( type *ptr ) {
numFrees++;
if ( ptr == NULL ) {
return;
}
Mem_Free16( ptr );
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
const char *idDynamicAlloc<type, baseBlockSize, minBlockSize, memoryTag>::CheckMemory( const type *ptr ) const {
return NULL;
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
void idDynamicAlloc<type, baseBlockSize, minBlockSize, memoryTag>::Clear( void ) {
numUsedBlocks = 0;
usedBlockMemory = 0;
numAllocs = 0;
numResizes = 0;
numFrees = 0;
}
/*
==============================================================================
Fast dynamic block allocator.
No constructor is called for the 'type'.
Allocated blocks are always 16 byte aligned.
==============================================================================
*/
#include "containers/BTree.h"
// RAVEN BEGIN
// jnewquist: Fast sanity checking of idDynamicBlockAlloc
//#ifdef _DEBUG
//#define DYNAMIC_BLOCK_ALLOC_CHECK
#define DYNAMIC_BLOCK_ALLOC_FASTCHECK
#define DYNAMIC_BLOCK_ALLOC_CHECK_IS_FATAL
//#endif
// RAVEN END
template<class type>
class idDynamicBlock {
public:
type * GetMemory( void ) const { return (type *)( ( (byte *) this ) + sizeof( idDynamicBlock<type> ) ); }
int GetSize( void ) const { return abs( size ); }
void SetSize( int s, bool isBaseBlock ) { size = isBaseBlock ? -s : s; }
bool IsBaseBlock( void ) const { return ( size < 0 ); }
// RAVEN BEGIN
// jnewquist: Fast sanity checking of idDynamicBlockAlloc
#if defined(DYNAMIC_BLOCK_ALLOC_CHECK) || defined(DYNAMIC_BLOCK_ALLOC_FASTCHECK)
// RAVEN END
int identifier[3];
void * allocator;
#endif
int size; // size in bytes of the block
idDynamicBlock<type> * prev; // previous memory block
idDynamicBlock<type> * next; // next memory block
idBTreeNode<idDynamicBlock<type>,int> *node; // node in the B-Tree with free blocks
};
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
class idDynamicBlockAlloc {
public:
idDynamicBlockAlloc( void );
~idDynamicBlockAlloc( void );
void Init( void );
void Shutdown( void );
void SetFixedBlocks( int numBlocks );
void SetLockMemory( bool lock );
void FreeEmptyBaseBlocks( void );
type * Alloc( const int num );
type * Resize( type *ptr, const int num );
void Free( type *ptr );
const char * CheckMemory( const type *ptr ) const;
int GetNumBaseBlocks( void ) const { return numBaseBlocks; }
int GetBaseBlockMemory( void ) const { return baseBlockMemory; }
int GetNumUsedBlocks( void ) const { return numUsedBlocks; }
int GetUsedBlockMemory( void ) const { return usedBlockMemory; }
int GetNumFreeBlocks( void ) const { return numFreeBlocks; }
int GetFreeBlockMemory( void ) const { return freeBlockMemory; }
int GetNumEmptyBaseBlocks( void ) const;
private:
idDynamicBlock<type> * firstBlock; // first block in list in order of increasing address
idDynamicBlock<type> * lastBlock; // last block in list in order of increasing address
idBTree<idDynamicBlock<type>,int,4>freeTree; // B-Tree with free memory blocks
bool allowAllocs; // allow base block allocations
bool lockMemory; // lock memory so it cannot get swapped out
// RAVEN BEGIN
// jnewquist: Fast sanity checking of idDynamicBlockAlloc
#if defined(DYNAMIC_BLOCK_ALLOC_CHECK) || defined(DYNAMIC_BLOCK_ALLOC_FASTCHECK)
// RAVEN END
int blockId[3];
#endif
int numBaseBlocks; // number of base blocks
int baseBlockMemory; // total memory in base blocks
int numUsedBlocks; // number of used blocks
int usedBlockMemory; // total memory in used blocks
int numFreeBlocks; // number of free blocks
int freeBlockMemory; // total memory in free blocks
int numAllocs;
int numResizes;
int numFrees;
void Clear( void );
idDynamicBlock<type> * AllocInternal( const int num );
idDynamicBlock<type> * ResizeInternal( idDynamicBlock<type> *block, const int num );
void FreeInternal( idDynamicBlock<type> *block );
void LinkFreeInternal( idDynamicBlock<type> *block );
void UnlinkFreeInternal( idDynamicBlock<type> *block );
void CheckMemory( void ) const;
// RAVEN BEGIN
// jnewquist: Fast sanity checking of idDynamicBlockAlloc
const char * CheckMemory( const idDynamicBlock<type> *block ) const;
// RAVEN END
};
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::idDynamicBlockAlloc( void ) {
Clear();
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::~idDynamicBlockAlloc( void ) {
Shutdown();
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
void idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::Init( void ) {
// RAVEN BEGIN
// jnewquist: Tag scope and callees to track allocations using "new".
MEM_SCOPED_TAG(tag,memoryTag);
// RAVEN END
freeTree.Init();
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
void idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::Shutdown( void ) {
idDynamicBlock<type> *block;
for ( block = firstBlock; block != NULL; block = block->next ) {
if ( block->node == NULL ) {
FreeInternal( block );
}
}
for ( block = firstBlock; block != NULL; block = firstBlock ) {
firstBlock = block->next;
assert( block->IsBaseBlock() );
if ( lockMemory ) {
idLib::sys->UnlockMemory( block, block->GetSize() + (int)sizeof( idDynamicBlock<type> ) );
}
Mem_Free16( block );
}
freeTree.Shutdown();
Clear();
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
void idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::SetFixedBlocks( int numBlocks ) {
int i;
idDynamicBlock<type> *block;
for ( i = numBaseBlocks; i < numBlocks; i++ ) {
//RAVEN BEGIN
//amccarthy: Added allocation tag
block = ( idDynamicBlock<type> * ) Mem_Alloc16( baseBlockSize, memoryTag );
//RAVEN END
if ( lockMemory ) {
idLib::sys->LockMemory( block, baseBlockSize );
}
// RAVEN BEGIN
// jnewquist: Fast sanity checking of idDynamicBlockAlloc
#if defined(DYNAMIC_BLOCK_ALLOC_CHECK) || defined(DYNAMIC_BLOCK_ALLOC_FASTCHECK)
// RAVEN END
memcpy( block->identifier, blockId, sizeof( block->identifier ) );
block->allocator = (void*)this;
#endif
block->SetSize( baseBlockSize - (int)sizeof( idDynamicBlock<type> ), true );
block->next = NULL;
block->prev = lastBlock;
if ( lastBlock ) {
lastBlock->next = block;
} else {
firstBlock = block;
}
lastBlock = block;
block->node = NULL;
FreeInternal( block );
numBaseBlocks++;
baseBlockMemory += baseBlockSize;
}
allowAllocs = false;
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
void idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::SetLockMemory( bool lock ) {
lockMemory = lock;
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
void idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::FreeEmptyBaseBlocks( void ) {
idDynamicBlock<type> *block, *next;
for ( block = firstBlock; block != NULL; block = next ) {
next = block->next;
if ( block->IsBaseBlock() && block->node != NULL && ( next == NULL || next->IsBaseBlock() ) ) {
UnlinkFreeInternal( block );
if ( block->prev ) {
block->prev->next = block->next;
} else {
firstBlock = block->next;
}
if ( block->next ) {
block->next->prev = block->prev;
} else {
lastBlock = block->prev;
}
if ( lockMemory ) {
idLib::sys->UnlockMemory( block, block->GetSize() + (int)sizeof( idDynamicBlock<type> ) );
}
numBaseBlocks--;
baseBlockMemory -= block->GetSize() + (int)sizeof( idDynamicBlock<type> );
Mem_Free16( block );
}
}
#ifdef DYNAMIC_BLOCK_ALLOC_CHECK
CheckMemory();
#endif
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
int idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::GetNumEmptyBaseBlocks( void ) const {
int numEmptyBaseBlocks;
idDynamicBlock<type> *block;
numEmptyBaseBlocks = 0;
for ( block = firstBlock; block != NULL; block = block->next ) {
if ( block->IsBaseBlock() && block->node != NULL && ( block->next == NULL || block->next->IsBaseBlock() ) ) {
numEmptyBaseBlocks++;
}
}
return numEmptyBaseBlocks;
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
type *idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::Alloc( const int num ) {
idDynamicBlock<type> *block;
numAllocs++;
if ( num <= 0 ) {
return NULL;
}
block = AllocInternal( num );
if ( block == NULL ) {
return NULL;
}
block = ResizeInternal( block, num );
if ( block == NULL ) {
return NULL;
}
#ifdef DYNAMIC_BLOCK_ALLOC_CHECK
CheckMemory();
#endif
numUsedBlocks++;
usedBlockMemory += block->GetSize();
return block->GetMemory();
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
type *idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::Resize( type *ptr, const int num ) {
numResizes++;
if ( ptr == NULL ) {
return Alloc( num );
}
if ( num <= 0 ) {
Free( ptr );
return NULL;
}
idDynamicBlock<type> *block = ( idDynamicBlock<type> * ) ( ( (byte *) ptr ) - (int)sizeof( idDynamicBlock<type> ) );
usedBlockMemory -= block->GetSize();
block = ResizeInternal( block, num );
if ( block == NULL ) {
return NULL;
}
#ifdef DYNAMIC_BLOCK_ALLOC_CHECK
CheckMemory();
#endif
usedBlockMemory += block->GetSize();
return block->GetMemory();
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
void idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::Free( type *ptr ) {
numFrees++;
if ( ptr == NULL ) {
return;
}
idDynamicBlock<type> *block = ( idDynamicBlock<type> * ) ( ( (byte *) ptr ) - (int)sizeof( idDynamicBlock<type> ) );
numUsedBlocks--;
usedBlockMemory -= block->GetSize();
FreeInternal( block );
#ifdef DYNAMIC_BLOCK_ALLOC_CHECK
CheckMemory();
#endif
}
// RAVEN BEGIN
// jnewquist: Fast sanity checking of idDynamicBlockAlloc
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
const char *idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::CheckMemory( const idDynamicBlock<type> *block ) const {
if ( block->node != NULL ) {
return "memory has been freed";
}
#if defined(DYNAMIC_BLOCK_ALLOC_CHECK) || defined(DYNAMIC_BLOCK_ALLOC_FASTCHECK)
// RAVEN END
if ( block->identifier[0] != 0x11111111 || block->identifier[1] != 0x22222222 || block->identifier[2] != 0x33333333 ) {
return "memory has invalid identifier";
}
// RAVEN BEGIN
// jsinger: attempt to eliminate cross-DLL allocation issues
#ifndef RV_UNIFIED_ALLOCATOR
if ( block->allocator != (void*)this ) {
return "memory was allocated with different allocator";
}
#endif // RV_UNIFIED_ALLOCATOR
// RAVEN END
#endif
/* base blocks can be larger than baseBlockSize which can cause this code to fail
idDynamicBlock<type> *base;
for ( base = firstBlock; base != NULL; base = base->next ) {
if ( base->IsBaseBlock() ) {
if ( ((int)block) >= ((int)base) && ((int)block) < ((int)base) + baseBlockSize ) {
break;
}
}
}
if ( base == NULL ) {
return "no base block found for memory";
}
*/
return NULL;
}
// RAVEN BEGIN
// jnewquist: Fast sanity checking of idDynamicBlockAlloc
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
const char *idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::CheckMemory( const type *ptr ) const {
idDynamicBlock<type> *block;
if ( ptr == NULL ) {
return NULL;
}
block = ( idDynamicBlock<type> * ) ( ( (byte *) ptr ) - (int)sizeof( idDynamicBlock<type> ) );
return CheckMemory( block );
}
// RAVEN END
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
void idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::Clear( void ) {
firstBlock = lastBlock = NULL;
allowAllocs = true;
lockMemory = false;
numBaseBlocks = 0;
baseBlockMemory = 0;
numUsedBlocks = 0;
usedBlockMemory = 0;
numFreeBlocks = 0;
freeBlockMemory = 0;
numAllocs = 0;
numResizes = 0;
numFrees = 0;
// RAVEN BEGIN
// jnewquist: Fast sanity checking of idDynamicBlockAlloc
#if defined(DYNAMIC_BLOCK_ALLOC_CHECK) || defined(DYNAMIC_BLOCK_ALLOC_FASTCHECK)
// RAVEN END
blockId[0] = 0x11111111;
blockId[1] = 0x22222222;
blockId[2] = 0x33333333;
#endif
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
idDynamicBlock<type> *idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::AllocInternal( const int num ) {
idDynamicBlock<type> *block;
int alignedBytes = ( num * sizeof( type ) + 15 ) & ~15;
block = freeTree.FindSmallestLargerEqual( alignedBytes );
if ( block != NULL ) {
UnlinkFreeInternal( block );
} else if ( allowAllocs ) {
int allocSize = Max( baseBlockSize, alignedBytes + (int)sizeof( idDynamicBlock<type> ) );
//RAVEN BEGIN
//amccarthy: Added allocation tag
block = ( idDynamicBlock<type> * ) Mem_Alloc16( allocSize, memoryTag );
//RAVEN END
if ( lockMemory ) {
idLib::sys->LockMemory( block, baseBlockSize );
}
// RAVEN BEGIN
// jnewquist: Fast sanity checking of idDynamicBlockAlloc
#if defined(DYNAMIC_BLOCK_ALLOC_CHECK) || defined(DYNAMIC_BLOCK_ALLOC_FASTCHECK)
// RAVEN END
memcpy( block->identifier, blockId, sizeof( block->identifier ) );
block->allocator = (void*)this;
#endif
block->SetSize( allocSize - (int)sizeof( idDynamicBlock<type> ), true );
block->next = NULL;
block->prev = lastBlock;
if ( lastBlock ) {
lastBlock->next = block;
} else {
firstBlock = block;
}
lastBlock = block;
block->node = NULL;
numBaseBlocks++;
baseBlockMemory += allocSize;
}
return block;
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
idDynamicBlock<type> *idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::ResizeInternal( idDynamicBlock<type> *block, const int num ) {
int alignedBytes = ( num * sizeof( type ) + 15 ) & ~15;
// RAVEN BEGIN
// jnewquist: Fast sanity checking of idDynamicBlockAlloc
#if defined(DYNAMIC_BLOCK_ALLOC_CHECK) || defined(DYNAMIC_BLOCK_ALLOC_FASTCHECK)
#if defined(DYNAMIC_BLOCK_ALLOC_CHECK_IS_FATAL)
const char *chkstr = CheckMemory( block );
if ( chkstr ) {
throw idException( chkstr );
}
#endif
// jsinger: attempt to eliminate cross-DLL allocation issues
#ifdef RV_UNIFIED_ALLOCATOR
assert( block->identifier[0] == 0x11111111 && block->identifier[1] == 0x22222222 && block->identifier[2] == 0x33333333); // && block->allocator == (void*)this );
#else
assert( block->identifier[0] == 0x11111111 && block->identifier[1] == 0x22222222 && block->identifier[2] == 0x33333333 && block->allocator == (void*)this );
#endif
// RAVEN END
#endif
// if the new size is larger
if ( alignedBytes > block->GetSize() ) {
idDynamicBlock<type> *nextBlock = block->next;
// try to annexate the next block if it's free
if ( nextBlock && !nextBlock->IsBaseBlock() && nextBlock->node != NULL &&
block->GetSize() + (int)sizeof( idDynamicBlock<type> ) + nextBlock->GetSize() >= alignedBytes ) {
UnlinkFreeInternal( nextBlock );
block->SetSize( block->GetSize() + (int)sizeof( idDynamicBlock<type> ) + nextBlock->GetSize(), block->IsBaseBlock() );
block->next = nextBlock->next;
if ( nextBlock->next ) {
nextBlock->next->prev = block;
} else {
lastBlock = block;
}
} else {
// allocate a new block and copy
idDynamicBlock<type> *oldBlock = block;
block = AllocInternal( num );
if ( block == NULL ) {
return NULL;
}
memcpy( block->GetMemory(), oldBlock->GetMemory(), oldBlock->GetSize() );
FreeInternal( oldBlock );
}
}
// if the unused space at the end of this block is large enough to hold a block with at least one element
if ( block->GetSize() - alignedBytes - (int)sizeof( idDynamicBlock<type> ) < Max( minBlockSize, (int)sizeof( type ) ) ) {
return block;
}
idDynamicBlock<type> *newBlock;
newBlock = ( idDynamicBlock<type> * ) ( ( (byte *) block ) + (int)sizeof( idDynamicBlock<type> ) + alignedBytes );
// RAVEN BEGIN
// jnewquist: Fast sanity checking of idDynamicBlockAlloc
#if defined(DYNAMIC_BLOCK_ALLOC_CHECK) || defined(DYNAMIC_BLOCK_ALLOC_FASTCHECK)
// RAVEN END
memcpy( newBlock->identifier, blockId, sizeof( newBlock->identifier ) );
newBlock->allocator = (void*)this;
#endif
newBlock->SetSize( block->GetSize() - alignedBytes - (int)sizeof( idDynamicBlock<type> ), false );
newBlock->next = block->next;
newBlock->prev = block;
if ( newBlock->next ) {
newBlock->next->prev = newBlock;
} else {
lastBlock = newBlock;
}
newBlock->node = NULL;
block->next = newBlock;
block->SetSize( alignedBytes, block->IsBaseBlock() );
FreeInternal( newBlock );
return block;
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
void idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::FreeInternal( idDynamicBlock<type> *block ) {
assert( block->node == NULL );
// RAVEN BEGIN
// jnewquist: Fast sanity checking of idDynamicBlockAlloc
#if defined(DYNAMIC_BLOCK_ALLOC_CHECK) || defined(DYNAMIC_BLOCK_ALLOC_FASTCHECK)
#if defined(DYNAMIC_BLOCK_ALLOC_CHECK_IS_FATAL)
const char *chkstr = CheckMemory( block );
if ( chkstr ) {
throw idException( chkstr );
}
#endif
// jsinger: attempt to eliminate cross-DLL allocation issues
#ifdef RV_UNIFIED_ALLOCATOR
assert( block->identifier[0] == 0x11111111 && block->identifier[1] == 0x22222222 && block->identifier[2] == 0x33333333 );//&& block->allocator == (void*)this );
#else
assert( block->identifier[0] == 0x11111111 && block->identifier[1] == 0x22222222 && block->identifier[2] == 0x33333333 && block->allocator == (void*)this );
#endif // RV_UNIFIED_ALLOCATOR
// RAVEN END
#endif
// try to merge with a next free block
idDynamicBlock<type> *nextBlock = block->next;
if ( nextBlock && !nextBlock->IsBaseBlock() && nextBlock->node != NULL ) {
UnlinkFreeInternal( nextBlock );
block->SetSize( block->GetSize() + (int)sizeof( idDynamicBlock<type> ) + nextBlock->GetSize(), block->IsBaseBlock() );
block->next = nextBlock->next;
if ( nextBlock->next ) {
nextBlock->next->prev = block;
} else {
lastBlock = block;
}
}
// try to merge with a previous free block
idDynamicBlock<type> *prevBlock = block->prev;
if ( prevBlock && !block->IsBaseBlock() && prevBlock->node != NULL ) {
UnlinkFreeInternal( prevBlock );
prevBlock->SetSize( prevBlock->GetSize() + (int)sizeof( idDynamicBlock<type> ) + block->GetSize(), prevBlock->IsBaseBlock() );
prevBlock->next = block->next;
if ( block->next ) {
block->next->prev = prevBlock;
} else {
lastBlock = prevBlock;
}
LinkFreeInternal( prevBlock );
} else {
LinkFreeInternal( block );
}
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
ID_INLINE void idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::LinkFreeInternal( idDynamicBlock<type> *block ) {
block->node = freeTree.Add( block, block->GetSize() );
numFreeBlocks++;
freeBlockMemory += block->GetSize();
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
ID_INLINE void idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::UnlinkFreeInternal( idDynamicBlock<type> *block ) {
freeTree.Remove( block->node );
block->node = NULL;
numFreeBlocks--;
freeBlockMemory -= block->GetSize();
}
template<class type, int baseBlockSize, int minBlockSize, byte memoryTag>
void idDynamicBlockAlloc<type, baseBlockSize, minBlockSize, memoryTag>::CheckMemory( void ) const {
idDynamicBlock<type> *block;
for ( block = firstBlock; block != NULL; block = block->next ) {
// RAVEN BEGIN
// jnewquist: Fast sanity checking of idDynamicBlockAlloc
#if defined(DYNAMIC_BLOCK_ALLOC_CHECK) || defined(DYNAMIC_BLOCK_ALLOC_FASTCHECK)
#if defined(DYNAMIC_BLOCK_ALLOC_CHECK_IS_FATAL)
const char *chkstr = CheckMemory( block );
if ( chkstr ) {
throw idException( chkstr );
}
#endif
// jsinger: attempt to eliminate cross-DLL allocation issues
#ifdef RV_UNIFIED_ALLOCATOR
assert( block->identifier[0] == 0x11111111 && block->identifier[1] == 0x22222222 && block->identifier[2] == 0x33333333); // && block->allocator == (void*)this );
#else
assert( block->identifier[0] == 0x11111111 && block->identifier[1] == 0x22222222 && block->identifier[2] == 0x33333333 && block->allocator == (void*)this );
#endif
// RAVEN END
#endif
// make sure the block is properly linked
if ( block->prev == NULL ) {
assert( firstBlock == block );
} else {
assert( block->prev->next == block );
}
if ( block->next == NULL ) {
assert( lastBlock == block );
} else {
assert( block->next->prev == block );
}
}
}
#endif /* !__HEAP_H__ */
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/crostini/crostini_share_path.h"
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/run_loop.h"
#include "base/sys_info.h"
#include "base/test/scoped_task_environment.h"
#include "chrome/browser/chromeos/crostini/crostini_manager.h"
#include "chrome/browser/chromeos/crostini/crostini_pref_names.h"
#include "chrome/browser/chromeos/crostini/crostini_util.h"
#include "chrome/browser/chromeos/file_manager/path_util.h"
#include "chrome/test/base/testing_profile.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/fake_cicerone_client.h"
#include "chromeos/dbus/fake_concierge_client.h"
#include "chromeos/dbus/fake_seneschal_client.h"
#include "components/prefs/pref_service.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace crostini {
const char kLsbRelease[] =
"CHROMEOS_RELEASE_NAME=Chrome OS\n"
"CHROMEOS_RELEASE_VERSION=1.2.3.4\n";
class CrostiniSharePathTest : public testing::Test {
public:
void SharePathSuccessStartTerminaVmCallback(CrostiniResult result) {
EXPECT_TRUE(fake_concierge_client_->start_termina_vm_called());
EXPECT_EQ(result, CrostiniResult::SUCCESS);
SharePath(profile(), "success", share_path_,
base::BindOnce(&CrostiniSharePathTest::SharePathCallback,
base::Unretained(this), true, true, true, "",
run_loop()->QuitClosure()));
}
void SharePathErrorSeneschalStartTerminaVmCallback(CrostiniResult result) {
EXPECT_TRUE(fake_concierge_client_->start_termina_vm_called());
EXPECT_EQ(result, CrostiniResult::SUCCESS);
SharePath(profile(), "error-seneschal", share_path_,
base::BindOnce(&CrostiniSharePathTest::SharePathCallback,
base::Unretained(this), true, true, false,
"test failure", run_loop()->QuitClosure()));
}
void SharePathCallback(bool expected_path_saved_to_prefs,
bool expected_seneschal_client_called,
bool expected_success,
std::string expected_failure_reason,
base::OnceClosure closure,
bool success,
std::string failure_reason) {
const base::ListValue* prefs =
profile()->GetPrefs()->GetList(prefs::kCrostiniSharedPaths);
if (expected_path_saved_to_prefs) {
EXPECT_EQ(prefs->GetSize(), 1U);
std::string share_path;
prefs->GetString(0, &share_path);
EXPECT_EQ(share_path_.value(), share_path);
} else {
EXPECT_EQ(prefs->GetSize(), 0U);
}
EXPECT_EQ(fake_seneschal_client_->share_path_called(),
expected_seneschal_client_called);
EXPECT_EQ(success, expected_success);
EXPECT_EQ(failure_reason, expected_failure_reason);
std::move(closure).Run();
}
void SharePathErrorVmNotRunningCallback(base::OnceClosure closure,
bool success,
std::string failure_reason) {
EXPECT_FALSE(fake_seneschal_client_->share_path_called());
EXPECT_EQ(success, false);
EXPECT_EQ(failure_reason, "Cannot share, VM not running");
std::move(closure).Run();
}
CrostiniSharePathTest()
: scoped_task_environment_(
base::test::ScopedTaskEnvironment::MainThreadType::UI),
test_browser_thread_bundle_(
content::TestBrowserThreadBundle::REAL_IO_THREAD) {
chromeos::DBusThreadManager::Initialize();
fake_concierge_client_ = static_cast<chromeos::FakeConciergeClient*>(
chromeos::DBusThreadManager::Get()->GetConciergeClient());
fake_seneschal_client_ = static_cast<chromeos::FakeSeneschalClient*>(
chromeos::DBusThreadManager::Get()->GetSeneschalClient());
}
~CrostiniSharePathTest() override { chromeos::DBusThreadManager::Shutdown(); }
void SetUp() override {
run_loop_ = std::make_unique<base::RunLoop>();
profile_ = std::make_unique<TestingProfile>();
base::CommandLine::ForCurrentProcess()->AppendSwitch(
chromeos::switches::kCrostiniFiles);
// Fake that this is a real ChromeOS system in order to use TestingProfile
// /tmp path for Downloads rather than the current Linux user $HOME.
// SetChromeOSVersionInfoForTest() must not be called until D-Bus is
// initialized with fake clients, and then it must be cleared in TearDown()
// before D-Bus is re-initialized for the next test.
base::SysInfo::SetChromeOSVersionInfoForTest(kLsbRelease, base::Time());
// Setup Downloads and path to share.
downloads_ = file_manager::util::GetDownloadsFolderForProfile(profile());
share_path_ = downloads_.AppendASCII("path");
ASSERT_TRUE(base::CreateDirectory(share_path_));
// Create 'vm-running' VM instance which is running.
vm_tools::concierge::VmInfo vm_info;
CrostiniManager::GetForProfile(profile())->AddRunningVmForTesting(
"vm-running", vm_info);
}
void TearDown() override {
run_loop_.reset();
profile_.reset();
// Clear SetChromeOSVersionInfoForTest() so D-Bus will use fake clients
// again in the next test.
base::SysInfo::SetChromeOSVersionInfoForTest("", base::Time());
}
protected:
base::RunLoop* run_loop() { return run_loop_.get(); }
Profile* profile() { return profile_.get(); }
base::FilePath downloads_;
base::FilePath share_path_;
// Owned by chromeos::DBusThreadManager
chromeos::FakeSeneschalClient* fake_seneschal_client_;
chromeos::FakeConciergeClient* fake_concierge_client_;
std::unique_ptr<base::RunLoop>
run_loop_; // run_loop_ must be created on the UI thread.
std::unique_ptr<TestingProfile> profile_;
private:
base::test::ScopedTaskEnvironment scoped_task_environment_;
content::TestBrowserThreadBundle test_browser_thread_bundle_;
DISALLOW_COPY_AND_ASSIGN(CrostiniSharePathTest);
};
TEST_F(CrostiniSharePathTest, Success) {
vm_tools::concierge::StartVmResponse start_vm_response;
start_vm_response.set_status(vm_tools::concierge::VM_STATUS_RUNNING);
start_vm_response.mutable_vm_info()->set_seneschal_server_handle(123);
fake_concierge_client_->set_start_vm_response(start_vm_response);
CrostiniManager::GetForProfile(profile())->StartTerminaVm(
"success", share_path_,
base::BindOnce(
&CrostiniSharePathTest::SharePathSuccessStartTerminaVmCallback,
base::Unretained(this)));
run_loop()->Run();
}
TEST_F(CrostiniSharePathTest, SharePathErrorSeneschal) {
vm_tools::concierge::StartVmResponse start_vm_response;
start_vm_response.set_status(vm_tools::concierge::VM_STATUS_RUNNING);
start_vm_response.mutable_vm_info()->set_seneschal_server_handle(123);
fake_concierge_client_->set_start_vm_response(start_vm_response);
vm_tools::seneschal::SharePathResponse share_path_response;
share_path_response.set_success(false);
share_path_response.set_failure_reason("test failure");
fake_seneschal_client_->set_share_path_response(share_path_response);
CrostiniManager::GetForProfile(profile())->StartTerminaVm(
"error-seneschal", share_path_,
base::BindOnce(
&CrostiniSharePathTest::SharePathErrorSeneschalStartTerminaVmCallback,
base::Unretained(this)));
run_loop()->Run();
}
TEST_F(CrostiniSharePathTest, SharePathErrorPathNotAbsolute) {
const base::FilePath path("not/absolute/dir");
SharePath(profile(), "vm-running", path,
base::BindOnce(&CrostiniSharePathTest::SharePathCallback,
base::Unretained(this), false, false, false,
"Path must be absolute", run_loop()->QuitClosure()));
run_loop()->Run();
}
TEST_F(CrostiniSharePathTest, SharePathErrorNotUnderDownloads) {
const base::FilePath path("/not/under/downloads");
SharePath(profile(), "vm-running", path,
base::BindOnce(&CrostiniSharePathTest::SharePathCallback,
base::Unretained(this), false, false, false,
"Path must be under Downloads",
run_loop()->QuitClosure()));
run_loop()->Run();
}
TEST_F(CrostiniSharePathTest, SharePathErrorVmNotRunning) {
SharePath(profile(), "error-vm-not-running", share_path_,
base::BindOnce(&CrostiniSharePathTest::SharePathCallback,
base::Unretained(this), true, false, false,
"VM not running", run_loop()->QuitClosure()));
run_loop()->Run();
}
TEST_F(CrostiniSharePathTest, SharePathErrorNotValidDirectory) {
const base::FilePath path = share_path_.AppendASCII("not-exists");
SharePath(profile(), "vm-running", path,
base::BindOnce(&CrostiniSharePathTest::SharePathCallback,
base::Unretained(this), false, false, false,
"Path is not a valid directory",
run_loop()->QuitClosure()));
run_loop()->Run();
}
TEST_F(CrostiniSharePathTest, ShareAllPaths) {
base::FilePath share_path2_ = downloads_.AppendASCII("path");
ASSERT_TRUE(base::CreateDirectory(share_path2_));
vm_tools::concierge::VmInfo vm_info;
CrostiniManager::GetForProfile(profile())->AddRunningVmForTesting(
kCrostiniDefaultVmName, vm_info);
base::ListValue shared_paths = base::ListValue();
shared_paths.GetList().push_back(base::Value(share_path_.value()));
shared_paths.GetList().push_back(base::Value(share_path2_.value()));
profile()->GetPrefs()->Set(prefs::kCrostiniSharedPaths, shared_paths);
ShareAllPaths(profile(), run_loop()->QuitClosure());
run_loop()->Run();
}
} // namespace crostini
|
/*
ID: stevenh6
TASK: game1
LANG: C++
*/
#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
ofstream fout("game1.out");
ifstream fin("game1.in");
int sol[101][101];
vector<int> board;
int solve(int i, int j) {
if (i > j) {
return 0;
}
if (sol[i][j] == -1) {
int t1 = min(solve(i + 2, j), solve(i + 1, j - 1)) + board[i];
int t2 = min(solve(i + 1, j - 1), solve(i, j - 2)) + board[j];
sol[i][j] = max(t1, t2);
}
return sol[i][j];
}
int main()
{
int n;
fin >> n;
int sum = 0;
memset(sol, -1, sizeof(sol));
for (int i = 0; i < n; i++) {
int in;
fin >> in;
board.push_back(in);
sum += in;
sol[i][i] = in;
}
int p1 = solve(0, --n);
int p2 = sum - p1;
fout << p1 << " " << p2 << endl;
}
|
/*
* Copyright (c) 2016, The Regents of the University of California (Regents).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Please contact the author(s) of this library if you have any questions.
* Author: Erik Nelson ( eanelson@eecs.berkeley.edu )
*/
#include <shading/shader_factory.h>
#include <cstdio>
#include <iostream>
ShaderFactory* ShaderFactory::instance_ = NULL;
ShaderFactory::ShaderFactory() {
shader_map_ = std::map<std::string, GLuint>();
}
ShaderFactory::~ShaderFactory() {
std::map<std::string, GLuint>::iterator iter = shader_map_.begin();
for (; iter != shader_map_.end(); ++iter)
glDeleteProgram(iter->second);
}
ShaderFactory* ShaderFactory::Instance() {
if (instance_ == NULL)
instance_ = new ShaderFactory();
return instance_;
}
bool ShaderFactory::Initialize(const std::string& key,
const std::string& vertex_shader_file,
const std::string& fragment_shader_file) {
return LoadShaders(key, vertex_shader_file, fragment_shader_file);
}
Shader* ShaderFactory::GetShader(const std::string& key) {
return new Shader(shader_map_[key]);
}
bool ShaderFactory::LoadShaders(const std::string& key,
const std::string& vertex_shader_file,
const std::string& fragment_shader_file) {
GLuint program, vsp, fsp;
char* buffer;
program = glCreateProgram();
if (vertex_shader_file.length() > 0) {
// Prepare buffers.
vsp = glCreateShader(GL_VERTEX_SHADER);
buffer = LoadFile(vertex_shader_file);
if (buffer == NULL) {
std::cerr << "Failed to load vertex shader: " << vertex_shader_file << "."
<< std::endl;
return false;
}
// Load and compile shader.
glShaderSource(vsp, 1, (const GLchar**)&buffer, 0);
glCompileShader(vsp);
if (!CheckShaderSuccess(vsp))
return false;
// Attach shader to program.
glAttachShader(program, vsp);
glDeleteShader(vsp);
}
if (fragment_shader_file.length() > 0) {
// Prepare buffers.
fsp = glCreateShader(GL_FRAGMENT_SHADER);
buffer = LoadFile(fragment_shader_file);
if (buffer == NULL) {
std::cerr << "Failed to load fragment shader: " << fragment_shader_file << "."
<< std::endl;
return false;
}
// Load and compile shader.
glShaderSource(fsp, 1, (const GLchar**)&buffer, 0);
glCompileShader(fsp);
if (!CheckShaderSuccess(fsp))
return false;
// Attach shader to program.
glAttachShader(program, fsp);
glDeleteShader(fsp);
}
// Bind position and normal attributes to the shaders.
glBindAttribLocation(program, 0, "a_position");
glBindAttribLocation(program, 1, "a_normal");
// Link the shader and main program.
glLinkProgram(program);
if (!CheckProgramSuccess(program))
return false;
// Make note of where this shader is.
shader_map_[key] = program;
delete buffer;
return true;
}
char* ShaderFactory::LoadFile(const std::string& filename) {
char* data;
FILE* input;
fpos_t size;
// Open the file for reading.
input = fopen(filename.c_str(), "r");
if (input == NULL)
return NULL;
// Determine file size.
fseek(input, 0, SEEK_END);
fgetpos(input, &size);
fseek(input, 0, SEEK_SET);
// Allocate and populate array.
data = static_cast<char*>(malloc(size+1));
fread(data, sizeof(char), size, input);
// Clean up and finish.
fclose(input);
data[size] = '\0';
return data;
}
bool ShaderFactory::CheckShaderSuccess(GLuint shader) {
GLint status, length;
char* error;
// Check for success.
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status)
return true;
// If failure, retrieve error log.
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
error = static_cast<char*>(malloc(length));
glGetShaderInfoLog(shader, length, &length, error);
// Output error.
std::cerr << "Failed to compile shader: " << error;
// Clean up and exit.
delete error;
return false;
}
bool ShaderFactory::CheckProgramSuccess(GLuint program) {
GLint status, length;
char* error;
// Check for success.
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status)
return true;
// If failure, retrieve error log.
glGetShaderiv(program, GL_INFO_LOG_LENGTH, &length);
error = static_cast<char*>(malloc(length));
glGetShaderInfoLog(program, length, &length, error);
// Output error.
std::cerr << "Failed to link shader: " << error << "." << std::endl;
// Clean up and exit.
delete error;
return false;
}
|
// Created on: 1993-06-11
// Created by: Jean-Louis FRENKEL
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Prs3d_ArrowAspect_HeaderFile
#define _Prs3d_ArrowAspect_HeaderFile
#include <Graphic3d_AspectLine3d.hxx>
#include <Prs3d_BasicAspect.hxx>
//! A framework for displaying arrows in representations of dimensions and relations.
class Prs3d_ArrowAspect : public Prs3d_BasicAspect
{
DEFINE_STANDARD_RTTIEXT(Prs3d_ArrowAspect, Prs3d_BasicAspect)
public:
//! Constructs an empty framework for displaying arrows
//! in representations of lengths. The lengths displayed
//! are either on their own or in chamfers, fillets,
//! diameters and radii.
Standard_EXPORT Prs3d_ArrowAspect();
//! Constructs a framework to display an arrow with a
//! shaft of the length aLength and having a head with
//! sides at the angle anAngle from each other.
Standard_EXPORT Prs3d_ArrowAspect(const Standard_Real anAngle, const Standard_Real aLength);
Standard_EXPORT Prs3d_ArrowAspect(const Handle(Graphic3d_AspectLine3d)& theAspect);
//! defines the angle of the arrows.
Standard_EXPORT void SetAngle (const Standard_Real anAngle);
//! returns the current value of the angle used when drawing an arrow.
Standard_Real Angle() const { return myAngle; }
//! Defines the length of the arrows.
void SetLength (const Standard_Real theLength) { myLength = theLength; }
//! Returns the current value of the length used when drawing an arrow.
Standard_Real Length() const { return myLength; }
//! Turns usage of arrow zoomable on/off
void SetZoomable (bool theIsZoomable) { myIsZoomable = theIsZoomable; }
//! Returns TRUE when the Arrow Zoomable is on; TRUE by default.
bool IsZoomable() const { return myIsZoomable; }
void SetColor (const Quantity_Color& theColor) { myArrowAspect->SetColor (theColor); }
const Handle(Graphic3d_AspectLine3d)& Aspect() const { return myArrowAspect; }
void SetAspect (const Handle(Graphic3d_AspectLine3d)& theAspect) { myArrowAspect = theAspect; }
//! Dumps the content of me into the stream
Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE;
protected:
Handle(Graphic3d_AspectLine3d) myArrowAspect;
Standard_Real myAngle;
Standard_Real myLength;
Standard_Boolean myIsZoomable;
};
DEFINE_STANDARD_HANDLE(Prs3d_ArrowAspect, Prs3d_BasicAspect)
#endif // _Prs3d_ArrowAspect_HeaderFile
|
#pragma once
namespace Reflection
{
namespace Meta
{
class Method
{};
class Property
{};
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#include "adjunct/quick/widgets/OpPluginCrashedBar.h"
#include "adjunct/desktop_util/string/i18n.h"
#include "adjunct/quick/Application.h"
#include "adjunct/quick/controller/PluginCrashController.h"
#include "adjunct/quick_toolkit/widgets/OpLabel.h"
#include "adjunct/quick_toolkit/widgets/OpProgressbar.h"
#include "adjunct/quick_toolkit/windows/DesktopWindow.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/pi/system/OpFolderLister.h"
#include "modules/viewers/plugins.h"
OtlList<OpPluginCrashedBar*> OpPluginCrashedBar::s_visible_bars;
OpPluginCrashedBar::OpPluginCrashedBar()
: m_found_log_file(false)
, m_sending_report(false)
, m_sending_failed(false)
, m_spinner(NULL)
, m_progress_label(NULL)
, m_send_button(NULL)
{
}
OP_STATUS OpPluginCrashedBar::ShowCrash(const OpStringC& path, const OpMessageAddress& address)
{
time_t crash_time = g_timecache->CurrentTime();
m_logsender.reset(OP_NEW(LogSender, (false)));
RETURN_OOM_IF_NULL(m_logsender.get());
m_logsender->SetCrashTime(g_timecache->CurrentTime());
m_logsender->SetListener(this);
RETURN_IF_ERROR(FindFile(crash_time));
PluginViewer* plugin = g_plugin_viewers->FindPluginViewerByPath(path);
OpLabel* label = static_cast<OpLabel*>(GetWidgetByName("tbb_plugin_crashed_desc"));
if (plugin && label)
{
OpString description;
RETURN_IF_ERROR(I18n::Format(description, Str::D_PLUGIN_CRASH_DESCRIPTION, plugin->GetProductName()));
RETURN_IF_ERROR(label->SetText(description));
}
m_spinner = static_cast<OpProgressBar*>(GetWidgetByType(WIDGET_TYPE_PROGRESSBAR, FALSE));
if (!m_spinner)
return OpStatus::ERR;
m_spinner->SetType(OpProgressBar::Only_Label);
m_spinner->SetText(NULL);
m_send_button = GetWidgetByName("tbb_crash_report");
if (!m_send_button)
return OpStatus::ERR;
m_address = address;
m_sending_report = false;
m_sending_failed = false;
RETURN_IF_ERROR(s_visible_bars.Append(this));
Show();
return OpStatus::OK;
}
BOOL OpPluginCrashedBar::OnInputAction(OpInputAction* action)
{
switch (action->GetAction())
{
case OpInputAction::ACTION_GET_ACTION_STATE:
{
OpInputAction* child_action = action->GetChildAction();
switch (child_action->GetAction())
{
case OpInputAction::ACTION_CANCEL:
child_action->SetEnabled(TRUE);
return TRUE;
case OpInputAction::ACTION_CRASH_REPORT_ISSUE:
child_action->SetEnabled(m_found_log_file && !m_sending_report);
return TRUE;
}
break;
}
case OpInputAction::ACTION_CANCEL:
{
Hide();
return TRUE;
}
case OpInputAction::ACTION_CRASH_REPORT_ISSUE:
{
if (m_sending_failed)
{
OpStatus::Ignore(m_logsender->Send());
}
else
{
const uni_char* url = GetParentDesktopWindow()->GetWindowCommander()->GetCurrentURL(FALSE);
PluginCrashController* controller = OP_NEW(PluginCrashController, (m_send_button, url, *m_logsender));
OpStatus::Ignore(ShowDialog(controller, g_global_ui_context, GetParentDesktopWindow()));
}
return TRUE;
}
}
return OpInfobar::OnInputAction(action);
}
OP_STATUS OpPluginCrashedBar::FindFile(time_t crashtime)
{
m_found_log_file = false;
OpString crashlog_path;
RETURN_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_CRASHLOG_FOLDER, crashlog_path));
OpFolderLister* lister;
RETURN_IF_ERROR(OpFolderLister::Create(&lister));
OpAutoPtr<OpFolderLister> holder (lister);
// File name format: crashyyyymmddhhmmss.txt, find newest
RETURN_IF_ERROR(lister->Construct(crashlog_path, UNI_L("crash*.txt")));
OpString file;
while (lister->Next())
{
if (file.Compare(lister->GetFullPath()) < 0)
RETURN_IF_ERROR(file.Set(lister->GetFullPath()));
}
if (file.IsEmpty())
return OpStatus::OK;
// Check if the timestamp looks reasonable
const uni_char* timestamp_start = file.CStr() + file.Length() + 1 - sizeof("yyyymmddhhmmss.txt");
uni_char* endptr;
UINT64 timespec = uni_strtoui64(timestamp_start, &endptr, 10);
if (endptr - timestamp_start != sizeof("yyyymmddhhmmss") - 1)
return OpStatus::OK;
// Check for some time in advance, in case it took some time for the process to warn us
crashtime -= MaxCrashTimePassed;
struct tm* broken_crashtime = op_localtime(&crashtime);
if (!broken_crashtime)
return OpStatus::ERR;
UINT64 min_timespec = (broken_crashtime->tm_year + 1900) * OP_UINT64(10000000000)
+ (broken_crashtime->tm_mon + 1) * OP_UINT64(100000000)
+ broken_crashtime->tm_mday * OP_UINT64(1000000)
+ broken_crashtime->tm_hour * OP_UINT64(10000)
+ broken_crashtime->tm_min * OP_UINT64(100)
+ broken_crashtime->tm_sec;
if (timespec < min_timespec)
return OpStatus::OK;
m_found_log_file = true;
return m_logsender->SetLogFile(file);
}
BOOL OpPluginCrashedBar::Hide()
{
m_sending_report = false;
m_sending_failed = false;
m_logsender.reset();
s_visible_bars.RemoveItem(this);
return OpInfobar::Hide();
}
void OpPluginCrashedBar::OnSendingStarted(LogSender* sender)
{
m_sending_failed = false;
for (OtlList<OpPluginCrashedBar*>::Iterator it = s_visible_bars.Begin(); it != s_visible_bars.End(); ++it)
(*it)->OnSendingStarted(m_address);
g_input_manager->UpdateAllInputStates();
}
void OpPluginCrashedBar::OnSendingStarted(const OpMessageAddress& address)
{
if (m_address != address)
return;
m_spinner->SetType(OpProgressBar::Spinner);
m_sending_report = true;
Relayout();
}
void OpPluginCrashedBar::OnSendSucceeded(LogSender* sender)
{
for (OtlList<OpPluginCrashedBar*>::Iterator it = s_visible_bars.Begin(); it != s_visible_bars.End(); ++it)
(*it)->OnSendSucceeded(m_address);
g_input_manager->UpdateAllInputStates();
}
void OpPluginCrashedBar::OnSendSucceeded(const OpMessageAddress& address)
{
if (m_address != address)
return;
m_spinner->SetType(OpProgressBar::Only_Label);
OpString status;
OpStatus::Ignore(g_languageManager->GetString(Str::D_PLUGIN_CRASH_REPORT_SENT, status));
m_spinner->SetText(status.CStr());
m_sending_report = false;
m_found_log_file = false;
Relayout();
}
void OpPluginCrashedBar::OnSendFailed(LogSender* sender)
{
m_sending_failed = true;
OpString send_again;
OpStatus::Ignore(g_languageManager->GetString(Str::D_CRASH_LOGGING_DIALOG_SEND_AGAIN, send_again));
m_send_button->SetText(send_again.CStr());
for (OtlList<OpPluginCrashedBar*>::Iterator it = s_visible_bars.Begin(); it != s_visible_bars.End(); ++it)
(*it)->OnSendFailed(m_address);
g_input_manager->UpdateAllInputStates();
}
void OpPluginCrashedBar::OnSendFailed(const OpMessageAddress& address)
{
if (m_address != address)
return;
m_spinner->SetType(OpProgressBar::Only_Label);
OpString status;
OpStatus::Ignore(g_languageManager->GetString(Str::D_CRASH_LOGGING_DIALOG_PROGRESS_FAILURE, status));
m_spinner->SetText(status.CStr());
m_sending_report = false;
Relayout();
}
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- */
#include "core/pch.h"
#include "modules/ecmascript/carakan/src/es_pch.h"
#include "modules/ecmascript/ecmascript.h"
#include "modules/ecmascript/carakan/src/object/es_object.h"
#include "modules/ecmascript/carakan/src/object/es_function.h"
#include "modules/ecmascript/carakan/src/object/es_host_object.h"
#include "modules/ecmascript/carakan/src/vm/es_suspended_call.h"
#include "modules/ecmascript/carakan/src/builtins/es_array_builtins.h"
ES_Host_Object *
ES_Host_Object::Make(ES_Context *context, EcmaScript_Object* host_object, ES_Object* prototype, const char* object_class)
{
OP_ASSERT(prototype);
#if 0
OP_ASSERT(prototype->IsPrototypeObject());
#endif
OP_ASSERT(!prototype->HasMultipleIdentities());
ES_Host_Object *self;
GC_ALLOCATE(context, self, ES_Host_Object, (self, TRUE));
ES_CollectorLock gclock(context);
self->klass = ES_Class::MakeRoot(context, prototype, object_class);
self->AllocateProperties(context);
/* FIXME: We would much rather want prototype to be a prototype to begin with. */
if (!prototype->IsPrototypeObject())
prototype->ConvertToPrototypeObject(context, self->klass);
else
prototype->AddInstance(context, self->klass, FALSE);
self->host_object = host_object;
return self;
}
/* static */ ES_Host_Object *
ES_Host_Object::Make(ES_Context *context, void *&payload, unsigned payload_size, ES_Object *prototype, const char *object_class, BOOL need_destroy, BOOL is_singleton)
{
OP_ASSERT(prototype);
#if 0
OP_ASSERT(prototype->IsPrototypeObject());
#endif
OP_ASSERT(!prototype->HasMultipleIdentities());
ES_Host_Object *self;
GC_ALLOCATE_WITH_EXTRA_ALIGNED_PAYLOAD(context, self, payload, payload_size, ES_Host_Object, (self, need_destroy));
ES_CollectorLock gclock(context);
if (is_singleton)
self->klass = ES_Class::MakeSingleton(context, prototype, object_class);
else
self->klass = ES_Class::MakeRoot(context, prototype, object_class, is_singleton);
self->AllocateProperties(context);
/* FIXME: We would much rather want prototype to be a prototype to begin with. */
if (!prototype->IsPrototypeObject())
prototype->ConvertToPrototypeObject(context, self->klass);
else
prototype->AddInstance(context, self->klass, is_singleton);
return self;
}
void
ES_Host_Object::Initialize(ES_Host_Object *object, BOOL need_destroy, ES_Class *klass/* = NULL*/)
{
ES_Object::Initialize(object, klass);
object->SetIsHostObject();
object->host_object = NULL;
if (need_destroy)
object->SetNeedDestroy();
}
/* static */ void
ES_Host_Object::Destroy(ES_Host_Object *object)
{
if (EcmaScript_Object *host_object = object->host_object)
if (reinterpret_cast<char *>(host_object) > reinterpret_cast<char *>(object) &&
reinterpret_cast<char *>(host_object) < reinterpret_cast<char *>(object) + ObjectSize(object))
host_object->~EcmaScript_Object();
else
OP_DELETE(host_object);
}
static DeleteResult
FinishDelete(ES_Execution_Context *context, ES_DeleteStatus status)
{
switch (status)
{
default:
OP_ASSERT(!"Cannot happen");
case DELETE_OK:
return TRUE;
case DELETE_REJECT:
return FALSE;
case DELETE_NO_MEMORY:
context->AbortOutOfMemory();
return FALSE;
}
}
DeleteResult
ES_Host_Object::DeleteHostL(ES_Execution_Context *context, JString *name, unsigned &result)
{
OP_ASSERT(this == Identity(context, this));
ES_Property_Info info;
if (HasOwnNativeProperty(name, info))
{
if (!SecurityCheck(context))
{
context->ThrowReferenceError("Security error: attempted to delete protected variable: ", Storage(context, name), Length(name));
return FALSE;
}
if (info.IsDontDelete())
result = FALSE;
else
result = DeleteOwnPropertyL(context, name);
}
else
{
ES_SuspendedHostDeleteName call(host_object, StorageZ(context, name), context->GetRuntime());
context->SuspendedCall(&call);
result = FinishDelete(context, call.status);
}
return TRUE;
}
DeleteResult
ES_Host_Object::DeleteHostL(ES_Execution_Context *context, unsigned index, unsigned &result)
{
OP_ASSERT(this == Identity(context, this));
if (HasOwnNativeProperty(index))
{
if (!SecurityCheck(context))
{
context->ThrowReferenceError("Security error: attempted to delete protected variable");
return FALSE;
}
result = DeleteOwnPropertyL(context, index);
}
else
{
ES_SuspendedHostDeleteIndex call(host_object, index, context->GetRuntime());
context->SuspendedCall(&call);
result = FinishDelete(context, call.status);
}
return TRUE;
}
GetResult
ES_Host_Object::GetHostL(ES_Execution_Context *context, ES_Object *this_object, JString *name, ES_Value_Internal &value, ES_Object *&prototype_object, ES_PropertyIndex &index)
{
OP_ASSERT(this == Identity(context, this));
ES_Property_Info info;
ES_Value_Internal_Ref value_ref;
BOOL allow_cache = !HasVolatilePropertySet();
ES_Object *prototype = NULL;
BOOL is_secure = FALSE;
BOOL checked_prototype_chain = FALSE;
/* First check if the object has the property, if not look in the prototype chain else check security.
HasPropertyWithInfo keeps track of security in the prototype chain.
Delay checking the prototype chain if we know there isn't a getter somewhere, but if we do check
it, make sure to reuse that information.
*/
ES_Object *klass_prototype = klass->Prototype();
if (!GetOwnLocation(name, info, value_ref) && (klass_prototype && klass_prototype->HasGetterOrSetter() || name->Equals("__proto__", 9)))
{
checked_prototype_chain = TRUE;
if (klass_prototype && klass_prototype->HasPropertyWithInfo(context, name, info, prototype, is_secure, allow_cache))
/* If the property is found in the prototype chain, check if the property
has a getter function. If it has, check if the host object allows an
accessor function for this property. Allow [[Get]] if that doesn't apply. */
if (!is_secure)
{
context->ThrowReferenceError("Security error: attempted to read protected variable: ", Storage(context, name), Length(name));
return PROP_GET_FAILED;
}
else if (prototype->GetOwnLocation(name, info, value_ref) && value_ref.IsGetterOrSetter() && static_cast<ES_Special_Mutable_Access *>(value_ref.GetBoxed())->getter)
{
/* AllowGetterSetterFor() also checks security. */
if (!AllowGetterSetterFor(context, name))
return PROP_GET_FAILED;
}
else
value_ref.Set(NULL, ES_STORAGE_WHATEVER, ES_PropertyIndex(UINT_MAX));
}
else if (!value_ref.IsNull() && !SecurityCheck(context))
{
context->ThrowReferenceError("Security error: attempted to read protected variable: ", Storage(context, name), Length(name));
return PROP_GET_FAILED;
}
/* Here value_loc either point to a property of the instance or an
accessor function located in an object in the prototype chain or
to NULL. If it isn't NULL then security has been checked at this
point.
*/
GetResult res = PROP_GET_NOT_FOUND;
if (!value_ref.IsNull())
{
allow_cache = allow_cache && info.CanCacheGet();
res = GetWithLocationL(context, this_object, info, value_ref, value);
if (GET_FOUND(res))
{
if (!allow_cache)
res = GET_CANNOT_CACHE(res);
else
index = value_ref.Index();
return res;
}
}
else if (GET_FOUND(res = GetInOwnHostPropertyL(context, name, value)) || res == PROP_GET_FAILED)
/* If we haven't found it yet, look in the host object */
return allow_cache ? res : GET_CANNOT_CACHE(res);
else
{
/* If we haven't checked the prototype chain, do so now and check security. */
if (!checked_prototype_chain && klass_prototype && klass_prototype->HasPropertyWithInfo(context, name, info, prototype, is_secure, allow_cache) && !is_secure)
{
context->ThrowReferenceError("Security error: attempted to read protected variable: ", Storage(context, name), Length(name));
return PROP_GET_FAILED;
}
if (prototype)
{
/* If we found it in the prototype chain, get it from there. */
if (prototype->IsHostObject())
{
res = prototype->GetOwnPropertyL(context, this_object, this_object, name, value, index);
if (!GET_FOUND(res))
res = static_cast<ES_Host_Object *>(prototype)->GetInOwnHostPropertyL(context, name, value);
}
/* Impose a security check for prototype.constructor even if prototype is accessible; the
property is native and unprotected. */
else if ((!prototype->IsCrossDomainAccessible() || name->Equals("constructor", 11)) && !SecurityCheck(context))
{
context->ThrowReferenceError("Security error: attempted to read protected variable: ", Storage(context, name), Length(name));
return PROP_GET_FAILED;
}
else
res = prototype->GetOwnPropertyL(context, this_object, this_object, name, value, index);
if (GET_FOUND(res))
{
if (allow_cache)
{
prototype_object = prototype;
return res;
}
else
return GET_CANNOT_CACHE(res);
}
}
}
if (!SecurityCheck(context))
{
context->ThrowReferenceError("Security error: attempted to read protected variable: ", Storage(context, name), Length(name));
return PROP_GET_FAILED;
}
else
return PROP_GET_NOT_FOUND;
}
GetResult
ES_Host_Object::GetHostL(ES_Execution_Context *context, ES_Object *this_object, unsigned index, ES_Value_Internal &value)
{
GetResult result = GetOwnHostPropertyL(context, this_object, index, value);
if (GET_FOUND(result))
return result;
ES_Host_Object *foreign_object = this;
for (ES_Object *object = Class()->Prototype(); object != NULL; object = object->Class()->Prototype())
{
if (object->IsHostObject())
{
foreign_object = static_cast<ES_Host_Object *>(object);
result = foreign_object->GetOwnHostPropertyL(context, this_object, index, value);
if (GET_FOUND(result))
return result;
}
else if (object->HasOwnNativeProperty(index))
{
if (!foreign_object->SecurityCheck(context))
{
context->ThrowReferenceError("Security error: attempted to read protected variable");
return PROP_GET_FAILED;
}
return object->GetOwnPropertyL(context, this_object, this_object, index, value);
}
}
if (!SecurityCheck(context))
{
context->ThrowReferenceError("Security error: attempted to read protected variable");
return PROP_GET_FAILED;
}
else
return PROP_GET_NOT_FOUND;
}
PutResult
ES_Host_Object::PutHostL(ES_Execution_Context *context, JString *name, const ES_Value_Internal &value, BOOL in_class, ES_PropertyIndex &index)
{
ES_Property_Info info;
ES_Value_Internal_Ref value_ref;
BOOL allow_cache = TRUE;
ES_Object *prototype;
BOOL is_secure = FALSE;
BOOL checked_prototype_chain = FALSE;
/* First check if the object has the property, if not look in the prototype chain else check security.
HasPropertyWithInfo keeps track of security in the prototype chain.
Delay checking the prototype chain if we know there isn't a getter somewhere, but if we do check
it, make sure to reuse that information.
*/
ES_Object *klass_prototype = klass->Prototype();
if (!GetOwnLocation(name, info, value_ref) && (klass_prototype && klass_prototype->HasGetterOrSetter() || name->Equals("__proto__", 9)))
{
checked_prototype_chain = TRUE;
if (klass_prototype && klass_prototype->HasPropertyWithInfo(context, name, info, prototype, is_secure, allow_cache))
/* If the property is found in the prototype chain and writable, check
if it has a setter function. If it has, check if the host object allows
an accessor function for this property. */
if (!is_secure)
{
context->ThrowReferenceError("Security error: attempted to write protected variable: ", Storage(context, name), Length(name));
return PROP_PUT_FAILED;
}
else if (info.IsSpecial() && prototype->GetOwnLocation(name, info, value_ref) && value_ref.IsGetterOrSetter())
if (static_cast<ES_Special_Mutable_Access *>(value_ref.GetBoxed())->setter)
{
/* AllowGetterSetterFor() also checks security. */
if (!AllowGetterSetterFor(context, name))
return PROP_PUT_FAILED;
}
else
return PROP_PUT_READ_ONLY;
else if (info.IsReadOnly())
return PROP_PUT_READ_ONLY;
else
value_ref.Set(NULL, ES_STORAGE_WHATEVER, ES_PropertyIndex(UINT_MAX));
}
else if (!value_ref.IsNull() && !SecurityCheck(context))
{
context->ThrowReferenceError("Security error: attempted to write protected variable: ", Storage(context, name), Length(name));
return PROP_PUT_FAILED;
}
/* Here value_loc points either to a property of the instance or an
accessor function located in an object in the prototype chain or
to NULL.
Security has been checked at this point.
*/
if (!value_ref.IsNull() && info.IsNativeWriteable())
{
PutResult res = PutWithLocation(context, this, info, value_ref, value);
allow_cache = allow_cache && !info.IsSpecial();
if (allow_cache && PUT_OK(res) && info.IsClassProperty())
{
index = value_ref.Index();
return PROP_PUT_OK_CAN_CACHE;
}
else
return res;
}
FailedReason reason;
BOOL can_cache = TRUE;
if (PutInHostL(context, name, value, reason, can_cache, index) || !value_ref.IsNull() && reason == NotFound)
return PROP_PUT_OK;
if (reason == ReadOnly)
return PROP_PUT_READ_ONLY;
if (reason != NotFound)
return PROP_PUT_FAILED;
if (!SecurityCheck(context))
{
context->ThrowReferenceError("Security error: attempted to write protected variable: ", Storage(context, name), Length(name));
return PROP_PUT_FAILED;
}
/* If we haven't checked the prototype chain, do so now and check security. */
if (!checked_prototype_chain && klass_prototype && klass_prototype->HasPropertyWithInfo(context, name, info, prototype, is_secure, allow_cache))
/* See GetHostL() comment for why "constructor" is special-cased. */
if (!is_secure || prototype && prototype->IsCrossDomainAccessible() && name->Equals("constructor", 11) && !SecurityCheck(context))
{
context->ThrowReferenceError("Security error: attempted to write protected variable: ", Storage(context, name), Length(name));
return PROP_PUT_FAILED;
}
else if (info.IsReadOnly())
return PROP_PUT_READ_ONLY;
info.Reset();
if (in_class)
{
AppendValueL(context, name, index, value, CP, value.GetStorageType());
Invalidate();
if (reason == NotFound && can_cache == FALSE)
/* Some host objects track if a native property
have been created by catching when they first report a
failed put -- not marking their native objects during GC
prior to that event. When that transition do happen, the host object
must report that property as non-cacheable so as to ensure
that PutName() gets called on other host object instances of
the same class. PUT_FAILED_DONT_CACHE serves that purpose. */
return PROP_PUT_OK;
else if (IsSingleton() || HasHashTableProperties())
return PROP_PUT_OK_CAN_CACHE;
else
return PROP_PUT_OK_CAN_CACHE_NEW;
}
else
{
if (!HasHashTableProperties())
klass = ES_Class::MakeHash(context, klass, Count());
static_cast<ES_Class_Hash_Base *>(klass)->InsertL(context, name, value, info, Count());
Invalidate();
return PROP_PUT_OK;
}
}
PutResult
ES_Host_Object::PutHostL(ES_Execution_Context *context, unsigned index, unsigned *attributes, const ES_Value_Internal &value)
{
OP_ASSERT(this == Identity(context, this));
if (indexed_properties && ES_Indexed_Properties::HasProperty(indexed_properties, index))
{
if (!SecurityCheck(context))
{
context->ThrowReferenceError("Security error: attempted to write protected variable");
return PROP_PUT_FAILED;
}
return ES_Indexed_Properties::PutL(context, this, index, attributes, value, this);
}
FailedReason reason;
if (PutInHostL(context, index, value, reason))
return PROP_PUT_OK;
if (reason == ReadOnly)
return PROP_PUT_READ_ONLY;
if (reason != NotFound)
return PROP_PUT_FAILED;
if (!SecurityCheck(context))
{
context->ThrowReferenceError("Security error: attempted to write protected variable");
return PROP_PUT_FAILED;
}
return ES_Indexed_Properties::PutL(context, this, index, value, this);
}
BOOL
ES_Host_Object::HasPropertyHost(ES_Execution_Context *context, JString *name)
{
OP_ASSERT(this == Identity(context, this));
ES_Property_Info info;
BOOL is_secure = TRUE;
if (HasOwnHostProperty(context, name, info, is_secure))
return TRUE;
for (ES_Object *object = Class()->Prototype(); object != NULL; object = object->Class()->Prototype())
if (object->IsHostObject())
{
ES_Property_Info info;
if (static_cast<ES_Host_Object *>(object)->HasOwnHostProperty(context, name, info, is_secure))
return TRUE;
}
else if (object->HasOwnNativeProperty(name))
return TRUE;
return FALSE;
}
BOOL
ES_Host_Object::HasPropertyHost(ES_Execution_Context *context, unsigned index)
{
OP_ASSERT(this == Identity(context, this));
ES_Property_Info info;
BOOL is_secure = TRUE;
if (HasOwnHostProperty(context, index, info, is_secure))
return TRUE;
for (ES_Object *object = Class()->Prototype(); object != NULL; object = object->Class()->Prototype())
if (object->IsHostObject() && static_cast<ES_Host_Object *>(object)->HasOwnHostProperty(context, index, info, is_secure))
return TRUE;
else if (object->HasOwnNativeProperty(index))
return TRUE;
return FALSE;
}
/* static */ BOOL
ES_Host_Object::ConvertL(ES_Execution_Context *context, ES_PutState reason, const ES_Value_Internal &from, ES_Value_Internal &to)
{
to = from;
switch (reason)
{
case PUT_NEEDS_BOOLEAN:
to.ToBoolean();
return TRUE;
case PUT_NEEDS_NUMBER:
return to.ToNumber(context);
default:
return to.ToString(context);
}
}
/* static */ BOOL
ES_Host_Object::ConvertL(ES_Execution_Context *context, ES_ArgumentConversion reason, const ES_Value_Internal &from, ES_Value_Internal &to)
{
to = from;
switch (reason)
{
case ES_CALL_NEEDS_BOOLEAN:
to.ToBoolean();
return TRUE;
case ES_CALL_NEEDS_NUMBER:
return to.ToNumber(context);
default:
return to.ToString(context);
}
}
/* static */ GetResult
ES_Host_Object::FinishGet(ES_Execution_Context *context, ES_GetState state, const ES_Value &external_value)
{
GetResult result = PROP_GET_FAILED;
switch (state)
{
case GET_SECURITY_VIOLATION:
context->ThrowReferenceError("Security error: attempted to read protected variable");
result = PROP_GET_FAILED;
break;
case GET_EXCEPTION:
context->ThrowValue(external_value);
result = PROP_GET_FAILED;
break;
case GET_NO_MEMORY:
context->AbortOutOfMemory();
result = PROP_GET_FAILED;
break;
case GET_FAILED:
result = PROP_GET_NOT_FOUND;
break;
case GET_SUCCESS:
result = PROP_GET_OK;
break;
default: OP_ASSERT(!"implementation error");
}
return result;
}
/* static */ BOOL
ES_Host_Object::FinishPut(ES_Execution_Context *context, ES_PutState state, FailedReason &reason, BOOL &can_cache, const ES_Value &external_value)
{
switch (state)
{
case PUT_SUCCESS:
reason = NoReason;
return TRUE;
case PUT_FAILED_DONT_CACHE:
can_cache = FALSE;
/* fall through */
case PUT_FAILED:
reason = NotFound;
break;
case PUT_READ_ONLY:
reason = ReadOnly;
break;
case PUT_SECURITY_VIOLATION:
reason = SecurityViolation;
context->ThrowReferenceError("Security error: attempted to write protected variable");
break;
case PUT_NEEDS_STRING:
reason = NeedsString;
break;
case PUT_NEEDS_STRING_WITH_LENGTH:
reason = NeedsStringWithLength;
break;
case PUT_NEEDS_NUMBER:
reason = NeedsNumber;
break;
case PUT_NEEDS_BOOLEAN:
reason = NeedsBoolean;
break;
case PUT_NO_MEMORY:
context->AbortOutOfMemory();
break;
case PUT_EXCEPTION:
reason = Exception;
context->ThrowValue(external_value);
break;
default: OP_ASSERT(!"implementation error");
}
return FALSE;
}
/* static */ void
ES_Host_Object::SuspendL(ES_Execution_Context *context, ES_Value_Internal *restart_object, const ES_Value &external_value)
{
restart_object->ImportL(context, external_value);
context->Block();
}
static void
CheckDOMReturn(ES_Context *context, OP_STATUS e)
{
if (OpStatus::IsMemoryError(e))
context->AbortOutOfMemory();
else if (OpStatus::IsError(e))
{
OP_ASSERT(!"Implementation error, only oom errors are allowed");
context->AbortError();
}
}
/* static */ ES_Object *
ES_Host_Object::Identity(ES_Context *context, ES_Host_Object *target)
{
ES_Execution_Context *exec_context = context->GetExecutionContext();
if (!exec_context)
return IdentityStandardStack(target);
for (;;)
{
EcmaScript_Object *host = target->GetHostObject();
if (host == NULL)
return target;
if (host->GetRuntime() == NULL)
return target;
ES_SuspendedHostIdentity call(host);
exec_context->SuspendedCall(&call);
CheckDOMReturn(exec_context, call.result);
ES_Host_Object *identity = static_cast<ES_Host_Object *>(call.loc);
if (identity == target || !identity->HasMultipleIdentities())
return identity;
target = identity;
}
}
/* static */ ES_Object *
ES_Host_Object::IdentityStandardStack(ES_Host_Object *target)
{
for (;;)
{
EcmaScript_Object *host = target->GetHostObject();
if (host == NULL)
return target;
if (host->GetRuntime() == NULL)
return target;
ES_Object *loc;
OP_STATUS result = host->Identity(&loc);
if (OpStatus::IsMemoryError(result))
return target;
else if (OpStatus::IsError(result))
{
OP_ASSERT(!"Implementation error, only oom errors are allowed");
return target;
}
ES_Host_Object *identity = static_cast<ES_Host_Object *>(loc);
if (identity == target || !identity->HasMultipleIdentities())
return identity;
target = identity;
}
}
void
ES_Host_Object::FetchProperties(ES_Context *context, ES_PropertyEnumerator *enumerator)
{
if (context->IsUsingStandardStack())
{
ES_CollectorLock gclock(context);
ES_GetState result = host_object->FetchPropertiesL(enumerator, context->GetRuntime());
if (result == GET_NO_MEMORY)
context->AbortOutOfMemory();
OP_ASSERT(result != GET_SUSPEND);
}
else
{
ES_Execution_Context *exec_context = context->GetExecutionContext();
OP_ASSERT(exec_context);
ES_SuspendedHostFetchProperties call(host_object, enumerator, context->GetRuntime());
while (exec_context->SuspendedCall(&call), call.result == GET_SUSPEND)
exec_context->Block();
if (call.result == GET_NO_MEMORY)
context->AbortOutOfMemory();
}
}
unsigned
ES_Host_Object::GetIndexedPropertiesLength(ES_Context *context)
{
if (context->IsUsingStandardStack())
{
ES_CollectorLock gclock(context);
unsigned length;
ES_GetState result = host_object->GetIndexedPropertiesLength(length, context->GetRuntime());
if (result == GET_NO_MEMORY)
context->AbortOutOfMemory();
OP_ASSERT(result != GET_SUSPEND);
return length;
}
else
{
ES_Execution_Context *exec_context = context->GetExecutionContext();
OP_ASSERT(exec_context);
ES_SuspendedHostGetIndexedPropertiesLength call(host_object, context->GetRuntime());
while (exec_context->SuspendedCall(&call), call.result == GET_SUSPEND)
exec_context->Block();
if (call.result == GET_NO_MEMORY)
context->AbortOutOfMemory();
return call.return_value;
}
}
BOOL
ES_Host_Object::AllowOperationOnProperty(ES_Execution_Context *context, JString *name, EcmaScript_Object::PropertyOperation op)
{
ES_SuspendedHostAllowPropertyOperationFor call(host_object, context->GetRuntime(), StorageZ(context, name), op);
context->SuspendedCall(&call);
if (!call.result && op == EcmaScript_Object::ALLOW_ACCESSORS)
context->ThrowTypeError("Security error: getter/setter not allowed for: ", Storage(context, name), Length(name));
return call.result;
}
BOOL
ES_Host_Object::GetOwnHostPropertyL(ES_Execution_Context *context, PropertyDescriptor &desc, JString *name, unsigned index, BOOL fetch_value, BOOL fetch_accessors)
{
BOOL is_secure = IsCrossDomainAccessible() || SecurityCheck(context);
BOOL has_property;
if (name)
{
ES_SuspendedHostHasPropertyName call(host_object, StorageZ(context, name), name->HostCode(), context->GetRuntime());
while (context->SuspendedCall(&call), call.result == GET_SUSPEND)
{
context->Block();
call.is_restarted = TRUE;
}
if (call.result == GET_NO_MEMORY)
context->AbortOutOfMemory();
/* The handling of is_secure mirrors that for [[HasProperty]].
See it for explanation. */
has_property = call.result == GET_SUCCESS;
if (call.result == GET_SECURITY_VIOLATION)
is_secure = FALSE;
else if (has_property)
is_secure = TRUE;
}
else
{
ES_SuspendedHostHasPropertyIndex call(host_object, index, context->GetRuntime());
while (context->SuspendedCall(&call), call.result == GET_SUSPEND)
{
context->Block();
call.is_restarted = TRUE;
}
if (call.result == GET_NO_MEMORY)
context->AbortOutOfMemory();
has_property = call.result == GET_SUCCESS;
if (call.result == GET_SECURITY_VIOLATION)
is_secure = FALSE;
else if (has_property)
is_secure = TRUE;
}
if (!is_secure)
{
context->ThrowTypeError("Security error: protected variable accessed");
return FALSE;
}
if (context->ShouldYield())
context->YieldImpl();
if (has_property)
{
ES_Object *getter = NULL, *setter = NULL;
if (fetch_accessors)
{
ES_Global_Object *global_object = context->GetGlobalObject();
getter = ES_Function::Make(context, global_object->GetBuiltInGetterSetterClass(), global_object, 0, HostGetter, 0, 0, name, NULL);
ES_CollectorLock gclock(context);
setter = ES_Function::Make(context, global_object->GetBuiltInGetterSetterClass(), global_object, 1, HostSetter, 0, 0, name, NULL);
}
desc.SetEnumerable(TRUE);
if (name)
desc.SetConfigurable(AllowOperationOnProperty(context, name, EcmaScript_Object::ALLOW_NATIVE_OVERRIDE));
else
desc.SetConfigurable(FALSE);
desc.SetGetter(getter);
desc.SetSetter(setter);
desc.is_host_property = TRUE;
}
else
desc.is_undefined = TRUE;
return TRUE;
}
/* static */ BOOL
ES_Host_Object::HostGetter(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
OP_ASSERT(argv[-1].GetObject()->IsFunctionObject());
ES_Function *function_object = static_cast<ES_Function *>(argv[-1].GetObject());
ES_Value_Internal name_value;
function_object->GetCachedAtIndex(ES_PropertyIndex(ES_Function::NAME), name_value);
OP_ASSERT(name_value.IsString());
JString *name = name_value.GetString();
if (!argv[-2].IsObject() || !argv[-2].GetObject(context)->IsHostObject())
{
context->ThrowTypeError("Failed to call host getter");
return FALSE;
}
ES_Host_Object *this_object = static_cast<ES_Host_Object *>(argv[-2].GetObject(context));
GetResult res = this_object->GetInOwnHostPropertyL(context, name, *return_value);
if (GET_NOT_FOUND(res))
return_value->SetUndefined();
else if (!GET_OK(res))
{
context->ThrowTypeError("Failed to call host getter");
return FALSE;
}
return TRUE;
}
/* static */ BOOL
ES_Host_Object::HostSetter(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
OP_ASSERT(argv[-1].GetObject()->IsFunctionObject());
ES_Function *function_object = static_cast<ES_Function *>(argv[-1].GetObject());
ES_Value_Internal name_value;
function_object->GetCachedAtIndex(ES_PropertyIndex(ES_Function::NAME), name_value);
OP_ASSERT(name_value.IsString());
JString *name = name_value.GetString();
if (!argv[-2].IsObject() || !argv[-2].GetObject(context)->IsHostObject() || argc < 1)
{
context->ThrowTypeError("Failed to call host setter");
return FALSE;
}
ES_Host_Object *this_object = static_cast<ES_Host_Object *>(argv[-2].GetObject(context));
FailedReason reason;
ES_PropertyIndex dummy;
BOOL can_cache = TRUE;
if (this_object->PutInHostL(context, name, argv[0], reason, can_cache, dummy))
return TRUE;
context->ThrowTypeError("Failed to call host setter");
return FALSE;
}
GetResult
ES_Host_Object::GetOwnHostPropertyL(ES_Execution_Context *context, ES_Object *this_object, JString *name, ES_Value_Internal &value, ES_PropertyIndex &index)
{
BOOL allow_cache = !HasVolatilePropertySet();
if (!SecurityCheck(context))
{
context->ThrowReferenceError("Security error: attempted to read protected variable: ", Storage(context, name), Length(name));
return PROP_GET_FAILED;
}
GetResult res = GetOwnPropertyL(context, this_object, this_object, name, value, index);
if (allow_cache)
return res;
else
return GET_CANNOT_CACHE(res);
}
GetResult
ES_Host_Object::GetOwnHostPropertyL(ES_Execution_Context *context, ES_Object *this_object, unsigned index, ES_Value_Internal &value)
{
if (indexed_properties && ES_Indexed_Properties::HasProperty(indexed_properties, index))
{
if (!SecurityCheck(context))
{
context->ThrowReferenceError("Security error: attempted to read protected variable");
return PROP_GET_FAILED;
}
ES_Indexed_Properties::GetL(context, this_object, indexed_properties, index, value, this_object);
return PROP_GET_OK;
}
ES_Value external_value;
ES_Value_Internal tmp_value;
ES_Runtime *runtime = context->GetRuntime();
ES_Value_Internal *restart_object = NULL;
ES_SuspendedHostGetIndex call(host_object, index, &external_value, runtime);
while (context->SuspendedCall(&call), call.state == GET_SUSPEND)
{
OP_ASSERT(external_value.type == VALUE_NULL || external_value.type == VALUE_OBJECT);
if (!restart_object)
restart_object = context->AllocateRegisters(1);
SuspendL(context, restart_object, external_value);
call.is_restarted = TRUE;
call.restart_object = restart_object->IsNull() ? NULL : restart_object->GetObject();
}
if (restart_object)
context->FreeRegisters(1);
OP_ASSERT(call.state != GET_SUSPEND);
GetResult result;
if (GET_OK(result = FinishGet(context, call.state, external_value)))
value.ImportUnlockedL(context, external_value);
context->MaybeYield();
return result;
}
GetResult
ES_Host_Object::GetInOwnHostPropertyL(ES_Execution_Context *context, JString *name, ES_Value_Internal &value)
{
ES_Value external_value;
ES_Value_Internal tmp_value;
ES_Runtime *runtime = context->GetRuntime();
ES_Value_Internal *restart_object = NULL;
ES_SuspendedHostGetName call(host_object, StorageZ(context, name), name->HostCode(), &external_value, runtime);
while (context->SuspendedCall(&call), call.state == GET_SUSPEND)
{
OP_ASSERT(external_value.type == VALUE_NULL || external_value.type == VALUE_OBJECT);
if (!restart_object)
restart_object = context->AllocateRegisters(1);
SuspendL(context, restart_object, external_value);
call.is_restarted = TRUE;
call.restart_object = restart_object->IsNull() ? NULL : restart_object->GetObject();
}
if (restart_object)
context->FreeRegisters(1);
OP_ASSERT(call.state != GET_SUSPEND);
GetResult result;
if (GET_OK(result = FinishGet(context, call.state, external_value)))
value.ImportUnlockedL(context, external_value);
context->MaybeYield();
return result;
}
BOOL
ES_Host_Object::PutInHostL(ES_Execution_Context *context, JString *name, const ES_Value_Internal &value, FailedReason &reason, BOOL &can_cache, ES_PropertyIndex &index)
{
ES_Value external_value;
ES_ValueString external_string;
ES_Runtime *runtime = context->GetRuntime();
value.ExportL(context, external_value);
ES_Value_Internal *restart_object = NULL;
ES_SuspendedHostPutName call(host_object, StorageZ(context, name), name->HostCode(), &external_value, runtime);
while (context->SuspendedCall(&call), call.state == PUT_SUSPEND || call.state >= PUT_NEEDS_STRING && call.state <= PUT_NEEDS_BOOLEAN)
{
if (call.state == PUT_SUSPEND)
{
OP_ASSERT(external_value.type == VALUE_NULL || external_value.type == VALUE_OBJECT);
if (!restart_object)
restart_object = context->AllocateRegisters(1);
SuspendL(context, restart_object, external_value);
call.restart_object = restart_object->IsNull() ? NULL : restart_object->GetObject();
call.is_restarted = TRUE;
value.ExportL(context, external_value);
}
else
{
ES_Value_Internal converted;
if (!ConvertL(context, call.state, value, converted))
return FALSE;
char format;
if (call.state == PUT_NEEDS_STRING_WITH_LENGTH)
format = 'z';
else
format = '-';
converted.ExportL(context, external_value, format, &external_string);
}
}
if (restart_object)
context->FreeRegisters(1);
OP_ASSERT(call.state != PUT_SUSPEND);
BOOL success = FinishPut(context, call.state, reason, can_cache, external_value);
context->MaybeYield();
return success;
}
BOOL
ES_Host_Object::PutInHostL(ES_Execution_Context *context, unsigned index, const ES_Value_Internal &value, FailedReason &reason)
{
ES_Value external_value;
ES_ValueString external_string;
ES_Runtime *runtime = context->GetRuntime();
value.ExportL(context, external_value);
ES_Value_Internal *restart_object = NULL;
ES_SuspendedHostPutIndex call(host_object, index, &external_value, runtime);
while (context->SuspendedCall(&call), call.state == PUT_SUSPEND || call.state >= PUT_NEEDS_STRING && call.state <= PUT_NEEDS_BOOLEAN)
{
if (call.state == PUT_SUSPEND)
{
OP_ASSERT(external_value.type == VALUE_NULL || external_value.type == VALUE_OBJECT);
if (!restart_object)
restart_object = context->AllocateRegisters(1);
SuspendL(context, restart_object, external_value);
call.restart_object = restart_object->IsNull() ? NULL : restart_object->GetObject();
call.is_restarted = TRUE;
value.ExportL(context, external_value);
}
else
{
ES_Value_Internal converted;
if (!ConvertL(context, call.state, value, converted))
return FALSE;
char format;
if (call.state == PUT_NEEDS_STRING_WITH_LENGTH)
format = 'z';
else
format = '-';
converted.ExportL(context, external_value, format, &external_string);
}
}
if (restart_object)
context->FreeRegisters(1);
OP_ASSERT(call.state != PUT_SUSPEND);
BOOL can_cache_unused;
BOOL success = FinishPut(context, call.state, reason, can_cache_unused, external_value);
context->MaybeYield();
return success;
}
BOOL
ES_Host_Object::HasOwnHostProperty(ES_Context *context, JString *name, ES_Property_Info &info, BOOL &is_secure)
{
if (is_secure || (is_secure = IsCrossDomainAccessible() || SecurityCheck(static_cast<ES_Execution_Context *>(context))))
{
ES_Value_Internal_Ref value_ref;
if (GetOwnLocation(name, info, value_ref))
return TRUE;
info.Reset();
info.data.dont_enum = 1;
}
/* Property is not a secure native property.
At this point, 'is_secure' is set to TRUE if the caller considers
the access secure or the above security check passed. 'is_secure'
is FALSE if the security check failed.
Even if FALSE, [[HasProperty]] will be performed on the host object.
If that property is cross-domain accessible, that takes precedence
and must set is_secure to TRUE and allow the access. */
ES_Execution_Context *exec_context = static_cast<ES_Execution_Context *>(context);
ES_SuspendedHostHasPropertyName call(host_object, StorageZ(context, name), name->HostCode(), context->GetRuntime());
while (exec_context->SuspendedCall(&call), call.result == GET_SUSPEND)
{
exec_context->Block();
call.is_restarted = TRUE;
}
if (exec_context->ShouldYield())
{
exec_context->YieldImpl();
exec_context->SuspendedCall(&call);
}
BOOL result = call.result == GET_SUCCESS;
/* If 'result' is TRUE, the corresponding 'is_secure' value allows or denies
the access. If 'result' is FALSE, 'is_secure' determines the security
of performing [[HasProperty]] further along the prototype chain.
Hence updating 'is_result' correctly in light of the host [[HasProperty]]
call matters and must be done carefully.
The 'is_secure' result must be updated iff:
- The host property access was reported as insecure and not
present; set 'is_secure' to FALSE.
- The host property was reported as present, then it is a
cross-domain property; set 'is_secure' to TRUE.
- The host property doesn't exist but the prototype is marked as
having insecure host properties; delegate the security decision
to the prototype by setting 'is_secure' to TRUE. */
if (call.result == GET_SECURITY_VIOLATION)
is_secure = FALSE;
else if (result)
is_secure = TRUE;
else if (!is_secure)
if (ES_Object *prototype = klass->Prototype())
is_secure = prototype->IsCrossDomainHostAccessible();
return result;
}
BOOL
ES_Host_Object::HasOwnHostProperty(ES_Context *context, unsigned index, ES_Property_Info &info, BOOL &is_secure)
{
if (is_secure || (is_secure = IsCrossDomainAccessible() || SecurityCheck(static_cast<ES_Execution_Context *>(context))))
{
if (indexed_properties && ES_Indexed_Properties::HasProperty(indexed_properties, index, info))
return TRUE;
info.Reset();
info.data.dont_enum = 1;
}
ES_SuspendedHostHasPropertyIndex call(host_object, index, context->GetRuntime());
ES_Execution_Context *exec_context = static_cast<ES_Execution_Context *>(context);
while (exec_context->SuspendedCall(&call), call.result == GET_SUSPEND)
{
exec_context->Block();
call.is_restarted = TRUE;
}
if (exec_context->ShouldYield())
{
exec_context->YieldImpl();
exec_context->SuspendedCall(&call);
}
BOOL result = call.result == GET_SUCCESS;
/* See above comment for [[HasProperty]] over property names for explanation. */
if (call.result == GET_SECURITY_VIOLATION)
is_secure = FALSE;
else if (result)
is_secure = TRUE;
else if (!is_secure)
if (ES_Object *prototype = klass->Prototype())
is_secure = prototype->IsCrossDomainHostAccessible();
return call.result;
}
BOOL
ES_Host_Object::SecurityCheck(ES_Context *context)
{
if (host_object->GetRuntime() == context->GetRuntime())
return TRUE;
else if (context->IsUsingStandardStack())
{
return host_object->SecurityCheck(context->GetRuntime());
}
else
{
ES_SuspendedHostSecurityCheck call(host_object, context->GetRuntime());
static_cast<ES_Execution_Context *>(context)->SuspendedCall(&call);
return call.result;
}
}
void
ES_Host_Object::SignalIdentityChange(ES_Object *previous_identity)
{
if (previous_identity && IsProxyInstanceAdded())
{
previous_identity->Class()->RemoveInstance(Class()->GetRootClass());
ClearProxyInstanceAdded();
Class()->Invalidate();
}
}
void
ES_Host_Object::SignalDisableCaches(ES_Object *current_identity)
{
if (current_identity && IsProxyInstanceAdded())
{
current_identity->Class()->RemoveInstance(Class()->GetRootClass());
ClearProxyInstanceAdded();
}
SetProxyCachingDisabled();
Class()->Invalidate();
}
/* host functions */
ES_Host_Function *
ES_Host_Function::Make(ES_Context *context, ES_Global_Object *global_object, EcmaScript_Object* host_object, ES_Object* prototype, const uni_char *function_name, const char* object_class, const char *parameter_types)
{
OP_ASSERT(prototype);
#if 0
OP_ASSERT(prototype->IsPrototypeObject());
#endif
OP_ASSERT(!prototype->HasMultipleIdentities());
ES_Class *klass = ES_Class::MakeRoot(context, prototype, object_class);
ES_CollectorLock gclock(context);
ES_Host_Function *self;
GC_ALLOCATE(context, self, ES_Host_Function, (self, TRUE, klass, parameter_types));
/* FIXME: We would much rather want prototype to be a prototype to begin with. */
if (!prototype->IsPrototypeObject())
prototype->ConvertToPrototypeObject(context, self->klass);
else
prototype->AddInstance(context, self->klass, FALSE);
self->function_name = context->rt_data->GetSharedString(function_name);
self->AllocateProperties(context);
self->host_object = host_object;
return self;
}
/* static */ ES_Host_Function *
ES_Host_Function::Make(ES_Context *context, ES_Global_Object *global_object, void *&payload, unsigned payload_size, ES_Object* prototype, const uni_char *function_name, const char* object_class, const char *parameter_types, BOOL need_destroy, BOOL is_singleton)
{
OP_ASSERT(prototype);
#if 0
OP_ASSERT(prototype->IsPrototypeObject());
#endif
OP_ASSERT(!prototype->HasMultipleIdentities());
ES_Class *klass;
if (is_singleton)
klass = ES_Class::MakeSingleton(context, prototype, object_class);
else
klass = ES_Class::MakeRoot(context, prototype, object_class);
ES_CollectorLock gclock(context);
ES_Host_Function *self;
GC_ALLOCATE_WITH_EXTRA_ALIGNED_PAYLOAD(context, self, payload, payload_size, ES_Host_Function, (self, need_destroy, klass, parameter_types));
/* FIXME: We would much rather want prototype to be a prototype to begin with. */
if (!prototype->IsPrototypeObject())
prototype->ConvertToPrototypeObject(context, self->klass);
else
prototype->AddInstance(context, self->klass, is_singleton);
self->function_name = context->rt_data->GetSharedString(function_name);
self->AllocateProperties(context);
return self;
}
void
ES_Host_Function::Initialize(ES_Host_Function *object, BOOL need_destroy, ES_Class *klass, const char *parameter_types)
{
ES_Host_Object::Initialize(object, need_destroy, klass);
object->ChangeGCTag(GCTAG_ES_Object_Function);
object->function_name = NULL;
object->parameter_types = parameter_types;
object->parameter_types_length = parameter_types ? op_strlen(parameter_types) : 0;
}
/*
There's a lot of code duplication going on in Call and Construct below:
*/
/* static */ BOOL
ES_Host_Function::Call(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
const ES_Value_Internal &host_fn_value = argv[-1];
ES_Value_Internal &this_value = argv[-2];
if (!this_value.ToObject(context, FALSE))
this_value.SetObject(context->GetGlobalObject());
ES_Host_Function *host_fn = static_cast<ES_Host_Function *>(host_fn_value.GetObject(context));
ES_Object *this_object = this_value.IsObject() ? this_value.GetObject() : context->GetGlobalObject();
OP_ASSERT(host_fn->IsHostFunctionObject());
ES_Value *conv_argv;
ES_ValueString *conv_argv_strings;
context->GetHostArguments(conv_argv, conv_argv_strings, argc);
if (!FormatArguments(context, argc, argv, conv_argv, conv_argv_strings, host_fn->parameter_types))
{
context->ReleaseHostArguments();
return FALSE;
}
ES_Value_Internal *restart_object = NULL;
ES_Value retval;
ES_SuspendedHostCall call(host_fn->host_object, this_object, conv_argv, argc, &retval, context->GetRuntime());
while (context->SuspendedCall(&call), (call.result & ES_RESTART) || (call.result & ES_NEEDS_CONVERSION))
{
if (call.result & ES_RESTART)
{
if (!restart_object)
restart_object = context->AllocateRegisters(1);
OP_ASSERT(call.result & ES_SUSPEND); // One without the other makes little sense
SuspendL(context, restart_object, retval);
}
else
{
OP_ASSERT ((call.result & ES_NEEDS_CONVERSION) && (retval.type == VALUE_NUMBER || retval.type == VALUE_STRING));
if (retval.type == VALUE_STRING)
{
// A hack..but allocating a temporary (const char *) here is trouble and somewhat lacking in point.
const char *format = reinterpret_cast<const char *>(retval.value.string);
if (!FormatArguments(context, argc, argv, conv_argv, conv_argv_strings, format))
return FALSE;
call.conversion_restarted = TRUE;
}
else
{
ES_ArgumentConversion convert = static_cast<ES_ArgumentConversion>(static_cast<unsigned>(retval.value.number) & 0xffff);
unsigned arg_number = (static_cast<unsigned>(retval.value.number) >> 16) & 0xffff;
OP_ASSERT(arg_number < argc);
ES_Value_Internal converted;
if (!ConvertL(context, convert, argv[arg_number], converted))
{
context->ReleaseHostArguments();
return FALSE;
}
char format;
if (convert == ES_CALL_NEEDS_STRING_WITH_LENGTH)
format = 'z';
else
format = '-';
converted.ExportL(context, conv_argv[arg_number], format, &conv_argv_strings[arg_number]);
}
call.restarted = FALSE;
}
}
if (restart_object)
context->FreeRegisters(1);
BOOL success = ES_Host_Function::FinishL(context, call.result, retval, return_value, FALSE);
context->ReleaseHostArguments();
context->MaybeYield();
return success;
}
/* static */ BOOL
ES_Host_Function::Construct(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
const ES_Value_Internal &host_fn_value = argv[-1];
ES_Host_Function *host_fn = static_cast<ES_Host_Function *>(host_fn_value.GetObject(context));
OP_ASSERT(host_fn->IsHostFunctionObject());
ES_Value *conv_argv;
ES_ValueString *conv_argv_strings;
context->GetHostArguments(conv_argv, conv_argv_strings, argc);
if (!FormatArguments(context, argc, argv, conv_argv, conv_argv_strings, host_fn->parameter_types))
return FALSE;
ES_Value_Internal *restart_object = NULL;
ES_Value retval;
ES_SuspendedHostConstruct call(host_fn->host_object, conv_argv, argc, &retval, context->GetRuntime());
while (context->SuspendedCall(&call), (call.result & ES_RESTART) || (call.result & ES_NEEDS_CONVERSION))
{
if (call.result & ES_RESTART)
{
if (!restart_object)
restart_object = context->AllocateRegisters(1);
OP_ASSERT(call.result & ES_SUSPEND); // One without the other makes little sense
SuspendL(context, restart_object, retval);
}
else
{
OP_ASSERT ((call.result & ES_NEEDS_CONVERSION) && (retval.type == VALUE_NUMBER || retval.type == VALUE_STRING));
if (retval.type == VALUE_STRING)
{
// A hack..but allocating a temporary (const char *) here is trouble and somewhat lacking in point.
const char *format = reinterpret_cast<const char *>(retval.value.string);
if (!FormatArguments(context, argc, argv, conv_argv, conv_argv_strings, format))
return FALSE;
call.conversion_restarted = TRUE;
}
else
{
ES_ArgumentConversion convert = static_cast<ES_ArgumentConversion>(static_cast<unsigned>(retval.value.number) & 0xffff);
unsigned arg_number = (static_cast<unsigned>(retval.value.number) >> 16) & 0xffff;
OP_ASSERT(arg_number < argc);
ES_Value_Internal converted;
if (!ConvertL(context, convert, argv[arg_number], converted))
{
context->ReleaseHostArguments();
return FALSE;
}
char format;
if (convert == ES_CALL_NEEDS_STRING_WITH_LENGTH)
format = 'z';
else
format = '-';
converted.ExportL(context, conv_argv[arg_number], format, &conv_argv_strings[arg_number]);
}
call.restarted = FALSE;
}
}
if (restart_object)
context->FreeRegisters(1);
BOOL success = ES_Host_Function::FinishL(context, call.result, retval, return_value, TRUE);
context->MaybeYield();
return success;
}
static void
ES_SkipFormatSpecifier(const char *&format)
{
unsigned level = 0;
if (*format == '?')
++format;
if (*format == '#')
{
++format;
while (*format != '|')
{
OP_ASSERT(*format != ')');
++format;
}
}
else
do
{
if (*format == '{' || *format == '[' || *format == '(')
++level;
else if (*format == '}' || *format == ']' || *format == ')')
--level;
++format;
}
while (level > 0);
}
/* static */ BOOL
ES_Host_Function::FormatDictionary(ES_Execution_Context *context, const char *&format, ES_Value_Internal &source)
{
ES_Value_Internal *registers = context->AllocateRegisters(2);
ES_Value_Internal &anchor = registers[0];
ES_Value_Internal &value = registers[1];
ES_Object *object = source.GetObject(context);
ES_Object *dictionary = ES_Object::Make(context, context->GetGlobalObject()->GetEmptyClass());
anchor.SetObject(dictionary);
OP_ASSERT(*format == '{');
do
{
const char *name_start = ++format;
while (*format != ':')
{
OP_ASSERT(*format && *format != '}');
++format;
}
JString *name = context->rt_data->GetSharedString(name_start, format - name_start);
GetResult result = object->GetL(context, name, value);
++format;
if (GET_OK(result))
{
if (!FormatValue(context, format, value))
goto failure;
#ifdef DEBUG_ENABLE_OPASSERT
PutResult result =
#endif // DEBUG_ENABLE_OPASSERT
dictionary->PutL(context, name, value);
/* We allocated an empty object that doesn't even have a prototype;
there's no way we can fail to put properties on it. */
OP_ASSERT(PUT_OK(result));
}
else if (result == PROP_GET_FAILED)
goto failure;
else
ES_SkipFormatSpecifier(format);
OP_ASSERT(*format == ',' || *format == '}');
}
while (*format == ',');
OP_ASSERT(*format == '}');
++format;
source.SetObject(dictionary);
context->FreeRegisters(2);
return TRUE;
failure:
context->FreeRegisters(2);
return FALSE;
}
/* static */ BOOL
ES_Host_Function::FormatArray(ES_Execution_Context *context, const char *&format, ES_Value_Internal &source)
{
ES_Value_Internal *registers = context->AllocateRegisters(2);
ES_Value_Internal &anchor = registers[0];
ES_Value_Internal &value = registers[1];
ES_Object *object = source.GetObject(context);
ES_Object *array = ES_Object::Make(context, context->GetGlobalObject()->GetEmptyClass());
anchor.SetObject(array);
OP_ASSERT(*format == '[');
++format;
GetResult result = object->GetL(context, context->rt_data->idents[ESID_length], value);
if (GET_OK(result))
{
if (!value.ToNumber(context))
goto failure;
unsigned length = value.GetNumAsUInt32(), index;
value.SetUInt32(length);
#ifdef DEBUG_ENABLE_OPASSERT
PutResult result =
#endif // DEBUG_ENABLE_OPASSERT
array->PutL(context, context->rt_data->idents[ESID_length], value);
OP_ASSERT(PUT_OK(result));
ES_Array_Property_Iterator iterator(context, object, length);
while (iterator.Next(index))
{
if (!iterator.GetValue(value))
goto failure;
const char *format_before = format;
if (!FormatValue(context, format, value))
goto failure;
format = format_before;
#ifdef DEBUG_ENABLE_OPASSERT
PutResult result =
#endif // DEBUG_ENABLE_OPASSERT
array->PutL(context, index, value);
OP_ASSERT(PUT_OK(result));
}
}
else if (result == PROP_GET_FAILED)
goto failure;
ES_SkipFormatSpecifier(format);
OP_ASSERT(*format == ']');
++format;
source.SetObject(array);
context->FreeRegisters(2);
return TRUE;
failure:
context->FreeRegisters(2);
return FALSE;
}
/* static */ BOOL
ES_Host_Function::FormatAlternatives(ES_Execution_Context *context, const char *&format, ES_Value_Internal &source, char &export_conversion)
{
OP_ASSERT(*format == '(');
export_conversion = '-';
do
{
++format;
if (*format == '#')
{
const char *name_start = ++format;
while (*format != '|')
{
OP_ASSERT(*format != ')');
++format;
}
if (source.IsObject())
{
unsigned name_length = format - name_start;
const char *object_name = source.GetObject(context)->ObjectName();
if (op_strncmp(object_name, name_start, name_length) == 0 && !object_name[name_length])
break;
}
}
else
{
const char *format_before = format;
ES_SkipFormatSpecifier(format);
if (*format == '|')
{
BOOL matched;
switch (*format_before)
{
case 'b': matched = source.IsBoolean(); break;
case 'n': matched = source.IsNumber(); break;
case 's':
case 'z': matched = source.IsString(); break;
default: OP_ASSERT(FALSE); matched = FALSE;
}
if (matched)
{
export_conversion = *format_before;
break;
}
}
else
{
if (!FormatValue(context, format_before, source))
return FALSE;
export_conversion = *format_before;
break;
}
}
}
while (*format == '|');
while (*format == '|')
{
++format;
ES_SkipFormatSpecifier(format);
}
OP_ASSERT(*format == ')');
++format;
return TRUE;
}
/* static */ BOOL
ES_Host_Function::FormatValue(ES_Execution_Context *context, const char *&format, ES_Value_Internal &source, ES_Value *destination, ES_ValueString *destination_string)
{
BOOL object_optional = *format == '?';
if (object_optional)
{
++format;
if (source.IsNullOrUndefined())
{
ES_SkipFormatSpecifier(format);
if (destination)
if (source.IsNull())
destination->type = VALUE_NULL;
else
destination->type = VALUE_UNDEFINED;
return TRUE;
}
}
if (*format == '{' || *format == '[')
{
if (!source.IsObject())
{
context->ThrowTypeError("object argument expected");
return FALSE;
}
BOOL success;
if (*format == '{')
success = FormatDictionary(context, format, source);
else
success = FormatArray(context, format, source);
if (!success)
return FALSE;
if (destination)
source.ExportL(context, *destination, '-');
}
else if (*format == '(')
{
char export_conversion;
if (!FormatAlternatives(context, format, source, export_conversion))
return FALSE;
if (destination)
source.ExportL(context, *destination, export_conversion, destination_string);
}
else
{
if (*format == 'p' || *format == 'P')
{
if (source.IsObject())
{
ES_Value_Internal::HintType hint;
if (*format == 'p')
hint = ES_Value_Internal::HintNone;
else
{
++format;
OP_ASSERT(*format == 's' || *format == 'n');
if (*format == 's')
hint = ES_Value_Internal::HintString;
else
hint = ES_Value_Internal::HintNumber;
}
if (!source.ToPrimitive(context, hint))
return FALSE;
}
}
else
{
if (!source.ConvertL(context, *format))
return FALSE;
}
if (destination)
source.ExportL(context, *destination, *format, destination_string);
++format;
}
return TRUE;
}
/* static */ BOOL
ES_Host_Function::FormatArguments(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *in_argv, ES_Value *out_argv, ES_ValueString *out_argv_strings, const char *format)
{
if (!format || !*format)
format = "-";
for (unsigned argi = 0; argi < argc; ++argi)
{
const char *format_before = format;
if (!FormatValue(context, format, in_argv[argi], &out_argv[argi], &out_argv_strings[argi]))
return FALSE;
if (!*format)
format = format_before;
}
return TRUE;
}
/* static */ BOOL
ES_Host_Function::FinishL(ES_Execution_Context *context, unsigned result, const ES_Value &external_value, ES_Value_Internal *return_value, BOOL constructing)
{
OP_ASSERT((result & ES_RESTART) ^ ES_RESTART);
OP_ASSERT((result & ES_TOSTRING) == 0); // ES_TOSTRING no longer supported
if (result & ES_VALUE)
{
return_value->ImportUnlockedL(context, external_value);
if (result == ES_VALUE)
return TRUE;
}
else if (result == 0)
{
if (constructing)
{
ES_CollectorLock gclock(context);
context->ThrowTypeError("Object is not a constructor.");
return FALSE;
}
else
{
return_value->SetUndefined();
return TRUE;
}
}
if (result & ES_SUSPEND)
context->YieldExecution();
ES_CollectorLock gclock(context);
if (result & ES_EXCEPTION)
{
context->ThrowValue(external_value);
return FALSE;
}
if (result & ES_VALUE)
return TRUE;
if (result & ES_ABORT)
{
#ifndef SELFTEST
OP_ASSERT(!"Should not happen normally, but not technically an error");
#endif
return TRUE;
}
if (result & ES_NO_MEMORY)
{
context->AbortOutOfMemory();
return FALSE;
}
if (result & ES_EXCEPT_SECURITY)
{
// FIXME: Throw the correct host function security error
context->ThrowReferenceError("Security violation");
return FALSE;
}
// Return undefined. Must always return something.
return_value->SetUndefined();
return TRUE;
}
|
//====================================================================================
// @Title: BATTLE HUD
//------------------------------------------------------------------------------------
// @Location: /game/battle/include/cBattleHud.h
// @Author: Kevin Chen
// @Rights: Copyright(c) 2011 Visionary Games
//------------------------------------------------------------------------------------
// @Description:
//
// The battle HUD presents vital information of a comrade's state of health. This
// class provides both the visual component and the class behaviour and definition.
//
//====================================================================================
#ifndef __GAME_BATTLE_HUD_H__
#define __GAME_BATTLE_HUD_H__
#include "../../../prolix/common/include/cBaseObject.h"
#include "../../../prolix/common/include/cLabel.h"
#include "../../../prolix/common/include/cSprite.h"
#include "../../../prolix/common/include/cTween.h"
#include "../../../prolix/engine/include/PrlxInput.h"
class cBaseObject;
class cCombatant;
class cBattleHudMgr;
static const bool BATTLE_HUD_ALLOW_OVERHEALING = true;
static const bool BATTLE_HUD_ENABLE_SNAPPING = true;
static const float BATTLE_HUD_SNAP_PRECISION = 4.5f;
//====================================================================================
// cBattleHud
//====================================================================================
class cBattleHud : public cBaseObject
{
friend class cBattleHudMgr;
// class for mugshot functions
class cMugshot : public cBaseObject
{
// Consider exposing these states in the DB
enum MugshotState { // ordered by priority (lowest to highest)
NEUTRAL, // unbiased state
/****** Emotional States ******/
HAPPY, // happy guy :)
CONFIDENT, // confident/cocky face
EMBARRASSED, // tsundere confession face
SAD, // very sad :(
AFRAID, // afraid face
WORRIED, // worried/nervous face
ANGRY, // angry face
OUTRAGED, // extremely angry face
/****** Chat States ******/
MUTTERING, // muttering state
SPEAK, // normal talking state
YELL, // yelling state
SCREAM, // screaming state
/****** Event States ******/
HEALED, // heal spell cast on actor
DAMAGED, // damage received
/****** Vital States ******/
BUFFED, // powered up by a buff
AFFLICTED, // afflicted with a negative condition
DANGER, // if in danger of dying
FAINTED // asserted when dead
} mState;
/* if we want to have animated faces as opposed to static ones
*
* cAnimationGroup *mAnimStates;
* std::string mAnimId; // currently playing animation group
*/
cSprite *mSprite;
public:
virtual void Display();
void ChangeState(MugshotState newState);
cMugshot(cTexture *Spritesheet);
~cMugshot();
};
enum VitalType{HEALTH, MANA, MASK};
float mHealthPct;
float mManaPct;
cBaseObject *mHealthBar;
cBaseObject *mManaBar;
cBaseObject *mMask;
void DrawVital(VitalType vitalType, float rotation);
float ApplyGaugeSnap(float val);
float CalculateLieuSpace();
cBattleHudMgr *mBattleHudMgr; // parent battle HUD manager
cCombatant *mCombatant; // the parent combatant (grab info from here)
bool mIsExtended; // if the HUD is the extended version
cMugshot *mMugshot;
cLabel *mHealthLabel;
cLabel *mManaLabel;
public:
// Default constructor
cBattleHud();
// Constructor
cBattleHud(cBattleHudMgr *BattleHudMgr, cCombatant *Combatant, bool IsExtended = false);
virtual void Initialize();
virtual void Display();
void Update();
// Destructor
~cBattleHud();
bool IsExtended() const;
void IsExtended(bool newExtendedState);
};
#endif
|
#pragma once
#include <crtdbg.h>
#include <math.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <string>
#include <fstream>
using namespace std;
const char* fileName = "lena256.raw";
const char* fileName_compressed = "lena256_compressed.raw";
const char* fileName_out = "lena256_decom.raw";
const int HEIGHT = 256;
const int WIDTH = 256;
const int PIXEL_MAX = 255;
class Tree {
public:
Tree() {
count = 0;
index = 0;
left = NULL;
right = NULL;
}
Tree(int _count, int _index) {
count = _count;
index = _index;
}
Tree(int _count, int _index, Tree* _left, Tree* _right) {
count = _count;
index = _index;
left = _left;
right = _right;
}
int count;
int index;
Tree* left;
Tree* right;
};
bool compareModel(const Tree& left, const Tree& right) {
return left.count < right.count;
}
void fileRead(const char* filename, unsigned char arr[][WIDTH], int height, int width)
{
FILE* fp = fopen(filename, "rb");
for (int h = 0; h < height; h++)
{
fread(arr[h], sizeof(unsigned char), width, fp);
}
fclose(fp);
}
void fileWrite(const char* filename, unsigned char* arr, int width)
{
FILE* fp_out = fopen(filename, "wb");
fwrite(arr, sizeof(unsigned char), width, fp_out);
fclose(fp_out);
}
void fileWrite(const char* filename, unsigned char** arr, int height, int width)
{
FILE* fp_out = fopen(filename, "wb");
for (int h = 0; h < height; h++)
{
fwrite(arr[h], sizeof(unsigned char), width, fp_out);
}
fclose(fp_out);
}
void treeToTable(map<int, string>* mappingTable, map<string, int>* demappingTable, Tree* head, string bit) {
if (head == NULL)
return;
if (head->index > 0) {
(*mappingTable)[head->index] = bit;
(*demappingTable)[bit] = head->index;
}
treeToTable(mappingTable, demappingTable, head->left, bit + '0');
treeToTable(mappingTable, demappingTable, head->right, bit + '1');
}
void makeMappingTable(vector<Tree> hist, map<int, string>* mappingTable, map<string, int>* demappingTable) {
Tree* head = NULL;
//make tree
while (true) {
Tree* left = new Tree(hist.front());
hist.erase(hist.begin());
Tree* right = new Tree(hist.front());
hist.erase(hist.begin());
Tree* parentTree = new Tree();
parentTree->count = left->count + right->count;
parentTree->index = -1;
parentTree->left = left;
parentTree->right = right;
if (hist.size() == 0) {
head = parentTree;
break;
}
else {
hist.push_back(*parentTree);
sort(hist.begin(), hist.end(), compareModel);
}
}
treeToTable(mappingTable,demappingTable, head, "");
}
string compress(unsigned char img[][WIDTH], map<int, string>* mappingTable) {
string compressedImage = "";
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
compressedImage += (*mappingTable)[img[i][j]];
}
}
return compressedImage;
}
void decompress(unsigned char** img_decom, string compressedImage, map<string, int>* demappingTable) {
int bitIndex = 0;
string currentBit = "";
for (int h = 0; h < HEIGHT; h++) {
for (int w = 0; w < WIDTH; w++) {
//find by key
while (true) {
currentBit += compressedImage[bitIndex++];
if ((*demappingTable).count(currentBit) == 1) {
img_decom[h][w] = (*demappingTable)[currentBit];
currentBit = "";
break;
}
if (bitIndex >= compressedImage.size())
return;
}
}
}
}
int main() {
unsigned char img[HEIGHT][WIDTH];
vector<Tree> hist;
cout << "file read" << endl;
fileRead(fileName, img, HEIGHT, WIDTH);
for (int i = 0; i <= PIXEL_MAX; i++) {
Tree newModel(0,i,NULL,NULL);
hist.push_back(newModel);
}
cout << "counting histogram of pixels" << endl;
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
hist[img[i][j]].count++;
}
}
sort(hist.begin(), hist.end(), compareModel);
while (hist.front().count == 0) {
hist.erase(hist.begin());
}
map<int, string>* mappingTable = new map<int,string>;
map<string, int>* demappingTable = new map<string, int>;
cout << "making mapping & demapping Table" << endl;
makeMappingTable(hist,mappingTable, demappingTable);
cout << "compressiong" << endl;
string compressedImage = compress(img, mappingTable);
//compressed string을 비트단위로 저장하기 위한 절차.
const int compressedBitSize = compressedImage.size() / 8;
unsigned char* compressedBit = new unsigned char[compressedBitSize];
memset(compressedBit, 0, compressedBitSize);
unsigned char c = 0;
int bitIndex = 0;
int cIndex = 0;
for (int i = 0; i < compressedImage.size(); i++) {
c += (((int)compressedImage[i] - 48) << (7 - cIndex));
cIndex++;
if (cIndex >=8 || i == compressedImage.size() - 1) {
compressedBit[bitIndex] = c;
c = 0;
cIndex = 0;
bitIndex++;
}
}
fileWrite(fileName_compressed, compressedBit, compressedBitSize);
//비트단위로 저장했던 compressed string을 다시 string으로만든다.
compressedImage = "";
for (int i = 0; i < compressedBitSize; i++) {
for (int j = 0; j < 8; j++) {
if ((compressedBit[i] / (1 << (7 - j)) == 1)) {
compressedImage += '1';
compressedBit[i] -= (1 << (7 - j));
}
else {
compressedImage += '0';
}
}
}
unsigned char** img_decom;
img_decom = new unsigned char*[HEIGHT];
for (int i = 0; i < HEIGHT; i++) {
img_decom[i] = new unsigned char[WIDTH];
memset(img_decom[i], 0, sizeof(unsigned char) * WIDTH);
}
cout << "decompressing" << endl;
decompress(img_decom, compressedImage, demappingTable);
cout << "writing decompressed file" << endl;
fileWrite(fileName_out, img_decom, HEIGHT, WIDTH);
return 0;
}
|
#include<cstdio>
using namespace std;
int main(){
//input
int a_capacity,b_capacity;
fscanf(stdin,"%d %d\n",&a_capacity,&b_capacity);
int n;
fscanf(stdin,"%d",&n);
int a_shout[n+5];
int b_shout[n+5];
int a_sum[n+5];
int b_sum[n+5];
for(int i=0;i<n;++i){
fscanf(stdin,"%d %d %d %d",&a_shout[i],&a_sum[i],&b_shout[i],&b_sum[i]);
}
//deal with
int a_can_drink = a_capacity;
int b_can_drink = b_capacity;
for(int i=0;i<n;++i){
int temp = a_shout[i] + b_shout[i];
if(a_sum[i]==temp&&b_sum[i]!=temp){
--a_can_drink;
}else if(a_sum[i]!=temp&&b_sum[i]==temp){
--b_can_drink;
}else{
continue;
}
if(a_can_drink<0){
printf("A\n");
printf("%d",b_capacity-b_can_drink);
return 0;
}else if(b_can_drink<0){
printf("B\n");
printf("%d",a_capacity-a_can_drink);
return 0;
}
}
}
|
// Ed Callaghan
// Early waveform studies
// April 2016
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include "argParse.h"
#include <TAxis.h>
#include <TF1.h>
#include <TFile.h>
#include <TGraph.h>
#include <TTree.h>
#include <TProfile.h>
using namespace std ;
int wformA(char *fname, char *oname) ;
int main(int argc, char **argv)
{
char *fname ;
char *oname ;
if (cmdOptionExists(argv, argv+argc, "-i"))
fname = getCmdOption(argv, argv+argc, "-i") ;
else
{
fprintf(stderr, "err: supply -i filename -o outname\n") ;
return 1 ;
}
if (cmdOptionExists(argv, argv+argc, "-o"))
oname = getCmdOption(argv, argv+argc, "-o") ;
else
oname = "trends.root" ;
wformA(fname, oname) ;
return 0 ;
}
int wformA(char *fname, char *oname)
{
const int nch = 8 ;
// TFile *fin = new TFile("../tier1_cathode_pulser_while_filling_2016-03-07_11-11-38.root") ;
TFile *fin = new TFile(fname) ;
TTree *tCh[nch] ;
char tname[15] ;
for (int ich = 0 ; ich < nch ; ich++)
{
sprintf(tname, "tree%d", ich) ;
tCh[ich] = (TTree *) fin->Get(tname) ;
}
bool sameEntries = true ;
int nEntries = tCh[0]->GetEntries() ;
for (int ich = 1 ; ich < nch ; ich++)
if (tCh[ich]->GetEntries() != nEntries)
sameEntries = false ;
if (!sameEntries)
{
fprintf(stderr, "err: channel trees not of same length\n") ;
return 1 ;
}
/* if (tCh[ich]->GetEntries() < nEntries)
{
fprintf(stderr, "err: channel trees not of same length\n") ;
nEntries = tCh[ich]->GetEntries() ;
} */
TTree *runtree = (TTree *) fin->Get("run_tree") ;
unsigned int wfmLength ; // Rtypes.h
runtree->SetBranchAddress("wfm_length", &wfmLength) ;
runtree->GetEntry(0) ;
cout << "Waveform length: " << wfmLength << '\n' ;
unsigned short *wfm = new unsigned short [wfmLength] ;
for (int ich = 0 ; ich < nch ; ich++)
tCh[ich]->SetBranchAddress("wfm", wfm) ;
TGraph *gWfm[nch] ;
TGraph *gTrend[nch] ;
TProfile *hTrend[nch] ;
char hname[15] ;
char htitle[50] ;
for (int ich = 0 ; ich < nch ; ich++)
{
gWfm[ich] = new TGraph() ;
gTrend[ich] = new TGraph() ;
sprintf(hname, "hTrend_%d", ich) ;
sprintf(htitle, "Y'/Y Channel %d", ich) ;
hTrend[ich] = new TProfile(hname, htitle, 100, 0.0, wfmLength) ;
}
TF1 *lfit = new TF1("lfit", "[0] + [1]*x") ;
const int fitlength = 50 ;
double scale = 1.0e9 ;
double x, y ;
int iqt ;
for (int ich = 0 ; ich < nch ; ich++) {
cout << "Processing channel " << ich << "...\n" ;
iqt = 0 ;
for (int iEntry = 0 ; iEntry < nEntries ; iEntry++)
{
tCh[ich]->GetEntry(iEntry) ;
for (int ipt = 0 ; ipt < wfmLength ; ipt++)
gWfm[ich]->SetPoint(ipt, ipt, wfm[ipt]) ;
for (int ipt = fitlength/2 ; ipt < wfmLength - fitlength/2 ; ipt += fitlength/4)
{
gWfm[ich]->GetPoint(ipt, x, y) ;
if (y < 9.0e3)
continue ;
lfit->SetRange(ipt - fitlength/2, ipt + fitlength/2) ;
gWfm[ich]->Fit(lfit, "RQ") ;
gTrend[ich]->SetPoint(iqt, ipt, scale*lfit->GetParameter(1)/y) ;
iqt++ ;
hTrend[ich]->Fill(ipt, scale*lfit->GetParameter(1)/y) ;
}
} }
TFile *fout = new TFile(oname, "RECREATE") ;
char name[50] ;
for (int ich = 0 ; ich < nch ; ich++)
{
sprintf(name, "Y'/Y Channel %d", ich) ;
gTrend[ich]->SetTitle(name) ;
gTrend[ich]->GetXaxis()->SetTitle("sample number") ;
gTrend[ich]->GetYaxis()->SetTitle("Y'/Y") ;
sprintf(name, "gTrend_%d", ich) ;
gTrend[ich]->SetName(name) ;
gTrend[ich]->Write() ;
hTrend[ich]->GetXaxis()->SetTitle("sample number") ;
hTrend[ich]->GetYaxis()->SetTitle("Y'/Y") ;
hTrend[ich]->Write() ;
}
delete fout ;
delete[] wfm ;
for (int ich = 0 ; ich < nch ; ich++)
{
delete gWfm[ich] ;
delete gTrend[ich] ;
delete hTrend[ich] ;
delete tCh[ich] ;
}
delete fin ;
return 0 ;
}
|
#include <iostream>
#include <queue>
#include <deque>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <set>
#include <map>
#include <math.h>
#include <string.h>
#include <bitset>
#include <cmath>
using namespace std;
int solution(vector<int> money)
{
int answer = 0;
int N = money.size();
int dp[1000001][2];
dp[0][0] = money[0];
dp[0][1] = 0;
dp[1][0] = money[1];
dp[1][1] = money[0];
for (int i = 2; i < N - 1; i++)
{
dp[i][0] = dp[i - 1][1] + money[i];
dp[i][1] = max(dp[i - 1][0], dp[i - 1][1]);
}
answer = max(dp[N - 2][0], dp[N - 2][1]);
dp[1][0] = money[1];
dp[1][1] = 0;
dp[2][0] = money[2];
dp[2][1] = money[1];
for (int i = 3; i < N; i++)
{
dp[i][0] = dp[i - 1][1] + money[i];
dp[i][1] = max(dp[i - 1][0], dp[i - 1][1]);
}
answer = max(answer, dp[N - 1][0]);
answer = max(answer, dp[N - 1][1]);
return answer;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
vector<int> a = {20, 21, 2};
cout << " ,,," << endl;
cout << solution(a) << endl;
return 0;
}
|
#define HAS_NRFS
#ifndef __USE_FILE_OFFSET64
#define __USE_FILE_OFFSET64
#endif
#include "mpi.h"
#ifdef HAS_NRFS
#include "nrfs.h"
#endif
#ifdef HAS_CEPH
#include <cephfs/libcephfs.h>
#endif
#ifdef HAS_GLFS
#include "api/glfs.h"
#include "api/glfs-handles.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFFER_SIZE 0x10000
#define WR_NUM (100)
int myid;
int numprocs;
#ifdef HAS_NRFS
nrfs fs;
#endif
#ifdef HAS_GLFS
glfs_t *fs;
glfs_fd_t *fd;
#endif
#ifdef HAS_CEPH
struct ceph_mount_info *fs;
int fd;
#endif
char buf[BUFFER_SIZE];
int collect_time(int cost)
{
int i;
char message[8];
MPI_Status status;
int *p = (int*)message;
int max = cost;
for(i = 1; i < numprocs; i++)
{
MPI_Recv(message, 8, MPI_CHAR, i, 99, MPI_COMM_WORLD, &status);
if(*p > max)
max = *p;
}
return max;
}
int locktest()
{
char path[255];
int i;
double start, end;
int time_cost;
char message[8];
int *p = (int*)message;
sprintf(path, "/file_%d", 0);
if(myid == 0)
{
#ifdef HAS_NRFS
nrfsOpenFile(fs, path, O_CREAT);
#endif
}
#ifdef HAS_CEPH
fd= ceph_open(fs, path, O_CREAT|O_RDWR,0777);
#endif
#ifdef HAS_GLFS
fd = glfs_creat (fs, path, O_RDWR, 0644);
#endif
MPI_Barrier ( MPI_COMM_WORLD );
start = MPI_Wtime();
for(i = 0; i < WR_NUM; i++)
{
#ifdef HAS_NRFS
//nrfsWrite(fs, path, buf, size, 0);
for(i = 0; i < 1000; i++)
nrfsRawRPC(fs);
#endif
#ifdef HAS_CEPH
ceph_write(fs, fd, buf, size, size * i);
ceph_fsync(fs, fd, 1);
#endif
#ifdef HAS_GLFS
glfs_write(fd, buf, size, size * i);
glfs_fdatasync(fd);
#endif
}
end = MPI_Wtime();
MPI_Barrier ( MPI_COMM_WORLD );
*p = (int)((end - start) * 1000000);
if(myid != 0)
{
MPI_Send(message, 8, MPI_CHAR, 0, 99, MPI_COMM_WORLD);
}
else
{
time_cost = collect_time(*p);
printf("write time cost: %d us\n", time_cost);
}
MPI_Barrier ( MPI_COMM_WORLD );
// start = MPI_Wtime();
// for(i = 0; i < WR_NUM; i++)
// {
// #ifdef HAS_NRFS
// nrfsRead(fs, path, buf, size, 0);
// #endif
// #ifdef HAS_CEPH
// ceph_read(fs, fd, buf, size, size * i);
// //ceph_fsync(fs, fd, 1);
// #endif
// #ifdef HAS_GLFS
// glfs_read(fd, buf, size, size * i);
// #endif
// }
// end = MPI_Wtime();
// MPI_Barrier ( MPI_COMM_WORLD );
// *p = (int)((end - start) * 1000000);
// if(myid != 0)
// {
// MPI_Send(message, 8, MPI_CHAR, 0, 99, MPI_COMM_WORLD);
// }
// else
// {
// time_cost = collect_time(*p);
// printf("read time cost: %d us\n", time_cost);
// }
return 0;
}
int main(int argc, char **argv)
{
#ifdef HAS_GLFS
if(argc < 3)
{
fprintf(stderr, "Usage: ./locktest [vol] [host]\n");
return -1;
}
#endif
MPI_Init( &argc, &argv);
MPI_Comm_rank( MPI_COMM_WORLD, &myid );
MPI_Comm_size( MPI_COMM_WORLD, &numprocs );
MPI_Barrier ( MPI_COMM_WORLD );
/* nrfs connection */
#ifdef HAS_NRFS
fs = nrfsConnect("default", 0, 0);
#endif
#ifdef HAS_CEPH
ret = ceph_create(&fs, NULL);
if(ret)
{
fprintf(stderr, "ceph_create=%d\n", ret);
exit(1);
}
printf("ceph create successful\n");
ret = ceph_conf_read_file(fs, "/etc/ceph/ceph.conf");
if(ret)
{
fprintf(stderr, "ceph_conf_read_file=%d\n", ret);
exit(1);
}
printf("ceph read config successful\n");
ret = ceph_mount(fs, NULL);
if (ret)
{
fprintf(stderr, "ceph_mount=%d\n", ret);
exit(1);
}
printf("ceph mount successful\n");
ret = ceph_chdir(fs, "/");
if (ret)
{
fprintf(stderr, "ceph_chdir=%d\n", ret);
exit(1);
}
#endif
#ifdef HAS_GLFS
fs = glfs_new (argv[1]);
if (!fs) {
fprintf (stderr, "glfs_new: returned NULL\n");
return 1;
}
ret = glfs_set_volfile_server (fs, "rdma", argv[2], 24007);
ret = glfs_set_logging (fs, "/dev/stderr", 1);
ret = glfs_init (fs);
fprintf (stderr, "glfs_init: returned %d\n", ret);
#endif
MPI_Barrier ( MPI_COMM_WORLD );
locktest();
MPI_Barrier ( MPI_COMM_WORLD );
#ifdef HAS_NRFS
nrfsDisconnect(fs);
#endif
#ifdef HAS_CEPH
ceph_unmount(fs);
ceph_release(fs);
#endif
#ifdef HAS_GLFS
glfs_fini (fs);
#endif
MPI_Finalize();
}
|
#ifndef CONTINUOUS_TIME_UTILITIES_H
#define CONTINUOUS_TIME_UTILITIES_H
#include <vector>
#include <list>
#include <cassert>
#include <iostream>
#include "rpoly.h"
struct Interval
{
Interval(double s, double e): m_s(s), m_e(e) {assert(m_s <= m_e);}
double m_s, m_e;
bool operator<(const Interval &other) const {return m_s < other.m_s;}
};
bool overlap(const Interval &a, const Interval &b);
Interval Iunion(const Interval &a, const Interval &b);
Interval Iintersect(const Interval &a, const Interval &b);
class Intervals
{
public:
Intervals(const std::vector<Interval> &intervals);
double findNextSatTime(double t);
friend Intervals intersect(const Intervals &i1, const Intervals &i2);
friend std::ostream& operator<<(std::ostream &os, const Intervals &inter);
private:
std::list<Interval> m_intervals;
void consolidateIntervals();
};
Intervals intersect(const Intervals &i1, const Intervals &i2);
std::ostream &operator<<(std::ostream &os, const Intervals &inter);
class Polynomial
{
public:
Polynomial(const std::vector<double> &coeffs);
double evaluate(double t) const ;
const std::vector<double> &getCoeffs() const {return m_coeffs;}
private:
std::vector<double> m_coeffs;
};
class PolynomialIntervalSolver
{
public:
static double findFirstIntersectionTime(const std::vector<Polynomial> &polys);
static void writePolynomials(std::ostream & os);
static void readPolynomials(std::vector<Polynomial> & polynomials, std::istream & is);
static std::vector<Polynomial> & getPolynomials() { return s_polynomials; }
static void clearPolynomials() { s_polynomials.clear(); }
private:
static Intervals findPolyIntervals(const Polynomial &poly);
static RootFinder rf;
private:
static std::vector<Polynomial> s_polynomials;
};
#endif
|
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
ofstream ansFile; //Have to define globally to be able to use inside display function and main()
void displayAnswer(vector<int> answer, int tcase){
ansFile<<"Case #"<<(tcase+1)<<": ";
for(int i = 0; i < answer.size(); i++){
ansFile<<answer.at(i)<<" ";
}
ansFile<<endl;
}
int checkSatisfy(vector<int> customerX, vector<int> customerY, vector<int> answer){ // customerX takes flavor, customerY takes malted or unmalted
// cout<<"Inside Function.";
// cin.ignore();
for(int i = 0; i< customerX.size(); i++){
// cout<<"In for loop iteration no : "<<i;
// cin.ignore();
// cout<<"\nIn iteration : "<<i<<" Value of Y : "<<customerY.at(i)<<" Value at answer : "<<answer.at(customerX.at(i) - 1);
if((customerY.at(i) == 0) && (answer.at(customerX.at(i) - 1) == 0)) // if value is unmalted and the value of the same flavor(Told by customerX) at answer is +ve (unmalted)
return 0; //This customer is Satisfied.
else if((customerY.at(i) == 1) && (answer.at(customerX.at(i) - 1) == 1)) // Malted satisfibility.
return 0;
// cout<<"\nThis iteration not satisfied!\n";
}
// cout<<"Returning -1\n";
return -1; //unSatisfied
}
int milk()
{
ansFile.open("myAnswerLarge.txt", ios::app);
ifstream input;
//ofstream op;
input.open("B-large-practice.in", ios::in);
//op.open("Test.vs", ios::out);
int C, i = 0, N, M, T, j = 0, k = 0,testCase = 0;
int Impossible = 0; //Just used to stop printing answer in case of impossible.
input>>C; // C contains the Number of Test Cases.
//op<<"Number of test cases are : "<<C<<endl;
while(C > testCase) // Runs per test case.
{
// cout<<"\n\nTest number : "<<testCase<<"\n\n";
vector <vector<int> > X, Y;
vector <int> noFlavor; //Number of flavours a customer likes
// X is the vector of vector having the list of milkshake types and
// Y is the vector of vector of unmalted (0) or malted (1) corresponding to X.
input>>N;
// N is Total number of Milkshake flavors.
// op<<"Total number of flavors in "<<testCase<<" Case : "<<N<<endl;
input>>M;
// M takes the number of Customers in a Test Case.
// op<<"\n-----\nNumber of Customers : "<<M<<endl;
while(M > j){ // Runs for each customer in a single test case.
vector<int> tempX,tempY;
input>>T;
// op<<"\nNo. of Milkshake Types "<<j<<" Likes : "<<T<<endl<<"Type: | Malted?\n";
noFlavor.push_back(T);
// T takes number of Milkshake Types a customer likes.
while(T > k){ // Runs for a single customer, to fetch his likes.
int temp;
input>>temp;
// op<<temp;
tempX.push_back(temp); // Fill in Milkshake Type
input>>temp;
// op<<" "<<temp<<endl;
tempY.push_back(temp); // Fill in Malted (1) or unMalted (0)
k++;
}
X.push_back(tempX); // Fills in the vector of a single customer.
Y.push_back(tempY);
k = 0;
j++;
}
vector<int> answer; //3 means Type 3 is unmalted and -3 means it is malted.
for(int i = 0; i < N; i++) // Initializes all as unmalted.
{
answer.push_back(0);
}
int weight = 0, satisfy,foundAt;
vector<int> satisfied;
vector<int>::iterator findMalt,findSatisfy;
i = 0;
while(i<M){
// cout<<"Entered While for customer number : "<<i;
// cin.ignore();
findSatisfy = find(satisfied.begin(),satisfied.end(),i); // Check the satisfied list.
// cout<<"Entered Check for Satisfy.";
// cin.ignore();
if (findSatisfy == satisfied.end()){ //If the customer is not in satisfied list.
// cout<<"Customer is not in Satisfied list yet.";
// cin.ignore();
satisfy = checkSatisfy(X.at(i), Y.at(i), answer); // Check if he is satisfied with present answer.
// cout<<"Successfully Executed Function!";
// cin.ignore();
if (satisfy == 0){
i++;
// cout<<"Passed Check for Satisfaction.";
// cin.ignore();
continue; //Skips the rest of this iteration
}
// cout<<"Failed Satisfaction... Finding Malt.";
// cin.ignore();
findMalt = find(Y.at(i).begin(),Y.at(i).end(),1); // Only accessed if customer is not satisfied. Checks if he has a Malted flavor in his liking.
if (findMalt != Y.at(i).end()){ // If found a Malted.
foundAt = (findMalt - Y.at(i).begin()); // Location in Y vector,
// cout<<"Malt found at : "<<foundAt;
// cin.ignore();
answer.at(X.at(i).at(foundAt) - 1) = 1; // X.at(foundAt) tells the flavor number of the found Malted favorite
//and this statement change our answer to malted for that flavor.
// cout<<"Changed Answer\n";
// displayAnswer(answer);
satisfied.push_back(i); // Add him to satisfied list
i = 0; //Now back validate every customer.
}
else if (findMalt == Y.at(i).end()){ // No malted flavor found.
ansFile<<"Case #"<<(testCase+1)<<": IMPOSSIBLE ";
ansFile<<endl;
Impossible = -1;
i = M; //To exit Loop.
}
}
else{ //If customer is already in Satisfied list, i.e. - He caused a change to Malted.
i++;
}
}
if(Impossible == 0){
displayAnswer(answer,testCase);
}
//Reset for next iteration and increment.
Impossible = 0;
j = 0;
testCase++;
}
ansFile.close();
return 0;
}
|
#pragma once
#include "neighbor.h"
class BoneMapTreeNode
{
public:
BoneMapTreeNode();
~BoneMapTreeNode();
public:
int depth;
std::vector<BoneMapTreeNode*> children;
BoneMapTreeNode *parent;
public:
int indexOfMesh;
// leaf node
std::map<int,int> boneMeshIdxMap;
};
class BoneMapTree
{
public:
BoneMapTree(void);
~BoneMapTree(void);
void constructTree();
public:
BoneMapTreeNode *m_root;
std::vector<BoneMapTreeNode*> leaves;
public:
std::vector<bone*>* sortedBone;
std::vector<arrayInt>* boneAroundBone;
std::vector<Vec2i>* neighborPair;
int nbCenterBone;
private:
void constructTree(BoneMapTreeNode *node);
int *mark;
int findIdx(std::vector<bone*>* v, bone* e);
void boneMeshIdxMapRecur(BoneMapTreeNode * node, std::map<int,int>* boneMeshIdxMap);
};
|
template<typename T> struct hungarian {
int n, m;
vector<vector<T>> a;
vector<T> u, v;
vector<int> p, way;
T inf;
hungarian(int n_, int m_) : n(n_), m(m_), u(m+1), v(m+1), p(m+1), way(m+1) {
a = vector<vector<T>>(n, vector<T>(m));
inf = numeric_limits<T>::max();
}
pair<T, vector<int>> assignment() {
for (int i = 1; i <= n; i++) {
p[0] = i;
int j0 = 0;
vector<T> minv(m+1, inf);
vector<int> used(m+1, 0);
do {
used[j0] = true;
int i0 = p[j0], j1 = -1;
T delta = inf;
for (int j = 1; j <= m; j++) if (!used[j]) {
T cur = a[i0-1][j-1] - u[i0] - v[j];
if (cur < minv[j]) minv[j] = cur, way[j] = j0;
if (minv[j] < delta) delta = minv[j], j1 = j;
}
for (int j = 0; j <= m; j++)
if (used[j]) u[p[j]] += delta, v[j] -= delta;
else minv[j] -= delta;
j0 = j1;
} while (p[j0] != 0);
do {
int j1 = way[j0];
p[j0] = p[j1];
j0 = j1;
} while (j0);
}
vector<int> ans(m);
for (int j = 1; j <= n; j++) ans[p[j]-1] = j-1;
return make_pair(-v[0], ans);
}
};
|
#include "stdafx.h"
#include "TestBase.h"
#include "TestError.h"
TestError::TestError(TestBase *testBase, const string& msg)
:
m_testBase(testBase),
m_errorMsg(msg)
{
m_testName = testBase->GetCurrentTest();
}
string TestError::ToString()
{
string msg = string("Error in test ") + m_testName + string(" : ") + m_errorMsg;
return msg;
}
|
/*************************************************************************
> File Name: mytime1.h
> Author: JY.ZH
> Mail: xw2016@mail.ustc.edu.cn
> Created Time: 2018年07月19日 星期四 19时00分26秒
************************************************************************/
#ifndef MYTIME0_H_
#define MYTIME0_H_
class Time
{
private:
int hours;
int minutes;
public:
Time();
Time(int h, int m = 0);
void AddMin(int m);
void AddHr(int h);
void Reset(int h = 0, int m = 0);
Time operator+(const Time & t) const;
Time operator-(const Time & t) const;
Time operator*(double n) const;
void Show() const;
};
#endif
|
// ----------------------------------------------------------------------------
// nexus | PmtR11410.cc
//
// Geometry of the Hamamatsu R11410 photomultiplier.
//
// The NEXT Collaboration
// ----------------------------------------------------------------------------
#include "PmtR11410.h"
#include "MaterialsList.h"
#include "OpticalMaterialProperties.h"
#include "PmtSD.h"
#include "CylinderPointSampler.h"
#include "Visibilities.h"
#include <G4LogicalVolume.hh>
#include <G4PVPlacement.hh>
#include <G4UnionSolid.hh>
#include <G4Tubs.hh>
#include <G4Material.hh>
#include <G4NistManager.hh>
#include <G4LogicalSkinSurface.hh>
#include <G4SDManager.hh>
#include <G4NistManager.hh>
#include <G4VisAttributes.hh>
#include <Randomize.hh>
#include <G4OpticalSurface.hh>
#include <G4GenericMessenger.hh>
#include <CLHEP/Units/SystemOfUnits.h>
using namespace CLHEP;
PmtR11410::PmtR11410():
BaseGeometry(),
// Dimensions
front_body_diam_ (76. * mm),
front_body_length_ (38. * mm),
rear_body_diam_ (53. * mm),
rear_body_length_ (76. * mm),
body_thickness_ (.5 * mm), // To be checked
window_thickness_ (2. * mm),
photocathode_diam_ (64. * mm),
photocathode_thickness_ (.1 * mm),
visibility_(1),
sd_depth_(-1),
binning_(100.*nanosecond)
{
msg_ = new G4GenericMessenger(this, "/Geometry/PmtR11410/",
"Control commands of PmtR11410 geometry.");
msg_->DeclareProperty("visibility", visibility_, "Hamamatsu R11410 PMTs visibility");
G4GenericMessenger::Command& bin_cmd =
msg_->DeclareProperty("time_binning", binning_,
"Time binning of R11410 PMT");
bin_cmd.SetUnitCategory("Time");
bin_cmd.SetParameterName("time_binning", false);
bin_cmd.SetRange("time_binning>0.");
}
void PmtR11410::Construct()
{
// PMT BODY //////////////////////////////////////////////////////
G4Tubs* front_body_solid =
new G4Tubs("FRONT_BODY", 0., front_body_diam_/2., front_body_length_/2.,
0., twopi);
G4Tubs* rear_body_solid =
new G4Tubs("REAR_BODY", 0., rear_body_diam_/2., rear_body_length_/2.,
0., twopi);
// Union of the two volumes of the phototube body
G4double z_transl = -front_body_length_/2. - rear_body_length_/2.;
G4ThreeVector transl(0., 0., z_transl);
G4UnionSolid* pmt_solid =
new G4UnionSolid("PMT_R11410",front_body_solid,rear_body_solid,0,transl);
G4Material* Kovar = MaterialsList::Kovar();
G4LogicalVolume* pmt_logic =
new G4LogicalVolume(pmt_solid, Kovar, "PMT_R11410");
this->SetLogicalVolume(pmt_logic);
// PMT GAS //////////////////////////////////////////////////////
G4double front_body_gas_diam = front_body_diam_ - 2. * body_thickness_;
G4double front_body_gas_length = front_body_length_ - body_thickness_;
G4Tubs* front_body_gas_solid =
new G4Tubs("FRONT_BODY_GAS", 0., front_body_gas_diam/2., front_body_gas_length/2., 0., twopi);
G4double rear_body_gas_diam = rear_body_diam_ - 2. * body_thickness_;
G4double rear_body_gas_length = rear_body_length_;
G4Tubs* rear_body_gas_solid =
new G4Tubs("REAR_BODY_GAS", 0., rear_body_gas_diam/2., rear_body_gas_length/2., 0., twopi);
// Union of the two volumes of the phototube body gas
G4double z_gas_transl = -front_body_gas_length/2. - rear_body_gas_length/2.;
G4ThreeVector gas_transl(0., 0., z_gas_transl);
G4UnionSolid* pmt_gas_solid = new G4UnionSolid("PMT_GAS", front_body_gas_solid,
rear_body_gas_solid, 0, gas_transl);
G4Material* pmt_gas_mat = G4NistManager::Instance()->FindOrBuildMaterial("G4_Galactic");
G4LogicalVolume* pmt_gas_logic = new G4LogicalVolume(pmt_gas_solid, pmt_gas_mat, "PMT_GAS");
G4double pmt_gas_posz = body_thickness_/2.;
new G4PVPlacement(0, G4ThreeVector(0., 0., pmt_gas_posz), pmt_gas_logic,
"PMT_GAS", pmt_logic, false, 0);
// PMT WINDOW ////////////////////////////////////////////////////
window_diam_ = front_body_gas_diam;
G4Tubs* window_solid =
new G4Tubs("PMT_WINDOW", 0, window_diam_/2., window_thickness_/2., 0., twopi);
G4Material* silica = MaterialsList::FusedSilica();
silica->SetMaterialPropertiesTable(OpticalMaterialProperties::FusedSilica());
G4LogicalVolume* window_logic = new G4LogicalVolume(window_solid, silica, "PMT_WINDOW");
G4double window_posz = front_body_gas_length/2. - window_thickness_/2.;
new G4PVPlacement(0, G4ThreeVector(0.,0.,window_posz), window_logic,
"PMT_WINDOW", pmt_gas_logic, false, 0);
// PMT PHOTOCATHODE /////////////////////////////////////////////
G4Tubs* photocathode_solid =
new G4Tubs("PMT_PHOTOCATHODE", 0, photocathode_diam_/2., photocathode_thickness_/2.,
0., twopi);
G4Material* aluminum = G4NistManager::Instance()->FindOrBuildMaterial("G4_Al");
G4LogicalVolume* photocathode_logic =
new G4LogicalVolume(photocathode_solid, aluminum, "PMT_PHOTOCATHODE");
G4double photocathode_posz = window_posz - window_thickness_/2. - photocathode_thickness_/2.;
new G4PVPlacement(0, G4ThreeVector(0., 0., photocathode_posz), photocathode_logic,
"PMT_PHOTOCATHODE", pmt_gas_logic, false, 0);
// Optical properties
G4OpticalSurface* pmt_opt_surf = GetPhotOptSurf();
new G4LogicalSkinSurface("PMT_PHOTOCATHODE", photocathode_logic, pmt_opt_surf);
// Sensitive detector
PmtSD* pmtsd = new PmtSD("/PMT_R11410/PmtR11410");
if (sd_depth_ == -1)
G4Exception("[PmtR11410]", "Construct()", FatalException,
"Sensor Depth must be set before constructing");
pmtsd->SetDetectorVolumeDepth(sd_depth_);
pmtsd->SetTimeBinning(binning_);
G4SDManager::GetSDMpointer()->AddNewDetector(pmtsd);
photocathode_logic->SetSensitiveDetector(pmtsd);
// VISIBILITIES //////////////////////////////////////////////////
pmt_gas_logic->SetVisAttributes(G4VisAttributes::Invisible);
window_logic->SetVisAttributes(G4VisAttributes::Invisible);
if (visibility_) {
G4VisAttributes pmt_col = nexus::LightGrey();
pmt_col.SetForceSolid(true);
pmt_logic->SetVisAttributes(pmt_col);
G4VisAttributes phot_col = nexus::Brown();
phot_col.SetForceSolid(true);
photocathode_logic->SetVisAttributes(phot_col);
} else {
pmt_logic->SetVisAttributes(G4VisAttributes::Invisible);
photocathode_logic->SetVisAttributes(G4VisAttributes::Invisible);
}
PmtR11410::~PmtR11410()
{
delete front_body_gen_;
delete medium_body_gen_;
delete rear_body_gen_;
delete rear_cap_gen_;
delete front_cap_gen_;
}
G4ThreeVector PmtR11410::GetRelPosition()
{
return G4ThreeVector(0., 0., front_body_length_/2.);
}
G4OpticalSurface* PmtR11410::GetPhotOptSurf()
{
const G4int entries = 57;
G4double ENERGIES[entries] =
{ 2.06640321682 *eV, 2.10142700016 *eV, 2.13765850016 *eV, 2.17516128086 *eV,
2.21400344659 *eV, 2.25425805471 *eV, 2.29600357425 *eV, 2.3393243964 *eV,
2.38431140402 *eV, 2.43106260802 *eV, 2.47968386018 *eV, 2.53028965325 *eV,
2.58300402103 *eV, 2.63796155339 *eV, 2.69530854368 *eV, 2.75520428909 *eV,
2.81782256839 *eV, 2.8833533258 *eV, 2.95200459546 *eV, 3.02400470754 *eV,
3.09960482523 *eV, 3.17908187203 *eV, 3.2627419213 *eV, 3.35092413538 *eV,
3.44400536137 *eV, 3.54240551455 *eV, 3.64659391204 *eV, 3.75709675786 *eV,
3.87450603154 *eV, 3.99949009707 *eV, 4.13280643364 *eV, 4.27531700032 *eV,
4.42800689319 *eV, 4.59200714849 *eV, 4.76862280805 *eV, 4.95936772037 *eV,
5.16600804205 *eV, 5.39061708736 *eV, 5.63564513678 *eV, 5.90400919092 *eV,
6.19920965046 *eV, 6.358163744063561 *eV, 6.525483842591549 *eV, 6.7018482707697 *eV,
6.888010722735524 *eV, 7.084811029099397 *eV, 7.293187824072908 *eV, 7.314701652462505 *eV,
7.336342781611801 *eV, 7.358112344761985 *eV, 7.380011488645204 *eV, 7.402041373685937 *eV,
7.424203174205955 *eV, 7.446498078633 *eV, 7.4689272897132195 *eV, 7.491492024727459 *eV,
7.51419351571 *eV};
G4double EFFICIENCY[entries] =
{ 0.0530, 0.0625, 0.0720, 0.0850,
0.1050, 0.1190, 0.1335, 0.1550,
0.1770, 0.1970, 0.2100, 0.2200,
0.2300, 0.2430, 0.2580, 0.2770,
0.2920, 0.3050, 0.3150, 0.3270,
0.3320, 0.3400, 0.3480, 0.3500,
0.3530, 0.3600, 0.3680, 0.3650,
0.3640, 0.3640, 0.3560, 0.3420,
0.3280, 0.3180, 0.3050, 0.2980,
0.2920, 0.2900, 0.2920, 0.2945,
0.3100, 0.3280, 0.3560, 0.3880,
0.3920, 0.3900, 0.4040, 0.3930,
0.3700, 0.3500, 0.3300, 0.3150,
0.2950, 0.2750, 0.2550, 0.2450,
0.2400 };
G4double REFLECTIVITY[entries] =
{ 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0.,
0., 0., 0., 0., 0.,
0., 0., 0., 0., 0.,
0., 0., 0., 0., 0.,
0., 0., 0., 0., 0. };
G4MaterialPropertiesTable* phcath_mpt = new G4MaterialPropertiesTable();
phcath_mpt->AddProperty("EFFICIENCY", ENERGIES, EFFICIENCY, entries);
phcath_mpt->AddProperty("REFLECTIVITY", ENERGIES, REFLECTIVITY, entries);
G4OpticalSurface* opt_surf =
new G4OpticalSurface("PHOTOCATHODE", unified, polished, dielectric_metal);
opt_surf->SetMaterialPropertiesTable(phcath_mpt);
return opt_surf;
}
|
#include "Fingerprint.h"
using namespace std;
Fingerprint::Fingerprint(string fn, int s, int ww) {
kgram = s;
win_width = ww;
unsigned char* buffer = new unsigned char[max_length];
FILE * fp = fopen(fn.c_str(), "rb"); //binary
if (!fp) {
fprintf(stderr, "Error when reading files\n");
exit(-1);
}
while (!feof(fp)) {
int cnt = fread(buffer, 1, max_length, fp);
file_length += cnt;
}
fclose(fp);
hashes = new long long[file_length - kgram + 1];
delete[] buffer;
generate_hash(fn);
generate_fingerprint();
}
void Fingerprint::generate_hash(string fn) {
FILE* fp = fopen(fn.c_str(), "rb");
unsigned char* buffer = new unsigned char[file_length];
int cnt = fread(buffer, 1, file_length, fp);
rolling_hash(buffer, buffer + kgram, 0);
for (int i = 1; i < file_length - kgram + 1; i++) {
rolling_hash(buffer + i, buffer + i + kgram, i);
}
fclose(fp);
delete[] buffer;
}
long long Fingerprint::rolling_hash(unsigned char* beg, unsigned char* end, int idx) {
long long sum = 0;
long long b = 3;
long long cons = 1;
long long mod = 1e10;
for (int i = 1; i <= kgram - 1; i++) {
cons = (cons * b) % mod;
}
if (idx == 0) {
sum += (int)*beg;
for (unsigned char* i = beg + 1; i < end; i++) {
sum = (sum * b + (int)*i) % mod;
}
hashes[0] = sum;
}
else {
long long fix = hashes[idx - 1] - *(beg - 1);
if (fix < 0)
fix += mod;
hashes[idx] = ((fix * cons) % mod * b) % mod + *(end - 1);
}
return hashes[idx];
}
void Fingerprint::generate_fingerprint() {
bool* selected = new bool[file_length - kgram + 1];
memset(selected, 0, file_length - kgram + 1);
long long min = hashes[0];
int idx = 0;
for (int j = 0; j < win_width; j++) {
if (hashes[j] <= min) {
min = hashes[j];
idx = j;
}
}
if (min != 0)
fingerprint.push_back(min);
for (int i = 1; i < file_length - kgram + 1 - win_width + 1; i++) {
if (idx >= i && idx < i + win_width - 1) {
if (hashes[i + win_width - 1] <= min) {
min = hashes[i + win_width - 1];
idx = i + win_width - 1;
if (min != 0)
fingerprint.push_back(min);
}
}
else {
min = hashes[i];
idx = i;
for (int j = i; j < i + win_width; j++) {
if (hashes[j] <= min) {
min = hashes[j];
idx = j;
}
}
if (min != 0)
fingerprint.push_back(min);
}
}
fp_length = distance(fingerprint.begin(), fingerprint.end());
}
int Fingerprint::len() {
return fp_length;
}
long long Fingerprint::fp(int idx) {
return fingerprint[idx];
}
long long Fingerprint::hash(int idx) {
return hashes[idx];
}
Fingerprint::~Fingerprint() {
delete[] hashes;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @author Owner: Deepak Arora (deepaka) & Karianne Ekern (karie)
*/
#ifndef COLLECTION_THUMBNAIL_MANAGER
#define COLLECTION_THUMBNAIL_MANAGER
#include "adjunct/quick/widgets/CollectionViewPane.h"
#include "modules/hardcore/mh/messobj.h"
#include "modules/thumbnails/thumbnailmanager.h"
#define MAX_ZOOM 2.0
#define MIN_ZOOM 0.3
#define DEFAULT_ZOOM 1.0
#define SCALE_DELTA 0.1
class ViewPaneController;
/**
* @brief This class handles thumbnail generate and cancel requests.
* Also this class informs/notifies the result of thumbnail generate
* request to CollectionViewPane.
*
* The mechanism on which this is based relies on message passing.
* Reason behind using message passing is to have non-blocking,
* seamless operations likes scrolling, deleting, editing, etc. on
* items hosted by CollectionViewPane.
*/
class CollectionThumbnailGenerator
: private MessageObject
{
public:
enum ThumbnailStatus
{
STATUS_STARTED,
STATUS_SUCCESSFUL,
STATUS_FAILED,
};
CollectionThumbnailGenerator(CollectionViewPane&);
~CollectionThumbnailGenerator();
/** Initializes thumbnail generator.
* @returns OpStatus::OK is successfully initialized other wise error
*/
OP_STATUS Init();
/** Updates width and height states of thumbnail
*/
void UpdateThumbnailSize(double zoom_factor)
{
m_thumbnail_width = m_base_width * zoom_factor;
m_thumbnail_height = m_base_height * zoom_factor;
}
/** Fetches thumbnail size.
* @param[out] target_width width of thumbnail placeholder
* @param[out] target_height height of thumbnail placeholder
*/
void GetThumbnailSize(unsigned int& width, unsigned int& height) const { width = m_thumbnail_width ; height = m_thumbnail_height; }
/** Initiates thumbnail requests
* @param item_id identifies id of item/placeholder associated with thumbnail
* @param reload identifies whether thumbnail should be reloaded
*/
void GenerateThumbnail(INT32 item_id, bool reload = false);
/** Cancels requested thumbnail generation
* @param item_id identifies id of item associated with thumbnail
*/
void CancelThumbnail(INT32 item_id) { DeleteThumbnail(item_id); }
/** Cancels all thumbnail requests.
*/
void CancelThumbnails();
private:
class NullImageListener
: public ImageListener
{
virtual void OnPortionDecoded() { }
virtual void OnError(OP_STATUS status) { }
};
class CollectionThumbnailListener
: public ThumbnailManagerListener
, public ImageListener
{
public:
CollectionThumbnailListener(CollectionThumbnailGenerator& generator, INT32 id, URL url, bool reload = false);
~CollectionThumbnailListener();
OP_STATUS Initiate();
URL& GetURL() { return m_url; }
// ThumbnailManagerListener
virtual void OnThumbnailRequestStarted(const URL& url, BOOL reload);
virtual void OnThumbnailReady(const URL& url, const Image& thumbnail, const uni_char *title, long preview_refresh);
virtual void OnThumbnailFailed(const URL& url, OpLoadingListener::LoadingFinishStatus status);
virtual void OnInvalidateThumbnails() { }
bool HasRequestInitiated() { return m_req_initiated; }
bool HasRequestProcessed() { return m_req_processed; }
private:
// ImageListener
virtual void OnPortionDecoded();
virtual void OnError(OP_STATUS status) {}
OP_STATUS GenerateThumbnail();
CollectionThumbnailGenerator& m_thumbnail_generator;
Image m_image;
URL m_url;
INT32 m_id;
bool m_req_initiated;
bool m_req_processed;
bool m_reload_thumbnail;
};
// MessageObject
virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2);
void AddIntoGenerateList(INT32 item_id, bool reload);
void NotifyThumbnailStatus(ThumbnailStatus status, INT32 id, Image& thumbnail, bool has_fixed_image = false);
void GenerateThumbnails();
void RemoveProcessedThumbnailRequest();
void DeleteThumbnail(INT32 item_id);
void DeleteAllThumbnails();
void RemoveMessages();
bool IsSpecialURL(URL& url);
bool GetFixedImage(URL& url, Image& image_name) const;
const char* GetSpecialURIImage(URLType type) const;
CollectionViewPane& m_collection_view_pane;
OpINT32HashTable<CollectionThumbnailListener> m_item_id_to_thumbnail_listener;
OpINT32Vector m_thumbnail_req_processed_item_list;
unsigned int m_num_of_req_initiated;
NullImageListener m_null_img_listener;
const int m_base_height;
const int m_base_width;
unsigned int m_thumbnail_width;
unsigned int m_thumbnail_height;
};
#endif //COLLECTIONS_THUMBNAIL_MANAGER
|
#include<iostream>
#include<vector>
#include<string>
using namespace std;
class Solution {
public:
string countAndSay(int n) {
vector<string> res;
res.push_back("1");
int i, j, counter;
//基本思想:循环29次,根据前一个序列值,遍历,得到下一个序列值,直到得到所有30个序列值,返回下标值对于序列值
for (i = 1; i < 30; i++)
{
//计算当前下标的序列值
string curent;
//计数相同字符个数
counter = 1;
//遍历前一个序列的所有字符,如果当前字符与下一个字符相同counter++,反之则将counter和字符添加到curent
for (j = 0; j < res[i - 1].size() - 1; j++)
{
if (res[i - 1][j] == res[i - 1][j + 1])
counter++;
else
{
curent += char(counter + '0');
curent += res[i - 1][j];
counter = 1;
}
}
//对于最后字符的考虑:如果和前一个字符相同,因为counter已经++,所以直接写入curent;如果不同,counter已经变成1,所以也直接写入curent
curent += char(counter + '0');
curent += res[i - 1][res[i - 1].size() - 1];
//当前下标的序列值计算得到加入容器res
res.push_back(curent);
}
//最后返回所要求下标的序列值
return res[n - 1];
}
};
int main()
{
Solution solute;
int n = 3;
cout << solute.countAndSay(n) << endl;
return 0;
}
|
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <random>
using namespace std;
int main()
{
setlocale(LC_ALL, "Russian"); //Добавление русского языка
random_device rd;
mt19937 mersenne(rd()); // инициализируем Вихрь Мерсенна случайным стартовым числом
int i, j;
double d[300][300];
for (i = 0; i < 300; i++)
for (j = 0; j < 300; j++)
{
d[i][j] = mersenne();
//cout << d[i][j] << " "; //Добавлено для просмотра корректности заполнения массива 300 на 300
}
//cout << "\n"; //Добавлено для визуального разграничения
double sr[300];
for (i = 0; i < 300; i++)
{
double x = 0;
for (j = 0; j < 300; j++)
x += d[i][j];
sr[i] = x / 300;
//cout << sr[i] << " "; //Добавлено для просмотра корректности заполнения массива со средними арифметическими строк первого массива
}
//cout << "\n"; //Добавлено для визуального разграничения
double max = 0;
for (i = 0; i < 300; i++)
if (sr[i] > max)
max = sr[i];
cout << "\nМаксимальное среди значений среднего арифметического элементов каждой строки равно = " << max << "\n";
return 0;
}
|
#include <QCoreApplication>
#include <robot.h>
#include <mcl.h>
#include <map.h>
#include <iostream>
#include <mainwindow.h>
#include <unistd.h>
using namespace std;
int main(int argc, char *argv[])
{
//--------- SETTINGS -----------
int sizeMap = 580;
int amountPartic = 2000;
int timeThread = 300;
bool kindLocalization = false; //TRUE = LOCAL - FALSE = GLOBAL
bool kld = true; //TRUE = KLD - FALSE = NON KLD
//------------------------------
QApplication a(argc, argv);
Map *myMap = new Map(sizeMap); //Size of map
Robot robo(myMap);
Mcl myMcl(amountPartic, myMap); //Amount of particles
MainWindow mw(myMap->world_size);
thread_mcl tmcl(&robo, &myMcl, myMap, timeThread, kindLocalization, kld);
tmcl.start(); //Thread starts
mw.show(); //Show the image
return a.exec();
}
|
//===- MBlazeCallingConv.td - Calling Conventions for MBlaze ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This describes the calling conventions for MBlaze architecture.
//===----------------------------------------------------------------------===//
/// CCIfSubtarget - Match if the current subtarget has a feature F.
class CCIfSubtarget<string F, CCAction A>:
CCIf<!strconcat("State.getTarget().getSubtarget<MBlazeSubtarget>().", F), A>;
//===----------------------------------------------------------------------===//
// MBlaze ABI Calling Convention
//===----------------------------------------------------------------------===//
def CC_MBlaze : CallingConv<[
// Promote i8/i16 arguments to i32.
CCIfType<[i8, i16], CCPromoteToType<i32>>,
// Integer arguments are passed in integer registers.
CCIfType<[i32], CCAssignToReg<[R5, R6, R7, R8, R9, R10]>>,
// Single fp arguments are passed in floating point registers
CCIfType<[f32], CCAssignToReg<[F5, F6, F7, F8, F9, F10]>>,
// 32-bit values get stored in stack slots that are 4 bytes in
// size and 4-byte aligned.
CCIfType<[i32, f32], CCAssignToStack<4, 4>>
]>;
def RetCC_MBlaze : CallingConv<[
// i32 are returned in registers R3, R4
CCIfType<[i32], CCAssignToReg<[R3, R4]>>,
// f32 are returned in registers F3, F4
CCIfType<[f32], CCAssignToReg<[F3, F4]>>
]>;
|
#include "pch.h"
GateIocp* GateIocp::_Instance = nullptr;
DWORD WINAPI GameThreadCallback(LPVOID parameter)
{
GateIocp* iocp = (GateIocp*)parameter;
while (TRUE)
{
iocp->GameThreadCallback();
Sleep(1);
}
}
DWORD WINAPI KeepThreadCallback(LPVOID parameter)
{
GateIocp *Owner = (GateIocp*)parameter;
Owner->KeepThreadCallback();
return 0;
}
GateIocp::GateIocp()
{
}
GateIocp::~GateIocp()
{
}
VOID GateIocp::OnIoRead(VOID * object, DWORD dataLength)
{
CNetworkSession* pNetworkSession = (CNetworkSession*)object;
CPacketSession *pPacketSession = (CPacketSession*)pNetworkSession;
PACKET_DATA data;
data.user = pPacketSession;
data.dataLength = dataLength;
g_QueuePacket.Push(data);
}
VOID GateIocp::OnIoWrote(VOID * object, DWORD dataLength)
{
CNetworkSession* pNetworkSession = (CNetworkSession*)object;
CPacketSession *pPacketSession = (CPacketSession*)pNetworkSession;
pPacketSession->WriteComplete();
}
VOID GateIocp::OnIoConnected(VOID * object)
{
CNetworkSession* pNetworkSession = (CNetworkSession*)object;
CPacketSession *pPacketSession = (CPacketSession*)pNetworkSession;
GateUser *user = (GateUser*)pPacketSession;
if (!CIocp::RegisterSocketToIocp(user->GetSocket(), (ULONG_PTR)user))
{
CLog::WriteDebugLog(_T("! OnIoConnected : CIocp::RegisterSocketToIocp"));
End();
return;
}
if (!user->InitializeReadForIocp())
{
CLog::WriteDebugLog(_T("! OnIoConnected : CIocp::InitializeReadForIocp"));
End();
return;
}
user->SetIsConnected(TRUE);
CLog::WriteDebugLog(_T("# New client connected : 0x%x(= %d)"), user, user->GetSocket());
}
VOID GateIocp::OnIoDisconnected(VOID * object)
{
CNetworkSession* pNetworkSession = (CNetworkSession*)object;
CPacketSession *pPacketSession = (CPacketSession*)pNetworkSession;
GateUser *user = (GateUser*)pPacketSession;
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
if ((int)user->GetConnectState() == CONNECT_STATE::LOBBY)
{
m_LobbyServer->GetSession()->SendPacket(PT_SS_REQ_DISCONNECT_LOBBY, WriteBuffer,
WRITE_PT_SS_REQ_DISCONNECT_LOBBY(WriteBuffer, user->GetUID())
);
}
if (!user->Reload(m_ListenSession->GetSocket()))
{
CLog::WriteDebugLog(_T("! OnIoDisconnected : user->Reload"));
End();
return;
}
CLog::WriteLog(_T("# Client disconnected : 0x%x(0x%x)\n"), user, user->GetSocket());
}
BOOL GateIocp::Begin()
{
if (!CIocp::Begin())
{
//CLog::WriteDebugLog(_T(""));
End();
return FALSE;
}
m_ListenSession = new CNetworkSession();
m_UserManager = new GateUserManager();
m_LoginServer = new LoginServer();
m_LobbyServer = new LobbyServer();
m_GameServer = new GameServer();
if (!m_ListenSession->Begin())
{
CLog::WriteDebugLog(_T("m_ListenSession->Begin() Error"));
End();
return FALSE;
}
if (!m_ListenSession->TcpBind())
{
CLog::WriteDebugLog(_T("m_ListenSession->TcpBind() Error"));
End();
return FALSE;
}
if (!m_ListenSession->Listen(8001, 200))
{
CLog::WriteDebugLog(_T("m_ListenSession->Listen(8001, 200) Error"));
End();
return FALSE;
}
if (!CIocp::RegisterSocketToIocp(m_ListenSession->GetSocket(), reinterpret_cast<ULONG_PTR>(m_ListenSession)))
{
CLog::WriteDebugLog(_T("CIocp::RegisterSocketToIocp Error"));
End();
return FALSE;
}
if (!m_UserManager->Begin(100, m_ListenSession->GetSocket()))
{
CLog::WriteDebugLog(_T("m_UserManager->Begin Error"));
End();
return FALSE;
}
if (!m_UserManager->AcceptAll())
{
CLog::WriteDebugLog(_T("m_UserManager->AcceptAll() Error"));
End();
return FALSE;
}
mGameThreadDestroyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!mGameThreadDestroyEvent)
{
CLog::WriteDebugLog(_T("mGameThreadDestroyEvent Error"));
End();
return FALSE;
}
mGameThreadHandle = CreateThread(NULL, 0, ::GameThreadCallback, this, 0, NULL);
if (!mGameThreadHandle)
{
CLog::WriteDebugLog(_T("mGameThreadHandle Error"));
End();
return FALSE;
}
mKeepThreadDestroyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (!mKeepThreadDestroyEvent)
{
CLog::WriteDebugLog(_T("mKeepThreadDestroyEvent Error"));
End();
return FALSE;
}
mKeepThreadHandle = CreateThread(NULL, 0, ::KeepThreadCallback, this, 0, NULL);
if (!mKeepThreadHandle)
{
CLog::WriteDebugLog(_T("mKeepThreadHandle Error"));
End();
return FALSE;
}
m_LoginServer->Begin();
m_LobbyServer->Begin();
m_GameServer->Begin();
CLog::WriteDebugLog(_T("IOCP Load"));
return TRUE;
}
BOOL GateIocp::End()
{
m_ListenSession->End();
delete m_ListenSession;
m_UserManager->End();
delete m_UserManager;
return TRUE;
}
VOID GateIocp::GameThreadCallback(VOID)
{
PACKET_DATA data;
ZeroMemory(&data, sizeof(PACKET_DATA));
if (g_QueuePacket.Pop(data))
{
CPacketSession* pPacketSession = data.user;
DWORD dataLength = data.dataLength;
DWORD Protocol = 0;
BYTE Packet[MAX_BUFFER_LENGTH] = { 0, };
DWORD PacketLength = 0;
//CLog::WriteDebugLog(_T("Pop Success"));
if (pPacketSession->ReadPacketForIocp(dataLength))
{
//CLog::WriteDebugLog(_T("ReadPacket Success"));
while (pPacketSession->GetPacket(Protocol, Packet, PacketLength))
{
//CLog::WriteDebugLog(_T("GetPacket Success"));
//CLog::WriteDebugLog(_T("Packet Load : %d"), Protocol);
switch (Protocol)
{
case PT_CS_REQ_LOGIN:
{
onPT_CS_REQ_LOGIN(pPacketSession, Packet);
break;
}
case PT_SC_SEND_LOGIN:
{
onPT_SC_SEND_LOGIN(pPacketSession, Packet);
break;
}
case PT_SS_LOGIN_SERVER:
{
CLog::WriteDebugLog(_T(" == Connect Login Server == "));
CPacketSession* tempSession = (CPacketSession*)m_UserManager->GetSession(pPacketSession);
m_LoginServer->GetSession()->SetServerSession(tempSession);
break;
}
case PT_SS_LOBBY_SERVER:
{
CLog::WriteDebugLog(_T(" == Connect Lobby Server == "));
CPacketSession* tempSession = (CPacketSession*)m_UserManager->GetSession(pPacketSession);
m_LobbyServer->GetSession()->SetServerSession(tempSession);
break;
}
case PT_SS_GAME_SERVER:
{
CLog::WriteDebugLog(_T(" == Connect Game Server == "));
CPacketSession* tempSession = (CPacketSession*)m_UserManager->GetSession(pPacketSession);
m_GameServer->GetSession()->SetServerSession(tempSession);
break;
}
case PT_SS_SEND_CONNECT_LOBBY:
{
break;
}
case PT_CS_REQ_CREATE_ROOM:
{
onPT_CS_REQ_CREATE_ROOM(pPacketSession, Packet);
break;
}
case PT_SC_SEND_CREATE_ROOM:
{
onPT_SC_SEND_CREATE_ROOM(pPacketSession, Packet);
break;
}
case PT_CS_REQ_ROOM_LIST:
{
onPT_CS_REQ_ROOM_LIST(pPacketSession, Packet);
break;
}
case PT_SC_SEND_ROOM_LIST:
{
onPT_SC_SEND_ROOM_LIST(pPacketSession, Packet);
break;
}
case PT_SC_SEND_ENTERED_MEMBER:
{
onPT_SC_SEND_ENTERED_MEMBER(pPacketSession, Packet);
break;
}
case PT_CS_REQ_JOIN_ROOM:
{
onPT_CS_REQ_JOIN_ROOM(pPacketSession, Packet);
break;
}
case PT_SC_SEND_ROOM_INFO:
{
onPT_SC_SEND_ROOM_INFO(pPacketSession, Packet);
break;
}
case PT_CS_REQ_ROOM_INFO:
{
onPT_CS_REQ_ROOM_INFO(pPacketSession, Packet);
break;
}
case PT_CS_REQ_LEAVE_ROOM:
{
onPT_CS_REQ_LEAVE_ROOM(pPacketSession, Packet);
break;
}
case PT_SC_SEND_LEAVE_ROOM:
{
onPT_SC_SEND_LEAVE_ROOM(pPacketSession, Packet);
break;
}
case PT_SC_SEND_LEAVE_MEMBER:
{
onPT_SC_SEND_LEAVE_MEMBER(pPacketSession, Packet);
break;
}
case PT_CS_REQ_ROOM_READY:
{
onPT_CS_REQ_ROOM_READY(pPacketSession, Packet);
break;
}
case PT_SC_SEND_GAME_START:
{
onPT_SC_SEND_GAME_START(pPacketSession, Packet);
break;
}
case PT_CS_REQ_GAME_MOVE:
{
onPT_CS_REQ_GAME_MOVE(pPacketSession, Packet);
break;
}
case PT_SC_SEND_GAME_MOVE:
{
onPT_SC_SEND_GAME_MOVE(pPacketSession, Packet);
break;
}
default:
{
CLog::WriteDebugLog(_T("Empty Protocol"));
break;
}
}
}
}
if (!pPacketSession->InitializeReadForIocp())
{
CLog::WriteDebugLog(_T("OnIoRead Error"));
}
}
}
VOID GateIocp::KeepThreadCallback(VOID)
{
return VOID();
}
VOID GateIocp::onPT_CS_REQ_LOGIN(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_CS_REQ_LOGIN);
GateUser* gateUser = (GateUser*)user;
gateUser->SetID(Data.strID);
gateUser->SetConnectState(CONNECT_STATE::LOGIN);
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
m_LoginServer->GetSession()->SendPacket(PT_CS_REQ_LOGIN, WriteBuffer,
WRITE_PT_CS_REQ_LOGIN(WriteBuffer, Data.strID, Data.strPwd)
);
}
VOID GateIocp::onPT_SC_SEND_LOGIN(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_SC_SEND_LOGIN);
GateUser *gateUser = m_UserManager->GetSessionFromID(Data.strID);
gateUser->SetID(Data.strID);
gateUser->SetUID(Data.dwIndex);
gateUser->SetConnectState(CONNECT_STATE::LOBBY);
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
m_LobbyServer->GetSession()->SendPacket(PT_SS_REQ_CONNECT_LOBBY, WriteBuffer,
WRITE_PT_SS_REQ_CONNECT_LOBBY(WriteBuffer, gateUser->GetUID(), gateUser->GetID(), Data.dwCode)
);
ZeroMemory(WriteBuffer, sizeof(BYTE)*MAX_BUFFER_LENGTH);
gateUser->WritePacket(PT_SC_SEND_LOGIN, WriteBuffer,
WRITE_PT_SC_SEND_LOGIN(WriteBuffer, Data.dwCode, Data.strID, Data.dwIndex)
);
CLog::WriteDebugLog(_T("Login Success"));
}
VOID GateIocp::onPT_SS_SEND_CONNECT_LOBBY(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_SS_SEND_CONNECT_LOBBY);
GateUser *gateUser = m_UserManager->GetSessionFromID(Data.strID);
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
gateUser->WritePacket(PT_SS_SEND_CONNECT_LOBBY, WriteBuffer,
WRITE_PT_SS_SEND_CONNECT_LOBBY(WriteBuffer, Data.dwUID, Data.strID, Data.dwCode)
);
}
VOID GateIocp::onPT_CS_REQ_CREATE_ROOM(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_CS_REQ_CREATE_ROOM);
GateUser* gate_user = (GateUser*)user;
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
m_LobbyServer->GetSession()->SendPacket(PT_CS_REQ_CREATE_ROOM, WriteBuffer,
WRITE_PT_CS_REQ_CREATE_ROOM(WriteBuffer, Data.strName, gate_user->GetUID())
);
}
VOID GateIocp::onPT_SC_SEND_CREATE_ROOM(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_SC_SEND_CREATE_ROOM);
GateUser* gate_user = m_UserManager->GetUserFromUID(Data.dwIndex);
if (user)
{
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
gate_user->WritePacket(PT_SC_SEND_CREATE_ROOM,
WriteBuffer,
WRITE_PT_SC_SEND_CREATE_ROOM(WriteBuffer,Data.dwCode, Data.dwIndex));
}
}
VOID GateIocp::onPT_CS_REQ_ROOM_LIST(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_CS_REQ_ROOM_LIST);
GateUser* gate_user = (GateUser*)user;
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
m_LobbyServer->GetSession()->SendPacket(PT_CS_REQ_ROOM_LIST,
WriteBuffer,
WRITE_PT_CS_REQ_ROOM_LIST(WriteBuffer, gate_user->GetUID())
);
}
VOID GateIocp::onPT_SC_SEND_ROOM_LIST(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_SC_SEND_ROOM_LIST);
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
GateUser* gate_user = m_UserManager->GetUserFromUID(Data.dwUID);
if (gate_user)
{
gate_user->WritePacket(PT_SC_SEND_ROOM_LIST, WriteBuffer,
WRITE_PT_SC_SEND_ROOM_LIST(WriteBuffer, Data));
}
}
VOID GateIocp::onPT_SC_SEND_ENTERED_MEMBER(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_SC_SEND_ENTERED_MEMBER);
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
GateUser* gate_user = m_UserManager->GetUserFromUID(Data.UID);
if (gate_user)
{
gate_user->WritePacket(PT_SC_SEND_ENTERED_MEMBER, WriteBuffer, WRITE_PT_SC_SEND_ENTERED_MEMBER(
WriteBuffer,
Data
));
CLog::WriteDebugLog(_T("onPT_SC_SEND_ENTERED_MEMBER UID: %d"), gate_user->GetUID());
}
}
VOID GateIocp::onPT_CS_REQ_JOIN_ROOM(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_CS_REQ_JOIN_ROOM);
GateUser* gate_user = (GateUser*)user;
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
m_LobbyServer->GetSession()->SendPacket(PT_CS_REQ_JOIN_ROOM,
WriteBuffer,
WRITE_PT_CS_REQ_JOIN_ROOM(WriteBuffer, gate_user->GetUID(), Data.RoomIndex)
);
CLog::WriteDebugLog(_T("Req Join Room : %d"), gate_user->GetUID());
}
VOID GateIocp::onPT_SC_SEND_ROOM_INFO(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_SC_SEND_ROOM_INFO);
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
GateUser* gate_user = m_UserManager->GetUserFromUID(Data.UID);
if (gate_user)
{
gate_user->WritePacket(PT_SC_SEND_ROOM_INFO, WriteBuffer, WRITE_PT_SC_SEND_ROOM_INFO(
WriteBuffer,
Data
));
CLog::WriteDebugLog(_T("Send Room info : %d"), Data.UID);
}
}
VOID GateIocp::onPT_CS_REQ_ROOM_INFO(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_CS_REQ_ROOM_INFO);
GateUser* gate_user = (GateUser*)user;
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
m_LobbyServer->GetSession()->SendPacket(PT_CS_REQ_ROOM_INFO,
WriteBuffer,
WRITE_PT_CS_REQ_ROOM_INFO(WriteBuffer, gate_user->GetUID())
);
CLog::WriteDebugLog(_T("Req Room info : %d"), gate_user->GetUID());
}
VOID GateIocp::onPT_CS_REQ_LEAVE_ROOM(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_CS_REQ_LEAVE_ROOM);
GateUser* gate_user = (GateUser*)user;
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
m_LobbyServer->GetSession()->SendPacket(PT_CS_REQ_LEAVE_ROOM,
WriteBuffer,
WRITE_PT_CS_REQ_LEAVE_ROOM(WriteBuffer, gate_user->GetUID())
);
}
VOID GateIocp::onPT_SC_SEND_LEAVE_ROOM(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_SC_SEND_LEAVE_ROOM);
GateUser* gate_user = m_UserManager->GetUserFromUID(Data.UID);
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
gate_user->WritePacket(PT_SC_SEND_LEAVE_ROOM,
WriteBuffer,
WRITE_PT_SC_SEND_LEAVE_ROOM(WriteBuffer, Data.UID));
CLog::WriteDebugLog(_T("Leave Room : %d"), Data.UID);
}
VOID GateIocp::onPT_SC_SEND_LEAVE_MEMBER(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_SC_SEND_LEAVE_MEMBER);
GateUser* gate_user = m_UserManager->GetUserFromUID(Data.UID);
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
gate_user->WritePacket(PT_SC_SEND_LEAVE_MEMBER,
WriteBuffer,
WRITE_PT_SC_SEND_LEAVE_ROOM(WriteBuffer, Data.UID));
CLog::WriteDebugLog(_T("Nofy Leave Member : %d"), Data.UID);
}
VOID GateIocp::onPT_CS_REQ_ROOM_READY(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_CS_REQ_ROOM_READY);
GateUser* gate_user = (GateUser*)user;
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
m_LobbyServer->GetSession()->SendPacket(PT_CS_REQ_ROOM_READY,
WriteBuffer,
WRITE_PT_CS_REQ_ROOM_READY(WriteBuffer, gate_user->GetUID(), Data.IsReady)
);
}
VOID GateIocp::onPT_SC_SEND_GAME_START(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_SC_SEND_GAME_START);
GateUser* gate_user = m_UserManager->GetUserFromUID(Data.UID);
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
gate_user->WritePacket(PT_SC_SEND_GAME_START,
WriteBuffer,
WRITE_PT_SC_SEND_GAME_START(WriteBuffer, Data.UID, Data.UserData));
}
VOID GateIocp::onPT_CS_REQ_GAME_MOVE(CPacketSession * user, BYTE * Packet)
{
READ_PACKET(PT_CS_REQ_GAME_MOVE);
GateUser* gate_user = (GateUser*)user;
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
m_GameServer->GetSession()->SendPacket(PT_CS_REQ_GAME_MOVE, WriteBuffer, WRITE_PT_CS_REQ_GAME_MOVE(WriteBuffer, gate_user->GetUID(), Data.Direction));
}
VOID GateIocp::onPT_SC_SEND_GAME_MOVE(CPacketSession * User, BYTE * Packet)
{
READ_PACKET(PT_SC_SEND_GAME_MOVE);
GateUser* gate_user = m_UserManager->GetUserFromUID(Data.UID);
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
gate_user->WritePacket(PT_SC_SEND_GAME_MOVE,
WriteBuffer,
WRITE_PT_SC_SEND_GAME_MOVE(WriteBuffer, Data));
}
|
class equip_garlic_bulb : FoodEdible
{
scope = 2;
count = 1;
displayName = $STR_ITEM_NAME_equip_garlic_bulb;
descriptionShort = $STR_ITEM_DESC_equip_garlic_bulb;
model = "\z\addons\dayz_communityassets\models\herb_garlic_bulb.p3d";
picture = "\z\addons\dayz_communityassets\pictures\equip_garlic_bulb_ca.paa";
bloodRegen = 80;
};
class FoodPumpkin : FoodEdible
{
scope = 2;
count = 1;
bloodRegen = 100;
displayName = $STR_FOOD_NAME_PUMPKIN;
descriptionShort = $STR_FOOD_NAME_PUMPKIN;
weight = 1;
model = "\z\addons\dayz_epoch_w\items\veges\pumpkin.p3d";
picture = "\dayz_epoch_c\icons\plants\pumpkin.paa";
class ItemActions
{
class Consume
{
text = $STR_EAT_FOOD;
script = "spawn player_consume";
};
class Crafting
{
text = $STR_FOOD_NAME_PUMPKIN_CRAFT;
script = ";['Crafting','CfgMagazines', _id] spawn player_craftItem;";
neednearby[] = {""};
requiretools[] = {"ItemKnife"};
output[] = {{"ItemPumpkinSeed",5}};
input[] = {{"FoodPumpkin",1}};
};
};
};
class ItemPumpkinSeed: FoodEdible
{
scope = 2;
count = 1;
bloodRegen = 100;
displayName = $STR_CRAFT_NAME_PUMPKIN_SEED;
descriptionShort = $STR_CRAFT_DESC_PUMPKIN_SEED;
model = "\z\addons\dayz_epoch_w\items\veges\seedbag_01.p3d";
picture = "\dayz_epoch_c\icons\plants\pumpkinseeds.paa";
type = 256;
};
class FoodSunFlowerSeed : FoodEdible
{
scope = 2;
count = 1;
bloodRegen = 100;
displayName = $STR_FOOD_NAME_SUNFLOWER;
descriptionShort = $STR_FOOD_NAME_SUNFLOWER;
model = "\z\addons\dayz_epoch_w\items\veges\seedbag_01.p3d";
picture = "\dayz_epoch_c\icons\plants\sunflowerseeds.paa";
};
class FoodPotatoRaw : FoodRaw
{
scope = 2;
count = 1;
displayName = $STR_FOOD_NAME_POTATO;
descriptionShort = $STR_FOOD_NAME_POTATO;
model = "\z\addons\dayz_epoch_w\items\veges\dze_potato.p3d";
picture = "\dayz_epoch_c\icons\plants\potato.paa";
bloodRegen = 0;
Nutrition[] = {0,0,0,0};
cookOutput = "FoodPotatoBaked";
};
class FoodPotatoBaked : FoodCooked
{
scope = 2;
count = 1;
displayName = $STR_FOOD_NAME_POTATO_BAKED;
descriptionShort = $STR_FOOD_NAME_POTATO_BAKED;
model = "\z\addons\dayz_epoch_w\items\veges\dze_potato_baked.p3d";
picture = "\dayz_epoch_c\icons\plants\potatobaked.paa";
bloodRegen = 200;
Nutrition[] = {250,0,0,0};
};
class FoodCarrot : FoodCooked
{
scope = 2;
count = 1;
displayName = $STR_FOOD_NAME_CARROT;
descriptionShort = $STR_FOOD_NAME_CARROT;
model = "\z\addons\dayz_epoch_w\items\veges\dze_carrot.p3d";
picture = "\dayz_epoch_c\icons\plants\carrot.paa";
bloodRegen = 150;
Nutrition[] = {120,0,0,0};
};
|
#include "Game.h"
#include "SnakeNode.h"
void setDir(SnakeNode *node, int touchX, int touchY, int nodeX, int nodeY);
bool nodeImpact(Node * node, Rect * edage);
void setNodeLocation(SnakeNode * newNode, SnakeNode * preNode);
Game::Game(void)
{
}
Game::~Game(void)
{
}
int Game::sepHeight = 0;
int Game::sepWidth = 0;
float Game::sepTime=0.5;
SnakeNode* head = NULL;
SnakeNode* food = NULL;
Vector<SnakeNode *> allBody;
Rect * edgeRect = NULL;
Scene* Game::createScene()
{
Scene* scene = Scene::create();
Layer* layer = Game::create();
scene->addChild(layer);
return scene;
}
bool Game::init()
{
if (!Layer::init())
{
return false;
}
//添加背景
auto size = Director::getInstance()->getWinSize();
auto gameBG = Sprite::create("game_bg.jpg");
gameBG->setAnchorPoint(Point::ZERO);
gameBG->setPosition(0, 0);
gameBG->setOpacity(75);
int bgWidth = gameBG->getContentSize().width;
int bgHeight = gameBG->getContentSize().height;
float scaleX = size.width / bgWidth;
float scaleY = size.height / bgHeight;
gameBG->setScaleX(scaleX);
gameBG->setScaleY(scaleY);
this->addChild(gameBG);
//分数显示
auto scoreLabel = Label::create("Hello World", "Arial", 24);
scoreLabel->setPosition(Vec2(size.width - 80, size.height - 50));
this->addChild(scoreLabel);
////添加菜单
auto menuItemBack = MenuItemFont::create("Back", CC_CALLBACK_1(Game::menuCallBack, this));
auto menu = Menu::create(menuItemBack, NULL);
menu->setPosition(Point::ZERO);
menuItemBack->setPosition(Point(size.width - 80, menuItemBack->getContentSize().height + 30));
menuItemBack->setColor(Color3B::GREEN);
this->addChild(menu);
//添加地图
auto draw = DrawNode::create();
draw->setAnchorPoint(Point::ZERO);
draw->setPosition(Point::ZERO);
this->addChild(draw);
int mapWidth = (int)size.width*0.8 - (int)(size.width*0.8) % 10;
int mapHeight = (int)size.height*0.9 - (int)(size.height*0.9) % 10;
sepWidth = (int)mapWidth / 10;
sepHeight = (int)mapHeight / 10;
edgeRect = new Rect(-20, -20, mapWidth + 20, mapHeight + 20);
//添加蛇头,食物
head = SnakeNode::create(ENUM_TYPE::TYPE_HEAD);
food = SnakeNode::create(ENUM_TYPE::TYPE_FOOD);
allBody.pushBack(head);
for (int i = 0; i <= 10; i++)
{
draw->drawSegment(Point(0, sepHeight*i), Point(mapWidth, sepHeight*i), 1, Color4F(1, 1, 1, 1));
draw->drawSegment(Point(sepWidth*i, 0), Point(sepWidth*i, mapHeight), 1, Color4F(1, 1, 1, 1));
}
this->addChild(head);
this->addChild(food);
//添加触摸事件
auto litener = EventListenerTouchOneByOne::create();
litener->setSwallowTouches(true);//继续向下传递事件
litener->onTouchBegan = [&](Touch * touch, Event * event)
{
//改变移动方向
int touchX = touch->getLocation().x;
int touchY = touch->getLocation().y;
int headX = head->node->boundingBox().getMidX();
int headY = head->node->boundingBox().getMinY();
setDir(head, touchX, touchY, headX, headY);
return true;
};
this->schedule(schedule_selector(Game::updateFrame), Game::sepTime);
_eventDispatcher->addEventListenerWithSceneGraphPriority(litener, this);
return true;
}
void Game::menuCallBack(Ref * obj)
{
Director::getInstance()->popScene();
}
void setDir(SnakeNode * node, int touchX, int touchY, int nodeX, int nodeY)
{
node->m_last_dir=node->m_dir;
if (node->m_dir == ENUM_DIR::DIR_RIGHT || node->m_dir == ENUM_DIR::DIR_LEFT)
{
if ((touchY - nodeY) >= Game::sepHeight*0.5)
{
node->m_dir = ENUM_DIR::DIR_UP;
}
else if ((nodeY - touchY) >= Game::sepHeight*0.5)
{
node->m_dir = ENUM_DIR::DIR_DOWN;
}
else if (allBody.size() == 1){
if (touchX > nodeX)
{
node->m_dir = ENUM_DIR::DIR_RIGHT;
}
else
{
node->m_dir = ENUM_DIR::DIR_LEFT;
}
}
}
else
{
if ((touchX - nodeX) >= Game::sepWidth*0.5)
{
node->m_dir = ENUM_DIR::DIR_RIGHT;
}
else if ((nodeX - touchX) >= Game::sepWidth*0.5)
{
node->m_dir = ENUM_DIR::DIR_LEFT;
}
else if (allBody.size() == 1)
{
if (touchY > nodeY)
{
node->m_dir = ENUM_DIR::DIR_UP;
}
else
{
node->m_dir = ENUM_DIR::DIR_DOWN;
}
}
}
}
void Game::updateFrame(float t)
{
//检测食物碰撞
if (head->node->boundingBox().containsPoint(Point(food->node->boundingBox().getMidX(),food->node->boundingBox().getMidY())))
{
//添加新节点,并设置其位置和方向
int index = allBody.size() - 1;
SnakeNode* preNode = allBody.at(index);
food->setAnchorPoint(Point::ZERO);
setNodeLocation(food, preNode);
this->addBody(food);
food = SnakeNode::create(ENUM_TYPE::TYPE_FOOD);
this->addChild(food);
}
//检测边缘碰撞
if (nodeImpact(head->node, edgeRect))
{
this->gameOver();
return;
}
//检测头部和身体的碰撞
for (int i = 1; i < allBody.size(); i++)
{
if (head->node->boundingBox().containsPoint(Point(allBody.at(i)->node->boundingBox().getMidX(), allBody.at(i)->node->boundingBox().getMidY())))
{
this->gameOver();
return;
}
}
//移动bodys
moveBodys();
}
void Game::moveBodys()
{
//设置各body的移动方向
for(int i=allBody.size()-1;i>=1;i--)
{
SnakeNode* cur=allBody.at(i);
SnakeNode* pre=allBody.at(i-1);
if((int)cur->node->getPositionX()==(int)pre->node->getPositionX())
{
if(pre->node->getPositionY()>cur->node->getPositionY())
{
cur->m_dir=ENUM_DIR::DIR_UP;
}else
{
cur->m_dir=ENUM_DIR::DIR_DOWN;
}
}
if((int)cur->node->getPositionY()==(int)pre->node->getPositionY())
{
if(pre->node->getPositionX()>cur->node->getPositionX())
{
cur->m_dir=ENUM_DIR::DIR_RIGHT;
}else
{
cur->m_dir=ENUM_DIR::DIR_LEFT;
}
}
}
//移动
for(int i=0;i<allBody.size();i++)
{
allBody.at(i)->gameLogic();
}
}
void Game::addBody(SnakeNode* body)
{
allBody.pushBack(body);
}
bool nodeImpact(Node *node, Rect * edage)
{
Vec2 x = node->getPosition().ANCHOR_BOTTOM_LEFT;
int x1 = node->getPositionX();
int y1 = node->getPositionY();
if (node->getPositionX() <= (edage->getMinX()))//左边缘碰撞
{
return true;
}
if (node->getPositionX() >= (edage->getMaxX()))//右边缘碰撞
{
return true;
}
if (node->getPositionY() <= (edage->getMinY()))//下边缘碰撞
{
return true;
}
if (node->getPositionY() >= (edage->getMaxY()))//上边缘碰撞
{
return true;
}
return false;
}
void setNodeLocation(SnakeNode * newNode, SnakeNode * preNode)
{
switch (preNode->m_dir)
{
case ENUM_DIR::DIR_LEFT:
newNode->setPositionX(preNode->node->getPositionX() + Game::sepWidth);
newNode->setPositionY(preNode->node->getPositionY());
break;
case ENUM_DIR::DIR_RIGHT:
newNode->setPositionX(preNode->node->getPositionX() - Game::sepWidth);
newNode->setPositionY(preNode->node->getPositionY());
break;
case ENUM_DIR::DIR_UP:
newNode->setPositionX(preNode->node->getPositionX());
newNode->setPositionY(preNode->node->getPositionY()-Game::sepHeight);
break;
case ENUM_DIR::DIR_DOWN:
newNode->setPositionX(preNode->node->getPositionX());
newNode->setPositionY(preNode->node->getPositionY() + Game::sepHeight);
break;
}
newNode->m_dir=preNode->m_last_dir;
newNode->m_last_dir=preNode->m_last_dir;
}
void Game::gameOver()
{
this->cleanup();
Sprite* over = Sprite::create("HelloWorld.png");
Size size = Director::getInstance()->getWinSize();
Vec2 anchor=over->getAnchorPoint();
over->setPosition(Point(size.width / 2, size.height / 2));
this->addChild(over);
}
|
#pragma once
#include <GL/glew.h>
#include "Window.h"
#include "Camera.h"
class TPSCamera : public Camera {
public:
TPSCamera(float distance, float pitch, float rotation);
void update();
float distance = 0, pitchTps = 0, rotation = 0;
glm::vec3 center;
private:
float pitchSpeed = 0, rotationSpeed = 0, distanceSpeed = 0;
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2009 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef JSON_SERIALIZER_H
#define JSON_SERIALIZER_H
class JSONSerializer
{
TempBuffer &buffer;
BOOL add_comma;
OP_STATUS AddComma(); // if needed
public:
JSONSerializer(TempBuffer &out);
virtual OP_STATUS EnterArray();
virtual OP_STATUS LeaveArray();
virtual OP_STATUS EnterObject();
virtual OP_STATUS LeaveObject();
virtual OP_STATUS AttributeName(const OpString& str);
OP_STATUS AttributeName(const uni_char *str);
// Values
virtual OP_STATUS PlainString(const OpString& str); // Don't JSONify.
OP_STATUS PlainString(const uni_char *str); // Don't JSONify.
virtual OP_STATUS String(const OpString& str);
OP_STATUS String(const uni_char *str);
virtual OP_STATUS Number(double num);
virtual OP_STATUS Int(int num);
virtual OP_STATUS UnsignedInt(unsigned int num);
virtual OP_STATUS Bool(BOOL val);
virtual OP_STATUS Null();
};
#endif // JSON_SERIALIZER_H
|
#include <iostream>
using namespace std;
class Mpg_log{
private:
double last_odometer;
double this_odometer;
double this_gas;
double initial_odometer;
public:
Mpg_log(double starting_odometer){
last_odometer = starting_odometer;
}
void gas(double initodometer)
{
initial_odometer = initodometer;
}
void buy_gas(double odometer, double gas)
{
this_odometer = odometer;
this_gas = gas;
}
double get_current_mpg()
{
return ((this_odometer - last_odometer) / this_gas);
}
double get_ave_mpg()
{
return ((this_odometer - initial_odometer) / this_gas);
}
};
int main (){
double initial;
double last;
double gas;
cout << "Initial odometer: " << endl;
cin >> initial;
while (initial > 0.0) // make sure odometer reading is positive
{
Mpg_log init(initial);
cout << "Odometer: " << endl;
cin >> last;
if (last <= initial)
{
break;
}
cout << "Gallons: " << endl;
cin >> gas;
init.buy_gas(last, gas);
cout << "This mpg: " << init.get_current_mpg() << endl;
cout << "Ave mpg: " << init.get_ave_mpg() << endl;
}
cout << "Ending program" << endl;
return 0;
}
|
#ifndef GerstnerWaveModel_H
#define GerstnerWaveModel_H
#include "GerstnerWave.h"
#include "WaveModel.h"
#include <vector>
class GerstnerWaveModel : public WaveModel
{
private :
std::vector<GerstnerWave> gerstnerWaveList;
public:
GerstnerWaveModel();
GerstnerWaveModel(const GerstnerWaveModel & gWM);
void addGerstnerWave(const GerstnerWave &gW);
~GerstnerWaveModel();
};
#endif
|
// Created on: 1994-11-04
// Created by: Christian CAILLET
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _MoniTool_ElemHasher_HeaderFile
#define _MoniTool_ElemHasher_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Integer.hxx>
class MoniTool_Element;
//! ElemHasher defines HashCode for Element, which is : ask a
//! Element its HashCode ! Because this is the Element itself
//! which brings the HashCode for its Key
//!
//! This class complies to the template given in TCollection by
//! MapHasher itself
class MoniTool_ElemHasher
{
public:
DEFINE_STANDARD_ALLOC
//! Returns hash code for the given element, in the range [1, theUpperBound].
//! Asks theElement its HashCode, then transforms it to be in the required range.
//! @param theElement the element which hash code is to be computed
//! @param theUpperBound the upper bound of the range a computing hash code must be within
//! @return a computed hash code, in the range [1, theUpperBound]
Standard_EXPORT static Standard_Integer HashCode (const Handle (MoniTool_Element) & theElement,
Standard_Integer theUpperBound);
//! Returns True if two keys are the same.
//! The test does not work on the Elements themselves but by
//! calling their methods Equates
Standard_EXPORT static Standard_Boolean IsEqual (const Handle(MoniTool_Element)& K1, const Handle(MoniTool_Element)& K2);
protected:
private:
};
#endif // _MoniTool_ElemHasher_HeaderFile
|
class PluginVersion {
public:
static void CreateVersionString();
static char VersionString[64];
private:
static void AddVersion(char* FileName);
};
|
// Created on: 1993-06-17
// Created by: Jean Yves LEBEY
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TopOpeBRepBuild_WireEdgeClassifier_HeaderFile
#define _TopOpeBRepBuild_WireEdgeClassifier_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Boolean.hxx>
#include <gp_Pnt2d.hxx>
#include <BRepClass_Edge.hxx>
#include <BRepClass_FacePassiveClassifier.hxx>
#include <TopoDS_Shape.hxx>
#include <TopOpeBRepBuild_CompositeClassifier.hxx>
#include <TopAbs_State.hxx>
class TopOpeBRepBuild_BlockBuilder;
class TopOpeBRepBuild_Loop;
//! Classify edges and wires.
//! shapes are Wires, Element are Edge.
class TopOpeBRepBuild_WireEdgeClassifier : public TopOpeBRepBuild_CompositeClassifier
{
public:
DEFINE_STANDARD_ALLOC
//! Creates a classifier on edge <F>.
//! Used to compare edges and wires on the edge <F>.
Standard_EXPORT TopOpeBRepBuild_WireEdgeClassifier(const TopoDS_Shape& F, const TopOpeBRepBuild_BlockBuilder& BB);
Standard_EXPORT virtual TopAbs_State Compare (const Handle(TopOpeBRepBuild_Loop)& L1, const Handle(TopOpeBRepBuild_Loop)& L2) Standard_OVERRIDE;
Standard_EXPORT TopoDS_Shape LoopToShape (const Handle(TopOpeBRepBuild_Loop)& L);
//! classify wire <B1> with wire <B2>
Standard_EXPORT TopAbs_State CompareShapes (const TopoDS_Shape& B1, const TopoDS_Shape& B2) Standard_OVERRIDE;
//! classify edge <E> with wire <B>
Standard_EXPORT TopAbs_State CompareElementToShape (const TopoDS_Shape& E, const TopoDS_Shape& B) Standard_OVERRIDE;
//! prepare classification involving wire <B>
//! calls ResetElement on first edge of <B>
Standard_EXPORT void ResetShape (const TopoDS_Shape& B) Standard_OVERRIDE;
//! prepare classification involving edge <E>
//! define 2D point (later used in Compare()) on first vertex of edge <E>.
Standard_EXPORT void ResetElement (const TopoDS_Shape& E) Standard_OVERRIDE;
//! Add the edge <E> in the set of edges used in 2D point
//! classification.
Standard_EXPORT Standard_Boolean CompareElement (const TopoDS_Shape& E) Standard_OVERRIDE;
//! Returns state of classification of 2D point, defined by
//! ResetElement, with the current set of edges, defined by Compare.
Standard_EXPORT TopAbs_State State() Standard_OVERRIDE;
protected:
private:
Standard_Boolean myFirstCompare;
gp_Pnt2d myPoint2d;
BRepClass_Edge myBCEdge;
BRepClass_FacePassiveClassifier myFPC;
TopoDS_Shape myShape;
};
#endif // _TopOpeBRepBuild_WireEdgeClassifier_HeaderFile
|
#include "ZipDialog.h"
ZipDialog::ZipDialog(wxWindow *parent)
:wxDialog(parent, wxID_ANY, "Import Template ZipFile")
{
wxBoxSizer* dlgbox = new wxBoxSizer(wxVERTICAL);
wxBoxSizer* dlgbox1 = new wxBoxSizer(wxHORIZONTAL);
wxStaticText* pathtext = new wxStaticText(this, wxID_ANY, "Path: ");
zip_path = new wxTextCtrl(this, ID_ZipPath, wxEmptyString, wxDefaultPosition, wxSize(300,-1));
btn_choose = new wxButton(this, ID_ChooseBtn, "...", wxDefaultPosition, wxSize(40,-1));
dlgbox1->Add(pathtext, 0, wxALL|wxALIGN_CENTER_VERTICAL, wxBorder(10));
dlgbox1->Add(zip_path, 1, wxALL|wxALIGN_CENTER_VERTICAL, wxBorder(10));
dlgbox1->Add(btn_choose, 0, wxALL|wxALIGN_CENTER_VERTICAL, wxBorder(10));
wxBoxSizer* dlgbox2 = new wxBoxSizer(wxHORIZONTAL);
btn_ok = new wxButton(this, ID_Unzip, "Import", wxDefaultPosition, wxDefaultSize);
btn_all = new wxButton(this, ID_UnzipAll, "All zipfiles under template_dir", wxDefaultPosition, wxDefaultSize);
btn_help = new wxButton(this, ID_Help, "Help", wxDefaultPosition, wxDefaultSize);
dlgbox2->Add(btn_help, 0, wxALL, wxBorder(10));
dlgbox2->Add(btn_all, 0, wxALL, wxBorder(10));
dlgbox2->Add(btn_ok, 0, wxALL, wxBorder(10));
dlgbox->Add(dlgbox1, 0, wxTOP|wxBOTTOM|wxALIGN_CENTER, wxBorder(20));
dlgbox->Add(dlgbox2, 0, wxALIGN_CENTER);
SetSizerAndFit(dlgbox);
this->Bind(wxEVT_BUTTON, &ZipDialog::OnShowChoice, this, ID_ChooseBtn);
this->Bind(wxEVT_BUTTON, &ZipDialog::OnTips, this, ID_Help);
this->Bind(wxEVT_BUTTON, &ZipDialog::OnImport, this, ID_Unzip);
this->Bind(wxEVT_BUTTON, &ZipDialog::OnUnzipAll, this, ID_UnzipAll);
}
ZipDialog::~ZipDialog()
{
this->Unbind(wxEVT_BUTTON, &ZipDialog::OnShowChoice, this, ID_ChooseBtn);
this->Unbind(wxEVT_BUTTON, &ZipDialog::OnTips, this, ID_Help);
this->Unbind(wxEVT_BUTTON, &ZipDialog::OnImport, this, ID_Unzip);
this->Unbind(wxEVT_BUTTON, &ZipDialog::OnUnzipAll, this, ID_UnzipAll);
}
void ZipDialog::OnShowChoice(wxCommandEvent& event)
{
wxUnusedVar(event);
const wxString ALL(wxT("Zip File (*.zip)|*.zip"));
wxFileDialog dlg(this, _("Open File"), wxEmptyString, wxEmptyString, ALL, wxFD_OPEN | wxFD_FILE_MUST_EXIST, wxDefaultPosition);
if(dlg.ShowModal() == wxID_OK) {
zip_path->Clear();
*zip_path<<dlg.GetPath();
}
}
void ZipDialog::OnTips(wxCommandEvent& event)
{
wxMessageBox("Tips:\n This plugin is to unzip the template.zip.", "Help", wxOK, this);
}
void ZipDialog::OnImport(wxCommandEvent& event)
{
if(wxFileName::FileExists(zip_path->GetLineText(0)))
{
wxString folder = clStandardPaths::Get().GetUserProjectTemplatesDir();
wxFileName srcfile(zip_path->GetLineText(0), wxPATH_NATIVE);
wxFileName objfile(folder, srcfile.GetFullName(), wxPATH_NATIVE);
if(!wxCopyFile(srcfile.GetFullPath(), objfile.GetFullPath(), true))
{
wxMessageBox("Copy Failed!", "Notice", wxOK, this);
}
else
{
clZipReader zip_file(objfile);
zip_file.Extract("*", folder);
if(!wxRemoveFile(objfile.GetFullPath())) {
clLogMessage(wxT("Failed to remove"+objfile.GetFullPath()));
}
}
}
else
{
wxMessageBox("Can't find the zipfile, please check the path again", "Notice", wxOK, this);
}
}
void ZipDialog::OnUnzipAll(wxCommandEvent& event)
{
wxString folder = clStandardPaths::Get().GetUserProjectTemplatesDir();
if(wxFileName::DirExists(folder)){
//find and unzip *.zip under root index
wxString* zip_name = new wxString;
wxDir zip_path(folder);
if(zip_path.GetFirst(zip_name, "*.zip", wxDIR_DEFAULT))
{
do{
wxFileName zip_filename(folder, *zip_name, wxPATH_NATIVE);
zip_name->Prepend(zip_filename.GetPathWithSep(wxPATH_NATIVE));
clZipReader zip_file(zip_filename);
zip_file.Extract("*", folder);
if(!wxRemoveFile(*zip_name)) {
clLogMessage(wxT("Failed to remove"+(*zip_name)));
}
}while(zip_path.GetNext(zip_name));
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 Bryce Lelbach
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
////////////////////////////////////////////////////////////////////////////////
// This is example is equivalent to fibonacci.cpp, except that this example does
// not use actions (only plain functions). Many more variations are found in
// fibonacci_futures.cpp. This example is mainly intended to demonstrate async,
// futures and get for the documentation.
#include <pika/chrono.hpp>
#include <pika/future.hpp>
#include <pika/init.hpp>
#include <fmt/ostream.h>
#include <fmt/printf.h>
#include <chrono>
#include <cstdint>
#include <iostream>
///////////////////////////////////////////////////////////////////////////////
//[fibonacci
std::uint64_t fibonacci(std::uint64_t n)
{
if (n < 2) return n;
// Invoking the Fibonacci algorithm twice is inefficient.
// However, we intentionally demonstrate it this way to create some
// heavy workload.
pika::future<std::uint64_t> n1 = pika::async(fibonacci, n - 1);
pika::future<std::uint64_t> n2 = pika::async(fibonacci, n - 2);
return n1.get() + n2.get(); // wait for the Futures to return their values
}
//fibonacci]
///////////////////////////////////////////////////////////////////////////////
//[pika_main
int pika_main(pika::program_options::variables_map& vm)
{
// extract command line argument, i.e. fib(N)
std::uint64_t n = vm["n-value"].as<std::uint64_t>();
{
// Keep track of the time required to execute.
pika::chrono::detail::high_resolution_timer t;
std::uint64_t r = fibonacci(n);
constexpr char const* fmt = "fibonacci({}) == {}\nelapsed time: {} [s]\n";
fmt::print(std::cout, fmt, n, r, t.elapsed<std::chrono::seconds>());
}
return pika::finalize(); // Handles pika shutdown
}
//pika_main]
///////////////////////////////////////////////////////////////////////////////
//[main
int main(int argc, char* argv[])
{
// Configure application-specific options
pika::program_options::options_description desc_commandline(
"Usage: " PIKA_APPLICATION_STRING " [options]");
desc_commandline.add_options()("n-value",
pika::program_options::value<std::uint64_t>()->default_value(10),
"n value for the Fibonacci function");
// Initialize and run pika
pika::init_params init_args;
init_args.desc_cmdline = desc_commandline;
return pika::init(pika_main, argc, argv, init_args);
}
//main]
|
// NOTE: this doesn't really test anything except that things compile
#include "gtest/gtest.h"
#include "opennwa/Nwa.hpp"
#include "opennwa/nwa_pds/plusWpds.hpp"
#include "Tests/unit-tests/Source/opennwa/fixtures.hpp"
using namespace wali::wpds;
namespace opennwa {
namespace nwa_pds {
TEST(opennwa$nwa_pds$$plusWpds, compilationTest)
{
WPDS wpds;
Nwa nwa;
wpds = plusWpds(nwa, wpds);
}
}
}
|
#ifndef TREEFACE_QUAT_H
#define TREEFACE_QUAT_H
#include "treeface/math/Vec4.h"
#include <treecore/FloatUtils.h>
namespace treeface {
/**
* Quaternions are frequently used in 3D rotation.
*/
template<typename T>
struct Quat
{
typedef treecore::SimdObject<T, 4> DataType;
typedef typename treecore::similar_float<T>::type FloatType;
TREECORE_ALIGNED_ALLOCATOR(Quat);
/**
* @brief create quaternion representing zero rotation
*/
Quat(): data(T(0), T(0), T(0), T(1)) {}
/**
* @brief crete quaternion with value specified
* @param value
*/
Quat(const DataType& value): data(value) {}
Quat(const typename DataType::DataType& value): data(value) {}
/**
* @brief create quaternion by specifying all four components
* @param x: component 1
* @param y: component 2
* @param z: component 3
* @param w: component 4, represents cos(a/2)
*/
Quat(T x, T y, T z, T w): data(x, y, z, w) {}
/**
* @brief create quaternion with rotation specified by right-hand angle and axis
* @param angle: rotation around axis
* @param axis: direction of rotaton axis. The 4rd component will be omitted
*/
Quat(T angle, const Vec3<T>& axis)
{
set_angle_axis(angle, axis);
}
Quat(T angle, const Vec4<T>& axis)
{
set_angle_axis(angle, axis);
}
/**
* @brief get the value of 1st (x) axis component
* @return x
*/
T get_x() const noexcept
{
return data.template get<0>();
}
/**
* @brief get the value of 2nd (y) axis component
* @return y
*/
T get_y() const noexcept
{
return data.template get<1>();
}
/**
* @brief get the value of 3rd (z) axis component
* @return z
*/
T get_z() const noexcept
{
return data.template get<2>();
}
/**
* @brief get the value of 4th (w) component
* @return w
*/
T get_w() const noexcept
{
return data.template get<3>();
}
/**
* @brief get rotation represented by this quaternion
* @param angle: variable for storing angle
* @param axis: variable for storing axis in (x, y, z, 0)
*/
void get_angle_axis(T& angle, Vec3<T>& axis) const noexcept
{
T cos_d2 = data.template get<3>();
T sin_d2 = std::sqrt(1 - cos_d2 * cos_d2);
angle = std::acos(cos_d2) * 2;
DataType tmp = data / DataType(sin_d2);
axis.set(tmp.template get<0>(), tmp.template get<1>(), tmp.template get<2>());
}
void get_angle_axis(T& angle, Vec4<T>& axis) const noexcept
{
Vec3<T> tmp_axis;
get_angle_axis(angle, tmp_axis);
axis.set_direction(tmp_axis);
}
/**
* @brief set the value of 1st (x) axis component
* @param value: the value to be set to x component
*/
void set_x(T value) noexcept
{
data.template set<0>(value);
}
/**
* @brief set the value of 2nd (y) axis component
* @param value: the value to be set to y component
*/
void set_y(T value) noexcept
{
data.template set<1>(value);
}
/**
* @brief set the value of 3rd (z) axis component
* @param value: the value to be set to z component
*/
void set_z(T value) noexcept
{
data.template set<2>(value);
}
/**
* @brief set the value of 4th (w) component
* @param value: the value to be set to w component
*/
void set_w(T value) noexcept
{
data.template set<3>(value);
}
/**
* @brief set rotation by specifying right-hand angle and axis
* @param angle: rotation around axis
* @param axis: direction of rotation axis. The 4rd component will be omitted.
*/
void set_angle_axis(T angle, const Vec3<T>& axis) noexcept
{
T sine = std::sin(angle/2);
Vec3<T> tmp = axis;
tmp.normalize();
tmp *= sine;
data.set_all( tmp.x, tmp.y, tmp.z, std::sqrt(T(1) - sine*sine) );
}
void set_angle_axis(T angle, const Vec4<T>& axis) noexcept
{
set_angle_axis(angle, Vec3<T>(axis.get_x(), axis.get_y(), axis.get_z()) );
}
/**
* @brief set values to (-x, -y, -z, w)
*/
void inverse() noexcept;
/**
* @brief make quaternion length to be one
* @return length before normalize
*/
FloatType normalize() noexcept
{
FloatType len = length();
data /= DataType(T(len));
return len;
}
/**
* @brief get quaternion length
* @return length value
*/
FloatType length() const noexcept
{
return std::sqrt(length2());
}
/**
* @brief get length square
* @return length * length
*/
FloatType length2() const noexcept
{
return (data * data).sum();
}
/**
* @brief apply rotation represented by this quaternion to a vector
* @param input: vector to be rotated. To get correct result, the 4rd
* component of input vector should be zero.
* @return rotated vector
*/
Vec4<T> rotate(Vec4<T> input) const noexcept
{
Quat<T> inv(data);
inv.inverse();
Quat<T> re = *this * Quat<T>(input.data) * inv;
return Vec4<T>(re.data);
}
DataType data;
} TREECORE_ALN_END(16);
template<>
inline void Quat<float>::inverse() noexcept
{
// directly operate on float's sign bit
data ^= treecore::SimdObject<treecore::int32, 4>(0x80000000, 0x80000000, 0x80000000, 0x00000000);
}
/**
* @brief quaternion multiply
*/
template<typename T, int SZ = sizeof(T) * 4>
inline Quat<T> operator * (const Quat<T>& a, const Quat<T>& b) noexcept
{
//res.x = + a.x*b.w + a.y*b.z - a.z*b.y + a.w*b.x;
//res.y = - a.x*b.z + a.y*b.w + a.z*b.x + a.w*b.y;
//res.z = + a.x*b.y - a.y*b.x + a.z*b.w + a.w*b.z;
//res.w = - a.x*b.x - a.y*b.y - a.z*b.z + a.w*b.w;
Quat<T> result;
typename Quat<T>::DataType tmp1;
typename Quat<T>::DataType tmp2;
T av = a.get_x();
tmp1.set_all(av, -av, av, -av);
tmp2 = b.data;
tmp2.template shuffle<3, 2, 1, 0>();
result.data = tmp1 * tmp2;
av = a.get_y();
tmp1.set_all(av, av, -av, -av);
tmp2 = b.data;
tmp2.template shuffle<2, 3, 0, 1>();
result.data += tmp1 * tmp2;
av = a.get_z();
tmp1.set_all(-av, av, av, -av);
tmp2 = b.data;
tmp2.template shuffle<1, 0, 3, 2>();
result.data += tmp1 * tmp2;
av = a.get_w();
tmp1.set_all(av, av, av, av);
tmp2 = b.data;
result.data += tmp1 * tmp2;
return result;
}
typedef Quat<float> Quatf;
} // namespace treeface
#endif // TREEFACE_QUAT_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.