text
stringlengths 8
6.88M
|
|---|
#pragma once
namespace Constantes
{
const float PI = 3.1415927f;
const glm::mat4 biasMatrix(
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0
);
}
|
#include <iostream>
class CCSprite
{
public:
CCSprite(int d);
static void traverseCCSprite();
private:
int data;
CCSprite* next;
static CCSprite* head;
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef _SSL_UPDATERS_H_
#define _SSL_UPDATERS_H_
#if defined(_NATIVE_SSL_SUPPORT_) && defined(LIBSSL_AUTO_UPDATE)
#include "modules/updaters/update_man.h"
#ifdef LIBSSL_AUTO_UPDATE_ROOTS_PERIODICALLY
# include "modules/hardcore/base/periodic_task.h"
# include "modules/prefs/prefsmanager/opprefslistener.h"
#endif // LIBSSL_AUTO_UPDATE_ROOTS_PERIODICALLY
typedef class AutoFetch_Element SSL_AutoUpdaterElement;
class SSL_AutoUpdaters :
public AutoFetch_Manager
#ifdef LIBSSL_AUTO_UPDATE_ROOTS_PERIODICALLY
, public OpPrefsListener
#endif
{
#ifdef LIBSSL_AUTO_UPDATE_ROOTS_PERIODICALLY
private:
class PeriodicCheckUpdates: public PeriodicTask
{
public:
virtual void Run() { g_main_message_handler->PostMessage(MSG_SSL_START_AUTO_UPDATE, 0, 0); }
} m_checkUpdates;
#endif // LIBSSL_AUTO_UPDATE_ROOTS_PERIODICALLY
public:
SSL_AutoUpdaters()
: AutoFetch_Manager(MSG_SSL_FINISHED_AUTOUPDATE_BATCH)
{};
virtual ~SSL_AutoUpdaters();
void InitL();
virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2);
#ifdef LIBSSL_AUTO_UPDATE_ROOTS_PERIODICALLY
virtual void PrefChanged(OpPrefsCollection::Collections id , int pref, int newvalue);
#endif // LIBSSL_AUTO_UPDATE_ROOTS_PERIODICALLY
};
#endif
#endif //_SSL_UPDATERS_H_
|
/* -*- 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.
*/
#include "core/pch.h"
#include "adjunct/quick/managers/opsetupmanager.h"
#include "adjunct/quick/Application.h"
#include "adjunct/quick/dialogs/SimpleDialog.h"
#include "modules/inputmanager/inputmanager.h"
#include "modules/locale/locale-enum.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/prefs/prefsmanager/prefsmanager.h"
#include "modules/prefsfile/prefsentry.h"
#include "modules/prefsfile/prefssection.h"
#include "modules/prefsfile/prefsfile.h"
#include "modules/prefs/prefsmanager/collections/pc_core.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
#include "modules/skin/OpSkinManager.h"
#include "modules/util/filefun.h"
#include "modules/util/opstrlst.h"
// This can't be a desktop manager as it's used before the desktop managers are initialized
OpSetupManager* OpSetupManager::s_instance = NULL;
//==================================================================================
// Update these when new features are added that make older setups incompatible
// (This is only used for displaying 'incompatible version' dialogs to user)
#define CURRENT_TOOLBAR_VERSION_NUMBER 15
#define CURRENT_MENU_VERSION_NUMBER 2
#define CURRENT_KEYBOARD_VERSION_NUMBER 1
#define CURRENT_MOUSE_VERSION_NUMBER 1
//==================================================================================
#ifdef EMBROWSER_SUPPORT
extern long gVendorDataID;
#endif //EMBROWSER_SUPPORT
/***********************************************************************************
**
** OpSetupManager
**
***********************************************************************************/
OpSetupManager::OpSetupManager()
: m_mouse_prefsfile(NULL)
, m_default_mouse_prefsfile(NULL)
, m_keyboard_prefsfile(NULL)
, m_default_keyboard_prefsfile(NULL)
, m_menu_prefsfile(NULL)
, m_custom_menu_prefsfile(NULL)
, m_default_menu_prefsfile(NULL)
, m_toolbar_prefsfile(NULL)
, m_custom_toolbar_prefsfile(NULL)
, m_default_toolbar_prefsfile(NULL)
, m_override_dialog_prefsfile(NULL)
, m_custom_dialog_prefsfile(NULL)
, m_dialog_prefsfile(NULL)
#ifdef PREFS_HAVE_FASTFORWARD
, m_fastforward_section(NULL)
#endif // PREFS_HAVE_FASTFORWARD
{
}
/***********************************************************************************
**
** ~OpSetupManager
**
***********************************************************************************/
OpSetupManager::~OpSetupManager()
{
TRAPD(err, CommitL());
OpStatus::Ignore(err);
OP_DELETE(m_mouse_prefsfile);
OP_DELETE(m_default_mouse_prefsfile);
OP_DELETE(m_keyboard_prefsfile);
OP_DELETE(m_default_keyboard_prefsfile);
OP_DELETE(m_menu_prefsfile);
OP_DELETE(m_toolbar_prefsfile);
OP_DELETE(m_custom_menu_prefsfile);
OP_DELETE(m_custom_toolbar_prefsfile);
OP_DELETE(m_default_toolbar_prefsfile);
OP_DELETE(m_override_dialog_prefsfile);
OP_DELETE(m_custom_dialog_prefsfile);
OP_DELETE(m_dialog_prefsfile);
OP_DELETE(m_default_menu_prefsfile);
#ifdef PREFS_HAVE_FASTFORWARD
OP_DELETE(m_fastforward_section);
#endif // PREFS_HAVE_FASTFORWARD
}
/***********************************************************************************
**
** Init
**
***********************************************************************************/
OP_STATUS OpSetupManager::Init()
{
TRAPD(rc, InitL());
return rc;
}
/***********************************************************************************
**
** InitL
**
***********************************************************************************/
void OpSetupManager::InitL()
{
OpFile mousefile; ANCHOR(OpFile, mousefile);
OpFile keyboardfile; ANCHOR(OpFile, keyboardfile);
OpFile toolbarfile; ANCHOR(OpFile, toolbarfile);
OpFile menufile; ANCHOR(OpFile, menufile);
OpFile dialogfile; ANCHOR(OpFile, dialogfile);
# ifdef PREFS_HAVE_FASTFORWARD
OpFile fastforwardfile; ANCHOR(OpFile, fastforwardfile);
# endif // PREFS_HAVE_FASTFORWARD
g_pcfiles->GetFileL(PrefsCollectionFiles::ToolbarConfig, toolbarfile);
g_pcfiles->GetFileL(PrefsCollectionFiles::MenuConfig, menufile);
g_pcfiles->GetFileL(PrefsCollectionFiles::DialogConfig, dialogfile);
# ifdef PREFS_HAVE_FASTFORWARD
g_pcfiles->GetFileL(PrefsCollectionFiles::FastForwardFile, fastforwardfile);
# endif // PREFS_HAVE_FASTFORWARD
g_pcfiles->GetFileL(PrefsCollectionFiles::KeyboardConfig, keyboardfile);
g_pcfiles->GetFileL(PrefsCollectionFiles::MouseConfig, mousefile);
////////////////// toolbar configuration file //////////////////////
m_toolbar_prefsfile = InitializeCustomPrefsFileL(&toolbarfile, "standard_toolbar.ini", OPFILE_TOOLBARSETUP_FOLDER);
m_custom_toolbar_prefsfile = InitializeCustomPrefsFileL(NULL, "standard_toolbar.ini", OPFILE_UI_INI_CUSTOM_FOLDER);
////////////////// default toolbar configuration file //////////////////////
m_default_toolbar_prefsfile = InitializeCustomPrefsFileL(NULL, "standard_toolbar.ini", OPFILE_UI_INI_FOLDER);
////////////////// dialog configuration file //////////////////////
m_override_dialog_prefsfile = InitializeCustomPrefsFileL(&dialogfile, "dialog.ini", OPFILE_TOOLBARSETUP_FOLDER);
m_dialog_prefsfile = InitializeCustomPrefsFileL(NULL, "dialog.ini", OPFILE_UI_INI_FOLDER);
m_custom_dialog_prefsfile = InitializeCustomPrefsFileL(NULL, "dialog.ini", OPFILE_UI_INI_CUSTOM_FOLDER);
////////////////// default menu configuration file //////////////////////
m_default_menu_prefsfile = InitializeCustomPrefsFileL(NULL, "standard_menu.ini", OPFILE_UI_INI_FOLDER);
////////////////// mouse, keyboard and menu configuration file //////////////////////
#ifdef EMBROWSER_SUPPORT
if (gVendorDataID != 'OPRA')
{
m_mouse_prefsfile = InitializePrefsFileL(&mousefile, "embedded_mouse.ini", 0);
m_keyboard_prefsfile = InitializePrefsFileL(&keyboardfile, "embedded_keyboard.ini", 0);
m_menu_prefsfile = InitializePrefsFileL(&menufile, "embedded_menu.ini", 0);
}
else
#endif // EMBROWSER_SUPPORT
{
m_mouse_prefsfile = InitializePrefsFileL(&mousefile, "standard_mouse.ini", 0);
m_keyboard_prefsfile = InitializePrefsFileL(&keyboardfile, "standard_keyboard.ini", 0);
m_custom_menu_prefsfile = InitializeCustomPrefsFileL(NULL, "standard_menu.ini", OPFILE_UI_INI_CUSTOM_FOLDER);
m_menu_prefsfile = InitializeCustomPrefsFileL(&menufile, "standard_menu.ini", OPFILE_MENUSETUP_FOLDER);
}
////////////////// default mouse configuration file //////////////////////
m_default_mouse_prefsfile = InitializePrefsFileL(NULL, "standard_mouse.ini", 0);
////////////////// default keyboard configuration file //////////////////////
m_default_keyboard_prefsfile = InitializePrefsFileL(NULL, "standard_keyboard.ini", 0);
#ifdef PREFS_HAVE_FASTFORWARD
////////////////// fastforward configuration file //////////////////////
PrefsFile *fastforward_prefsfile = InitializeCustomPrefsFileL(&fastforwardfile, "fastforward.ini", OPFILE_UI_INI_FOLDER);
if (fastforward_prefsfile)
{
m_fastforward_section = fastforward_prefsfile->ReadSectionL(UNI_L("Fast forward"));
OP_DELETE(fastforward_prefsfile);
// Load the custom fast forward over the top
OpStackAutoPtr<PrefsFile> custom_fastforward_prefsfile (InitializeCustomPrefsFileL(NULL, "fastforward.ini", OPFILE_UI_INI_CUSTOM_FOLDER));
if (custom_fastforward_prefsfile.get())
{
OpStackAutoPtr<PrefsSection> custom_fastforward_section (custom_fastforward_prefsfile->ReadSectionL(UNI_L("Fast forward")));
// Copy this section over the last section
m_fastforward_section->CopyKeysL(custom_fastforward_section.get());
}
}
#endif // PREFS_HAVE_FASTFORWARD
ScanSetupFoldersL(); //need to know which files is where
}
void OpSetupManager::CommitL()
{
if (m_mouse_prefsfile)
m_mouse_prefsfile->CommitL(FALSE, FALSE);
if (m_keyboard_prefsfile)
m_keyboard_prefsfile->CommitL(FALSE, FALSE);
if (m_menu_prefsfile)
m_menu_prefsfile->CommitL(FALSE, FALSE);
if (m_toolbar_prefsfile)
m_toolbar_prefsfile->CommitL(FALSE, FALSE);
}
/***********************************************************************************
**
** GetCurrentSetupRevision
**
***********************************************************************************/
INT32 OpSetupManager::GetCurrentSetupRevision(enum OpSetupType type)
{
switch(type)
{
case OPTOOLBAR_SETUP:
return CURRENT_TOOLBAR_VERSION_NUMBER;
case OPMENU_SETUP:
return CURRENT_MENU_VERSION_NUMBER;
case OPMOUSE_SETUP:
return CURRENT_MOUSE_VERSION_NUMBER;
case OPKEYBOARD_SETUP:
return CURRENT_KEYBOARD_VERSION_NUMBER;
default:
return -1;
}
}
/***********************************************************************************
**
** InitializePrefsFileL
**
***********************************************************************************/
PrefsFile* OpSetupManager::InitializePrefsFileL(OpFile* defaultfile, const char* fallbackfile, INT32 flag )
{
PrefsFile* prefsfile = OP_NEW_L(PrefsFile, (PREFS_STD));
OpFile* file; // warning: variable 'file' might be clobbered by 'longjmp' or 'vfork'
OP_STATUS err; // FIXME: status values saved here aren't checked for error !
BOOL fileexists = FALSE;
if (defaultfile && OpStatus::IsSuccess(defaultfile->Exists(fileexists)) && fileexists)
{
file = defaultfile;
}
else
{
file = OP_NEW_L(OpFile, ()); // FIXME: leaks prefsfile if it LEAVE()s
OpString fallback;
LEAVE_IF_ERROR(fallback.Set(fallbackfile));
err = file->Construct(fallback.CStr(), OPFILE_USERPREFS_FOLDER);
err = file->Exists(fileexists);
if (!fileexists) // fallback to system folder:
{
OP_DELETE(file);
file = OP_NEW_L(OpFile, ()); // FIXME: leaks prefsfile if it LEAVE()s
err = file->Construct(fallback.CStr(), OPFILE_UI_INI_FOLDER);
}
}
// FIXME: handle errors !
TRAP(err, prefsfile->ConstructL());
TRAP(err, prefsfile->SetFileL(file));
TRAP(err, prefsfile->LoadAllL());
// ... but note that error handling mustn't leak these (or prefsfile) !
if (file != defaultfile)
OP_DELETE(file);
return prefsfile;
}
PrefsFile* OpSetupManager::InitializeCustomPrefsFileL(OpFile* defaultfile, const char* pref_filename, OpFileFolder op_folder)
{
BOOL fileexists = FALSE;
PrefsFile* prefsfile = OP_NEW_L(PrefsFile, (PREFS_STD));
OpFile* file; // warning: variable 'file' might be clobbered by 'longjmp' or 'vfork'
OP_STATUS err; // FIXME: status values saved here aren't checked for error !
if (defaultfile && OpStatus::IsSuccess(defaultfile->Exists(fileexists)) && fileexists)
{
file = defaultfile;
}
else
{
file = OP_NEW_L(OpFile, ()); // FIXME: leaks prefsfile if it LEAVE()s
OpString filename;
LEAVE_IF_ERROR(filename.Set(pref_filename));
err = file->Construct(filename.CStr(), op_folder);
}
// FIXME: handle errors !
TRAP(err, prefsfile->ConstructL());
TRAP(err, prefsfile->SetFileL(file));
TRAP(err, prefsfile->LoadAllL());
// ... but note that error handling mustn't leak these (or prefsfile) !
if (file != defaultfile)
OP_DELETE(file);
return prefsfile;
}
/***********************************************************************************
**
** ScanSetupFoldersL
**
***********************************************************************************/
void OpSetupManager::ScanSetupFoldersL()
{
m_toolbar_setup_list.DeleteAll();
m_menu_setup_list.DeleteAll();
m_mouse_setup_list.DeleteAll();
m_keyboard_setup_list.DeleteAll();
//manually add the known files to the top of the vector, we are a bit bold here, but lets assume the installer makes no mistakes
// these are today :
//
// toolbar
// standard_toolbar.ini *
// minimal_toolbar.ini
// keyboard
// standard_keyboard.ini *
// mouse
// standard_mouse.ini *
// menu
// standard_menu.ini *
//
// * these are fallback-files, meaning if a copy is made, an empty will be sufficient
OpString defaultsfolder;
LEAVE_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_UI_INI_FOLDER, defaultsfolder));
OpString* defaults_standard_toolbarfile = OP_NEW(OpString, ());
defaults_standard_toolbarfile->SetL(defaultsfolder);
defaults_standard_toolbarfile->AppendL(UNI_L("standard_toolbar.ini"));
m_toolbar_setup_list.Add(defaults_standard_toolbarfile); // FIXME: MAP
OpString* defaults_standard_menufile = OP_NEW(OpString, ());
defaults_standard_menufile->SetL(defaultsfolder);
defaults_standard_menufile->AppendL(UNI_L("standard_menu.ini"));
m_menu_setup_list.Add(defaults_standard_menufile);
RemoveNonExistingFiles(m_menu_setup_list);
OpString* defaults_standard_mousefile = OP_NEW(OpString, ());
defaults_standard_mousefile->SetL(defaultsfolder);
defaults_standard_mousefile->AppendL(UNI_L("standard_mouse.ini"));
m_mouse_setup_list.Add(defaults_standard_mousefile);
RemoveNonExistingFiles(m_mouse_setup_list);
OpString* defaults_standard_keyboardfile = OP_NEW(OpString, ());
defaults_standard_keyboardfile->SetL(defaultsfolder);
defaults_standard_keyboardfile->AppendL(UNI_L("standard_keyboard.ini"));
m_keyboard_setup_list.Add(defaults_standard_keyboardfile);
// 9.2 compatable file
OpString* defaults_standard_keyboard_compat_file = OP_NEW(OpString, ());
defaults_standard_keyboard_compat_file->SetL(defaultsfolder);
defaults_standard_keyboard_compat_file->AppendL(UNI_L("standard_keyboard_compat.ini"));
m_keyboard_setup_list.Add(defaults_standard_keyboard_compat_file);
#if defined(UNIX)
OpString* unix_keyboardfile = OP_NEW(OpString, ());
unix_keyboardfile->SetL(defaultsfolder);
unix_keyboardfile->AppendL(UNI_L("unix_keyboard.ini"));
m_keyboard_setup_list.Add(unix_keyboardfile);
#endif
RemoveNonExistingFiles(m_keyboard_setup_list);
// then scan the user directory
OpString wildcard; ANCHOR(OpString, wildcard);
wildcard.SetL(UNI_L("*.ini"));
OpString directory; ANCHOR(OpString, directory);
OpString mousesetupdirectory;
LEAVE_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_MOUSESETUP_FOLDER, mousesetupdirectory));
directory.SetL(mousesetupdirectory);
ScanFolderL(wildcard, directory, OPMOUSE_SETUP); // FIXME: MAP
OpString keyboardsetupdirectory;
LEAVE_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_KEYBOARDSETUP_FOLDER, keyboardsetupdirectory));
directory.SetL(keyboardsetupdirectory);
ScanFolderL(wildcard, directory, OPKEYBOARD_SETUP);
OpString toolbarsetupdirectory;
LEAVE_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_TOOLBARSETUP_FOLDER, toolbarsetupdirectory));
directory.SetL(toolbarsetupdirectory);
ScanFolderL(wildcard, directory, OPTOOLBAR_SETUP);
OpString menusetupdirectory;
LEAVE_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_MENUSETUP_FOLDER, menusetupdirectory));
directory.SetL(menusetupdirectory);
ScanFolderL(wildcard, directory, OPMENU_SETUP);
// We need at least one working file of each type
if (m_toolbar_setup_list.GetCount() == 0 || m_menu_setup_list.GetCount() == 0 || m_mouse_setup_list.GetCount() == 0 || m_keyboard_setup_list.GetCount() == 0)
LEAVE(OpStatus::ERR);
}
/***********************************************************************************
**
** CheckFolders
**
***********************************************************************************/
void OpSetupManager::RemoveNonExistingFiles(OpVector<OpString>& list)
{
for (UINT32 i=0; i < list.GetCount();)
{
OpFile file;
file.Construct(*list.Get(i));
BOOL exists;
if (OpStatus::IsError(file.Exists(exists)) || !exists)
list.Delete(i);
else
i++;
}
}
/***********************************************************************************
**
** IsEditable
**
***********************************************************************************/
bool OpSetupManager::IsEditable(UINT32 index, OpSetupType type)
{
OpVector<OpString>* list = NULL;
switch (type)
{
case OPTOOLBAR_SETUP:
list = &m_toolbar_setup_list;
break;
case OPMENU_SETUP:
list = &m_menu_setup_list;
break;
case OPMOUSE_SETUP:
list = &m_mouse_setup_list;
break;
case OPKEYBOARD_SETUP:
list = &m_keyboard_setup_list;
break;
}
if (list && index < list->GetCount())
{
OpFile file;
file.Construct(*list->Get(index));
BOOL exists;
if (OpStatus::IsSuccess(file.Exists(exists)) && exists)
{
OpString defaultsfolder;
g_folder_manager->GetFolderPath(OPFILE_UI_INI_FOLDER, defaultsfolder);
OpStringC name = file.GetFullPath();
if (name.Find(defaultsfolder) != 0)
return true;
}
}
return false;
}
/***********************************************************************************
**
** ScanFolderL
**
***********************************************************************************/
void OpSetupManager::ScanFolderL( const OpString& searchtemplate, const OpString& rootfolder, enum OpSetupType type)
{
#ifdef DIRECTORY_SEARCH_SUPPORT
if( rootfolder.Length() > 0 && searchtemplate.Length() > 0 )
{
OpFolderLister *dirlist = OpFile::GetFolderLister(OPFILE_ABSOLUTE_FOLDER, searchtemplate.CStr(), rootfolder.CStr());
if (!dirlist)
return;
while(dirlist->Next())
{
const uni_char *candidate = dirlist->GetFullPath();
if( candidate )
{
OpString* filename = OP_NEW_L(OpString, ());
filename->Set( candidate );
switch(type)
{
case OPTOOLBAR_SETUP:
m_toolbar_setup_list.Add(filename);
break;
case OPMENU_SETUP:
m_menu_setup_list.Add(filename);
break;
case OPMOUSE_SETUP:
m_mouse_setup_list.Add(filename);
break;
case OPKEYBOARD_SETUP:
m_keyboard_setup_list.Add(filename);
break;
}
}
}
OP_DELETE(dirlist);
}
#endif // DIRECTORY_SEARCH_SUPPORT
}
/***********************************************************************************
**
** GetTypeCount
**
***********************************************************************************/
UINT32 OpSetupManager::GetTypeCount(enum OpSetupType type)
{
switch(type)
{
case OPTOOLBAR_SETUP:
return m_toolbar_setup_list.GetCount();
case OPMENU_SETUP:
return m_menu_setup_list.GetCount();
case OPMOUSE_SETUP:
return m_mouse_setup_list.GetCount();
case OPKEYBOARD_SETUP:
return m_keyboard_setup_list.GetCount();
}
return 0;
}
/***********************************************************************************
**
** SelectSetupFile
**
***********************************************************************************/
OP_STATUS OpSetupManager::SelectSetupFile(INT32 index, enum OpSetupType type, BOOL broadcast_change)
{
PrefsFile* setupfile;
TRAPD(rc, setupfile = GetSetupPrefsFileL(index, type));
if (OpStatus::IsSuccess(rc))
{
rc = SelectSetupByFile(setupfile, type, broadcast_change);
}
return rc;
}
/***********************************************************************************
**
** SelectSetupByFile
**
***********************************************************************************/
OP_STATUS OpSetupManager::SelectSetupByFile(PrefsFile* setupfile, enum OpSetupType type, BOOL broadcast_change)
{
INT32 setupfile_version = 0;
if (setupfile)
{
setupfile_version = setupfile->ReadIntL(UNI_L("Version"),UNI_L("File Version"), -1);
}
// if the file didn't have a file version entry we 'assume' it is a empty fallback file
// else check check if the file is a compatible file
if(setupfile_version != -1 && setupfile_version < GetCurrentSetupRevision(type))
{
if (g_application)
{
SetupVersionError* versiondialog = OP_NEW(SetupVersionError, ());
versiondialog->Init(g_application->GetActiveDesktopWindow());
}
return OpStatus::ERR;
}
switch(type)
{
case OPSKIN_SETUP:
{
OP_ASSERT(FALSE); // this is not possible, use g_skin_manager instead
}
break;
case OPTOOLBAR_SETUP:
{
OP_DELETE(m_toolbar_prefsfile);
m_toolbar_prefsfile = setupfile;
TRAPD(err, g_pcfiles->WriteFilePrefL(PrefsCollectionFiles::ToolbarConfig, (OpFile*)setupfile->GetFile()));
}
break;
case OPMENU_SETUP:
{
OP_DELETE(m_menu_prefsfile);
m_menu_prefsfile = setupfile;
TRAPD(err, g_pcfiles->WriteFilePrefL(PrefsCollectionFiles::MenuConfig, (OpFile*)setupfile->GetFile()));
}
break;
case OPMOUSE_SETUP:
{
OP_DELETE(m_mouse_prefsfile);
m_mouse_prefsfile = setupfile;
TRAPD(err, g_pcfiles->WriteFilePrefL(PrefsCollectionFiles::MouseConfig, (OpFile*)setupfile->GetFile()));
}
break;
case OPKEYBOARD_SETUP:
{
OP_DELETE(m_keyboard_prefsfile);
m_keyboard_prefsfile = setupfile;
TRAPD(err, g_pcfiles->WriteFilePrefL(PrefsCollectionFiles::KeyboardConfig, (OpFile*)setupfile->GetFile()));
}
break;
}
if(broadcast_change)
{
BroadcastChange(type);
}
TRAPD(err, g_prefsManager->CommitL());
return OpStatus::OK;
}
/***********************************************************************************
**
** SelectSetupByFile
**
***********************************************************************************/
OP_STATUS OpSetupManager::SelectSetupByFile(const uni_char* filename, enum OpSetupType type, BOOL broadcast_change)
{
OpAutoPtr<OpFile> file(OP_NEW(OpFile, ()));
RETURN_OOM_IF_NULL(file.get());
PrefsFile* pfile = OP_NEW(PrefsFile, (PREFS_STD));
RETURN_OOM_IF_NULL(pfile);
TRAPD(err, pfile->ConstructL());
TRAP(err, pfile->SetFileL(file.get()));
TRAP(err, pfile->LoadAllL());
return SelectSetupByFile(pfile, type, broadcast_change);
}
/***********************************************************************************
**
** ReloadSetupFile
**
***********************************************************************************/
OP_STATUS OpSetupManager::ReloadSetupFile(enum OpSetupType type)
{
PrefsFile* file = GetSetupFile(type);
if(file)
{
file->Flush();
TRAPD(err, file->LoadAllL());
g_input_manager->Flush();
return OpStatus::OK;
}
return OpStatus::ERR_NULL_POINTER;
}
/***********************************************************************************
**
** GetSetupName
**
***********************************************************************************/
OP_STATUS OpSetupManager::GetSetupName(OpString* filename, INT32 index, enum OpSetupType type)
{
OpString actualfilename;
PrefsFile* prefsfile;
TRAPD(ret, prefsfile = GetSetupPrefsFileL(index, type, &actualfilename, FALSE));
RETURN_IF_ERROR(ret);
OpString name;
TRAPD(ignore_ret, prefsfile->ReadStringL(UNI_L("INFO"),UNI_L("NAME"), name));
OP_DELETE(prefsfile);
if (name.HasContent())
{
ret = filename->Set(name);
}
else
{
int patseppos = actualfilename.FindLastOf(PATHSEPCHAR);
if (KNotFound != patseppos) //we got a pathseparator, remove it
ret = actualfilename.Set(actualfilename.SubString(patseppos+1));
if (OpStatus::IsSuccess(ret))
{
int dot = actualfilename.FindLastOf('.');
if (KNotFound != dot) //we got a dot, terminate at it
ret = filename->Set(actualfilename.CStr(), dot);
else
ret = filename->Set(actualfilename);
}
}
return ret;
}
/***********************************************************************************
**
** GetIndexOfMouseSetup
**
***********************************************************************************/
INT32 OpSetupManager::GetIndexOfMouseSetup()
{
UINT no = GetMouseConfigurationCount();
OpString currentmousefile; ANCHOR(OpString, currentmousefile);
currentmousefile.Set(((OpFile*)m_mouse_prefsfile->GetFile())->GetFullPath()); // FIXME: MAP
while(no)
{
if(m_mouse_setup_list.Get(--no)->CompareI(currentmousefile) == 0)
{
return no;
}
}
return -1;
}
/***********************************************************************************
**
** GetIndexOfKeyboardSetup
**
***********************************************************************************/
INT32 OpSetupManager::GetIndexOfKeyboardSetup()
{
UINT no = GetKeyboardConfigurationCount();
OpString currentkeyboardfile; ANCHOR(OpString, currentkeyboardfile);
currentkeyboardfile.Set(((OpFile*)m_keyboard_prefsfile->GetFile())->GetFullPath()); // FIXME: MAP
while(no)
{
if(m_keyboard_setup_list.Get(--no)->CompareI(currentkeyboardfile) == 0)
{
return no;
}
}
return -1;
}
/***********************************************************************************
**
** GetIndexOfMenuSetup
**
***********************************************************************************/
INT32 OpSetupManager::GetIndexOfMenuSetup()
{
UINT no = GetMenuConfigurationCount();
OpString currentfile; ANCHOR(OpString, currentfile);
currentfile.Set(((OpFile*)m_menu_prefsfile->GetFile())->GetFullPath()); // FIXME: MAP
while(no)
{
if(m_menu_setup_list.Get(--no)->CompareI(currentfile) == 0)
{
return no;
}
}
return -1;
}
/***********************************************************************************
**
** GetIndexOfToolbarSetup
**
***********************************************************************************/
INT32 OpSetupManager::GetIndexOfToolbarSetup()
{
UINT no = GetToolbarConfigurationCount();
OpString currenttoolbarfile; ANCHOR(OpString, currenttoolbarfile);
currenttoolbarfile.Set(((OpFile*)m_toolbar_prefsfile->GetFile())->GetFullPath()); // FIXME: MAP
while(no)
{
if(m_toolbar_setup_list.Get(--no)->CompareI(currenttoolbarfile) == 0)
{
return no;
}
}
return -1;
}
/***********************************************************************************
**
** DeleteSetup
**
***********************************************************************************/
void OpSetupManager::DeleteSetupL(INT32 index, enum OpSetupType type)
{
OpString* discard_filename = NULL;
INT32 currentindex = -1;
switch(type)
{
case OPTOOLBAR_SETUP:
{
if(index == 0)
{
LEAVE(OpStatus::ERR);
}
currentindex = GetIndexOfToolbarSetup();
discard_filename = m_toolbar_setup_list.Get(index);
}
break;
case OPMENU_SETUP:
{
if(index == 0)
{
LEAVE(OpStatus::ERR);
}
currentindex = GetIndexOfMenuSetup();
discard_filename = m_menu_setup_list.Get(index);
}
break;
case OPMOUSE_SETUP:
{
if(index == 0)
{
LEAVE(OpStatus::ERR);
}
currentindex = GetIndexOfMouseSetup();
discard_filename = m_mouse_setup_list.Get(index);
}
break;
case OPKEYBOARD_SETUP:
{
if(index == 0)
{
LEAVE(OpStatus::ERR);
}
currentindex = GetIndexOfKeyboardSetup();
discard_filename = m_keyboard_setup_list.Get(index);
}
break;
}
if(currentindex == index)
{
INT32 newidx = (index == 0) ? 1 : index - 1;
LEAVE_IF_ERROR(SelectSetupFile(newidx, type));
}
OpFile filetodelete;
filetodelete.Construct(discard_filename->CStr());
filetodelete.Delete();
ScanSetupFoldersL();
}
/***********************************************************************************
**
** DuplicateSetupL
**
***********************************************************************************/
void OpSetupManager::DuplicateSetupL(INT32 index, enum OpSetupType type, BOOL copy_contents, BOOL index_check, BOOL modified, UINT32 *returnindex)
{
#if defined(SUPPORT_ABSOLUTE_TEXTPATH) //this should really get into the next generation of OpFile
PrefsFile* duplicated = GetSetupPrefsFileL(index, type, NULL, FALSE);
ANCHOR_PTR(PrefsFile, duplicated);
OpFile* source = (OpFile*)duplicated->GetFile();
OpString only_filename;
ANCHOR(OpString, only_filename);
OpString only_extension;
ANCHOR(OpString, only_extension);
OpString* duplicate_filename = OP_NEW(OpString, ());
LEAVE_IF_NULL(duplicate_filename);
duplicate_filename->ReserveL(_MAX_PATH);
uni_strncpy(duplicate_filename->DataPtr(), source->GetName(), _MAX_PATH-1);
int pos = duplicate_filename->FindLastOf('.');
if(pos != KNotFound)
{
only_filename.SetL(duplicate_filename->CStr(), pos);
only_extension.SetL(duplicate_filename->SubString(pos+1));
}
else
{
only_filename.SetL(*duplicate_filename);
}
BOOL exist = FALSE;
LEAVE_IF_ERROR(source->Exists(exist));
if (exist)
{
OpString only_path;
ANCHOR(OpString, only_path);
switch(type)
{
case OPMOUSE_SETUP:
{
LEAVE_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_MOUSESETUP_FOLDER, only_path));
}
break;
case OPKEYBOARD_SETUP:
{
LEAVE_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_KEYBOARDSETUP_FOLDER, only_path));
}
break;
case OPTOOLBAR_SETUP:
{
LEAVE_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_TOOLBARSETUP_FOLDER, only_path));
}
break;
case OPMENU_SETUP:
{
LEAVE_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_MENUSETUP_FOLDER, only_path));
}
break;
}
LEAVE_IF_ERROR(CreateUniqueFilename(*duplicate_filename, only_path, only_filename, only_extension, TRUE));
}
OpFile destination;
ANCHOR(OpFile, destination);
if(copy_contents)
{
destination.Construct(duplicate_filename->CStr());
LEAVE_IF_ERROR(destination.CopyContents(source, TRUE));
}
else
{
LEAVE_IF_ERROR(destination.Construct(duplicate_filename->CStr()));
LEAVE_IF_ERROR(destination.Open(OPFILE_WRITE | OPFILE_TEXT));
destination.Close();
}
ANCHOR_PTR_RELEASE(duplicated);
OP_DELETE(duplicated);
#endif //(SUPPORT_ABSOLUTE_TEXTPATH)
switch(type)
{
case OPTOOLBAR_SETUP:
{
m_toolbar_setup_list.Add(duplicate_filename);
if(returnindex)
{
*returnindex=m_toolbar_setup_list.GetCount()-1;
}
}
break;
case OPMENU_SETUP:
{
m_menu_setup_list.Add(duplicate_filename);
if(returnindex)
{
*returnindex=m_menu_setup_list.GetCount()-1;
}
}
break;
case OPMOUSE_SETUP:
{
m_mouse_setup_list.Add(duplicate_filename);
if(returnindex)
{
*returnindex=m_mouse_setup_list.GetCount()-1;
}
}
break;
case OPKEYBOARD_SETUP:
{
m_keyboard_setup_list.Add(duplicate_filename);
if(returnindex)
{
*returnindex=m_keyboard_setup_list.GetCount()-1;
}
}
break;
}
OpString copyofstr;
ANCHOR(OpString, copyofstr);
OpString name;
ANCHOR(OpString, name);
LEAVE_IF_ERROR(GetSetupName(&name, index, type));
if(modified)
{
OpString modified_str;
copyofstr.SetL(name);
g_languageManager->GetStringL(Str::S_MODIFIED_SETUPFILE, modified_str);
copyofstr.AppendL(UNI_L(" "));
copyofstr.AppendL(modified_str);
}
else
{
g_languageManager->GetStringL(Str::S_COPY_OF_SETUPFILE, copyofstr);
copyofstr.AppendL(UNI_L(" "));
copyofstr.AppendL(name);
}
RenameSetupPrefsFileL(copyofstr.CStr(), GetTypeCount(type)-1, type); //the duplicate is always the last
}
/***********************************************************************************
**
** GetSetupPrefsFileL
**
***********************************************************************************/
PrefsFile* OpSetupManager::GetSetupPrefsFileL(volatile INT32 index, enum OpSetupType type, OpString* actualfilename, BOOL index_check)
{
// before we load, make sure the current setup of that type is commited
PrefsFile* current = GetSetupFile(type);
if (current)
{
current->CommitL(FALSE, FALSE);
}
#ifndef PREFS_NO_WRITE
// if the index is one of the locked indexes, take a copy of the file and return this.
if (index_check)
{
BOOL locked_index = index == 0;
// We provide more than one keyboard file that is locked
if (!locked_index && type == OPKEYBOARD_SETUP)
{
OpString* name = m_keyboard_setup_list.Get(index);
if (name)
{
OpString defaultsfolder;
g_folder_manager->GetFolderPath(OPFILE_UI_INI_FOLDER, defaultsfolder);
locked_index = name->Find(defaultsfolder) == 0;
}
}
if (locked_index)
{
// Copy content to new file if we do not modify the first file. A missing
// section will cause a fallback to the first file.
volatile BOOL copy_contents = type == OPKEYBOARD_SETUP && index > 0;
UINT32 newindex;
DuplicateSetupL(index, type, copy_contents, FALSE, TRUE, &newindex);
SelectSetupFile(newindex, type, FALSE);
index = newindex;
}
}
#endif // PREFS_NO_WRITE
OpString* filename = NULL;
switch(type)
{
case OPTOOLBAR_SETUP:
{
filename = m_toolbar_setup_list.Get(index);
}
break;
case OPMENU_SETUP:
{
filename = m_menu_setup_list.Get(index);
}
break;
case OPMOUSE_SETUP:
{
filename = m_mouse_setup_list.Get(index);
}
break;
case OPKEYBOARD_SETUP:
{
filename = m_keyboard_setup_list.Get(index);
}
break;
}
if(filename == NULL)
{
LEAVE(OpStatus::ERR_NULL_POINTER);
}
if(actualfilename)
{
actualfilename->SetL(*filename);
}
OpFile file;
LEAVE_IF_ERROR(file.Construct(filename->CStr()));
PrefsFile* prefsfile = OP_NEW(PrefsFile, (PREFS_STD));
ANCHOR_PTR(PrefsFile, prefsfile);
prefsfile->ConstructL();
prefsfile->SetFileL(&file);
prefsfile->LoadAllL();
ANCHOR_PTR_RELEASE(prefsfile);
return prefsfile;
}
/***********************************************************************************
**
** RenameSetupPrefsFileL
**
***********************************************************************************/
void OpSetupManager::RenameSetupPrefsFileL(const uni_char* newname, INT32 index, enum OpSetupType type)
{
PrefsFile* prefsfile = GetSetupPrefsFileL(index, type);
OpString name;
prefsfile->WriteStringL(UNI_L("INFO"),UNI_L("NAME"), newname);
prefsfile->CommitL();
OP_DELETE(prefsfile);
}
/***********************************************************************************
**
** GetStringL
**
***********************************************************************************/
void OpSetupManager::GetStringL(OpString &string, const OpStringC8 §ionname, const OpStringC &key, enum OpSetupType type, BOOL master)
{
PrefsSection* section = GetSectionL(sectionname, type, NULL, master);
if(section)
{
OP_STATUS err = string.Set(section->Get(key));
OP_DELETE(section);
LEAVE_IF_ERROR(err);
}
}
/***********************************************************************************
**
** GetIntL
**
***********************************************************************************/
int OpSetupManager::GetIntL(const OpStringC8 §ionname, const OpStringC &key, enum OpSetupType type, int defval, BOOL master)
{
PrefsSection* section = GetSectionL(sectionname, type, NULL, master);
int result_int = defval;
if(section)
{
const uni_char *result;
result = section->Get(key);
if(result) // we could try to get it from the default file, if section is in the "user-file"
{
result_int = uni_strtol(result, NULL, 0);
}
OP_DELETE(section);
}
return result_int;
}
/***********************************************************************************
**
** GetIntL
**
***********************************************************************************/
int OpSetupManager::GetIntL(PrefsSection* section, const OpStringC8 &key, int defval)
{
if(section)
{
const uni_char *result;
OpString key_uni;
key_uni.Set(key);
result = section->Get(key_uni);
if(result) // we could try to get it from the default file, if section is in the "user-file"
{
return uni_strtol(result, NULL, 0);
}
}
return defval;
}
/***********************************************************************************
**
** SetKeyL
**
***********************************************************************************/
OP_STATUS OpSetupManager::SetKeyL(const OpStringC8 §ion, const OpStringC8 &key, int value, enum OpSetupType type)
{
PrefsFile* file = GetSetupFile(type);
if(file)
{
return file->WriteIntL(section, key, value);
}
return OpStatus::ERR;
}
/***********************************************************************************
**
** SetKeyL
**
***********************************************************************************/
OP_STATUS OpSetupManager::SetKeyL(const OpStringC8 §ion, const OpStringC8 &key, const OpStringC &value, enum OpSetupType type)
{
PrefsFile* file = GetSetupFile(type);
if(file)
{
return file->WriteStringL(section, key, value);
}
return OpStatus::ERR;
}
/***********************************************************************************
**
** GetSectionL
**
***********************************************************************************/
PrefsSection* OpSetupManager::GetSectionL(const char* name, enum OpSetupType type, BOOL* was_default, BOOL master)
{
PrefsSection* section = NULL;
switch(type)
{
case OPDIALOG_SETUP:
{
if(!m_override_dialog_prefsfile->IsSection(name) || master)
{
if(!m_custom_dialog_prefsfile->IsSection(name) || master)
{
section = m_dialog_prefsfile->ReadSectionL(name);
if(was_default)
{
*was_default = TRUE;
}
}
else
{
section = m_custom_dialog_prefsfile->ReadSectionL(name);
}
}
else
{
section = m_override_dialog_prefsfile->ReadSectionL(name);
}
}
break;
case OPTOOLBAR_SETUP:
{
// TODO: Add platform specific sections that override default
if(!m_toolbar_prefsfile->IsSection(name) || master)
{
if(!m_custom_toolbar_prefsfile->IsSection(name) || master)
{
section = m_default_toolbar_prefsfile->ReadSectionL(name);
if(was_default)
{
*was_default = TRUE;
}
}
else
{
section = m_custom_toolbar_prefsfile->ReadSectionL(name);
}
}
else
{
section = m_toolbar_prefsfile->ReadSectionL(name);
}
}
break;
case OPMENU_SETUP:
{
if(!m_menu_prefsfile->IsSection(name) || master)
{
if(!m_custom_menu_prefsfile->IsSection(name) || master)
{
section = m_default_menu_prefsfile->ReadSectionL(name);
if(was_default)
{
*was_default = TRUE;
}
}
else
{
section = m_custom_menu_prefsfile->ReadSectionL(name);
}
}
else
{
section = m_menu_prefsfile->ReadSectionL(name);
}
}
break;
case OPMOUSE_SETUP:
{
if(!m_mouse_prefsfile->IsSection(name) || master)
{
section = m_default_mouse_prefsfile->ReadSectionL(name);
if(was_default)
{
*was_default = TRUE;
}
}
else
{
section = m_mouse_prefsfile->ReadSectionL(name);
}
}
break;
case OPKEYBOARD_SETUP:
{
if(!m_keyboard_prefsfile->IsSection(name) || master)
{
section = m_default_keyboard_prefsfile->ReadSectionL(name);
if(was_default)
{
*was_default = TRUE;
}
}
else
{
section = m_keyboard_prefsfile->ReadSectionL(name);
}
}
break;
}
return section;
}
/***********************************************************************************
**
** DeleteSectionL
**
***********************************************************************************/
BOOL OpSetupManager::DeleteSectionL(const char* name, enum OpSetupType type)
{
PrefsFile* file = GetSetupFile(type);
if(file)
{
BOOL ret = file->DeleteSectionL(name);
file->CommitL(FALSE, FALSE);
return ret;
}
return OpStatus::ERR;
}
PrefsFile* OpSetupManager::GetSetupFile(OpSetupType type, BOOL check_readonly, BOOL copy_contents)
{
switch(type)
{
case OPTOOLBAR_SETUP:
{
if(check_readonly && GetIndexOfToolbarSetup() == 0) // if the file is one of the read-onlys, copy to the user directory
{
UINT32 newindex;
TRAPD(err,DuplicateSetupL(0, type, copy_contents, TRUE, TRUE, &newindex));
SelectSetupFile(newindex, type, FALSE);
}
return m_toolbar_prefsfile;
}
case OPMENU_SETUP:
{
if(check_readonly && GetIndexOfMenuSetup() == 0) // if the file is one of the read-onlys, copy to the user directory
{
UINT32 newindex;
TRAPD(err,DuplicateSetupL(0, type, copy_contents, TRUE, TRUE, &newindex));
SelectSetupFile(newindex, type, FALSE);
}
return m_menu_prefsfile;
}
case OPMOUSE_SETUP:
{
if(check_readonly && GetIndexOfMouseSetup() == 0) // if the file is one of the read-onlys, copy to the user directory
{
UINT32 newindex;
TRAPD(err,DuplicateSetupL(0, type, copy_contents, TRUE, TRUE, &newindex));
SelectSetupFile(newindex, type, FALSE);
}
return m_mouse_prefsfile;
}
case OPKEYBOARD_SETUP:
{
if(check_readonly && GetIndexOfKeyboardSetup() == 0) // if the file is one of the read-onlys, copy to the user directory
{
UINT32 newindex;
TRAPD(err,DuplicateSetupL(0, type, copy_contents, TRUE, TRUE, &newindex));
SelectSetupFile(newindex, type, FALSE);
}
return m_keyboard_prefsfile;
}
default:
{
OP_ASSERT(FALSE); //something is seriously wrong!
}
}
return NULL;
}
const PrefsFile* OpSetupManager::GetDefaultSetupFile(OpSetupType type)
{
switch(type)
{
case OPTOOLBAR_SETUP:
{
return m_default_toolbar_prefsfile;
}
case OPMENU_SETUP:
{
return m_default_menu_prefsfile;
}
case OPMOUSE_SETUP:
{
return m_default_mouse_prefsfile;
}
case OPKEYBOARD_SETUP:
{
return m_default_keyboard_prefsfile;
}
default:
{
OP_ASSERT(FALSE); //something is seriously wrong!
}
}
return NULL;
}
/***********************************************************************************
**
** MergeSectionIntoExisting
**
***********************************************************************************/
OP_STATUS OpSetupManager::MergeSetupIntoExisting(PrefsFile* file, enum OpSetupType type, SetupPatchMode patchtype, OpFile*& backupfile)
{
// const uni_char* fixedsections[] = { UNI_L("info"), UNI_L("version"), NULL};
PrefsFile* currentfile = NULL;
currentfile = GetSetupFile(type, TRUE, FALSE);
//we need copy the previous setup to a temp-file if the user wants to revert to old settings...
OP_ASSERT(FALSE); //we need tempfile here!
return OpStatus::ERR;
}
void OpSetupManager::BroadcastChange(OpSetupType type)
{
switch(type)
{
case OPSKIN_SETUP:
{
g_application->SettingsChanged(SETTINGS_SKIN);
}
break;
case OPTOOLBAR_SETUP:
{
g_application->SettingsChanged(SETTINGS_TOOLBAR_SETUP);
}
break;
case OPMENU_SETUP:
{
g_application->SettingsChanged(SETTINGS_MENU_SETUP);
}
break;
case OPMOUSE_SETUP:
{
g_application->SettingsChanged(SETTINGS_MOUSE_SETUP);
}
break;
case OPKEYBOARD_SETUP:
{
g_application->SettingsChanged(SETTINGS_KEYBOARD_SETUP);
}
break;
}
}
BOOL OpSetupManager::IsFallback(const uni_char* fullpath, OpSetupType type)
{
const PrefsFile* currentfile = GetDefaultSetupFile(type);
const uni_char* currentsetup = ((OpFile*)currentfile->GetFile())->GetFullPath();
if(!currentsetup)
{
return FALSE;
}
return (uni_stricmp(currentsetup, fullpath) == 0);
}
|
#ifndef _FMT_FLAG_HPP_
#define _FMT_FLAG_HPP_
namespace fmt {
enum Flag : uint32_t {
AlignLeft = 1,
AlignRight = 1 << 1,
SignPlus = 1 << 2,
SignSpace = 1 << 3,
Char = 1 << 4,
Hex = 1 << 5,
UpperHex = 1 << 6,
Exponent = 1 << 7,
UpperExponent = 1 << 8,
Fixed = 1 << 9,
LargeExponent = 1 << 10,
Percentage = 1 << 11,
Prefixed = 1 << 12,
ZeroPadding = 1 << 13,
Comma = 1 << 14
};
}
#endif
|
#include <systemc.h>
#include <fstream>
#include <iostream>
SC_MODULE ( tester ){
sc_in <bool> clk ;
sc_in <sc_uint <8> > out1, out2, out3, out4;
sc_out <sc_uint <8> > in ;
sc_out <sc_bv <4> > we ;
sc_out <bool> reset ;
ifstream infile;
void tester_func ();
SC_CTOR( tester ){
SC_THREAD( tester_func ) ;
sensitive << clk.pos( ) ;
infile.open("usr.in") ;
}
};
|
// SPI full-duplex slave example
// STM32 acts as a SPI slave and reads 8 bit data frames over SPI.
// Master also gets a reply from the slave, which is a a simple count (0, 1, 2, 3)
// that is incremented each time a data frame is received.
// Serial output is here for debug
#include <SPI.h>
void setup()
{
// The clock value is not used
// SPI1 is selected by default
// MOSI, MISO, SCK and NSS PINs are set by the library
SPI.beginTransactionSlave(SPISettings(250000, MSBFIRST, SPI_MODE0, DATA_SIZE_8BIT));
}
void loop()
{
static uint8_t i = 0;
SPI.transfer(i++); // blocking call
}
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// Генератор 32-х битных случайных чисел.
// V 1.0
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
#include <iostream>
#include <random>
int main() {
using namespace std;
random_device rd;
mt19937 mersenne(rd()); // Инициализируем Вихрь Мерсенна случайным
for (int count = 0; count < 8; ++count) {
cout << mersenne() << "\t";
// Разбивка на столбцы по пять
if ((count + 1) % 5 == 0) {
cout << "\n";
}
}
return 0;
}
// Output:
/*
2
*/
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
// END FILE
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=//
|
#pragma once
#include <string>
#include <sstream>
namespace StringHelper {
const char FORMAT_SYMBOL = '$';
inline std::string ToString(int x) { return std::to_string(x); };
inline std::string ToString(unsigned int x) { return std::to_string(x); };
inline std::string ToString(long x) { return std::to_string(x); };
inline std::string ToString(unsigned long x) { return std::to_string(x); };
inline std::string ToString(long long x) { return std::to_string(x); };
inline std::string ToString(unsigned long long x) { return std::to_string(x); };
inline std::string ToString(float x) { return std::to_string(x); };
inline std::string ToString(double x) { return std::to_string(x); };
inline std::string ToString(long double x) { return std::to_string(x); };
inline std::string ToString(const std::string& x) { return x; };
inline std::string ToString(const char* x) { return std::string(x); };
template<typename T>
inline std::string ToString(const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
};
template<typename T, typename... Targs>
inline std::string Format(const std::string& fstr, const T& value, const Targs& ... args)
{
std::size_t pos = fstr.find_first_of(FORMAT_SYMBOL);
if (pos == std::string::npos)
return fstr;
return fstr.substr(0, pos) + ToString(value) + Format(fstr.substr(pos + 1), args...);
};
inline std::string Format(const std::string& fstr) { return fstr; };
};
|
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
// Copyright (C) 2016, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
/*
Implementation of various functions which are related to Tensorflow models reading.
*/
#ifdef HAVE_PROTOBUF
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include <opencv2/core.hpp>
#include <map>
#include <string>
#include <fstream>
#include <vector>
#include "graph.pb.h"
#include "tf_io.hpp"
#include "../caffe/glog_emulator.hpp"
namespace cv {
namespace dnn {
using std::string;
using std::map;
using namespace tensorflow;
using namespace ::google::protobuf;
using namespace ::google::protobuf::io;
const int kProtoReadBytesLimit = INT_MAX; // Max size of 2 GB minus 1 byte.
// TODO: remove Caffe duplicate
bool ReadProtoFromBinaryFileTF(const char* filename, Message* proto) {
std::ifstream fs(filename, std::ifstream::in | std::ifstream::binary);
CHECK(fs.is_open()) << "Can't open \"" << filename << "\"";
ZeroCopyInputStream* raw_input = new IstreamInputStream(&fs);
CodedInputStream* coded_input = new CodedInputStream(raw_input);
coded_input->SetTotalBytesLimit(kProtoReadBytesLimit, 536870912);
bool success = proto->ParseFromCodedStream(coded_input);
delete coded_input;
delete raw_input;
fs.close();
return success;
}
void ReadTFNetParamsFromBinaryFileOrDie(const char* param_file,
tensorflow::GraphDef* param) {
CHECK(ReadProtoFromBinaryFileTF(param_file, param))
<< "Failed to parse GraphDef file: " << param_file;
}
}
}
#endif
|
#include <bits/stdc++.h>
using namespace std;
void subString(string str, string initial=" ", int index=0) {
if(index==str.size()) {
cout << initial << " " << endl;
return;
}
subString(str, initial, index+1);
subString(str, initial + str[index], index+1);
}
int main() {
string str="ABC";
subString(str);
return 0;
}
|
#pragma once
#include <iberbar/Renderer/Effect.h>
#include <DirectXMath.h>
namespace iberbar
{
namespace Renderer
{
class __iberbarRendererApi__ CEffectMatrices
: public CEffectBase
{
protected:
struct _Data
{
DirectX::XMFLOAT4X4 ViewMatrix;
DirectX::XMFLOAT4X4 ProjectionMatrix;
DirectX::XMFLOAT4X4 ViewProjectionMatrix;
};
public:
CResult Initial();
void SetViewMatrix( const DirectX::XMFLOAT4X4& Matrix );
void SetProjectionMatrix( const DirectX::XMFLOAT4X4& Matrix );
void Apply();
protected:
uint32 m_DirtyData;
_Data m_Data;
};
}
}
inline void iberbar::Renderer::CEffectMatrices::SetViewMatrix( const DirectX::XMFLOAT4X4& Matrix )
{
m_Data.ViewMatrix = Matrix;
m_DirtyData = 1;
}
inline void iberbar::Renderer::CEffectMatrices::SetProjectionMatrix( const DirectX::XMFLOAT4X4& Matrix )
{
m_Data.ProjectionMatrix = Matrix;
m_DirtyData = 1;
}
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
/// The XBee data type(s)
#include "xbee.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
// The coordinator
XBee *m_Coordinator;
// The router
XBee *m_Router;
// Measure Performance
int m_BytesSent;
int m_CycleCounter;
QElapsedTimer m_RateTimer;
// Run the Router in a thread
void runRouter();
// Run the Coordinator in a thread
void runCoordinator();
};
#endif // MAINWINDOW_H
|
#include "EquidistantModel.h"
Cvl::EquidistantModel::EquidistantModel(double focalLengthX, double focalLengthY, double principalPointX, double principalPointY) :
ProjectionModel(focalLengthX, focalLengthY, principalPointX, principalPointY)
{
}
Cvl::ProjectionModel::Uptr Cvl::EquidistantModel::clone() const
{
return ProjectionModel::Uptr(new EquidistantModel(mFocalLengthX, mFocalLengthY, mPrincipalPointX, mPrincipalPointY));
}
Eigen::Array2Xd Cvl::EquidistantModel::project(Eigen::Array2Xd const& distortedPoints) const
{
Eigen::Array<double, 1, Eigen::Dynamic> norms = distortedPoints.matrix().colwise().norm();
Eigen::Array<double, 1, Eigen::Dynamic> angles = norms.atan();
return (((distortedPoints.colwise() * Eigen::Array2d(mFocalLengthX, mFocalLengthY)).rowwise() * angles).rowwise() / norms).colwise() + Eigen::Array2d(mPrincipalPointX, mPrincipalPointY);
}
Eigen::Array2Xd Cvl::EquidistantModel::unproject(Eigen::Array2Xd const& imagePoints) const
{
// this is the same solution as below to test eigen broadcasting and reduction features
//Eigen::Array2Xd result(2, imagePoints.cols());
//double pixelLengthRatio = mFocalLengthX / mFocalLengthY;
//double pixelLengthRatioSquared = pixelLengthRatio*pixelLengthRatio;
//Eigen::Array2d temp1;
//double radiusX = 0.0;
//double radiusCamera = 0.0;
//for (int i=0; i<imagePoints.cols(); ++i)
//{
// temp1 = imagePoints.col(i) - Eigen::Array2d(mPrincipalPointX, mPrincipalPointY);
// radiusX = std::sqrt(temp1.x()*temp1.x() + temp1.y()*temp1.y()*pixelLengthRatioSquared);
// radiusCamera = std::tan(radiusX/ mFocalLengthX);
// result(0, i) = temp1.x() * radiusCamera / radiusX;
// result(1, i) = temp1.y() * radiusCamera * pixelLengthRatio / radiusX;
//}
Eigen::Array2Xd centeredPoints = imagePoints.colwise() - Eigen::Array2d(mPrincipalPointX, mPrincipalPointY);
centeredPoints.row(1) *= mFocalLengthX / mFocalLengthY;
Eigen::Array<double, 1, Eigen::Dynamic> radiX = centeredPoints.matrix().colwise().norm().array();
return ((centeredPoints.rowwise() * (radiX / mFocalLengthX).tan()).rowwise() / radiX);
}
|
#include<iostream>
#include<vector>
#include<algorithm>
#include<unordered_map>
#include<unordered_set>
using namespace std;
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
//基本思想:HashMap,map保存nums中元素对应下标位置的映射
//遍历nums所有元素,对于当前元素nums[i],如果存在于HashMap,计算当前下标i与HashMap[nums[i]]的距离
//如果小于等于k返回true,同时更新HashMap[nums[i]]为当前下标i
unordered_map<int, int> HashMap;
for (int i = 0; i < nums.size(); i++)
{
if (HashMap.find(nums[i]) != HashMap.end())
{
if (i - HashMap[nums[i]] <= k)
return true;
}
HashMap[nums[i]] = i;
}
return false;
}
};
class Solution1 {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
//基本思想:哈希表+滑动窗口,用哈希表来维护这个k大小的滑动窗口
//如果下一个元素存在于滑动窗口内,返回true,否则加入到滑动窗口,同时滑动窗口去掉最旧的元素
unordered_set<int> container;
for (int i = 0; i < nums.size(); i++)
{
if (container.find(nums[i]) != container.end())
return true;
container.insert(nums[i]);
if (container.size() > k)
container.erase(nums[i - k]);
}
return false;
}
};
int main()
{
Solution1 solute;
vector<int> nums = { 1,2,3,1,2,3 };
int k = 2;
cout << solute.containsNearbyDuplicate(nums, k) << endl;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 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 WINGOGI_SHARED_MEMORY_MUTEX_H
#define WINGOGI_SHARED_MEMORY_MUTEX_H
/** Implementation of WindowsOpSharedMemoryMutex PI.
*
* Internally uses a semaphore instead of a mutex because
* Windows Mutexes are natively recursive. The implementation
* is relatively complex because there's no easy way of sharing
* an object representing a semaphore or mutex in Windows.
* Sync primitives are represented by HANDLEs which are not
* valid in other processes out-of-the-box.
*/
class WindowsOpSharedMemoryMutex
{
public:
WindowsOpSharedMemoryMutex();
~WindowsOpSharedMemoryMutex();
OP_STATUS Construct();
OP_STATUS Acquire();
OP_STATUS Release();
bool TryAcquire();
private:
HANDLE GetSemaphoreHandleForThisProcess();
OP_STATUS AcquireWithTimeout(DWORD time);
DWORD m_originalProcessId;
HANDLE m_originalSemaphoreHandle;
HANDLE m_currentSemaphoreHandle;
class CurrentHolder
{
public:
CurrentHolder();
void setToMe();
void reset();
bool isMe() const;
private:
DWORD m_holdingProcess;
DWORD m_holdingThread;
} m_currentHolder;
};
typedef WindowsOpSharedMemoryMutex OpSharedMemoryMutex;
#endif // WINGOGI_SHARED_MEMORY_MUTEX_H
|
/* Copyright 2023 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#if defined(INTEL_MKL) && defined(ENABLE_ONEDNN_V3)
#include "xla/service/cpu/onednn_rewriter.h"
#include "xla/hlo/ir/dfs_hlo_visitor_with_default.h"
#include "xla/hlo/ir/hlo_instruction.h"
#include "xla/service/cpu/backend_config.pb.h"
#include "xla/service/cpu/onednn_memory_util.h"
#include "xla/service/pattern_matcher.h"
#include "xla/status_macros.h"
#include "tsl/platform/cpu_info.h"
namespace xla {
namespace cpu {
namespace {
namespace m = match;
Status ValidateDotDimensionNumbers(const DotDimensionNumbers& dim_numbers) {
// Checks some invariants that do not hold in general, but DotDecomposer
// should have established for us.
TF_RET_CHECK(dim_numbers.lhs_contracting_dimensions_size() == 1);
std::vector<int64_t> batch_dim_numbers(
dim_numbers.lhs_batch_dimensions_size());
absl::c_iota(batch_dim_numbers, 0);
TF_RET_CHECK(
absl::c_equal(batch_dim_numbers, dim_numbers.lhs_batch_dimensions()));
TF_RET_CHECK(
absl::c_equal(batch_dim_numbers, dim_numbers.rhs_batch_dimensions()));
return OkStatus();
}
bool IsSupportedType(xla::PrimitiveType dtype) {
using tsl::port::TestCPUFeature;
using tsl::port::CPUFeature;
switch (dtype) {
case F32:
return true;
case BF16:
return TestCPUFeature(CPUFeature::AVX512_BF16) ||
TestCPUFeature(CPUFeature::AMX_BF16);
default:
return false;
}
return false;
}
} // namespace
class OneDnnRewriterVisitor : public DfsHloRewriteVisitor {
public:
// Matches patterns for possible MatMul fusions that are supported by oneDNN
// library. Matched hlo instruction(s) are replaced by custom call.
Status HandleDot(HloInstruction* instr) override {
// Currently, blocking control dependencies
if (instr->HasControlDependencies()) return OkStatus();
HloInstruction* dot_instr;
auto pattern = m::Op(&dot_instr).WithOpcode(HloOpcode::kDot);
if (!Match(instr, pattern)) return OkStatus();
// TODO(intel-tf): The rewrite pass runs after dot-decomposition pass.
// Adjust the rewrite condition when the rewrite pass is moved to a
// different point in the pass-pipeline.
// Currently, we rewrite when the data type is F32 or BF16. Note we do not
// need to check equality of contraction dim-size of the operands. HLO
// verifier already does the job. We, however, need to check if contraction
// is over only 1 dimension (a.k.a. K dimension in matrix-multiplication
// parlance). We also restrict that batch dimensions of the operands
// matches.
if (!IsSupportedType(dot_instr->shape().element_type())) return OkStatus();
auto dot_dim_numbers = dot_instr->dot_dimension_numbers();
TF_RETURN_IF_ERROR(ValidateDotDimensionNumbers(dot_dim_numbers));
const Shape& lhs_shape = dot_instr->operand(0)->shape();
const Shape& rhs_shape = dot_instr->operand(1)->shape();
const Shape& output_shape = dot_instr->shape();
bool should_rewrite = true;
// None of the operands and result should be ZeroElementArray.
should_rewrite &= !ShapeUtil::IsZeroElementArray(lhs_shape);
should_rewrite &= !ShapeUtil::IsZeroElementArray(rhs_shape);
should_rewrite &= !ShapeUtil::IsZeroElementArray(output_shape);
// OneDNN only supports 2 <= rank <= kOneDnnMaxNDims.
should_rewrite &= (lhs_shape.rank() == rhs_shape.rank());
should_rewrite &= (rhs_shape.rank() == output_shape.rank());
should_rewrite &=
(lhs_shape.rank() >= 2 && lhs_shape.rank() <= kOneDnnMaxNDims);
if (!should_rewrite) return OkStatus();
// Transpose scenario needs some care and blocked for oneDNN rewrite for
// now.
// TODO(intel-tf): Add transpose scenarios
should_rewrite &= LayoutUtil::IsMonotonicWithDim0Major(lhs_shape.layout());
if (!should_rewrite) return OkStatus();
should_rewrite &= LayoutUtil::IsMonotonicWithDim0Major(rhs_shape.layout());
if (!should_rewrite) return OkStatus();
should_rewrite &=
LayoutUtil::IsMonotonicWithDim0Major(output_shape.layout());
if (!should_rewrite) return OkStatus();
// Check contracting dimensions: [..., M, K] x [..., K, N]
should_rewrite &=
(dot_dim_numbers.lhs_contracting_dimensions(0) == lhs_shape.rank() - 1);
should_rewrite &=
(dot_dim_numbers.rhs_contracting_dimensions(0) == rhs_shape.rank() - 2);
if (!should_rewrite) return OkStatus();
HloInstruction* matmul_call =
dot_instr->AddInstruction(HloInstruction::CreateCustomCall(
output_shape,
{dot_instr->mutable_operand(0), dot_instr->mutable_operand(1)},
"__onednn$matmul"));
// Set additional info via config, e.g., fusion info.
BackendConfig backend_config;
// No fusion is supported now, so nothing to add to the config.
TF_RETURN_IF_ERROR(matmul_call->set_backend_config(backend_config));
TF_RETURN_IF_ERROR(ReplaceInstruction(dot_instr, matmul_call));
return OkStatus();
}
};
StatusOr<bool> OneDnnRewriter::Run(
HloModule* module,
const absl::flat_hash_set<absl::string_view>& execution_threads) {
OneDnnRewriterVisitor visitor;
return visitor.RunOnModule(module, execution_threads);
}
} // namespace cpu
} // namespace xla
#endif // INTEL_MKL && ENABLE_ONEDNN_V3
|
#include "pch.h"
#include "OrderWriter.h"
using namespace std;
using namespace concurrency;
OrderWriter::OrderWriter(ISource<OrderMsg>& order_channel,
const string& filepath) :
order_channel_(order_channel), filepath_(filepath) {
double cash = 10000;
Asset asset(cash);
// TODO Load asset from a file or somewhere persistent
// connect sockets signals and
// publish stoploss
}
void OrderWriter::run() {
// TODO implement followings
// 1. Load all signal
// 2. Calculate quantity to buy/sell
// 3. Place an order
// 4. Send stoploss
while (true) {
OrderMsg msg = receive(order_channel_);
clog << "Received OrderMsg: " << msg.ToString() << endl;
}
done();
}
|
#pragma once
#ifndef Software_Student_H
#define Software_Student_H
#include "student.h"
class SoftwareStudent : public Student {
public:
SoftwareStudent(string, string, string, string, int, int, int, int, Degree);
Degree GetDegreeProgram();
void Print();
private:
Degree degreeType;
};
#endif
|
#ifndef LABPROG_BUTTON_H
#define LABPROG_BUTTON_H
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <sstream>
enum button_states {
BTN_IDLE = 0, BTN_HOVER, BTN_ACTIVE
};
class Button {
public:
Button(float x, float y, sf::Font *font, const std::string &text, sf::Color idleColor,
sf::Color hoverColor, sf::Color activeColor);
virtual ~Button();
void update(sf::Vector2f mousePos);
void render(sf::RenderTarget *target);
bool isPressed() const;
unsigned int getButtonState() const;
private:
unsigned buttonState;
sf::Texture buttonTexture;
sf::Sprite button;
sf::Font *font;
sf::Text text;
sf::Color idleColor;
sf::Color hoverColor;
sf::Color activeColor;
};
#endif
|
//
// generators.cpp
// Total Control
//
// Created by Parker Lawrence on 1/16/16.
// Copyright (c) 2016 Parker Lawrence. All rights reserved.
//
#include "generators.h"
void Generator::firstdump() {
Structure mainland;
mainland.bounded = false;
mainland.structureid = "mainland";
mainland.transform = glm::translate(glm::mat4(),glm::vec3(3,3,3));
pool->push_back(mainland);
Structure spinrock;
spinrock.bounded = true;
spinrock.upperbounds = Location(0,0,0);
spinrock.lowestbounds = Location(-1,-1,-1);
spinrock.structureid = "spinnyrock";
glm::mat4 mat1 = glm::translate(glm::mat4(),glm::vec3(0,100,0));
spinrock.transform = mat1;
pool->push_back(spinrock);
}
int (*Generator::terrain_update(Structure* target,Location po))[CHSIZE][CHSIZE] {
// DetailedPortion* myportion = new DetailedPortion();
// int*** = new int[CHSIZE][CHSIZE][CHSIZE];
int (*data)[CHSIZE][CHSIZE] = new int[CHSIZE][CHSIZE][CHSIZE];
for (int xi=0;xi<CHSIZE;xi++) {
for (int yi=0;yi<CHSIZE;yi++) {
for (int zi=0;zi<CHSIZE;zi++) {
int xt = po.x*CHSIZE+xi;
int yt = po.y*CHSIZE+yi;
int zt = po.z*CHSIZE+zi;
if (target->structureid == "mainland") {
// if ((xi==0 or yi==0 or zi==0) and ((xt+yt+zt)%10==0)) {
// myportion->data[xi][yi][zi] = 3;
// }
// continue;
// if ((MOD(xt,11)<4)and(MOD(yt,11)<4)and(MOD(zt,11)<4)) {
// if (MOD(xt+yt+zt,2)==1) {
// myportion->data[xi][yi][zi] = 5;
// } else {
// myportion->data[xi][yi][zi] = 4;
// }
// continue;
// }
// continue;
double density = -yt;
double mu = 64.0;
density += sample1.sample(xt/(mu*3),yt/(mu*3),zt/(mu*3))*3;
density += sample2.sample(xt/(mu*6),yt/(mu*6),zt/(mu*6))*6;
density += sample3.sample(xt/(mu*12),yt/(mu*12),zt/(mu*12))*12;
density += sample1.sample(xt/(mu*24),yt/(mu*24),zt/(mu*24))*24;
density += sample2.sample(xt/(mu*48),yt/(mu*48),zt/(mu*48))*48;
density += sample3.sample(xt/(mu*72),yt/(mu*72),zt/(mu*72))*72;
density += sample3.sample(xt/(mu*148),yt/(mu*148),zt/(mu*148))*148;
density -= 32*(TRUNC_DIV(yt,32));
double scale = 3;
if (density>scale) {
data[xi][yi][zi] = 3;
} else if (density>(scale/2.0)) {
data[xi][yi][zi] = 2;
} else if (density>0) {
data[xi][yi][zi] = 1;
} else {
data[xi][yi][zi] = 0;
}
// if (xt*xt+zt*zt>yt*yt*2) {
// myportion->data[xi][yi][zi] = 1;
// } else {
// myportion->data[xi][yi][zi] = 0;
// }
}
else if (target->structureid == "spinnyrock") {
// if ((xi==0 or yi==0 or zi==0) and ((xt+yt+zt)%10==0)) {
// myportion->data[xi][yi][zi] = 3;
// }
// continue;
double density = 40-sqrt(xt*xt+yt*yt+zt*zt);
double mu = 64.0;
density += sample1.sample(xt/(mu*3),yt/(mu*3),zt/(mu*3))*3;
density += sample2.sample(xt/(mu*6),yt/(mu*6),zt/(mu*6))*6;
density += sample3.sample(xt/(mu*12),yt/(mu*12),zt/(mu*12))*12;
density += sample1.sample(xt/(mu*24),yt/(mu*24),zt/(mu*24))*24;
// density += sample2.sample(xt/(mu*48),yt/(mu*48),zt/(mu*48))*48;
// density += sample3.sample(xt/(mu*72),yt/(mu*72),zt/(mu*72))*72;
// density += sample3.sample(xt/(mu*148),yt/(mu*148),zt/(mu*148))*148;
// density -= 32*(TRUNC_DIV(yt,32));
//oesguh
double scale = 3;
if (density>scale) {
data[xi][yi][zi] = 3;
} else if (density>(scale/2.0)) {
data[xi][yi][zi] = 2;
} else if (density>0) {
data[xi][yi][zi] = 1;
} else {
data[xi][yi][zi] = 0;
}
}
}
}
}
return data;
}
//double NoiseVolume::interp(float &x, float &y, float &a) {
// return (x*a)+(y*(1-a));
//}
NoiseVolume::NoiseVolume() {
for (int xi=0;xi<RANDSIZE;xi++) {
for (int yi=0;yi<RANDSIZE;yi++) {
for (int zi=0;zi<RANDSIZE;zi++) {
data[xi][yi][zi] = (((float)std::rand())/(RAND_MAX/2))-1;
}
}
}
}
float NoiseVolume::sample(double x, double y, double z) {
// std::cout<<x<<","<<y<<","<<z<<"\n";
// int xmax = MOD((int)ceil(x*RANDSIZE),RANDSIZE);
// int xmin = MOD((int)floor(x*RANDSIZE),RANDSIZE);
int xmax = (int)ceil(x*RANDSIZE)&63;
int xmin = (int)floor(x*RANDSIZE)&63;
float xi = (x*RANDSIZE)-floor(x*RANDSIZE);
int ymax = (int)ceil(y*RANDSIZE)&63;
int ymin = (int)floor(y*RANDSIZE)&63;
float yi = (y*RANDSIZE)-floor(y*RANDSIZE);
int zmax = (int)ceil(z*RANDSIZE)&63;
int zmin = (int)floor(z*RANDSIZE)&63;
float zi = (z*RANDSIZE)-floor(z*RANDSIZE);
// return 0.0;
// std::cout<<xmin<<","<<ymin<<","<<zmin<<"\n";
// return data[xmin][ymin][zmin];
// return interp(interp(interp(data[xmax][ymax][zmax],data[xmax][ymax][zmin],zi),interp(data[xmax][ymin][zmax],data[xmax][ymin][zmin],zi),yi),interp(interp(data[xmin][ymax][zmax],data[xmin][ymax][zmin],zi),interp(data[xmin][ymin][zmax],data[xmin][ymin][zmin],zi),yi),xi);
return
((data[xmax][ymax][zmax]*zi+data[xmax][ymax][zmin]*(1-zi))*yi+
(data[xmax][ymin][zmax]*zi+data[xmax][ymin][zmin]*(1-zi))*(1-yi))*xi+
((data[xmin][ymax][zmax]*zi+data[xmin][ymax][zmin]*(1-zi))*yi+
(data[xmin][ymin][zmax]*zi+data[xmin][ymin][zmin]*(1-zi))*(1-yi))*(1-xi);
}
|
#pragma once
#include "Person.h"
#include <iostream>
using namespace std;
class Employee : public Person
{
public:
Employee();
Employee(string, double);
~Employee();
virtual void printName() const;
protected:
double salary;
};
|
/**
* @author Umaralikhon Kayumov
* @version 3.5
*/
#include "Header.h"
void menu();
void innerMenu();
int main() {
srand(time(NULL));
setlocale(0, "");
int choice;
int elem;
int nextStep;
ProgresssionSet user;
cout << "Выберите действие: " << endl;
menu();
cin >> choice;
while (choice != 0) {
cout << "Введите кол - во объектов: " << endl;
cin >> elem;
user.setElem(elem); //Кол -во объектов
if (choice == 1) {
user.GenerateHandValue();
}
else if (choice == 2) {
user.GenerateRandomValue();
}
cout << "_________________________________________________" << endl;
user.printInfo();
cout << "_________________________________________________" << endl;
cout << "ПРОГРЕССИИ" << endl;
user.printEveryProg();
cout << "_________________________________________________" << endl;
{
innerMenu();
cin >> nextStep;
cout << endl;
if (nextStep == 2) {
user.changeElem();
user.printInfo();
cout << "_________________________________________________" << endl;
}
else if (nextStep == 0) {
return 0;
}
}
menu();
cin >> choice;
}
user.~ProgresssionSet();
}
void menu() {
cout << "<1> Ручной ввод" << endl;
cout << "<2> Рандомный ввод" << endl;
cout << "<0> Выход" << endl;
cout << ">>> ";
}
void innerMenu() {
cout << "<1> Главное меню" << endl;
cout << "<2> Изменить значение массива" << endl;
cout << "<0> Выход из программы" << endl;
cout << ">>> ";
}
|
#include<iostream>
#include<stdio.h>
using namespace std;
int main(){
int npinit, rodadas;
int npart, ordem, depois, acao;
int cont, cont2, cont3, cont1 = 0;
int gamers[100] = {};
cin >> npinit >> rodadas;
while ( npinit != 0 && rodadas != 0 ){
for ( cont = 0; cont <= npinit; cont++ ){
cin >> gamers[cont];
}
for ( cont = 0; cont <= rodadas; cont++ ){
cin >> npart >> ordem;
depois = 0;
for ( cont2 = 0; cont2 <= npart; cont2++ ){
cin >> acao;
if ( acao == ordem ){
depois += 1;
}
else{
for ( cont3 = depois+1; cont3 < npart; cont3++ ){
gamers[cont3-1] = gamers[cont3];
}
}
}
}
cont1++;
cout << "Teste " << cont1 << "\n";
cout << gamers[0] << "\n";
cin >> npinit >> rodadas;
}
return 0;
}
|
#pragma once
#include "Enums.h"
#include "Animation.h"
/*
GameObjectData is responsible for defining the interface with which
any class is going to communicate with when trying to access that
GameObjects Data
*/
class GameObjectData
{
public:
typedef Vector2i SpriteSheedIndex;
GameObjectData() = default;
virtual ~GameObjectData() = default;
virtual const Animation& GetAnimationState(State aState, PossibleOrientation aOrientation = PossibleOrientation::up) const = 0;
};
|
class T72_INS;
class T72_RUST: T72_INS {
displayName = "$STR_VEH_NAME_T72_RUST";
hiddenSelectionsTextures[] = {"\dayz_epoch_c\skins\t72\T72_1_wrecked_co.paa","\dayz_epoch_c\skins\t72\T72_2_wrecked_co.paa","\dayz_epoch_c\skins\t72\T72_3_wrecked_co.paa"};
};
class T72_WINTER: T72_INS {
displayName = "$STR_VEH_NAME_T72_WINTER";
hiddenSelectionsTextures[] = {"\dayz_epoch_c\skins\t72\T72_1_winter_co.paa","\dayz_epoch_c\skins\t72\T72_2_winter_co.paa","\dayz_epoch_c\skins\t72\T72_3_winter_co.paa"};
};
|
#include <iostream>
#include<fstream>
#include<stdlib.h>
#include <iomanip>
#include<time.h>
#include<math.h>
#define MAXLARGO 21
#define TOTALNUM 100 //Total de numeros que genera
using namespace std;
int main()
{
int i, x;
float prom, sum = 0;
double sum2 = 0, des;
char nombrearchivo[MAXLARGO] = "numeros.txt";
//Creacion del archivo
ofstream archivo_out;
archivo_out.open(nombrearchivo);
if(archivo_out.fail()){
cout << "El archivo no se abrio con exito";
exit(1);
}
cout << setiosflags(ios::fixed)
<< setiosflags(ios::showpoint)
<< setprecision(4);
srand(time(NULL));
for(i=1;i<=6;i++){
archivo_out << (rand());
archivo_out << " ";
}
archivo_out.close();
//Cierre del archivo
//int long desplazamiento, ultimo;
ifstream archivo_in;
archivo_in.open(nombrearchivo);
if(archivo_in.fail()){
cout<<"El archivo no se abrio con exito";
exit(1);
}
archivo_in.seekg(0L, ios::beg);
//ultimo = archivo_in.tellg();
/* Primer recorrido del archivo
Obtiene media aritmetica */
while(!archivo_in.eof()){
archivo_in >> x;
sum = sum + x;
}
sum = sum - x; //Restar el numero entero que agrega al leer al archivo
prom=sum/6.0;
archivo_in.close();
archivo_in.open(nombrearchivo);
if(archivo_in.fail()){
cout<<"El archivo no se abrio con exito";
exit(1);
}
archivo_in.seekg(0L, ios::beg);
/* Segundo recorrido del archivo */
while(!archivo_in.eof()){
archivo_in >> x;
sum2 = sum2 + pow(((x-prom)),2);
}
sum2 = sum2 - pow(((x-prom)),2); //Restar el numero entero que agrega al leer al archivo
des = sqrt(sum2/6.0);
cout << "Promedio= " << prom << endl;
cout<<"La desviacion estandar es: "<<des<<endl;
archivo_in.close();
cin.ignore();
return 0;
}
|
//
// Created by kamlesh on 30/10/15.
//
#ifndef UV_MULTI_WORKER_THREADS_H
#define UV_MULTI_WORKER_THREADS_H
#include <uv.h>
class worker {
private:
public:
worker();
void on_write(uv_write_t *req, int status);
void on_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf);
void on_connect(uv_stream_t *q, ssize_t nread, const uv_buf_t *buf);
int start();
};
#endif //UV_MULTI_WORKER_THREADS_H
|
#pragma once
#ifndef Game_hpp
#define Game_hpp
#include <SDL2/SDL.h>
#include <stdio.h>
#include <SDL2/SDL_image.h>
#include "Texture.hpp"
#include <fstream>
#include <string>
#include <stdio.h>
#include <iostream>
using namespace std;
#include "Audio.hpp"
class Game
{
public:
Game();
~Game();
bool initialize();
void initBots();
void update();
void render();
void handleEvents();
void Cleanup();
bool running() { return isRunning; };
bool createMap();
bool loadTiles();
void triggerAttack();
void createMapSurface();
bool checkWall(int x, int y);
bool isRunning;
Audio intro;
int speed;
bool l, r, u, d, fall;
bool l2, r2, u2, d2;
int idoll, idolr, runl, runr;
int idolu, idold, runu, rund;
int die;
bool attack = false;
int attackl, attackr, attacku, attackd;
SDL_Window *window;
inline static SDL_Renderer *renderer;
SDL_Texture *wallTexture;
const static int MAP_WIDTH = 35;
const static int MAP_HEIGHT = 25;
const static int TILE_SIZE = 32;
const static int scoreboardWidth = 300;
int map[MAP_HEIGHT][MAP_WIDTH];
static int tiles[MAP_WIDTH * MAP_HEIGHT];
const static int SCREEN_WIDTH = MAP_WIDTH * TILE_SIZE + scoreboardWidth;
const static int SCREEN_HEIGHT = MAP_HEIGHT * TILE_SIZE;
SDL_Rect rectTile;
SDL_Event event;
};
#endif /* Game_hpp */
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
// only gravity will pull me down
// Find first set bit
int t, n;
cin >> t;
while (t--) {
cin >> n;
int pos=1;
if(!n) {
cout << 0 << endl;
continue;
}
while(!(n&1)) {
n = n >> 1;
pos++;
}
cout << pos << endl;
}
return 0;
}
|
#include <iberbar/RHI/D3D11/Device.h>
extern "C" __iberbarD3DApi__ iberbar::RHI::IDevice * iberbarRhiDeviceCreate()
{
return new iberbar::RHI::D3D11::CDevice();
}
|
#include<bits/stdc++.h>
#define rep(i,n) for (int i =0; i <(n); i++)
using namespace std;
using ll = long long;
const double PI = 3.14159265358979323846;
int main(){
string S;
cin >> S;
int N = (int)S.size();
bool I = false;
bool C = false;
bool T = false;
rep(i,N){
if(!I && S.at(i) == 'I')I =true;
else if(!I && S.at(i) == 'i')I =true;
else if(I && !C && S.at(i) == 'C')C = true;
else if(I && !C && S.at(i) == 'c')C = true;
else if(I && C && !T && S.at(i) == 'T')T = true;
else if(I && C && !T && S.at(i) == 't')T = true;
}
if(T)cout << "YES" << endl;
else cout << "NO" << endl;
return 0;
}
|
#include "BoardPiece.h"
#include <string>
using namespace std;
BoardPiece::BoardPiece() {
}
string BoardPiece::print() const {
return "XX";
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <queue>
#include <unordered_set>
#include <unordered_map>
#include <stack>
#include <cstdio>
#define INT_MIN (1<<31)
#define INT_MAX (~INT_MIN)
#define UNREACHABLE (INT_MAX>>2)
#define INF (1e300)
#define eps (1e-9)
using namespace std;
ifstream fin("378_input.txt");
#define cin fin
struct Point
{
Point() {
}
Point(double x, double y) {
this->x = x;
this->y = y;
}
bool isSamePoint(Point p) {
return (this->x == p.x && this->y == p.y);
}
bool isSameDir(Point d) {
return (this->xProduct(d) == 0);
}
double xProduct(Point other) {
return (this->x * other.y - this->y*other.x);
}
double x;
double y;
};
typedef Point Direction;
struct Line
{
Line(Point p1, Point p2) {
this->p = p1;
this->dir = Direction(p2.x - p1.x, p2.y - p1.y);
}
bool containsPoint(Point p) {
Direction d = Direction(p.x - this->p.x, p.y - this->p.y);
if (d.isSameDir(this->dir)) {
return true;
}
return false;
}
Point intersectLine(Line other) {
Point p1 = this->p;
Point p2 = other.p;
Direction v1 = this->dir;
Direction v2 = other.dir;
double a = v1.xProduct(p2);
double b = p1.xProduct(v1);
double c = v2.xProduct(v1);
double t2 = (a + b) / c;
return Point(p2.x + t2 * v2.x, p2.y + t2 * v2.y);
}
Point p;
Direction dir;
};
int main()
{
int N;
cin >> N;
cout << "INTERSECTING LINES OUTPUT" << endl;
while (N--)
{
Point a1, a2, b1, b2;
long long x, y;
cin >> x >> y;
a1 = Point(x, y);
cin >> x >> y;
a2 = Point(x, y);
cin >> x >> y;
b1 = Point(x, y);
cin >> x >> y;
b2 = Point(x, y);
Line l1 = Line(a1, a2);
Line l2 = Line(b1, b2);
if (l1.containsPoint(b1) && l1.containsPoint(b2)) { // if same line
cout << "LINE" << endl;
}
else if (l1.dir.isSameDir(l2.dir)) {
cout << "NONE" << endl;
}
else {
Point r = l1.intersectLine(l2);
printf("POINT %.2f %.2f\n", r.x, r.y);
}
}
cout << "END OF OUTPUT" << endl;
}
|
#include <stdio.h>
#include <math.h>
int main() {
int numero = 2;
float raiz;
printf("Quadrados perfeitos entre 1 e 40: ");
while (numero <= 40) {
raiz = (sqrt(numero));
if (raiz == int(raiz)) {
printf("\n%d", numero);
}
numero++;
}
}
|
#include <iostream>
#include <cassert>
#include <string>
#include <locale>
#include <stdio.h>
using namespace std;
struct Say {
Say operator()(string word) {
return {new_word + (new_word==""?"":" ") + word};
}
string operator()() {
return new_word;
}
string new_word;
} say;
int main() {
assert(say("hey")("batter")() == "hey batter");
assert(say("hey")("batter")("batter")() == "hey batter batter");
assert(say("hey")("batter")("batter")("swing")() == "hey batter batter swing");
}
|
#include "Terrain.h"
void Terrain::ConfigureGlobals()
{
Terrain::m_terrainGlobals = new Ogre::TerrainGlobalOptions();
}
void Terrain::ConfigureGroup()
{
m_terrainGroup = new Ogre::TerrainGroup(OgreFramework::getSingletonPtr()->m_pSceneMgr, Ogre::Terrain::ALIGN_X_Z, 513, 12000.0f);
m_terrainGroup->setFilenameConvention(Ogre::String("Uc3Terrain"), Ogre::String("dat"));
m_terrainGroup->setOrigin(Ogre::Vector3::ZERO);
ConfigureTerrainDefaults(OgreFramework::getSingletonPtr()->m_light);
/*
for (long x = 0; x <= 0; ++x)
for (long y = 0; y <= 0; ++y)
*/
DefineTerrain(0, 0);
// sync load since we want everything in place when we start
m_terrainGroup->loadAllTerrains(true);
if (m_terrainsImported)
{
Ogre::TerrainGroup::TerrainIterator ti = m_terrainGroup->getTerrainIterator();
while(ti.hasMoreElements())
{
Ogre::Terrain* t = ti.getNext()->instance;
InitBlendMaps(t);
}
}
m_terrainGroup->freeTemporaryResources();
}
void Terrain::ConfigureTerrainDefaults(Ogre::Light *light)
{
// Configure global
m_terrainGlobals->setMaxPixelError(8);
// testing composite map
m_terrainGlobals->setCompositeMapDistance(3000);
m_terrainGlobals->setLightMapDirection(light->getDerivedDirection());
m_terrainGlobals->setCompositeMapAmbient(OgreFramework::getSingletonPtr()->m_pSceneMgr->getAmbientLight());
m_terrainGlobals->setCompositeMapDiffuse(light->getDiffuseColour());
Ogre::Terrain::ImportData& defaultimp = m_terrainGroup->getDefaultImportSettings();
defaultimp.terrainSize = 513;
defaultimp.worldSize = 12000.0f;
defaultimp.inputScale = 600; // due terrain.png is 8 bpp
defaultimp.minBatchSize = 33;
defaultimp.maxBatchSize = 65;
defaultimp.layerList.resize(1);
defaultimp.layerList[0].worldSize = 100;
defaultimp.layerList[0].textureNames.push_back("dirt_grayrocky_diffusespecular.dds");
defaultimp.layerList[0].textureNames.push_back("dirt_grayrocky_normalheight.dds");
/*
defaultimp.layerList[1].worldSize = 30;
defaultimp.layerList[1].textureNames.push_back("grass_green-01_diffusespecular.dds");
defaultimp.layerList[1].textureNames.push_back("grass_green-01_normalheight.dds");
defaultimp.layerList[2].worldSize = 200;
defaultimp.layerList[2].textureNames.push_back("growth_weirdfungus-03_diffusespecular.dds");
defaultimp.layerList[2].textureNames.push_back("growth_weirdfungus-03_normalheight.dds");
*/
}
void Terrain::DefineTerrain(int x, int y)
{
Ogre::String filename = m_terrainGroup->generateFilename(x, y);
if (Ogre::ResourceGroupManager::getSingleton().resourceExists(m_terrainGroup->getResourceGroup(), filename))
{
m_terrainGroup->defineTerrain(x, y);
}
else
{
Ogre::Image img;
GetTerrainImage(x % 2 != 0, y % 2 != 0, img);
m_terrainGroup->defineTerrain(x, y, &img);
m_terrainsImported = true;
}
}
void Terrain::GetTerrainImage(bool flipX, bool flipY, Ogre::Image& img)
{
img.load("terrain.png", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
if (flipX)
img.flipAroundY();
if (flipY)
img.flipAroundX();
}
void Terrain::InitBlendMaps(Ogre::Terrain* terrain)
{
Ogre::TerrainLayerBlendMap* blendMap0 = terrain->getLayerBlendMap(1);
Ogre::TerrainLayerBlendMap* blendMap1 = terrain->getLayerBlendMap(2);
Ogre::Real minHeight0 = 70;
Ogre::Real fadeDist0 = 40;
Ogre::Real minHeight1 = 70;
Ogre::Real fadeDist1 = 15;
float* pBlend0 = blendMap0->getBlendPointer();
float* pBlend1 = blendMap1->getBlendPointer();
for (Ogre::uint16 y = 0; y < terrain->getLayerBlendMapSize(); ++y)
{
for (Ogre::uint16 x = 0; x < terrain->getLayerBlendMapSize(); ++x)
{
Ogre::Real tx, ty;
blendMap0->convertImageToTerrainSpace(x, y, &tx, &ty);
Ogre::Real height = terrain->getHeightAtTerrainPosition(tx, ty);
Ogre::Real val = (height - minHeight0) / fadeDist0;
val = Ogre::Math::Clamp(val, (Ogre::Real)0, (Ogre::Real)1);
*pBlend0++ = val;
val = (height - minHeight1) / fadeDist1;
val = Ogre::Math::Clamp(val, (Ogre::Real)0, (Ogre::Real)1);
*pBlend1++ = val;
}
}
blendMap0->dirty();
blendMap1->dirty();
blendMap0->update();
blendMap1->update();
}
|
// Created on: 1993-11-17
// Created by: Isabelle GRIGNON
// 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 _ChFiDS_State_HeaderFile
#define _ChFiDS_State_HeaderFile
//! This enum describe the different kinds of extremities
//! of a fillet. OnSame, Ondiff and AllSame are
//! particular cases of BreakPoint for a corner with 3
//! edges and three faces :
//! - AllSame means that the three concavities are on the
//! same side of the Shape,
//! - OnDiff means that the edge of the fillet has a
//! concave side different than the two other edges,
//! - OnSame means that the edge of the fillet has a
//! concave side different than one of the two other edges
//! and identical to the third edge.
enum ChFiDS_State
{
ChFiDS_OnSame,
ChFiDS_OnDiff,
ChFiDS_AllSame,
ChFiDS_BreakPoint,
ChFiDS_FreeBoundary,
ChFiDS_Closed,
ChFiDS_Tangent
};
#endif // _ChFiDS_State_HeaderFile
|
// O(N^2) two pointers skip duplicates
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> triplets;
int n = nums.size();
if (n < 3) return triplets;
sort(nums.begin(), nums.end());
for (int i = 0; i < n - 2;) {
int num = nums[i];
int target = -num;
int begin = i + 1, end = n - 1;
while (begin < end) {
int lhs = nums[begin], rhs = nums[end];
int sum = lhs + rhs;
if (sum < target) begin++;
else if (sum > target) end--;
else {
triplets.push_back(vector<int>{ num, lhs, rhs });
while (nums[++begin] == lhs);
while (nums[--end] == rhs);
}
}
while (nums[++i] == num);
}
return triplets;
}
};
|
#include<bits/stdc++.h>
using namespace std;
#define maxn 10005
typedef struct node{
int index;
int cnt;
}node;
bool cmp(node a,node b){
if(a.cnt>b.cnt)
return true;
else if(a.cnt==b.cnt){
if(a.index<b.index)
return true;
}
return false;
}
int n,m;
vector<int> g[maxn];
int dfn[maxn];
int low[maxn];
bool status[maxn];
int iscut[maxn];
bool instack[maxn];
int stk[maxn];
int top;
int belong[maxn];
int qlt;
vector<int> bcc[maxn];
node ans[maxn];
void init(){
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(dfn));
for(int i=0;i<maxn;i++){
g[i].clear();
// ans[i].index=i;
// ans[i].cnt=0;
}
memset(stk,0,sizeof(stk));
memset(status,false,sizeof(status));
memset(instack,false,sizeof(instack));
memset(iscut,false,sizeof(iscut));
memset(belong,0,sizeof(belong));
qlt=0;
top=0;
}
void tarjan(int c,int d,int from){
// printf("vis c=%d d=%d\n",c,d);
int child=0;
stk[++top]=c;
instack[c]=true;
status[c]=true;
dfn[c]=low[c]=d;
int sz=g[c].size();
int v;
for(int i=0;i<sz;i++){
v=g[c][i];
if(!status[v]){
child++;
tarjan(v,d+1,c);
low[c]=min(low[c],low[v]);
if(c!=0&&low[v]>=dfn[c]){
// printf("cut %d\n",c);
iscut[c]++;
}
}
else if(instack[v]&&v!=from){
// printf("v=%d c=%d\n",v,c);
low[c]=min(low[c],dfn[v]);
}
if(c==0&&child>1){
iscut[c]=1;
}
}
// printf("c=%d dfn=%d low=%d\n",c,dfn[c],low[c]);
// if(dfn[c]==low[c]){
// qlt++;
// printf("qlt=%d c=%d top=%d\n",qlt,c,top);
// printf("stack:\n");
// for(int i=1;i<=top;i++){
// printf("%d ",stk[i]);
// }
// printf("\n");
// while(true){
// v=stk[top--];
// instack[v]=false;
// belong[v]=qlt;
// // printf("qlt=%d v=%d\n",qlt,v);
// bcc[qlt].push_back(v);
// if(v==c)
// break;
// }
// }
return;
}
int main(){
while(scanf("%d%d",&n,&m)&&(n!=0&&m!=0)){
init();
int a,b;
while(scanf("%d%d",&a,&b)&&(a!=-1&&b!=-1)){
g[a].push_back(b);
g[b].push_back(a);
}
tarjan(0,1,-1);
// printf("qlt=%d\n",qlt);
for(int i=0;i<n;i++){
ans[i].index=i;
ans[i].cnt=iscut[i]+1;
}
// for(int i=1;i<=qlt;i++){
// int sz=bcc[i].size();
// printf("sz=%d i=%d\n",sz,i);
// for(int j=0;j<sz;j++){
// int v=bcc[i][j];
// printf("bcc i=%d j=%d v=%d\n",i,j,v);
// if(iscut[v]){
// // printf("anscnt++ %d\n",v);
// ans[v].cnt++;
// }
// }
// }
sort(ans,ans+n,cmp);
for(int i=0;i<m;i++){
printf("%d %d\n",ans[i].index,ans[i].cnt);
}
printf("\n");
}
return 0;
}
|
#pragma once
#include <vector>
#include "bsp_layout.hpp"
#include "grid.hpp"
#include "math.hpp"
#include "random.hpp"
#include "generate.hpp"
#include "direction.hpp"
namespace yama {
namespace detail {
class bsp_layout_impl {
public:
using params_t = bsp_layout::params_t;
struct node {
using index_t = int;
static index_t const EMPTY_VALUE = -1;
explicit node(rect_t const Bounds)
: first {EMPTY_VALUE}
, second {EMPTY_VALUE}
, bounds {Bounds}
{
}
bool is_leaf() const {
return first == EMPTY_VALUE;
}
bool is_empty() const {
return first == EMPTY_VALUE && second == EMPTY_VALUE;
}
void set_data(index_t i) {
BK_ASSERT(is_leaf());
second = i;
}
index_t get_data() const {
BK_ASSERT(is_leaf());
return second;
}
index_t first;
index_t second;
rect_t bounds;
};
static params_t validate(params_t params);
public:
//! construct with a (default) param set.
explicit bsp_layout_impl(params_t params = params_t {});
//! get the current param set.
params_t params() const {
return params_;
}
//! set the current param set.
void set_params(params_t const p) {
params_ = validate(p);
}
//! reset internal state and keep the current param set.
void clear();
//! generate a new map
map generate(random_t& random);
//! decide whether to split a node.
bool do_split(random_t& random, rect_t bounds) const;
//! decide whether to generate a room.
bool do_generate_room(random_t& random, rect_t bounds) const;
//! split a node into sub nodes
void split_node(random_t& random, node& n);
//! generate a room.
rect_t generate_room(random_t& random, rect_t bounds) const;
//! rasterize a room to the final map (grid).
void write_room(rect_t room);
//! fill the bsp tree with rooms
void generate_rooms(random_t& random);
//! create the bsp tree
void generate_tree(random_t& random);
////////////////////////////////////////////////////////////////////////////
//! Connect two rects contained within bounds.
////////////////////////////////////////////////////////////////////////////
void do_connect(random_t& random, rect_t bounds, rect_t first, rect_t second);
////////////////////////////////////////////////////////////////////////////
//! 3-state logic of sorts.
////////////////////////////////////////////////////////////////////////////
enum class possible {
no, yes, maybe
};
////////////////////////////////////////////////////////////////////////////
//! Given three co-linear points, return whether creating a tunnel at
//! @p ahead is possible.
////////////////////////////////////////////////////////////////////////////
possible can_tunnel(point_t left, point_t ahead, point_t right) const;
////////////////////////////////////////////////////////////////////////////
//! Get a tuple of three co-linear points relative to @p p.
////////////////////////////////////////////////////////////////////////////
template <direction Left, direction Ahead, direction Right>
static std::tuple<point_t, point_t, point_t> get_ahead(point_t const p) {
return std::make_tuple(relative_to<Left>(p), relative_to<Ahead>(p), relative_to<Right>(p));
}
////////////////////////////////////////////////////////////////////////////
//! Transform value given that a corridor passes over it.
////////////////////////////////////////////////////////////////////////////
static tile_category corridor_transform(tile_category value);
////////////////////////////////////////////////////////////////////////////
//! Make a tunnel segment of length abs(dx) or abs(dy).
////////////////////////////////////////////////////////////////////////////
point_t make_connection_tunnel(
point_t p, rect_t bounds, int dx, int dy
);
////////////////////////////////////////////////////////////////////////////
//! Recursively connect all rooms depth-first.
//!
//! @return {has_room, bounds} where @p bounds are the room itself if has_room
//! is true, otherise @p bounds are the region's bounds.
////////////////////////////////////////////////////////////////////////////
std::pair<bool, rect_t> connect(random_t& random, node const& n);
std::vector<rect_t> get_regions() const {
std::vector<rect_t> result;
for (auto const& n : nodes_) {
if (n.is_leaf()) {
result.push_back(n.bounds);
}
}
return result;
}
params_t params_;
std::vector<node> nodes_;
std::vector<rect_t> rooms_;
yama::map map_;
};
} //namespace detail
} //namespace yama
|
#include <math.h>
#include "Eigen/Dense"
#include <random>
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace Eigen;
class lin_reg{
private:
void linsolv(MatrixXd a, int n, VectorXd y);
public:
MatrixXd THETA;
bool bias = 1;
lin_reg(){ }
void learn(MatrixXd x, MatrixXd y, bool normalize_flag = 1, bool bias2 = 1);
~lin_reg(){}
};
void lin_reg::linsolv(MatrixXd a, int n, VectorXd y)
{
double c;
double s;
double r;
double up;
double low;
double temp_up = 0;
double temp_down = 0;
double *aa = new double[n*n];
double *yy = new double[n];
for (int i = 0; i < n*n; ++i)
{
aa[i] = a(i);
}
for (int i = 0; i < n; ++i)
{
yy[i] = y(i);
}
for (int i = 0; i < n-1; ++i)
{
for (int k = 1; k+i < n; ++k)
{
up = aa[n*i+i];
low = aa[(i+k)*n+i];
r = sqrt(up*up + low*low);
if (!r)
{
continue;
}
c = up/r;
s = -low/r;
for (int j = i; j < n; ++j)
{
temp_up = c*aa[i*n+j] - s*aa[(i+k)*n+j];
temp_down = s*aa[i*n+j] + c*aa[(i+k)*n+j];
aa[i*n + j] = temp_up;
aa[(i+k)*n+j] = temp_down;
}
temp_up = c*yy[i] - s*yy[i+k];
temp_down = s*yy[i] + c*yy[i+k];
yy[i] = temp_up;
yy[i+k] = temp_down;
}
}
double temp;
for (int i = n-1; i >= 0; --i)
{
temp = 0;
for (int j = i+1; j < n; ++j)
{
temp += THETA(j,0)*aa[i*n+j];
}
THETA(i,0) = (yy[i] - temp)/aa[i*n+i];
}
free(yy);
free(aa);
}
void lin_reg::learn(MatrixXd x, MatrixXd y, bool normalize_flag, bool bias2)
{
MatrixXd x_norm = x;
bias = bias2;
if (normalize_flag)
{
//normalize x in new matrix x_norm
}
if (bias)
{
//add bias term
x_norm.conservativeResize(x_norm.rows(), x_norm.cols()+1);
x_norm.col(x_norm.cols()-1).setOnes();
}
THETA.resize(x_norm.cols(),1);
MatrixXd y_help;
y_help.resize(y.rows(),1);
y_help = x_norm.transpose()*y;
x_norm = x_norm.transpose()*x_norm;
linsolv(x_norm, x_norm.rows(), y_help);
}
int main()
{
return 1;
}
|
/**
* Copyright (c) 2007-2012, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack 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 REGENTS 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 REGENTS 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.
*
* @file readline_curses.cc
*/
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include "config.h"
#ifdef HAVE_PTY_H
# include <pty.h>
#endif
#ifdef HAVE_UTIL_H
# include <util.h>
#endif
#ifdef HAVE_LIBUTIL_H
# include <libutil.h>
#endif
#include <string>
#include <utility>
#include "base/ansi_scrubber.hh"
#include "base/auto_mem.hh"
#include "base/itertools.hh"
#include "base/lnav_log.hh"
#include "base/paths.hh"
#include "base/string_util.hh"
#include "fmt/format.h"
#include "fts_fuzzy_match.hh"
#include "readline_curses.hh"
#include "shlex.hh"
#include "spookyhash/SpookyV2.h"
static int got_line = 0;
static int got_abort = 0;
static bool alt_done = 0;
static sig_atomic_t got_timeout = 0;
static sig_atomic_t got_winch = 0;
static readline_curses* child_this;
static sig_atomic_t looping = 1;
static const int HISTORY_SIZE = 256;
static int completion_start;
static const int FUZZY_PEER_THRESHOLD = 30;
static const char* RL_INIT[] = {
/*
* XXX Need to keep the input on a single line since the display screws
* up if it wraps around.
*/
"set horizontal-scroll-mode on",
"set bell-style none",
"set show-all-if-ambiguous on",
"set show-all-if-unmodified on",
"set menu-complete-display-prefix on",
"TAB: menu-complete",
"\"\\e[Z\": menu-complete-backward",
};
readline_context* readline_context::loaded_context;
std::set<std::string>* readline_context::arg_possibilities;
static std::string last_match_str;
static bool last_match_str_valid;
static bool arg_needs_shlex;
static nonstd::optional<std::string> rewrite_line_start;
static void
sigalrm(int sig)
{
got_timeout = 1;
}
static void
sigwinch(int sig)
{
got_winch = 1;
}
static void
sigterm(int sig)
{
looping = 0;
}
static void
line_ready_tramp(char* line)
{
child_this->line_ready(line);
got_line = 1;
rl_callback_handler_remove();
}
static int
sendall(int sock, const char* buf, size_t len)
{
off_t offset = 0;
while (len > 0) {
int rc = send(sock, &buf[offset], len, 0);
if (rc == -1) {
switch (errno) {
case EAGAIN:
case EINTR:
break;
default:
return -1;
}
} else {
len -= rc;
offset += rc;
}
}
return 0;
}
static int
sendstring(int sock, const char* buf, size_t len)
{
if (sendall(sock, (char*) &len, sizeof(len)) == -1) {
return -1;
} else if (sendall(sock, buf, len) == -1) {
return -1;
}
return 0;
}
static int
sendcmd(int sock, char cmd, const char* buf, size_t len)
{
size_t total_len = len + 2;
char prefix[2] = {cmd, ':'};
if (sendall(sock, (char*) &total_len, sizeof(total_len)) == -1) {
return -1;
} else if (sendall(sock, prefix, sizeof(prefix)) == -1
|| sendall(sock, buf, len) == -1)
{
return -1;
}
return 0;
}
static int
recvall(int sock, char* buf, size_t len)
{
off_t offset = 0;
while (len > 0) {
ssize_t rc = recv(sock, &buf[offset], len, 0);
if (rc == -1) {
switch (errno) {
case EAGAIN:
case EINTR:
break;
default:
return -1;
}
} else if (rc == 0) {
errno = EIO;
return -1;
} else {
len -= rc;
offset += rc;
}
}
return 0;
}
static ssize_t
recvstring(int sock, char* buf, size_t len)
{
ssize_t retval;
if (recvall(sock, (char*) &retval, sizeof(retval)) == -1) {
return -1;
} else if (retval > (ssize_t) len) {
return -1;
} else if (recvall(sock, buf, retval) == -1) {
return -1;
}
return retval;
}
char*
readline_context::completion_generator(const char* text_in, int state)
{
static std::vector<std::string> matches;
std::vector<std::string> long_matches;
char* retval = nullptr;
if (state == 0) {
auto text_str = std::string(text_in);
if (arg_needs_shlex) {
shlex arg_lexer(text_str);
std::map<std::string, scoped_value_t> scope;
std::string result;
if (arg_lexer.eval(result, scoped_resolver{&scope})) {
text_str = result;
}
}
matches.clear();
if (arg_possibilities != nullptr) {
for (const auto& poss : (*arg_possibilities)) {
auto cmpfunc
= (loaded_context->is_case_sensitive() ? strncmp
: strncasecmp);
auto poss_str = poss.c_str();
// Check for an exact match and for the quoted version.
if (cmpfunc(text_str.c_str(), poss_str, text_str.length()) == 0
|| ((strchr(loaded_context->rc_quote_chars, poss_str[0])
!= nullptr)
&& cmpfunc(text_str.c_str(),
&poss_str[1],
text_str.length())
== 0))
{
auto poss_slash_count
= std::count(poss.begin(), poss.end(), '/');
if (endswith(poss, "/")) {
poss_slash_count -= 1;
}
if (std::count(text_str.begin(), text_str.end(), '/')
== poss_slash_count)
{
matches.emplace_back(poss);
} else {
long_matches.emplace_back(poss);
}
}
}
if (matches.empty()) {
matches = std::move(long_matches);
}
if (matches.empty()) {
std::vector<std::pair<int, std::string>> fuzzy_matches;
std::vector<std::pair<int, std::string>> fuzzy_long_matches;
for (const auto& poss : (*arg_possibilities)) {
std::string poss_str = tolower(poss);
int score = 0;
if (fts::fuzzy_match(
text_str.c_str(), poss_str.c_str(), score)
&& score > 0)
{
if (score <= 0) {
continue;
}
auto poss_slash_count
= std::count(poss_str.begin(), poss_str.end(), '/');
if (endswith(poss, "/")) {
poss_slash_count -= 1;
}
if (std::count(text_str.begin(), text_str.end(), '/')
== poss_slash_count)
{
fuzzy_matches.emplace_back(score, poss);
} else {
fuzzy_long_matches.emplace_back(score, poss);
}
}
}
if (fuzzy_matches.empty()) {
fuzzy_matches = std::move(fuzzy_long_matches);
}
if (!fuzzy_matches.empty()) {
stable_sort(
begin(fuzzy_matches),
end(fuzzy_matches),
[](auto l, auto r) { return r.first < l.first; });
int highest = fuzzy_matches[0].first;
for (const auto& pair : fuzzy_matches) {
if (highest - pair.first < FUZZY_PEER_THRESHOLD) {
matches.push_back(pair.second);
} else {
break;
}
}
}
}
}
if (matches.size() == 1) {
if (text_str == matches[0]) {
matches.pop_back();
}
last_match_str_valid = false;
if (sendstring(
child_this->rc_command_pipe[readline_curses::RCF_SLAVE],
"m:0:0:0",
7)
== -1)
{
_exit(1);
}
}
}
if (!matches.empty()) {
retval = strdup(matches.back().c_str());
matches.pop_back();
}
return retval;
}
char**
readline_context::attempted_completion(const char* text, int start, int end)
{
char** retval = nullptr;
completion_start = start;
if (start == 0
&& loaded_context->rc_possibilities.find("__command")
!= loaded_context->rc_possibilities.end())
{
arg_possibilities = &loaded_context->rc_possibilities["__command"];
arg_needs_shlex = false;
rl_completion_append_character = loaded_context->rc_append_character;
} else {
char* space;
std::string cmd;
int point = rl_point;
while (point > 0 && rl_line_buffer[point] != ' ') {
point -= 1;
}
shlex lexer(rl_line_buffer, point);
std::map<std::string, scoped_value_t> scope;
arg_possibilities = nullptr;
rl_completion_append_character = 0;
auto split_res = lexer.split(scoped_resolver{&scope});
if (split_res.isOk()) {
auto prefix = split_res.unwrap()
| lnav::itertools::map(
[](const auto& elem) { return elem.se_value; });
auto prefix2
= fmt::format(FMT_STRING("{}"), fmt::join(prefix, "\x1f"));
auto prefix_iter = loaded_context->rc_prefixes.find(prefix2);
if (prefix_iter != loaded_context->rc_prefixes.end()) {
arg_possibilities
= &(loaded_context->rc_possibilities[prefix_iter->second]);
arg_needs_shlex = false;
}
}
if (arg_possibilities == nullptr) {
space = strchr(rl_line_buffer, ' ');
if (space == nullptr) {
space = rl_line_buffer + strlen(rl_line_buffer);
}
cmd = std::string(rl_line_buffer, space - rl_line_buffer);
auto iter = loaded_context->rc_prototypes.find(cmd);
if (iter == loaded_context->rc_prototypes.end()) {
if (loaded_context->rc_possibilities.find("*")
!= loaded_context->rc_possibilities.end())
{
arg_possibilities = &loaded_context->rc_possibilities["*"];
arg_needs_shlex = false;
rl_completion_append_character
= loaded_context->rc_append_character;
}
} else {
std::vector<std::string>& proto
= loaded_context->rc_prototypes[cmd];
if (proto.empty()) {
arg_possibilities = nullptr;
} else if (proto[0] == "dirname") {
shlex fn_lexer(rl_line_buffer, rl_point);
auto split_res = fn_lexer.split(scoped_resolver{&scope});
if (split_res.isOk()) {
auto fn_list = split_res.unwrap();
const auto& last_fn = fn_list.size() <= 1
? ""
: fn_list.back().se_value;
static std::set<std::string> dir_name_set;
dir_name_set.clear();
auto_mem<char> completed_fn;
int fn_state = 0;
while ((completed_fn = rl_filename_completion_function(
last_fn.c_str(), fn_state))
!= nullptr)
{
dir_name_set.insert(completed_fn.in());
fn_state += 1;
}
arg_possibilities = &dir_name_set;
arg_needs_shlex = true;
} else {
arg_possibilities = nullptr;
}
} else if (proto[0] == "filename") {
shlex fn_lexer(rl_line_buffer, rl_point);
int found = 0;
auto split_res = fn_lexer.split(scoped_resolver{&scope});
if (split_res.isOk()) {
auto fn_list = split_res.unwrap();
const auto& last_fn = fn_list.size() <= 1
? ""
: fn_list.back().se_value;
if (last_fn.find(':') != std::string::npos) {
auto rp_iter
= loaded_context->rc_possibilities.find(
"remote-path");
if (rp_iter
!= loaded_context->rc_possibilities.end())
{
for (const auto& poss : rp_iter->second) {
if (startswith(poss, last_fn.c_str())) {
found += 1;
}
}
if (found) {
arg_possibilities = &rp_iter->second;
arg_needs_shlex = false;
}
}
if (!found
|| (endswith(last_fn, "/") && found == 1))
{
char msg[2048];
snprintf(
msg, sizeof(msg), "\t:%s", last_fn.c_str());
sendstring(child_this->rc_command_pipe[1],
msg,
strlen(msg));
}
}
if (!found) {
static std::set<std::string> file_name_set;
file_name_set.clear();
auto_mem<char> completed_fn;
int fn_state = 0;
auto recent_netlocs_iter
= loaded_context->rc_possibilities.find(
"recent-netlocs");
if (recent_netlocs_iter
!= loaded_context->rc_possibilities.end())
{
file_name_set.insert(
recent_netlocs_iter->second.begin(),
recent_netlocs_iter->second.end());
}
while (
(completed_fn = rl_filename_completion_function(
last_fn.c_str(), fn_state))
!= nullptr)
{
file_name_set.insert(completed_fn.in());
fn_state += 1;
}
arg_possibilities = &file_name_set;
arg_needs_shlex = true;
}
} else {
arg_possibilities = nullptr;
}
} else {
arg_possibilities
= &(loaded_context->rc_possibilities[proto[0]]);
arg_needs_shlex = false;
}
}
}
}
retval = rl_completion_matches(text, completion_generator);
if (retval == nullptr) {
rl_attempted_completion_over = 1;
}
return retval;
}
static int
rubout_char_or_abort(int count, int key)
{
if (rl_line_buffer[0] == '\0') {
rl_done = true;
got_abort = 1;
got_line = 0;
return 0;
} else {
return rl_rubout(count, '\b');
}
}
static int
alt_done_func(int count, int key)
{
alt_done = true;
rl_newline(count, key);
return 0;
}
int
readline_context::command_complete(int count, int key)
{
if (loaded_context->rc_possibilities.find("__command")
!= loaded_context->rc_possibilities.end())
{
char* space = strchr(rl_line_buffer, ' ');
if (space == nullptr) {
return rl_menu_complete(count, key);
}
}
return rl_insert(count, key);
}
readline_context::readline_context(std::string name,
readline_context::command_map_t* commands,
bool case_sensitive)
: rc_name(std::move(name)), rc_case_sensitive(case_sensitive),
rc_quote_chars("\"'"), rc_highlighter(nullptr)
{
if (commands != nullptr) {
command_map_t::iterator iter;
for (iter = commands->begin(); iter != commands->end(); ++iter) {
std::string cmd = iter->first;
this->rc_possibilities["__command"].insert(cmd);
iter->second->c_func(
INIT_EXEC_CONTEXT, cmd, this->rc_prototypes[cmd]);
}
}
memset(&this->rc_history, 0, sizeof(this->rc_history));
history_set_history_state(&this->rc_history);
auto config_dir = lnav::paths::dotlnav();
auto hpath = (config_dir / this->rc_name).string() + ".history";
read_history(hpath.c_str());
this->save();
this->rc_append_character = ' ';
}
void
readline_context::load()
{
char buffer[128];
rl_completer_word_break_characters = (char*) " \t\n|()"; /* XXX */
/*
* XXX Need to keep the input on a single line since the display screws
* up if it wraps around.
*/
snprintf(buffer,
sizeof(buffer),
"set completion-ignore-case %s",
this->rc_case_sensitive ? "off" : "on");
rl_parse_and_bind(buffer); /* NOTE: buffer is modified */
loaded_context = this;
rl_attempted_completion_function = attempted_completion;
history_set_history_state(&this->rc_history);
for (auto& rc_var : this->rc_vars) {
*(rc_var.rv_dst.ch) = (char*) rc_var.rv_val.ch;
}
}
void
readline_context::save()
{
HISTORY_STATE* hs = history_get_history_state();
this->rc_history = *hs;
free(hs);
hs = nullptr;
}
readline_curses::readline_curses(
std::shared_ptr<pollable_supervisor> supervisor)
: pollable(supervisor, pollable::category::interactive),
rc_focus(noop_func{}), rc_change(noop_func{}), rc_perform(noop_func{}),
rc_alt_perform(noop_func{}), rc_timeout(noop_func{}),
rc_abort(noop_func{}), rc_display_match(noop_func{}),
rc_display_next(noop_func{}), rc_blur(noop_func{}),
rc_completion_request(noop_func{})
{
}
readline_curses::~readline_curses()
{
this->rc_pty[RCF_MASTER].reset();
this->rc_command_pipe[RCF_MASTER].reset();
if (this->rc_child == 0) {
_exit(0);
} else if (this->rc_child > 0) {
int status;
log_debug("terminating readline child %d", this->rc_child);
log_perror(kill(this->rc_child, SIGTERM));
this->rc_child = -1;
while (wait(&status) < 0 && (errno == EINTR)) {
;
}
log_debug(" child %d has exited", this->rc_child);
}
}
void
readline_curses::store_matches(char** matches, int num_matches, int max_len)
{
static int match_index = 0;
char msg[64];
int rc;
max_len = 0;
for (int lpc = 0; lpc <= num_matches; lpc++) {
max_len = std::max(max_len, (int) strlen(matches[lpc]));
}
if (last_match_str_valid && strcmp(last_match_str.c_str(), matches[0]) == 0)
{
match_index += 1;
rc = snprintf(msg, sizeof(msg), "n:%d", match_index);
if (sendstring(child_this->rc_command_pipe[RCF_SLAVE], msg, rc) == -1) {
_exit(1);
}
} else {
match_index = 0;
rc = snprintf(msg,
sizeof(msg),
"m:%d:%d:%d",
completion_start,
num_matches,
max_len);
if (sendstring(child_this->rc_command_pipe[RCF_SLAVE], msg, rc) == -1) {
_exit(1);
}
for (int lpc = 1; lpc <= num_matches; lpc++) {
if (sendstring(child_this->rc_command_pipe[RCF_SLAVE],
matches[lpc],
strlen(matches[lpc]))
== -1)
{
_exit(1);
}
}
last_match_str = matches[0];
last_match_str_valid = true;
}
}
void
readline_curses::start()
{
if (this->rc_child > 0) {
return;
}
struct winsize ws;
int sp[2];
if (socketpair(PF_UNIX, SOCK_STREAM, 0, sp) < 0) {
throw error(errno);
}
this->rc_command_pipe[RCF_MASTER] = sp[RCF_MASTER];
this->rc_command_pipe[RCF_MASTER].close_on_exec();
this->rc_command_pipe[RCF_SLAVE] = sp[RCF_SLAVE];
this->rc_command_pipe[RCF_SLAVE].close_on_exec();
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1) {
throw error(errno);
}
if (this->vc_width > 0) {
ws.ws_col = this->vc_width;
} else if (this->vc_width < 0) {
ws.ws_col -= this->vc_left;
ws.ws_col += this->vc_width;
}
if (openpty(this->rc_pty[RCF_MASTER].out(),
this->rc_pty[RCF_SLAVE].out(),
nullptr,
nullptr,
&ws)
< 0)
{
perror("error: failed to open terminal(openpty)");
throw error(errno);
}
this->rc_pty[RCF_MASTER].close_on_exec();
this->rc_pty[RCF_SLAVE].close_on_exec();
if ((this->rc_child = fork()) == -1) {
throw error(errno);
}
if (this->rc_child != 0) {
this->rc_command_pipe[RCF_SLAVE].reset();
this->rc_pty[RCF_SLAVE].reset();
return;
}
{
char buffer[1024];
this->rc_command_pipe[RCF_MASTER].reset();
this->rc_pty[RCF_MASTER].reset();
signal(SIGALRM, sigalrm);
signal(SIGWINCH, sigwinch);
signal(SIGINT, SIG_IGN);
signal(SIGTERM, sigterm);
dup2(this->rc_pty[RCF_SLAVE], STDIN_FILENO);
dup2(this->rc_pty[RCF_SLAVE], STDOUT_FILENO);
setenv("TERM", "vt52", 1);
rl_initialize();
using_history();
stifle_history(HISTORY_SIZE);
rl_add_defun("rubout-char-or-abort", rubout_char_or_abort, '\b');
rl_add_defun("alt-done", alt_done_func, '\x0a');
// rl_add_defun("command-complete", readline_context::command_complete,
// ' ');
for (const auto* init_cmd : RL_INIT) {
snprintf(buffer, sizeof(buffer), "%s", init_cmd);
rl_parse_and_bind(buffer); /* NOTE: buffer is modified */
}
child_this = this;
}
std::map<int, readline_context*>::iterator current_context;
int maxfd;
require(!this->rc_contexts.empty());
rl_completion_display_matches_hook = store_matches;
current_context = this->rc_contexts.end();
maxfd = std::max(STDIN_FILENO, this->rc_command_pipe[RCF_SLAVE].get());
while (looping) {
fd_set ready_rfds;
int rc;
FD_ZERO(&ready_rfds);
if (current_context != this->rc_contexts.end()) {
FD_SET(STDIN_FILENO, &ready_rfds);
}
FD_SET(this->rc_command_pipe[RCF_SLAVE], &ready_rfds);
rc = select(maxfd + 1, &ready_rfds, nullptr, nullptr, nullptr);
if (rc < 0) {
switch (errno) {
case EINTR:
break;
}
} else {
if (FD_ISSET(STDIN_FILENO, &ready_rfds)) {
static uint64_t last_h1, last_h2;
struct itimerval itv;
itv.it_value.tv_sec = 0;
itv.it_value.tv_usec = KEY_TIMEOUT;
itv.it_interval.tv_sec = 0;
itv.it_interval.tv_usec = 0;
setitimer(ITIMER_REAL, &itv, nullptr);
rl_callback_read_char();
if (RL_ISSTATE(RL_STATE_DONE) && !got_line) {
got_line = 1;
this->line_ready("");
rl_callback_handler_remove();
} else {
uint64_t h1 = 1, h2 = 2;
if (rl_last_func == readline_context::command_complete) {
rl_last_func = rl_menu_complete;
}
bool complete_done
= (rl_last_func != rl_menu_complete
&& rl_last_func != rl_backward_menu_complete);
if (complete_done) {
last_match_str_valid = false;
} else if (rewrite_line_start
&& !startswith(rl_line_buffer,
rewrite_line_start->c_str()))
{
// If the line was rewritten, the extra text stays on
// the screen, so we need to delete it, make sure the
// append character is there, and redisplay. For
// example, ':co<TAB>' will complete ':comment' and
// append the current comment. Pressing '<TAB>' again
// would switch to ':config' and the comment text would
// be left on the display.
rl_delete_text(rl_point, rl_end);
if (rl_completion_append_character
&& rl_line_buffer[rl_point]
!= rl_completion_append_character)
{
char buf[2]
= {(char) rl_completion_append_character, '\0'};
rl_insert_text(buf);
}
rl_redisplay();
}
rewrite_line_start = nonstd::nullopt;
SpookyHash::Hash128(rl_line_buffer, rl_end, &h1, &h2);
if (h1 == last_h1 && h2 == last_h2) {
// do nothing
} else if (sendcmd(this->rc_command_pipe[RCF_SLAVE],
complete_done ? 'l' : 'c',
rl_line_buffer,
rl_end)
!= 0)
{
perror("line: write failed");
_exit(1);
}
last_h1 = h1;
last_h2 = h2;
if (sendcmd(this->rc_command_pipe[RCF_SLAVE], 'w', "", 0)
!= 0)
{
perror("line: write failed");
_exit(1);
}
}
}
if (FD_ISSET(this->rc_command_pipe[RCF_SLAVE], &ready_rfds)) {
char msg[8 + MAXPATHLEN + 1024];
if ((rc = recvstring(this->rc_command_pipe[RCF_SLAVE],
msg,
sizeof(msg) - 1))
< 0)
{
looping = false;
} else {
int context, prompt_start = 0;
char type[1024];
msg[rc] = '\0';
if (startswith(msg, "cd:")) {
const char* cwd = &msg[3];
log_perror(chdir(cwd));
} else if (sscanf(msg, "i:%d:%n", &rl_point, &prompt_start)
== 1)
{
const char* initial = &msg[prompt_start];
rl_extend_line_buffer(strlen(initial) + 1);
strcpy(rl_line_buffer, initial);
rl_end = strlen(initial);
rewrite_line_start
= std::string(rl_line_buffer, rl_point);
rl_redisplay();
if (sendcmd(this->rc_command_pipe[RCF_SLAVE],
'c',
rl_line_buffer,
rl_end)
!= 0)
{
perror("line: write failed");
_exit(1);
}
} else if (sscanf(msg, "f:%d:%n", &context, &prompt_start)
== 1
&& prompt_start != 0
&& (current_context
= this->rc_contexts.find(context))
!= this->rc_contexts.end())
{
got_abort = 0;
current_context->second->load();
rl_callback_handler_install(&msg[prompt_start],
line_ready_tramp);
last_match_str_valid = false;
if (sendcmd(this->rc_command_pipe[RCF_SLAVE],
'l',
rl_line_buffer,
rl_end)
!= 0)
{
perror("line: write failed");
_exit(1);
}
if (sendcmd(
this->rc_command_pipe[RCF_SLAVE], 'w', "", 0)
!= 0)
{
perror("line: write failed");
_exit(1);
}
} else if (strcmp(msg, "a") == 0) {
char reply[4];
rl_done = 1;
got_timeout = 0;
got_line = 1;
rl_callback_handler_remove();
snprintf(reply, sizeof(reply), "a");
if (sendstring(this->rc_command_pipe[RCF_SLAVE],
reply,
strlen(reply))
== -1)
{
perror("abort: write failed");
_exit(1);
}
} else if (sscanf(msg,
"apre:%d:%1023[^\x1d]\x1d%n",
&context,
type,
&prompt_start)
== 2)
{
require(this->rc_contexts[context] != nullptr);
this->rc_contexts[context]
->rc_prefixes[std::string(type)]
= std::string(&msg[prompt_start]);
} else if (sscanf(msg,
"ap:%d:%31[^:]:%n",
&context,
type,
&prompt_start)
== 2)
{
require(this->rc_contexts[context] != nullptr);
this->rc_contexts[context]->add_possibility(
std::string(type), std::string(&msg[prompt_start]));
if (rl_last_func == rl_complete
|| rl_last_func == rl_menu_complete)
{
rl_last_func = NULL;
}
} else if (sscanf(msg,
"rp:%d:%31[^:]:%n",
&context,
type,
&prompt_start)
== 2)
{
require(this->rc_contexts[context] != nullptr);
this->rc_contexts[context]->rem_possibility(
std::string(type), std::string(&msg[prompt_start]));
} else if (sscanf(msg, "cpre:%d", &context) == 1) {
this->rc_contexts[context]->rc_prefixes.clear();
} else if (sscanf(msg, "cp:%d:%s", &context, type)) {
this->rc_contexts[context]->clear_possibilities(type);
} else {
log_error("unhandled message: %s", msg);
}
}
}
}
if (got_timeout) {
got_timeout = 0;
if (sendcmd(this->rc_command_pipe[RCF_SLAVE],
't',
rl_line_buffer,
rl_end)
== -1)
{
_exit(1);
}
}
if (got_line) {
struct itimerval itv;
got_line = 0;
itv.it_value.tv_sec = 0;
itv.it_value.tv_usec = 0;
itv.it_interval.tv_sec = 0;
itv.it_interval.tv_usec = 0;
if (setitimer(ITIMER_REAL, &itv, nullptr) < 0) {
log_error("setitimer: %s", strerror(errno));
}
if (current_context != this->rc_contexts.end()) {
current_context->second->save();
current_context = this->rc_contexts.end();
}
}
if (got_winch) {
struct winsize new_ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &new_ws) == -1) {
throw error(errno);
}
got_winch = 0;
rl_set_screen_size(new_ws.ws_row, new_ws.ws_col);
}
}
if (this->rc_save_history) {
auto config_dir = lnav::paths::dotlnav();
for (auto& pair : this->rc_contexts) {
pair.second->load();
auto hpath
= (config_dir / pair.second->get_name()).string() + ".history";
write_history(hpath.c_str());
pair.second->save();
}
}
_exit(0);
}
void
readline_curses::line_ready(const char* line)
{
auto_mem<char> expanded;
char msg[1024] = {0};
int rc;
const char* cmd_ch = alt_done ? "D" : "d";
alt_done = false;
if (got_abort || line == nullptr) {
snprintf(msg, sizeof(msg), "a");
if (sendstring(this->rc_command_pipe[RCF_SLAVE], msg, strlen(msg))
== -1)
{
perror("abort: write failed");
_exit(1);
}
return;
}
if (rl_line_buffer[0] == '^') {
rc = -1;
} else {
rc = history_expand(rl_line_buffer, expanded.out());
}
switch (rc) {
#if 0
/* TODO: fix clash between history and pcre metacharacters */
case -1:
/* XXX */
snprintf(msg, sizeof(msg),
"e:unable to expand history -- %s",
expanded.in());
break;
#endif
case -1:
snprintf(msg, sizeof(msg), "%s:%s", cmd_ch, line);
break;
case 0:
case 1:
case 2: /* XXX */
snprintf(msg, sizeof(msg), "%s:%s", cmd_ch, expanded.in());
break;
}
if (sendstring(this->rc_command_pipe[RCF_SLAVE], msg, strlen(msg)) == -1) {
perror("line_ready: write failed");
_exit(1);
}
{
HIST_ENTRY* entry;
if (line[0] != '\0'
&& (history_length == 0
|| (entry = history_get(history_base + history_length - 1))
== nullptr
|| strcmp(entry->line, line) != 0))
{
add_history(line);
}
}
}
void
readline_curses::check_poll_set(const std::vector<struct pollfd>& pollfds)
{
int rc;
if (pollfd_ready(pollfds, this->rc_pty[RCF_MASTER])) {
char buffer[128];
rc = read(this->rc_pty[RCF_MASTER], buffer, sizeof(buffer));
if (rc > 0) {
int old_x = this->vc_x;
this->map_output(buffer, rc);
if (this->vc_x != old_x) {
this->rc_change(this);
}
}
}
if (pollfd_ready(pollfds, this->rc_command_pipe[RCF_MASTER])) {
char msg[1024 + 1];
rc = recvstring(
this->rc_command_pipe[RCF_MASTER], msg, sizeof(msg) - 1);
if (rc >= 0) {
msg[rc] = '\0';
if (this->rc_matches_remaining > 0) {
this->rc_matches.emplace_back(msg);
this->rc_matches_remaining -= 1;
if (this->rc_matches_remaining == 0) {
this->rc_display_match(this);
}
} else if (msg[0] == 'm') {
if (sscanf(msg,
"m:%d:%d:%d",
&this->rc_match_start,
&this->rc_matches_remaining,
&this->rc_max_match_length)
!= 3)
{
require(0);
}
this->rc_matches.clear();
if (this->rc_matches_remaining == 0) {
this->rc_display_match(this);
}
this->rc_match_index = 0;
} else if (msg[0] == '\t') {
char path[2048];
if (sscanf(msg, "\t:%s", path) != 1) {
require(0);
}
this->rc_remote_complete_path = path;
this->rc_completion_request(this);
} else if (msg[0] == 'n') {
if (sscanf(msg, "n:%d", &this->rc_match_index) != 1) {
require(0);
}
this->rc_display_next(this);
} else {
switch (msg[0]) {
case 't':
case 'd':
case 'D':
this->rc_value = std::string(&msg[2]);
break;
}
switch (msg[0]) {
case 'a':
curs_set(0);
this->vc_line.clear();
this->rc_active_context = -1;
this->rc_matches.clear();
this->rc_abort(this);
this->rc_display_match(this);
this->rc_blur(this);
break;
case 't':
this->rc_timeout(this);
break;
case 'd':
case 'D':
curs_set(0);
this->rc_active_context = -1;
this->rc_matches.clear();
if (msg[0] == 'D' || this->rc_is_alt_focus) {
this->rc_alt_perform(this);
} else {
this->rc_perform(this);
}
this->rc_display_match(this);
this->rc_blur(this);
break;
case 'l':
this->rc_line_buffer = &msg[2];
if (this->rc_active_context != -1) {
this->rc_change(this);
}
this->rc_matches.clear();
if (this->rc_active_context != -1) {
this->rc_display_match(this);
}
break;
case 'c':
this->rc_line_buffer = &msg[2];
this->rc_change(this);
this->rc_display_match(this);
break;
case 'w':
this->rc_ready_for_input = true;
break;
}
}
}
}
}
void
readline_curses::handle_key(int ch)
{
const char* bch;
int len;
bch = this->map_input(ch, len);
if (write(this->rc_pty[RCF_MASTER], bch, len) == -1) {
perror("handle_key: write failed");
}
}
void
readline_curses::focus(int context,
const std::string& prompt,
const std::string& initial)
{
char cwd[MAXPATHLEN + 1024];
char buffer[8 + sizeof(cwd)];
curs_set(1);
this->rc_active_context = context;
getcwd(cwd, sizeof(cwd));
snprintf(buffer, sizeof(buffer), "cd:%s", cwd);
if (sendstring(
this->rc_command_pipe[RCF_MASTER], buffer, strlen(buffer) + 1)
== -1)
{
perror("focus: write failed");
}
snprintf(buffer, sizeof(buffer), "f:%d:%s", context, prompt.c_str());
if (sendstring(
this->rc_command_pipe[RCF_MASTER], buffer, strlen(buffer) + 1)
== -1)
{
perror("focus: write failed");
}
wmove(this->vc_window, this->get_actual_y(), this->vc_left);
wclrtoeol(this->vc_window);
if (!initial.empty()) {
this->rewrite_line(initial.size(), initial);
}
this->rc_is_alt_focus = false;
this->rc_focus(this);
}
void
readline_curses::rewrite_line(int pos, const std::string& value)
{
char buffer[1024];
snprintf(buffer, sizeof(buffer), "i:%d:%s", pos, value.c_str());
if (sendstring(
this->rc_command_pipe[RCF_MASTER], buffer, strlen(buffer) + 1)
== -1)
{
perror("rewrite_line: write failed");
}
}
void
readline_curses::abort()
{
char buffer[1024];
this->vc_x = 0;
snprintf(buffer, sizeof(buffer), "a");
if (sendstring(this->rc_command_pipe[RCF_MASTER], buffer, strlen(buffer))
== -1)
{
perror("abort: write failed");
}
}
void
readline_curses::add_prefix(int context,
const std::vector<std::string>& prefix,
const std::string& value)
{
char buffer[1024];
auto prefix_wire = fmt::format(FMT_STRING("{}"), fmt::join(prefix, "\x1f"));
snprintf(buffer,
sizeof(buffer),
"apre:%d:%s\x1d%s",
context,
prefix_wire.c_str(),
value.c_str());
if (sendstring(
this->rc_command_pipe[RCF_MASTER], buffer, strlen(buffer) + 1)
== -1)
{
perror("add_prefix: write failed");
}
}
void
readline_curses::clear_prefixes(int context)
{
char buffer[1024];
snprintf(buffer, sizeof(buffer), "cpre:%d", context);
if (sendstring(
this->rc_command_pipe[RCF_MASTER], buffer, strlen(buffer) + 1)
== -1)
{
perror("add_possibility: write failed");
}
}
void
readline_curses::add_possibility(int context,
const std::string& type,
const std::string& value)
{
char buffer[1024];
if (value.empty()) {
return;
}
snprintf(buffer,
sizeof(buffer),
"ap:%d:%s:%s",
context,
type.c_str(),
value.c_str());
if (sendstring(
this->rc_command_pipe[RCF_MASTER], buffer, strlen(buffer) + 1)
== -1)
{
perror("add_possibility: write failed");
}
}
void
readline_curses::rem_possibility(int context,
const std::string& type,
const std::string& value)
{
char buffer[1024];
snprintf(buffer,
sizeof(buffer),
"rp:%d:%s:%s",
context,
type.c_str(),
value.c_str());
if (sendstring(
this->rc_command_pipe[RCF_MASTER], buffer, strlen(buffer) + 1)
== -1)
{
perror("rem_possiblity: write failed");
}
}
void
readline_curses::clear_possibilities(int context, std::string type)
{
char buffer[1024];
snprintf(buffer, sizeof(buffer), "cp:%d:%s", context, type.c_str());
if (sendstring(
this->rc_command_pipe[RCF_MASTER], buffer, strlen(buffer) + 1)
== -1)
{
perror("clear_possiblity: write failed");
}
}
void
readline_curses::do_update()
{
if (!this->vc_visible || this->vc_window == nullptr) {
return;
}
auto actual_width = this->get_actual_width();
if (this->rc_active_context == -1) {
int alt_start = -1;
struct line_range lr(0, 0);
attr_line_t alt_al;
auto& vc = view_colors::singleton();
wmove(this->vc_window, this->get_actual_y(), this->vc_left);
auto attrs = vc.attrs_for_role(role_t::VCR_TEXT);
wattr_set(this->vc_window,
attrs.ta_attrs,
vc.ensure_color_pair(attrs.ta_fg_color, attrs.ta_bg_color),
nullptr);
whline(this->vc_window, ' ', actual_width);
if (time(nullptr) > this->rc_value_expiration) {
this->rc_value.clear();
}
if (!this->rc_alt_value.empty()) {
alt_al.get_string() = this->rc_alt_value;
scrub_ansi_string(alt_al.get_string(), &alt_al.get_attrs());
alt_start = getmaxx(this->vc_window) - alt_al.get_string().size();
}
if (alt_start >= (int) (this->rc_value.length() + 5)) {
lr.lr_end = alt_al.get_string().length();
view_curses::mvwattrline(
this->vc_window, this->get_actual_y(), alt_start, alt_al, lr);
}
lr.lr_end = this->rc_value.length();
view_curses::mvwattrline(this->vc_window,
this->get_actual_y(),
this->vc_left,
this->rc_value,
lr);
this->set_x(0);
}
if (this->rc_active_context != -1) {
readline_context* rc = this->rc_contexts[this->rc_active_context];
readline_highlighter_t hl = rc->get_highlighter();
attr_line_t al = this->vc_line;
if (hl != nullptr) {
hl(al, this->vc_left + this->vc_x);
}
view_curses::mvwattrline(this->vc_window,
this->get_actual_y(),
this->vc_left,
al,
line_range{0, (int) actual_width});
wmove(
this->vc_window, this->get_actual_y(), this->vc_left + this->vc_x);
}
}
std::string
readline_curses::get_match_string() const
{
auto len = std::min((size_t) this->vc_x, this->rc_line_buffer.size())
- this->rc_match_start;
auto* context = this->get_active_context();
if (context->get_append_character() != 0) {
if (this->rc_line_buffer.length() > (this->rc_match_start + len - 1)
&& this->rc_line_buffer[this->rc_match_start + len - 1]
== context->get_append_character())
{
len -= 1;
} else if (this->rc_line_buffer.length()
> (this->rc_match_start + len - 2)
&& this->rc_line_buffer[this->rc_match_start + len - 2]
== context->get_append_character())
{
len -= 2;
}
}
return this->rc_line_buffer.substr(this->rc_match_start, len);
}
void
readline_curses::set_value(const std::string& value)
{
this->set_attr_value(attr_line_t::from_ansi_str(value.c_str()));
}
void
readline_curses::set_attr_value(const attr_line_t& value)
{
this->rc_value = value;
if (this->rc_value.length() > 1024) {
this->rc_value = this->rc_value.subline(0, 1024);
}
this->rc_value_expiration = time(nullptr) + VALUE_EXPIRATION;
this->set_needs_update();
}
void
readline_curses::update_poll_set(std::vector<struct pollfd>& pollfds)
{
if (this->rc_pty[RCF_MASTER] != -1) {
pollfds.push_back((struct pollfd){this->rc_pty[RCF_MASTER], POLLIN, 0});
}
if (this->rc_command_pipe[RCF_MASTER] != -1) {
pollfds.push_back(
(struct pollfd){this->rc_command_pipe[RCF_MASTER], POLLIN, 0});
}
}
void
readline_curses::window_change()
{
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1) {
throw error(errno);
}
if (this->vc_width > 0) {
ws.ws_col = this->vc_width;
} else if (this->vc_width < 0) {
ws.ws_col -= this->vc_left;
ws.ws_col += this->vc_width;
}
if (ioctl(this->rc_pty[RCF_MASTER], TIOCSWINSZ, &ws) == -1) {
throw error(errno);
}
kill(this->rc_child, SIGWINCH);
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Patricia Aas (psmaas)
*/
#ifndef __FILEHANDLER_MANAGER_H__
#define __FILEHANDLER_MANAGER_H__
#include "modules/util/adt/opvector.h"
#include "modules/util/OpTypedObject.h"
#include "modules/util/opfile/opfile.h"
#include "platforms/viewix/src/nodes/FileHandlerNode.h"
#include "platforms/viewix/src/nodes/GlobNode.h"
#include "platforms/viewix/src/FileHandlerStore.h"
#include "platforms/viewix/src/input_files/InputFileManager.h"
#include "platforms/viewix/src/HandlerElement.h"
// Switches :
#define CHECK_DESKTOP_FILE_SECURITY 1
#define CHECK_SHELL_SCRIPT_SECURITY 1
#define CHECK_EXECUTABLE_FLAG_ITSELF 1
#define LINUX_FREEDESKTOP_INTEGRATION
class ApplicationNode;
class MimeTypeNode;
class GlobNode;
class StringHash;
/**
*
* Pixels :
*
* 1) Note that max pixel size supported (both for height and width)
* is 128 and min pixel size is 16.
* 2) Note also that the normal pixel sizes supported on linux are:
*
* 16x16
* 22x22
* 32x32
* 48x48
* 64x64
* 128x128
*
**/
class FileHandlerManager
{
friend class FileHandlerNode;
friend class FileHandlerStore;
friend class InputFileManager;
friend class AliasesFile;
friend class SubclassesFile;
friend class DefaultListFile;
friend class GlobsFile;
friend class MailcapFile;
friend class MimeInfoCacheFile;
friend class ProfilercFile;
friend class GnomeVFSFile;
public:
/**
Get method for singleton class FileHandlerManager
@return pointer to the instance of class FileHandlerManager
*/
static FileHandlerManager* GetManager();
/**
Scans file system for applicatons that can handle filetypes. This
function can block for some time (seconds) anf should not be used
until necessary. Opera will call this function automatically if there
has been no mouse or keyboard input for some time.
*/
void DelayedInit();
/**
Gets a file handler for the mime-type of the file (if any)
Current priority:
1. User specified handler (if no contenttype is supplied)*
2. System default handler
3. First in list of handlers for this mime-type (should be considered random
since implementation could change here)
@param filename - name of file (eg. document.pdf)
@param content_type - reference to a (possibly empty) string with the known content type
@param handler - reference to string where handler (if any) will be placed
@return OpStatus::OK or OpStatus::ERR_NO_MEMORY if OOM
* If content type is supplied the client should use the viewers to find handler
and GetFileHandler should only present system defaults.
*/
OP_STATUS GetFileHandler( const OpString& filename,
const OpString& content_type,
OpString &handler,
OpString &handler_name);
/**
Gets a file handler for the protocol of the uri (if any)
Current priority:
1. System default handler
2. First in list of handlers for this protocol (should be considered random
since implementation could change here)
@param uri_string - the uri one wants a handler for (possibly empty)
@param protocol - reference to a (possibly empty) string with the known protocol
@param handler - reference to string where handler (if any) will be placed
@return OpStatus::OK or OpStatus::ERR_NO_MEMORY if OOM
*/
OP_STATUS GetProtocolHandler( const OpString &uri_string,
const OpString& protocol,
OpString &handler);
/**
Gets all file handlers for the mime type of the file. The file handlers specified
in the opera_default_handler and default_handler are not repeated in the handlers
vector.
@param filename - name of file (eg. document.pdf)
@param content_type - reference to a string with the content type
@param handlers - reference to vector where handlers (if any) will be placed
@param default_handler - reference to string where default handler (if any) will be placed
@param opera_default_handler - reference to string where opera default handler (if any) will be placed
@return OpStatus::OK or OpStatus::ERR_NO_MEMORY if OOM
*/
OP_STATUS GetFileHandlers( const OpString& filename,
const OpString &content_type,
OpVector<OpString>& handlers,
OpVector<OpString>& handler_names,
OpVector<OpBitmap>& handler_icons,
URLType type,
UINT32 icon_size = 16);
/**
Attempts to find the desktop file name of handler for file.
@param filename - name of file (eg. document.pdf)
@param content_type - contenttype of file
@param handler - handler (eg. acroread)
@return name of desktop file if found, else 0
*/
const uni_char * GetDesktopFilename( const OpStringC & filename,
const OpStringC & content_type,
const OpStringC & handler);
/**
Attempts to guess the mimetype based on the filename
@param filename - filename for which to guess mimetype
@param content_type - string inwhich to place mimetype
@return will return an ERROR if setting the contenttype resulted in an error
*/
OP_STATUS GuessMimeType( const OpStringC & filename,
OpString & content_type);
/**
Attempts to aquire the full path of the mime-type icon for
the mimetype of the file.
@param filename - name of file (eg. document.pdf)
@param icon_size - preferred height/width in pixels
@return full path to icon if found, else 0
*/
const uni_char * GetFileTypeIconPath( const OpStringC & filename,
const OpStringC & content_type,
UINT32 icon_size = 16);
/**
@param filename - name of file (eg. document.pdf)
@param content_type - contenttype of file
@param icon_size - preferred height/width in pixels
@return pointer to OpBitmap containing the icon if an icon was found, else 0
*/
OpBitmap* GetFileTypeIcon( const OpStringC& filename,
const OpStringC& content_type,
UINT32 icon_size = 16);
/**
@param filename - name of file (eg. document.pdf)
@param content_type - contenttype of file
@return textual description of mimetype of file (eg. "PDF document")
*/
const uni_char * GetFileTypeName( const OpStringC& filename,
const OpStringC& content_type);
/**
* Get info about the content type of a file - name of contenttype and icon for it.
*
* @param filename - name of file (eg. document.pdf)
* @param content_type - contenttype of file
* @param content_type_name - an OpString where the textual description of mimetype of file should be placed (eg. "PDF document")
* @param content_type_bitmap - reference to an OpBitmap pointer where the icon should be placed
* @param content_type_bitmap_size - the required size of the icon
* @return OpStatus::OK if filetype info was found
*/
OP_STATUS GetFileTypeInfo( const OpStringC& filename,
const OpStringC& content_type,
OpString & content_type_name,
OpBitmap *& content_type_bitmap,
UINT32 content_type_bitmap_size = 16);
/**
@param filename - name of file (eg. document.pdf)
@return textual description of handler for the file (eg. "Acrobat Reader")
*/
const uni_char * GetFileHandlerName( const OpStringC& handler,
const OpStringC& filename,
const OpStringC& content_type);
/**
Attempts to aquire the full path of the file handler icon for
the file handler corresponding to the desktop file.
@param handler - name of desktop file (eg. acroread.desktop)
@param icon_size - preferred height/width in pixels
@return full path to icon if found, else 0
*/
const uni_char * GetApplicationIcon( const OpStringC & handler,
UINT32 icon_size = 16);
/**
@param handler - handler command
@param filename - name of file (eg. document.pdf)
@param content_type - contenttype of file
@param icon_size - preferred height/width in pixels
@return pointer to OpBitmap containing the icon if an icon was found, else 0
*/
OpBitmap* GetApplicationIcon( const OpStringC& handler,
const OpStringC& filename,
const OpStringC& content_type,
UINT32 icon_size = 16);
/**
@param filename
@param handler
@return
*/
BOOL ValidateHandler( const OpStringC & filename,
const OpStringC & handler );
/**
Open a file browser to the folder that the file is in and select the file,
however if the file_path is to a folder then whether to open the parent folder
or the folder itself will depend on treat_folders_as_files. If TRUE this indicates
that the parent folder should be opened and the subfolder selected, otherwise the
folder itself should be opened and nothing selected.
TODO: Selecting the file or folder is not implemeted
@param file_path - full path to the file to be opened in a filebrowser
@param treat_folders_as_files - if TRUE and file_path is a path to a directory,
the parent directory is opened, with the highlighting the folder.
if FALSE, the path to the directory specified is opened.
@return OpStatus::OK if successful
*/
OP_STATUS OpenFileFolder(const OpStringC & file_path, BOOL treat_folders_as_files = TRUE);
/**
@param filename
@param handler
@param validate
@return
*/
BOOL OpenFileInApplication( const OpStringC & filename,
const OpStringC & handler,
BOOL validate,
BOOL convert_to_locale_encoding = TRUE );
/**
@param filename
@param parameters
@param handler
@param validate
@return
*/
BOOL OpenFileInApplication( const OpStringC & filename,
const OpStringC & parameters,
const OpStringC & handler,
BOOL validate );
/**
@param protocol
@param application
@param parameters
@param run_in_terminal
@return
*/
BOOL ExecuteApplication( const OpStringC & protocol,
const OpStringC & application,
const OpStringC & parameters,
BOOL run_in_terminal = FALSE);
/**
@param filename
@return
*/
BOOL CheckSecurityProblem( const OpStringC & filename );
/**
@param file_handler
@param directory_handler
@param list
*/
void WriteHandlersL( HandlerElement& file_handler,
HandlerElement& directory_handler,
OpVector<HandlerElement>& list);
//--------------------------------------------------------------
// Inline public methods:
//--------------------------------------------------------------
/**
Sets m_validation_enabled to the value of the parameter
@param enable
*/
void EnableValidation( BOOL enable ) { m_validation_enabled = enable; }
/**
Get the default file handler for all files
@return reference to default file handler element
*/
HandlerElement& GetDefaultFileHandler() { return m_default_file_handler; }
/**
Get the default directory handler for all files
@return reference to default directory handler element
*/
HandlerElement& GetDefaultDirectoryHandler() { return m_default_directory_handler; }
/**
@return
*/
const OpVector<HandlerElement>& GetEntries() const { return m_list; }
//--------------------------------------------------------------
// Selftest public methods:
//--------------------------------------------------------------
int GetNumberOfMimeTypes() { return m_store.GetNumberOfMimeTypes(); }
void EmptyStore() { m_store.EmptyStore(); }
static void DeleteManager();
/* _________________________ MIME ___________________________ */
private:
/**
Gets the user specified file handler for the mime-type of the file (if any)
@param filename - name of file (eg. document.pdf)
@param content_type - reference to a string with the content type
@param handler - reference to string where opera default handler (if any) will be placed
@return OpStatus::OK or OpStatus::ERR_NO_MEMORY if OOM
*/
OP_STATUS GetOperaDefaultFileHandler( const OpString& filename,
const OpString &content_type,
OpString &handler,
OpString &handler_name);
/**
Gets the system specified file handler for the mime-type of the file (if any)
@param filename - name of file (eg. document.pdf)
@param content_type - reference to a string with the content type
@param handler - reference to string where default handler (if any) will be placed
@return OpStatus::OK or OpStatus::ERR_NO_MEMORY if OOM
*/
OP_STATUS GetDefaultFileHandler( const OpString& filename,
const OpString &content_type,
OpString &handler,
OpString &handler_name,
OpBitmap ** handler_bitmap);
const uni_char * GetMimeType( const OpStringC & filename,
const OpStringC & content_type,
BOOL strip_path = FALSE);
//BACKEND:
ApplicationNode * GetDefaultFileHandler( const OpStringC& content_type );
OP_STATUS GetAllHandlers( const OpStringC & content_type,
OpVector<ApplicationNode>& handlers);
OP_STATUS GetDefaultApplication(const OpStringC& filename,
OpString& application);
//Interface :
// InputManager
void LoadNode( FileHandlerNode * node )
{ m_input_manager.LoadNode(node); }
OP_STATUS LoadIcon( FileHandlerNode* node,
UINT32 icon_size)
{ return m_input_manager.LoadIcon(node, icon_size); }
OP_STATUS MakeIconPath( FileHandlerNode * node,
OpString & icon_path,
UINT32 icon_size = 16)
{ return m_input_manager.MakeIconPath(node, icon_path, icon_size); }
OP_STATUS FindDesktopFile( const OpStringC & filename,
OpVector<OpString>& files)
{ return m_input_manager.FindDesktopFile(filename, files); }
// Store :
MimeTypeNode* GetMimeTypeNode( const OpStringC & mime_type ) { return m_store.GetMimeTypeNode(mime_type); }
MimeTypeNode* MakeMimeTypeNode( const OpStringC & mime_type ) { return m_store.MakeMimeTypeNode(mime_type); }
OP_STATUS LinkMimeTypeNode( const OpStringC & mime_type,
MimeTypeNode* node,
BOOL subclass_type = FALSE)
{ return m_store.LinkMimeTypeNode(mime_type, node, subclass_type); }
// Will delete node_1 since node_1 will be merged into node_2 (if both are non null and not equal)
OP_STATUS MergeMimeNodes( MimeTypeNode* node_1,
MimeTypeNode* node_2)
{ return m_store.MergeMimeNodes(node_1, node_2); }
ApplicationNode * InsertIntoApplicationList( MimeTypeNode* node,
const OpStringC & desktop_file,
const OpStringC & path,
const OpStringC & command,
BOOL default_app = FALSE)
{ return m_store.InsertIntoApplicationList(node, desktop_file, path, command, default_app); }
ApplicationNode * InsertIntoApplicationList( MimeTypeNode* node,
ApplicationNode * app,
BOOL default_app)
{ return m_store.InsertIntoApplicationList(node, app, default_app); }
ApplicationNode * MakeApplicationNode( const OpStringC & desktop_file_name,
const OpStringC & path,
const OpStringC & command,
const OpStringC & icon)
{ return m_store.MakeApplicationNode(desktop_file_name, path, command, icon); }
GlobNode * MakeGlobNode( const OpStringC & glob,
const OpStringC & mime_type,
GlobType type)
{ return m_store.MakeGlobNode(glob, mime_type, type); }
//MEMBER VARS:
BOOL m_initialized;
private:
FileHandlerManager();
virtual ~FileHandlerManager();
void LoadL();
private:
OpAutoVector<HandlerElement> m_list;
HandlerElement m_default_file_handler;
HandlerElement m_default_directory_handler;
BOOL m_validation_enabled;
friend class OpAutoPtr<FileHandlerManager>;
static OpAutoPtr<FileHandlerManager> m_manager;
FileHandlerStore m_store;
InputFileManager m_input_manager;
};
#endif
|
/*
* Copyright (c) 2018-2021 Morwenn
* SPDX-License-Identifier: MIT
*/
#ifndef CPPSORT_DETAIL_NTH_ELEMENT_H_
#define CPPSORT_DETAIL_NTH_ELEMENT_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <iterator>
#include <utility>
#include "adaptive_quickselect.h"
#include "introselect.h"
#include "iterator_traits.h"
namespace cppsort
{
namespace detail
{
////////////////////////////////////////////////////////////
// nth_element for forward iterators with introselect
template<typename ForwardIterator, typename Compare, typename Projection>
auto nth_element(std::forward_iterator_tag,
ForwardIterator first, ForwardIterator last,
difference_type_t<ForwardIterator> nth_pos,
difference_type_t<ForwardIterator> size,
Compare compare, Projection projection)
-> ForwardIterator
{
return introselect(first, last, nth_pos, size, detail::log2(size),
std::move(compare), std::move(projection));
}
////////////////////////////////////////////////////////////
// nth_element for random-access iterators with Andrei
// Alexandrescu's adaptive quickselect
template<typename RandomAccessIterator, typename Compare, typename Projection>
auto nth_element(std::random_access_iterator_tag,
RandomAccessIterator first, RandomAccessIterator last,
difference_type_t<RandomAccessIterator> nth_pos,
difference_type_t<RandomAccessIterator>, // unused
Compare compare, Projection projection)
-> RandomAccessIterator
{
return median_of_ninthers_select(first, first + nth_pos, last,
std::move(compare), std::move(projection));
}
////////////////////////////////////////////////////////////
// Generic nth_element overload, slightly modified compared
// to the standard library one to avoid recomputing sizes
// over and over again, which might be too expensive for
// forward and bidirectional iterators - also returns the
// nth iterator
template<typename ForwardIterator, typename Compare, typename Projection>
auto nth_element(ForwardIterator first, ForwardIterator last,
difference_type_t<ForwardIterator> nth_pos,
difference_type_t<ForwardIterator> size,
Compare compare, Projection projection)
-> ForwardIterator
{
using category = iterator_category_t<ForwardIterator>;
return detail::nth_element(category{}, first, last, nth_pos, size,
std::move(compare), std::move(projection));
}
}}
#endif // CPPSORT_DETAIL_NTH_ELEMENT_H_
|
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
bool isprime(int n) {
if(n <= 1) return false;
int sqr = int(sqrt(n * 1.0));
for(int i = 2; i <= sqr; i++) {
if(n % i == 0)
return false;
}
return true;
}
int rev(int n, int d){
vector<int> x;
int out = 0;
while(n > 0){
x.push_back(n % d);
n = n / d;
}
for(int i = 0; i < x.size(); i++)
out = out * d + x[i];
return out;
}
int main(){
int n, d, re_n;
cin >> n;
while(n >= 0){
cin >> d;
re_n = rev(n, d);
//cout<<re_n<<endl;
if(isprime(n) && isprime(re_n))
cout << "Yes" << endl;
else
cout << "No" << endl;
cin >> n;
}
return 0;
}
|
// OpenVDB_Softimage
// VDB_Node_Write.h
// ICE node to write grids to disk
#ifndef VDB_NODE_WRITE_H
#define VDB_NODE_WRITE_H
#include <xsi_pluginregistrar.h>
#include <xsi_status.h>
#include <xsi_icenodecontext.h>
#include <openvdb/openvdb.h>
class VDB_Node_Write
{
public:
VDB_Node_Write();
~VDB_Node_Write();
XSI::CStatus Evaluate(XSI::ICENodeContext& ctxt);
static XSI::CStatus Register(XSI::PluginRegistrar& reg);
};
#endif
|
//Declaración de constantes
const int boton = 2; //Da el nombre “boton” al pin 2
const int led = 12;
bool estadoDeLed = 0;
void setup()
{
//Inicializa la comunicación serial a 9600 bits por segundo
Serial.begin(9600);
pinMode(boton, INPUT_PULLUP); //Configura el pin "boton" como entrada digital
}
void loop()
{
int estadoDeBoton = digitalRead(boton);//Almacena la información de la entrada digital en la variable “estadoDeBoton”
if (estadoDeBoton == 0){//Si el botón es preionado
estadoDeLed = !estadoDeLed;//Tomamos el valor guardado en "estadoDeLed" invertimos dicho valor para volver a guardarlo en la variable "estadoDeLed"
digitalWrite(led , estadoDeLed);//Escribimos el nuevo estado del led al pin respectivo
Serial.println(estadoDeLed);//Envia por el puerto serial la información almacenada en “estadoDeBoton”,
//esta información será visualizada en el monitor serial
delay(300);//Esperamos 300 ms antes de continuar para evitar que una sola pulsación rápida del botón alterne el estado del led más de una vez
}
//Espera 1 milisegundos entre cada lectura
delay(1);
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
using namespace std;
const int pow2[18] = {1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536,131072};
int maxd,n;
set<int> S;
bool dfs(int k,int m) {
//cout << k << " " << m << endl;
if (m == n) return true;
if (m > n) {
if (k == maxd) return false;
for (set<int>::iterator i = S.begin();i != S.end(); i++) {
if (m - *i == n) return true;
}
return false;
}
if (k == maxd || m*pow2[maxd - k] < n) return false;
for (set<int>::iterator i = S.end();i != S.begin(); i--)
for (set<int>::iterator j = S.end();j != S.begin(); j--) {
if (*j > *i) continue;
int sav = *i + *j;
if (S.count(sav)) continue;
S.insert(sav);
if (dfs(k+1,max(sav,m))) return true;
S.erase(sav);
}
return false;
}
int main() {
//while (scanf("%d",&n) != EOF) {
for (n = 1;n <= 1000; n++) {
if (n == 1) {printf("0,");continue;}
if (n == 2) {printf("1,");continue;}
S.clear();
S.insert(1);
for (maxd = 1; ;maxd++)
if (dfs(0,1)) break;
printf("%d,",maxd);
}
return 0;
}
|
#include <Tanker/Opener.hpp>
#include <Tanker/BlockGenerator.hpp>
#include <Tanker/Client.hpp>
#include <Tanker/Crypto/Crypto.hpp>
#include <Tanker/Crypto/Format/Format.hpp>
#include <Tanker/Errors/AssertionError.hpp>
#include <Tanker/Errors/Errc.hpp>
#include <Tanker/Errors/Exception.hpp>
#include <Tanker/Errors/ServerErrc.hpp>
#include <Tanker/Format/Enum.hpp>
#include <Tanker/Format/Format.hpp>
#include <Tanker/GhostDevice.hpp>
#include <Tanker/Identity/Delegation.hpp>
#include <Tanker/Identity/Extract.hpp>
#include <Tanker/Identity/Utils.hpp>
#include <Tanker/Log/Log.hpp>
#include <Tanker/Network/ConnectionFactory.hpp>
#include <Tanker/Serialization/Serialization.hpp>
#include <Tanker/Session.hpp>
#include <Tanker/Status.hpp>
#include <Tanker/Trustchain/Block.hpp>
#include <Tanker/Trustchain/UserId.hpp>
#include <Tanker/Types/Passphrase.hpp>
#include <Tanker/Types/VerificationKey.hpp>
#include <Tanker/Unlock/Create.hpp>
#include <Tanker/Unlock/Verification.hpp>
#include <gsl-lite.hpp>
#include <nlohmann/json.hpp>
#include <tconcurrent/promise.hpp>
#include <Tanker/Tracer/ScopeTimer.hpp>
#include <memory>
#include <utility>
using namespace Tanker::Errors;
TLOG_CATEGORY(Core);
namespace Tanker
{
Opener::Opener(std::string url, Network::SdkInfo info, std::string writablePath)
: _url(std::move(url)),
_info(std::move(info)),
_writablePath(std::move(writablePath))
{
}
Status Opener::status() const
{
return _status;
}
tc::cotask<Status> Opener::open(std::string const& b64Identity)
{
SCOPE_TIMER("opener_open", Proc);
if (_identity.has_value())
{
throw Exception(make_error_code(Errc::PreconditionFailed),
"start() has already been called");
}
_identity = Identity::extract<Identity::SecretPermanentIdentity>(b64Identity);
_userId = _identity->delegation.userId;
if (_identity->trustchainId != _info.trustchainId)
{
throw formatEx(Errc::InvalidArgument,
TFMT("identity's trustchain is {:s}, expected {:s}"),
_identity->trustchainId,
_info.trustchainId);
}
_client =
std::make_unique<Client>(Network::ConnectionFactory::create(_url, _info));
_client->start();
std::string dbPath;
if (_writablePath == ":memory:")
dbPath = _writablePath;
else
dbPath = fmt::format(TFMT("{:s}/tanker-{:S}.db"),
_writablePath,
_identity->delegation.userId);
_db = TC_AWAIT(DataStore::createDatabase(dbPath, _identity->userSecret));
_keyStore = TC_AWAIT(DeviceKeyStore::open(_db.get()));
auto const userStatusResult = TC_AWAIT(_client->userStatus(
_info.trustchainId, _userId, _keyStore->signatureKeyPair().publicKey));
if (userStatusResult.deviceExists)
_status = Status::Ready;
else if (userStatusResult.userExists)
_status = Status::IdentityVerificationNeeded;
else
_status = Status::IdentityRegistrationNeeded;
TC_RETURN(status());
}
tc::cotask<VerificationKey> Opener::fetchVerificationKey(
Unlock::Verification const& verification)
{
TC_RETURN(TC_AWAIT(_client->fetchVerificationKey(_info.trustchainId,
_identity->delegation.userId,
verification,
_identity->userSecret)));
}
tc::cotask<std::vector<Unlock::VerificationMethod>>
Opener::fetchVerificationMethods()
{
TC_RETURN(
TC_AWAIT(_client->fetchVerificationMethods(_info.trustchainId,
_identity->delegation.userId,
_identity->userSecret)));
}
tc::cotask<void> Opener::unlockCurrentDevice(
VerificationKey const& verificationKey)
{
TINFO("unlockCurrentDevice");
FUNC_TIMER(Proc);
try
{
auto const ghostDevice = GhostDevice::create(verificationKey);
auto const encryptedUserKey = TC_AWAIT(_client->getLastUserKey(
_info.trustchainId,
Crypto::makeSignatureKeyPair(ghostDevice.privateSignatureKey)
.publicKey));
auto const block =
Unlock::createValidatedDevice(_info.trustchainId,
_identity->delegation.userId,
ghostDevice,
_keyStore->deviceKeys(),
encryptedUserKey);
TC_AWAIT(_client->pushBlock(Serialization::serialize(block)));
}
catch (Exception const& e)
{
if (e.errorCode() == ServerErrc::DeviceNotFound ||
e.errorCode() == Errc::DecryptionFailed)
throw Exception(make_error_code(Errc::InvalidVerification), e.what());
throw;
}
}
Session::Config Opener::makeConfig()
{
return {std::move(_db),
_info.trustchainId,
_identity->delegation.userId,
_identity->userSecret,
std::move(_keyStore),
std::move(_client)};
}
tc::cotask<Session::Config> Opener::createUser(
Unlock::Verification const& verification)
{
TINFO("createUser");
FUNC_TIMER(Proc);
if (status() != Status::IdentityRegistrationNeeded)
{
throw formatEx(Errc::PreconditionFailed,
TFMT("invalid status {:e}, should be {:e}"),
status(),
Status::IdentityRegistrationNeeded);
}
auto const verificationKey =
boost::variant2::get_if<VerificationKey>(&verification);
auto const ghostDeviceKeys =
verificationKey ? GhostDevice::create(*verificationKey).toDeviceKeys() :
DeviceKeys::create();
auto const ghostDevice = GhostDevice::create(ghostDeviceKeys);
auto const userCreation = Serialization::deserialize<Trustchain::Block>(
BlockGenerator(_info.trustchainId, {}, {})
.addUser(_identity->delegation,
ghostDeviceKeys.signatureKeyPair.publicKey,
ghostDeviceKeys.encryptionKeyPair.publicKey,
Crypto::makeEncryptionKeyPair()));
auto const action =
Serialization::deserialize<Trustchain::Actions::DeviceCreation::v3>(
userCreation.payload);
auto const firstDevice = Unlock::createValidatedDevice(
_info.trustchainId,
_identity->delegation.userId,
ghostDevice,
_keyStore->deviceKeys(),
EncryptedUserKey{Trustchain::DeviceId{userCreation.hash()},
action.sealedPrivateUserEncryptionKey()});
auto const encryptVerificationKey = Crypto::encryptAead(
_identity->userSecret,
gsl::make_span(Unlock::ghostDeviceToVerificationKey(ghostDevice))
.as_span<uint8_t const>());
TC_AWAIT(_client->createUser(*_identity,
userCreation,
firstDevice,
verification,
_identity->userSecret,
encryptVerificationKey));
TC_RETURN(makeConfig());
}
tc::cotask<VerificationKey> Opener::getVerificationKey(
Unlock::Verification const& verification)
{
using boost::variant2::get_if;
using boost::variant2::holds_alternative;
if (auto const verificationKey = get_if<VerificationKey>(&verification))
TC_RETURN(*verificationKey);
else if (holds_alternative<Unlock::EmailVerification>(verification) ||
holds_alternative<Passphrase>(verification) ||
holds_alternative<OidcIdToken>(verification))
TC_RETURN(TC_AWAIT(fetchVerificationKey(verification)));
throw AssertionError("invalid verification, unreachable code");
}
tc::cotask<VerificationKey> Opener::generateVerificationKey() const
{
TC_RETURN(Unlock::generate(_userId,
_keyStore->encryptionKeyPair(),
BlockGenerator(_info.trustchainId, {}, {})));
}
tc::cotask<Session::Config> Opener::createDevice(
Unlock::Verification const& verification)
{
TINFO("createDevice");
FUNC_TIMER(Proc);
if (status() != Status::IdentityVerificationNeeded)
{
throw formatEx(Errc::PreconditionFailed,
TFMT("invalid status {:e}, should be {:e}"),
status(),
Status::IdentityVerificationNeeded);
}
auto const verificationKey = TC_AWAIT(getVerificationKey(verification));
TC_AWAIT(unlockCurrentDevice(verificationKey));
TC_RETURN(makeConfig());
}
tc::cotask<Session::Config> Opener::openDevice()
{
TINFO("openDevice");
if (status() != Status::Ready)
{
throw formatEx(Errc::PreconditionFailed,
TFMT("invalid status {:e}, should be {:e}"),
status(),
Status::Ready);
}
TC_RETURN(makeConfig());
}
}
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i <= (int)(n); i++)
#define showmap(is, js, x) {rep(i, is){rep(j, js){cout << x[i][j] << " ";}cout << endl;}}
#define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;}
#define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;}
typedef long long ll;
typedef pair<int, int> P;
typedef pair<ll, ll> llP;
ll gcd(int x, int y){ return y?gcd(y, x%y):x;}
ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);}
template<class T> inline bool chmax(T& a, T b) {if (a < b) {a = b; return true;} return false;}
template<class T> inline bool chmin(T& a, T b) {if (a > b) {a = b; return true;} return false;}
int main()
{
int n;
cin >> n;
vector<ll> a(n);
rep(i, n){ cin >> a[i]; }
vector<ll> maxlen(n);
vector<ll> lastlen(n);
ll maxtmp = -1e9;
ll sum = 0;
rep(i, n){
sum += a[i];
chmax(maxtmp, sum);
maxlen[i] = maxtmp;
lastlen[i] = sum;
}
//show(maxlen);
//show(lastlen);
ll ans = 0;
ll lsum = 0;
rep(i, n){
chmax(ans, lsum+maxlen[i]);
lsum += lastlen[i];
}
cout << ans << endl;
}
|
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved.
#include "SoundBoarding.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, SoundBoarding, "SoundBoarding" );
|
#pragma once
#include "Grid.hpp"
#include <BWAPI.h>
#include <map>
#include <vector>
#include "BaseManager.h"
class InformationManager
{
InformationManager();
void parseUnitsInfo();
std::map<BWAPI::UnitType, int> m_unitCountMap;
std::map<BWAPI::UnitType, std::vector<int>> m_unitsMap;
std::vector<BaseManager> m_enemyBases;
std::vector<BaseManager> m_bases;
int m_usedSupply;
int m_totalSupply;
int m_mineral;
int m_gas;
bool m_camperWorking;
public:
static InformationManager& Instance()
{
static InformationManager instance;
return instance;
}
const int usedSupply();
const int totalSupply();
const int mineral();
const int gas();
const std::vector<BaseManager> getBases() const;
const std::vector<int> getAllUnitsOfType(BWAPI::UnitType type) const;
const std::vector<BaseManager> getEnemyBases() const;
void addEnemyBase(BWAPI::Position pos);
void onFrame();
void onStart();
void deductResources(BWAPI::UnitType type);
bool hasEnoughResources(BWAPI::UnitType type);
void deductResources(BWAPI::UpgradeType type);
bool hasEnoughResources(BWAPI::UpgradeType type);
void addBase(BaseManager base);
int getCountOfType(BWAPI::UnitType type);
int getUsedSupply();
int getTotalSupply(bool inProgress = false);
int getMinerals(bool inProgress = false);
int getGas(bool inProgress = false);
void setCamperWorking(bool working);
bool isCamperWorking();
};
|
#include <nan.h>
#include "display_device_manager.h"
using v8::Object;
using v8::String;
using Nan::GetFunction;
using Nan::New;
using Nan::Set;
NAN_METHOD(DisplayWakeupRequest) {
int ret = DisplayDeviceManager::getDisplayManager()->SetDisplayState(true);
info.GetReturnValue().Set(ret);
}
NAN_METHOD(DisplaySleepRequest)
{
int ret = DisplayDeviceManager::getDisplayManager()->SetDisplayState(false);
info.GetReturnValue().Set(ret);
}
NAN_METHOD(EnumerateAttachedDisplay) {
int ret = DisplayDeviceManager::getDisplayManager()->EnumerateDisplay();
info.GetReturnValue().Set(ret);
}
void LastInputTime(const Nan::FunctionCallbackInfo<v8::Value>& info) {
std::string str = MillisecondToTime(DisplayDeviceManager::getDisplayManager()->LastInputTime());
info.GetReturnValue().Set(Nan::New(str).ToLocalChecked());
}
|
#ifndef QUEEN_H_INCLUDED
#define QUEEN_H_INCLUDED
#include "BasePiece.h"
#include "Rook.h"
#include "Bishop.h"
class Queen: public virtual BasePiece , public Bishop, public Rook
{
public:
Queen(Color color, Position pos);
~Queen();
bool validateMove(Position moveToPosition, BasePiece* &piece);
};
#endif // QUEEN_H_INCLUDED
|
int Solution::isPalindrome(int A) {
if (A < 0)
return 0;
long long int orignalA = A;
long long int res = 0;
while (A) {
res *= 10;
res += A % 10;
A /= 10;
}
if (res == orignalA)
return 1;
return 0;
}
|
#include <maya/MGlobal.h>
#include <maya/MPxCommand.h>
#include <maya/MArgList.h>
#include <maya/MSyntax.h>
#include <maya/MFn.h>
#include <maya/MFnPlugin.h>
#include <maya/MPoint.h>
#include <maya/MSelectionList.h>
#include <maya/MDagPath.h>
#include <maya/MItSelectionList.h>
#include <maya/MObject.h>
#include <maya/MFnNurbsCurve.h>
#include <maya/MArgDatabase.h>
const char *pluginName = "posts4";
//Syntax string definitions
const char *numberFlag = "-n", *numberLongFlag = "-number";
const char *radiusFlag = "-r", *radiusLongFlag = "-radius";
const char *heightFlag = "-he", *heightLongFlag = "-height";
const char *helpFlag = "-h", *helpLongFlag = "-help";
const char *helpText =
"\nThe posts4 command is used to create a series of posts"
"(c y l i n d e r s) along all the selected curves."
"\n l t is possible to set the number of posts, as well as"
"t h e i r width and h e i g h t ."
"\nFor f u r t h e r d e t a i l s consult the help documentation."
"\nFor quick help use: help posts4";
class Posts4Cmd : public MPxCommand
{
public:
static void * creator()
{
return new Posts4Cmd;
}
virtual MStatus doIt(const MArgList &args);
static MSyntax newSyntax();
};
MStatus Posts4Cmd::doIt(const MArgList & args)
{
int nPosts = 5;
double radius = 0.5;
double height = 5.0;
MArgDatabase argData(syntax(), args);
if (argData.isFlagSet(numberFlag))
{
argData.getFlagArgument(numberFlag, 0, nPosts);
}
if (argData.isFlagSet(radiusFlag))
{
argData.getFlagArgument(radiusFlag, 0, radius);
}
if (argData.isFlagSet(heightFlag))
{
argData.getFlagArgument(heightFlag, 0, height);
}
if (argData.isFlagSet(helpFlag))
{
setResult(helpText);
return MS::kSuccess;
}
MSelectionList selection;
MGlobal::getActiveSelectionList(selection);
MDagPath dagPath;
MFnNurbsCurve curveFn;
double heightRatio = height / radius;
MItSelectionList iter(selection, MFn::kNurbsCurve);
for (; !iter.isDone(); iter.next())
{
iter.getDagPath(dagPath);
curveFn.setObject(dagPath);
double tStart, tEnd;
curveFn.getKnotDomain(tStart, tEnd);
MPoint pt;
int i;
double t;
double tIncr = (tEnd - tStart) / (nPosts - 1);
for (i = 0, t = tStart; i < nPosts; i++, t += tIncr)
{
curveFn.getPointAtParam(t, pt, MSpace::kWorld);
pt.y += 0.5 * height;
MGlobal::executeCommand(MString("cylinder -pivot ") +
pt.x + " " + pt.y + " " + pt.z + " -radius 0.5 -axis 0 1 0 -heightRatio " +
heightRatio);
}
}
return MS::kSuccess;
}
MSyntax Posts4Cmd::newSyntax()
{
MSyntax syntax;
syntax.addFlag(numberFlag, numberLongFlag, MSyntax::kLong);
syntax.addFlag(radiusFlag, radiusLongFlag, MSyntax::kDouble);
syntax.addFlag(heightFlag, heightLongFlag, MSyntax::kDouble);
syntax.addFlag(helpFlag, helpLongFlag, MSyntax::kString);
return syntax;
}
MStatus initializePlugin(MObject obj)
{
MFnPlugin pluginFn(obj, "jason.li", "0.3");
MStatus stat;
stat = pluginFn.registerCommand(pluginName, Posts4Cmd::creator, Posts4Cmd::newSyntax);
if (!stat)
{
stat.perror("registerCommand failed.");
}
return stat;
}
MStatus uninitializePlugin(MObject obj)
{
MFnPlugin pluginFn(obj);
MStatus stat;
stat = pluginFn.deregisterCommand(pluginName);
if (!stat)
{
stat.perror("deregisterCommand failed.");
}
return stat;
}
|
#pragma once
#include <list>
#include <mutex>
#include <algorithm>
#include <iostream>
class Protected_List
{
public:
void add_to_list();
bool list_contains(int value_to_find);
void print();
private:
std::list<int> some_list;
std::mutex some_mutex;
};
void Protected_List::add_to_list()
{
std::lock_guard<std::mutex> guard(some_mutex);
for (int i = 0; i < 100; ++i)
some_list.push_back(i);
}
bool Protected_List::list_contains(int value_to_find)
{
auto p = std::find(some_list.begin(), some_list.end(), value_to_find);
if (p == some_list.end())
return false;
return true;
}
void Protected_List::print()
{
for (auto p:some_list)
{
std::cout << p << " ";
}
std::cout << std::endl;
}
|
#ifndef VARIANT3_H
#define VARIANT3_H
#include <demonstrationclass.h>
class variant3
{
public:
variant3(Ui::MainWindow* _ui,DemonstrationClass *_parent);
void on_task_button_clicked();
private:
};
#endif // VARIANT3_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2012 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Kajetan Switalski
**
*/
#ifndef _SPDY_DATACONSUMER_H_
#define _SPDY_DATACONSUMER_H_
/**
* An interface for all classes that consume SPDY frames data
*/
class SpdyDataConsumer
{
public:
virtual ~SpdyDataConsumer() {}
/**
* Consumes some portion of the data given in the parameter.
* @param data Data to be consumed
* @return TRUE if still hungry or FALSE if already sated
*/
virtual BOOL ConsumeDataL(OpData &data) = 0;
};
class SpdyDevNullConsumer: public SpdyDataConsumer
{
protected:
size_t dataToConsume;
public:
void SetAmountOfDataToConsume(size_t n) { dataToConsume = n; }
virtual BOOL ConsumeDataL(OpData &data);
};
class SpdyCompressionProvider;
class SpdyDecompressingConsumer: public SpdyDevNullConsumer
{
SpdyCompressionProvider *compressionProvider;
public:
void SetCompressionProvider(SpdyCompressionProvider *provider) { compressionProvider = provider; }
virtual BOOL ConsumeDataL(OpData &data);
};
#endif // _SPDY_DATACONSUMER_H_
|
/*
tplane.cpp
Colin Fitt -- cfitt -- C6312039
Course CpSci 1020, Prof. Catherine Hochrine
Major Programming Assignment #3: Due 11:59pm Sunday, April 20th
To be honest I got this completely on accident. I was getting crazy
ppms and it was not working at all, and then one day I returned to it
and it started to work. I'm not gonna mess with it cause you-know
"If it ain't broke don't fix it", but here what I think is happening.
tplane_t creates an instance of a plane_t, uses the parse, and uses
vec_cross to build a rotation matrix that rotates the plane normal
into the z-axis, and the projected xdir into the x-axis. The
tplane_t::select() function:
apply the rot matrix to last_hit to rotate it into the plane
having normal (0, 0, 1) with the projected xdir of the tiling parallel
to the x-axis (creating new vector newloc; z-component = 0).
Add 100000 to newloc.x and newloc.y (avoid doublewide stripe at origin).
Divide newloc.x / dims[0], newloc.y / dims[1], use thesum of these values
to determine if the tile is foreground or background. Then some magic
happened because this was so frustrating 3 days ago.
*/
#include "ray.h"
static pparm_t tplane_parse[] =
{
{"xdir", 3, sizeof(double),"%lf",0},
{"dimensions", 2, sizeof(double), "%lf", 0},
{"altmaterial", 1, sizeof(char), "%s", 0},
};
#define NUM_ATTRS (sizeof(tplane_parse) / sizeof(pparm_t))
tplane_t::tplane_t(FILE *in, model_t *model, int attrmax):plane_t(in,model,2)
{
char altname [NAME_LEN];
cookie = OBJ_COOKIE;
strcpy(obj_type, "tiled_plane"); //Copies over the string plane to obj_type
tplane_parse[0].loc = &xdir; //Sends in the normal to the parser
tplane_parse[1].loc = &dims; //Sends in the point to the parser
tplane_parse[2].loc = &altname;
//This calls the parser which acts like the load attributes function
parser(in, tplane_parse, NUM_ATTRS, attrmax);
//fscanf(in, "%s", altname);
altmat = material_getbyname(model, altname);
vec_project(&normal, &xdir, &projxdir);
vec_unit(&xdir,&xdir);
vec_copy(&projxdir, &rot.row[0]);
vec_copy(&normal, &rot.row[2]);
vec_cross(&rot.row[2], &rot.row[0], &rot.row[1]);
}
void tplane_t::printer(FILE *out)
{
object_t::printer(out);
fprintf(out,"%-12s %5.1lf %5.1lf %5.1lf\n",
"normal",normal.x,normal.y,normal.z);
fprintf(out,"%-12s %5.1lf %5.1lf %5.1lf\n",
"xdir",xdir.x,xdir.y,xdir.z);
fprintf(out,"%-12s %5.1lf %5.1lf\n",
"dimensions", dims[0],dims[1]);
fprintf(out,"%-12s %-5s\n",
"altmaterial", altmat->material_getname());
}
void tplane_t::getambient(drgb_t *value)
{
if(select() == 0)
{
object_t::getambient(value);
}
else
{
altmat->material_getdiffuse(value);
}
}
void tplane_t::getspecular(double *value)
{
if(select() == 0)
{
object_t::getspecular(value);
}
else
{
altmat->material_getspecular(value);
}
}
void tplane_t::getdiffuse(drgb_t *value)
{
if(select() == 0)
{
object_t::getdiffuse(value);
}
else
{
altmat->material_getdiffuse(value);
}
}
int tplane_t::select(void)
{
vec_t newloc = {0.0, 0.0, 1};
vec_xform(&rot, &last_hitpt, &newloc);
newloc.x = (newloc.x + 100000) / dims[0];
newloc.y = (newloc.y + 100000) / dims[1];
if((((int)newloc.x +(int)newloc.y)%2)==0)
return 0;
else
return 1;
}
|
// Created on: 1995-02-01
// Created by: Marie Jose MARTZ
// Copyright (c) 1995-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 _Geom2dToIGES_Geom2dCurve_HeaderFile
#define _Geom2dToIGES_Geom2dCurve_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Geom2dToIGES_Geom2dEntity.hxx>
class IGESData_IGESEntity;
class Geom2d_Curve;
//! This class implements the transfer of the Curve Entity from Geom2d
//! To IGES. These can be :
//! Curve
//! . BoundedCurve
//! * BSplineCurve
//! * BezierCurve
//! * TrimmedCurve
//! . Conic
//! * Circle
//! * Ellipse
//! * Hyperbloa
//! * Line
//! * Parabola
//! . OffsetCurve
class Geom2dToIGES_Geom2dCurve : public Geom2dToIGES_Geom2dEntity
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT Geom2dToIGES_Geom2dCurve();
//! Creates a tool Geom2dCurve ready to run and sets its
//! fields as G2dE's.
Standard_EXPORT Geom2dToIGES_Geom2dCurve(const Geom2dToIGES_Geom2dEntity& G2dE);
//! Transfert an Entity from Geom2d to IGES. If this
//! Entity could not be converted, this member returns a NullEntity.
Standard_EXPORT Handle(IGESData_IGESEntity) Transfer2dCurve (const Handle(Geom2d_Curve)& start, const Standard_Real Udeb, const Standard_Real Ufin);
protected:
private:
};
#endif // _Geom2dToIGES_Geom2dCurve_HeaderFile
|
#include "threadfactory.h"
ThreadFactory::ThreadFactory()
{
}
void ThreadFactory::startThreads()
{
QMap<QObject*, QThread*> *map = IThread::getMap();
}
void ThreadFactory::stopAndDeleteThreads()
{
}
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- */
#ifndef ES_BOOLEAN_BUILTINS_H
#define ES_BOOLEAN_BUILTINS_H
class ES_BooleanBuiltins
{
public:
static BOOL ES_CALLING_CONVENTION constructor_call(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
/**< 'Boolean()' */
static BOOL ES_CALLING_CONVENTION constructor_construct(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
/**< 'new Boolean()' */
static BOOL ES_CALLING_CONVENTION toString(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static BOOL ES_CALLING_CONVENTION valueOf(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value);
static void PopulatePrototype(ES_Context *context, ES_Global_Object *global_object, ES_Object *prototype);
static void PopulatePrototypeClass(ES_Context *context, ES_Class_Singleton *prototype_klass);
enum
{
ES_BooleanBuiltins_constructor = 0,
ES_BooleanBuiltins_toString,
ES_BooleanBuiltins_valueOf,
ES_BooleanBuiltinsCount,
ES_BooleanBuiltins_LAST_PROPERTY = ES_BooleanBuiltins_valueOf
};
};
#endif // ES_BOOLEAN_BUILTINS_H
|
#include "GameObject.h"
#include "UIElement.h"
GameObject::GameObject(int UnitTypeID, GameEngine* Engine, Player* PlayerID) {
engine = Engine;
}
GameObject::GameObject() {
}
void GameObject::setPosition(double x, double y) {
posX = x;
posY = y;
icon.setPosition(x,y);
if (healthBars.size() > 0) {
healthBars[0]->setPosition(x, y - 10);
healthBars[1]->setPosition(x, y - 10);
}
}
void GameObject::setPosX(double x) {
posX = x;
}
void GameObject::setPosY(double y) {
posY = y;
}
void GameObject::onRightClick(int x, int y, sf::Time time) {
}
void GameObject::onLeftClick() {
}
void GameObject::update(sf::Time time) {
}
void GameObject::animate() {
}
void GameObject::move(int x, int y) {
posX = posX + x;
posY = posY + y;
icon.setPosition(posX, posY);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @file
* @author Owner: Karianne Ekern (karie)
*
*/
#ifndef __ST_SYNC_NOTE_ITEMS_H__
#define __ST_SYNC_NOTE_ITEMS_H__
#ifdef SUPPORT_DATA_SYNC
#include "adjunct/quick/sync/SyncNoteItems.h"
/*************************************************************************
**
** ST_SyncNoteItems
**
**
**************************************************************************/
class ST_SyncNoteItems :
public SyncNoteItems
{
public:
ST_SyncNoteItems() :
SyncNoteItems(),
m_received_notification(FALSE),
m_sent_to_server(FALSE),
m_note_listening(FALSE),
m_bookmark_listening(FALSE),
m_sent_add(0),
m_sent_delete(0),
m_sent_modified(0),
m_moved_from(0)
{}
// virtual ~ST_SyncNoteItems();
void EnableNoteListening(BOOL enable)
{
m_note_listening = enable;
SyncNoteItems::EnableNoteListening(enable);
}
BOOL ReceivedNotification() { return m_received_notification; }
void ResetNotification() { m_received_notification = FALSE;}
OP_STATUS ProcessSyncItem(OpSyncItem *item, BOOL& dirty) { return SyncNoteItems::ProcessSyncItem(item, dirty);}
BOOL IsProcessingIncomingItems() { return m_is_receiving_items; }
BOOL ItemsSentToServer() { return m_sent_to_server; }
void ResetSentToServer() { m_sent_to_server = FALSE; }
BOOL IsNoteListening(){ return m_note_listening; }
// Implementing HotlistModelListener interface
void OnHotlistItemAdded(HotlistModelItem* item)
{
m_received_notification = TRUE;
if (!IsProcessingIncomingItems())
{
m_sent_to_server = TRUE;
m_sent_add++;
}
}
void OnHotlistItemChanged(HotlistModelItem* item, BOOL moved_as_child, UINT32 changed_flag = HotlistModel::FLAG_UNKNOWN)
{
m_received_notification = TRUE;
if (!IsProcessingIncomingItems() && !moved_as_child)
{
m_sent_modified++;
m_sent_to_server = TRUE;
}
}
void OnHotlistItemRemoved(HotlistModelItem* item, BOOL removed_as_child)
{
m_received_notification = TRUE;
if (!IsProcessingIncomingItems() && !removed_as_child)
{
m_sent_to_server = TRUE;
m_sent_delete++;
}
}
void OnHotlistItemMovedFrom(HotlistModelItem* item)
{
m_received_notification = TRUE;
if (!IsProcessingIncomingItems())
{
m_sent_to_server = TRUE;
m_moved_from++;
}
}
void ResetSentCounts()
{
m_sent_add = m_sent_delete = m_sent_modified = m_moved_from = 0;
}
INT32 GetAddCount() { return m_sent_add; }
INT32 GetDeleteCount() { return m_sent_delete; }
INT32 GetModifiedCount() { return m_sent_modified; }
INT32 GetMovedFromCount() { return m_moved_from; }
BOOL m_received_notification;
BOOL m_sent_to_server;
BOOL m_note_listening;
BOOL m_bookmark_listening;
INT32 m_sent_add;
INT32 m_sent_delete;
INT32 m_sent_modified;
INT32 m_moved_from;
};
#endif // SUPPORT_DATA_SYNC
#endif // __ST_SYNC_SPEEDDIAL_ENTRIES_H__
|
/*
* @lc app=leetcode.cn id=234 lang=cpp
*
* [234] 回文链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* left;
bool isPalindrome(ListNode* head) {
left = head;
return traverse(head);
}
bool traverse(ListNode* right){
if(right==NULL)return true;
bool res = traverse(right->next); // res是两边比较的结果
res = res && (right->val == left->val);
left = left->next;
return res;
}
};
// @lc code=end
|
#ifndef TreeSetting_h
#define TreeSetting_h
#include <iostream>
#include "TTree.h"
#include "TFile.h"
#include "TBranch.h"
#include "TROOT.h"
#include "TClonesArray.h"
#include "TChain.h"
using namespace std;
const int maxBranchSize = 1000;
// import the tree to the RooDataSet
UInt_t runNb;
UInt_t eventNb, LS;
float zVtx;
Int_t Centrality;
ULong64_t HLTriggers;
Int_t Reco_QQ_size;
Int_t Reco_mu_size;
TClonesArray *Reco_QQ_4mom;
TClonesArray *Reco_mu_4mom;
ULong64_t Reco_QQ_trig[maxBranchSize]; //[Reco_QQ_size]
ULong64_t Reco_mu_trig[maxBranchSize]; //[Reco_QQ_size]
Float_t Reco_QQ_VtxProb[maxBranchSize]; //[Reco_QQ_size]
TBranch *b_runNb; //!
TBranch *b_eventNb; //!
TBranch *b_LS;
TBranch *b_zVtx; //!
TBranch *b_Centrality; //!
TBranch *b_HLTriggers; //!
TBranch *b_Reco_QQ_size; //!
TBranch *b_Reco_QQ_4mom; //!
TBranch *b_Reco_mu_size; //!
TBranch *b_Reco_mu_4mom; //!
TBranch *b_Reco_QQ_trig; //!
TBranch *b_Reco_mu_trig; //!
TBranch *b_Reco_QQ_VtxProb; //!
Bool_t Reco_mu_highPurity[maxBranchSize]; //[Reco_QQ_size]
TBranch *b_Reco_mu_highPurity; //!
// muon id
Int_t Reco_QQ_mupl_idx[maxBranchSize];
Int_t Reco_QQ_mumi_idx[maxBranchSize];
TBranch *b_Reco_QQ_mupl_idx;
TBranch *b_Reco_QQ_mumi_idx;
Int_t Reco_mu_nTrkHits[maxBranchSize]; //[Reco_mu_size]
TBranch *b_Reco_mu_nTrkHits; //!
Float_t Reco_mu_normChi2_global[maxBranchSize]; //[Reco_mu_size]
TBranch *b_Reco_mu_normChi2_global; //!
Int_t Reco_mu_nMuValHits[maxBranchSize]; //[Reco_mu_size]
TBranch *b_Reco_mu_nMuValHits; //!
Int_t Reco_mu_StationsMatched[maxBranchSize]; //[Reco_mu_size]
TBranch *b_Reco_mu_StationsMatched; //!
Float_t Reco_mu_dxy[maxBranchSize]; //[Reco_mu_size]
Float_t Reco_mu_dxyErr[maxBranchSize]; //[Reco_mu_size]
TBranch *b_Reco_mu_dxy; //!
TBranch *b_Reco_mu_dxyErr; //!
Float_t Reco_mu_dz[maxBranchSize]; //[Reco_mu_size]
Float_t Reco_mu_dzErr[maxBranchSize]; //[Reco_mu_size]
TBranch *b_Reco_mu_dz; //!
TBranch *b_Reco_mu_dzErr; //!
Int_t Reco_mu_nTrkWMea[maxBranchSize]; //[Reco_mu_size]
TBranch *b_Reco_mu_nTrkWMea; //!
Bool_t Reco_mu_TMOneStaTight[maxBranchSize]; //[Reco_mu_size]
TBranch *b_Reco_mu_TMOneStaTight; //!
Int_t Reco_mu_nPixWMea[maxBranchSize]; //[Reco_mu_size]
TBranch *b_Reco_mu_nPixWMea; //!
Int_t Reco_QQ_sign[maxBranchSize]; //[Reco_QQ_size]
TBranch *b_Reco_QQ_sign; //!
Int_t Reco_mu_nPixValHits[maxBranchSize]; //[Reco_QQ_size]
TBranch *b_Reco_mu_nPixValHits; //!
Float_t Reco_mu_ptErr_global[maxBranchSize]; //[Reco_QQ_size]
TBranch *b_Reco_mu_ptErr_global; //!
Int_t Reco_mu_SelectionType[maxBranchSize];
TBranch *b_Reco_mu_SelectionType;
Float_t Reco_QQ_ctau[maxBranchSize];
Float_t Reco_QQ_ctau3D[maxBranchSize];
TBranch *b_Reco_QQ_ctau;
TBranch *b_Reco_QQ_ctau3D;
/////////////////////////////////////////
////// Gen QQ
/////////////////////////////////////////
Int_t Gen_QQ_size;
Int_t Gen_QQ_type[maxBranchSize]; //[Gen_QQ_size]
TClonesArray *Gen_QQ_4mom;
TClonesArray *Gen_QQ_mupl_4mom;
TClonesArray *Gen_QQ_mumi_4mom;
TBranch *b_Gen_QQ_size; //!
TBranch *b_Gen_QQ_type; //!
TBranch *b_Gen_QQ_4mom; //!
TBranch *b_Gen_QQ_mupl_4mom; //!
TBranch *b_Gen_QQ_mumi_4mom; //!
Int_t Reco_mu_whichGen[maxBranchSize];
TBranch *b_Reco_mu_whichGen;
Float_t Gen_weight;
TBranch *b_Gen_weight;
//~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~//
//~*~*~*~*~*~*~*Conversion~*~*~*~*~*~*~*~*~//
//~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~//
const int MaxTrackBranchSize = 5000;
Int_t Reco_trk_size;
TClonesArray *Reco_trk_4mom;
TClonesArray *Reco_trk_vtx;
Int_t Reco_trk_charge[MaxTrackBranchSize];
Float_t Reco_trk_dxyError[MaxTrackBranchSize];
Float_t Reco_trk_dzError[MaxTrackBranchSize];
TBranch *Reco_trk_size;
TBranch *Reco_trk_4mom;
TBranch *Reco_trk_vtx;
TBranch *Reco_trk_charge;
TBranch *Reco_trk_dxyError;
TBranch *Reco_trk_dzError;
class SetTree
{
public:
SetTree(){};
virtual ~SetTree();
virtual void TreeSetting(TTree* tree, bool isMC, bool isConversion);
Bool_t SoftMuIdCut(int irqq);
};
SetTree::~SetTree()
{
}
void SetTree::TreeSetting(TTree* tree, bool isMC, bool isConversion)
{
Reco_QQ_4mom = 0;
Reco_QQ_mupl_4mom = 0;
Reco_QQ_mumi_4mom = 0;
tree->SetBranchAddress("runNb", &runNb, &b_runNb);
tree->SetBranchAddress("LS", &LS, &b_LS);
tree->SetBranchAddress("eventNb", &eventNb, &b_eventNb);
tree->SetBranchAddress("zVtx", &zVtx, &b_zVtx);
tree->SetBranchAddress("Centrality", &Centrality, &b_Centrality);
tree->SetBranchAddress("HLTriggers", &HLTriggers, &b_HLTriggers);
tree->SetBranchAddress("Reco_QQ_size", &Reco_QQ_size, &b_Reco_QQ_size);
tree->SetBranchAddress("Reco_QQ_4mom", &Reco_QQ_4mom, &b_Reco_QQ_4mom);
tree->SetBranchAddress("Reco_mu_size", &Reco_mu_size, &b_Reco_mu_size);
tree->SetBranchAddress("Reco_mu_4mom", &Reco_mu_4mom, &b_Reco_mu_4mom);
tree->SetBranchAddress("Reco_QQ_trig", Reco_QQ_trig, &b_Reco_QQ_trig);
tree->SetBranchAddress("Reco_QQ_VtxProb", Reco_QQ_VtxProb, &b_Reco_QQ_VtxProb);
tree->SetBranchAddress("Reco_QQ_mupl_idx",Reco_QQ_mupl_idx,&b_Reco_QQ_mupl_idx);
tree->SetBranchAddress("Reco_QQ_mumi_idx",Reco_QQ_mumi_idx,&b_Reco_QQ_mumi_idx);
tree->SetBranchAddress("Reco_mu_trig", Reco_mu_trig, &b_Reco_mu_trig);
tree->SetBranchAddress("Reco_mu_nTrkHits", Reco_mu_nTrkHits, &b_Reco_mu_nTrkHits);
tree->SetBranchAddress("Reco_mu_normChi2_global", Reco_mu_normChi2_global, &b_Reco_mu_normChi2_global);
tree->SetBranchAddress("Reco_mu_nMuValHits", Reco_mu_nMuValHits, &b_Reco_mu_nMuValHits);
tree->SetBranchAddress("Reco_mu_StationsMatched", Reco_mu_StationsMatched, &b_Reco_mu_StationsMatched);
tree->SetBranchAddress("Reco_mu_dxy", Reco_mu_dxy, &b_Reco_mu_dxy);
tree->SetBranchAddress("Reco_mu_dxyErr", Reco_mu_dxyErr, &b_Reco_mu_dxyErr);
tree->SetBranchAddress("Reco_mu_dz", Reco_mu_dz, &b_Reco_mu_dz);
tree->SetBranchAddress("Reco_mu_dzErr", Reco_mu_dzErr, &b_Reco_mu_dzErr);
tree->SetBranchAddress("Reco_mu_TMOneStaTight", Reco_mu_TMOneStaTight, &b_Reco_mu_TMOneStaTight);
tree->SetBranchAddress("Reco_mu_nPixWMea", Reco_mu_nPixWMea, &b_Reco_mu_nPixWMea);
tree->SetBranchAddress("Reco_QQ_sign", Reco_QQ_sign, &b_Reco_QQ_sign);
tree->SetBranchAddress("Reco_mu_nTrkWMea", Reco_mu_nTrkWMea, &b_Reco_mu_nTrkWMea);
tree->SetBranchAddress("Reco_QQ_ctau",Reco_QQ_ctau,&b_Reco_QQ_ctau);
tree->SetBranchAddress("Reco_QQ_ctau3D",Reco_QQ_ctau3D,&b_Reco_QQ_ctau3D);
tree->SetBranchAddress("Reco_mu_nPixValHits", Reco_mu_nPixValHits, &b_Reco_mu_nPixValHits);
tree->SetBranchAddress("Reco_mu_ptErr_global", Reco_mu_ptErr_global, &b_Reco_mu_ptErr_global);
tree->SetBranchAddress("Reco_mu_SelectionType", Reco_mu_SelectionType, &b_Reco_mu_SelectionType);
tree->SetBranchAddress("Reco_mu_highPurity", Reco_mu_highPurity, &b_Reco_mu_highPurity);
if (isMC) {
Gen_QQ_4mom = 0;
Gen_QQ_mupl_4mom = 0;
Gen_QQ_mumi_4mom = 0;
tree->SetBranchAddress("Gen_QQ_size", &Gen_QQ_size, &b_Gen_QQ_size);
tree->SetBranchAddress("Gen_QQ_type", Gen_QQ_type, &b_Gen_QQ_type);
tree->SetBranchAddress("Gen_QQ_4mom", &Gen_QQ_4mom, &b_Gen_QQ_4mom);
tree->SetBranchAddress("Gen_QQ_mupl_4mom", &Gen_QQ_mupl_4mom, &b_Gen_QQ_mupl_4mom);
tree->SetBranchAddress("Gen_QQ_mumi_4mom", &Gen_QQ_mumi_4mom, &b_Gen_QQ_mumi_4mom);
tree->SetBranchAddress("Reco_mu_whichGen",Reco_mu_whichGen, &b_Reco_mu_whichGen);
tree->SetBranchAddress("Gen_weight",&Gen_weight, &b_Gen_weight);
}
if(isTrack) {
Reco_trk_4mom=0;
Reco_trk_vtx=0;
tree->SetBranchAddress("Reco_trk_size", &Reco_trk_size, &b_Reco_trk_size);
tree->SetBranchAddress("Reco_trk_4mom", &Reco_trk_4mom, &b_Reco_trk_4mom);
tree->SetBranchAddress("Reco_trk_vtx", &Reco_trk_vtx, &b_Reco_trk_vtx);
tree->SetBranchAddress("Reco_trk_charge", Reco_trk_charge, &b_Reco_trk_charge);
tree->SetBranchAddress("Reco_trk_dxyError", Reco_trk_dxyError, &b_Reco_trk_dxyError);
tree->SetBranchAddress("Reco_trk_dzError", Reco_trk_dzError, &b_Reco_trk_dzError);
}
};
Bool_t SetTree::SoftMuIdCut(int irqq)
{
bool passMuonTypePl = true;
passMuonTypePl = passMuonTypePl && (Reco_mu_SelectionType[Reco_QQ_mupl_idx[irqq]]&((int)pow(2,1)));
passMuonTypePl = passMuonTypePl && (Reco_mu_SelectionType[Reco_QQ_mupl_idx[irqq]]&((int)pow(2,3)));
bool passMuonTypeMi = true;
passMuonTypeMi = passMuonTypeMi && (Reco_mu_SelectionType[Reco_QQ_mumi_idx[irqq]]&((int)pow(2,1)));
passMuonTypeMi = passMuonTypeMi && (Reco_mu_SelectionType[Reco_QQ_mumi_idx[irqq]]&((int)pow(2,3)));
bool muplSoft = ( //(Reco_mu_TMOneStaTight[Reco_QQ_mupl_idx[irqq]]==true) &&
(Reco_mu_nTrkWMea[Reco_QQ_mupl_idx[irqq]] > 5) &&
(Reco_mu_nPixWMea[Reco_QQ_mupl_idx[irqq]] > 0) &&
(fabs(Reco_mu_dxy[Reco_QQ_mupl_idx[irqq]])<0.3) &&
(fabs(Reco_mu_dz[Reco_QQ_mupl_idx[irqq]])<20.) &&
passMuonTypePl // && (Reco_mu_highPurity[Reco_QQ_mupl_idx[irqq]]==true)
) ;
bool mumiSoft = ( //(Reco_mu_TMOneStaTight[Reco_QQ_mumi_idx[irqq]]==true) &&
(Reco_mu_nTrkWMea[Reco_QQ_mumi_idx[irqq]] > 5) &&
(Reco_mu_nPixWMea[Reco_QQ_mumi_idx[irqq]] > 0) &&
(fabs(Reco_mu_dxy[Reco_QQ_mumi_idx[irqq]])<0.3) &&
(fabs(Reco_mu_dz[Reco_QQ_mumi_idx[irqq]])<20.) &&
passMuonTypeMi // && (Reco_mu_highPurity[Reco_QQ_mupl_idx[irqq]]==true)
) ;
return (muplSoft && mumiSoft);
}
#endif
|
class Solution {
private:
int dir[4][2]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
bool exist(int pos, int i, int j, vector<vector<char>>& board, string& word) {
if(pos == word.length())
return true;
char c = board[i][j];
// mark as visited.
board[i][j] = ' ';
bool res = false;
for(int y=0;y<4;y++){
int ni = i + dir[y][0];
int nj = j + dir[y][1];
if(ni>=0 && ni<board.size() && nj>=0 && nj<board[0].size() && board[ni][nj] == word[pos]){
res = exist(pos+1, ni, nj, board, word);
if(res)
break;
}
}
board[i][j] = c;
return res;
}
public:
bool exist(vector<vector<char>>& board, string word) {
int n = board.size();
if(!n)
return (word == "");
int m = board[0].size();
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(board[i][j] == word[0]){
bool res = exist(1, i, j, board, word);
if(res)
return true;
}
return false;
}
};
|
#include <iostream>
int main(){
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int a, k;
std::cin >> a;
k = 2;
for(int i = 2; i < a+1; ++i)
k += i;
std::cout << k;
}
|
//
// Created by 송지원 on 2020/06/27.
//
//바킹독님 6강 큐 boj10845 직접 구현한 큐를 이용하는 버젼
#include <iostream>
using namespace std;
const int MAX = 10005; //여기서 그냥 "int MAX = ~" 이렇게 하면 아래 "int dat[MAX];" 구문에서 에러남
int dat[MAX];
int head = 0, tail = 0;
int N;
string s;
int t;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N;
while (N--) {
cin >> s;
if (s == "push") {
cin >> t;
dat[tail++] = t;
}
else if (s == "pop") {
if (tail - head == 0) cout << "-1\n";
else {
cout << dat[head++] <<"\n";
}
}
else if (s == "size") {
cout << tail - head << "\n";
}
else if (s == "empty") {
cout << (int)(bool)!(tail-head) << "\n";
//이 부분 바킹독님은
// cout << (head == tail) << "\n";
// 이렇게 하심!!!
}
else if (s == "front") {
if (tail-head==0) cout << "-1\n";
else cout << dat[head] << "\n";
}
else if (s == "back") {
if (tail-head==0) cout << "-1\n";
else cout << dat[tail-1] << "\n";
}
}
}
|
std::ostream& operator << (std::ostream& out, VkLayerProperties& layer)
{
out << layer.layerName << " "
<< layer.specVersion << " "
<< layer.implementationVersion << " "
<< layer.description << std::endl;
return out;
}
std::ostream& operator << (std::ostream& out, VkPhysicalDevice& device)
{
//https://www.khronos.org/registry/vulkan/specs/1.1-extensions/man/html/VkPhysicalDeviceProperties.html
VkPhysicalDeviceProperties p;
//https://www.khronos.org/registry/vulkan/specs/1.1-extensions/man/html/vkGetPhysicalDeviceProperties.html
vkGetPhysicalDeviceProperties(device, &p);
out << ""
"apiVersion: " << p.apiVersion << std::endl <<
"driverVersion: " << p.driverVersion << std::endl <<
"vendorID: " << p.vendorID << std::endl <<
"deviceID: " << p.deviceID << std::endl <<
"deviceType: " << (int)p.deviceType << std::endl <<
"deviceName: " << p.deviceName << std::endl <<
"pipelineCacheUUID: " << p.pipelineCacheUUID << std::endl <<
"limites.maxImageDimension1D: " << p.limits.maxImageDimension1D << std::endl <<
"limites.maxImageDimension2D: " << p.limits.maxImageDimension2D << std::endl <<
"limites.maxImageDimension3D: " << p.limits.maxImageDimension3D << std::endl <<
"limites.maxImageDimensionCube: " << p.limits.maxImageDimensionCube << std::endl <<
"limites.maxImageArrayLayers: " << p.limits.maxImageArrayLayers << std::endl <<
"limites.maxTexelBufferElements: " << p.limits.maxTexelBufferElements << std::endl <<
"limites.maxUniformBufferRange: " << p.limits.maxUniformBufferRange << std::endl <<
"limites.maxStorageBufferRange: " << p.limits.maxStorageBufferRange << std::endl <<
"limites.maxPushConstantsSize: " << p.limits.maxPushConstantsSize << std::endl <<
"limites.maxMemoryAllocationCount: " << p.limits.maxMemoryAllocationCount << std::endl <<
"limites.maxSamplerAllocationCount: " << p.limits.maxSamplerAllocationCount << std::endl <<
"limites.bufferImageGranularity: " << p.limits.bufferImageGranularity << std::endl <<
"limites.sparseAddressSpaceSize: " << p.limits.sparseAddressSpaceSize << std::endl <<
"limites.maxBoundDescriptorSets: " << p.limits.maxBoundDescriptorSets << std::endl <<
"limites.maxPerStageDescriptorSamplers: " << p.limits.maxPerStageDescriptorSamplers << std::endl <<
"limites.maxPerStageDescriptorUniformBuffers: " << p.limits.maxPerStageDescriptorUniformBuffers << std::endl <<
"limites.maxPerStageDescriptorStorageBuffers: " << p.limits.maxPerStageDescriptorStorageBuffers << std::endl <<
"limites.maxPerStageDescriptorSampledImages: " << p.limits.maxPerStageDescriptorSampledImages << std::endl <<
"limites.maxPerStageDescriptorStorageImages: " << p.limits.maxPerStageDescriptorStorageImages << std::endl <<
"limites.maxPerStageDescriptorInputAttachments: " << p.limits.maxPerStageDescriptorInputAttachments << std::endl <<
"limites.maxPerStageResources: " << p.limits.maxPerStageResources << std::endl <<
"limites.maxDescriptorSetSamplers: " << p.limits.maxDescriptorSetSamplers << std::endl <<
"limites.maxDescriptorSetUniformBuffers: " << p.limits.maxDescriptorSetUniformBuffers << std::endl <<
"limites.maxDescriptorSetUniformBuffersDynamic: " << p.limits.maxDescriptorSetUniformBuffersDynamic << std::endl <<
"limites.maxDescriptorSetStorageBuffers: " << p.limits.maxDescriptorSetStorageBuffers << std::endl <<
"limites.maxDescriptorSetStorageBuffersDynamic: " << p.limits.maxDescriptorSetStorageBuffersDynamic << std::endl <<
"limites.maxDescriptorSetSampledImages: " << p.limits.maxDescriptorSetSampledImages << std::endl <<
"limites.maxDescriptorSetStorageImages: " << p.limits.maxDescriptorSetStorageImages << std::endl <<
"limites.maxDescriptorSetInputAttachments: " << p.limits.maxDescriptorSetInputAttachments << std::endl <<
"limites.maxVertexInputAttributes: " << p.limits.maxVertexInputAttributes << std::endl <<
"limites.maxVertexInputBindings: " << p.limits.maxVertexInputBindings << std::endl <<
"limites.maxVertexInputAttributeOffset: " << p.limits.maxVertexInputAttributeOffset << std::endl <<
"limites.maxVertexInputBindingStride: " << p.limits.maxVertexInputBindingStride << std::endl <<
"limites.maxVertexOutputComponents: " << p.limits.maxVertexOutputComponents << std::endl <<
"limites.maxTessellationGenerationLevel: " << p.limits.maxTessellationGenerationLevel << std::endl <<
"limites.maxTessellationPatchSize: " << p.limits.maxTessellationPatchSize << std::endl <<
"limites.maxTessellationControlPerVertexInputComponents: " << p.limits.maxTessellationControlPerVertexInputComponents << std::endl <<
"limites.maxTessellationControlPerVertexOutputComponents: " << p.limits.maxTessellationControlPerVertexOutputComponents << std::endl <<
"limites.maxTessellationControlPerPatchOutputComponents: " << p.limits.maxTessellationControlPerPatchOutputComponents << std::endl <<
"limites.maxTessellationControlTotalOutputComponents: " << p.limits.maxTessellationControlTotalOutputComponents << std::endl <<
"limites.maxTessellationEvaluationInputComponents: " << p.limits.maxTessellationEvaluationInputComponents << std::endl <<
"limites.maxTessellationEvaluationOutputComponents: " << p.limits.maxTessellationEvaluationOutputComponents << std::endl <<
"limites.maxGeometryShaderInvocations: " << p.limits.maxGeometryShaderInvocations << std::endl <<
"limites.maxGeometryInputComponents: " << p.limits.maxGeometryInputComponents << std::endl <<
"limites.maxGeometryOutputComponents: " << p.limits.maxGeometryOutputComponents << std::endl <<
"limites.maxGeometryOutputVertices: " << p.limits.maxGeometryOutputVertices << std::endl <<
"limites.maxGeometryTotalOutputComponents: " << p.limits.maxGeometryTotalOutputComponents << std::endl <<
"limites.maxFragmentInputComponents: " << p.limits.maxFragmentInputComponents << std::endl <<
"limites.maxFragmentOutputAttachments: " << p.limits.maxFragmentOutputAttachments << std::endl <<
"limites.maxFragmentDualSrcAttachments: " << p.limits.maxFragmentDualSrcAttachments << std::endl <<
"limites.maxFragmentCombinedOutputResources: " << p.limits.maxFragmentCombinedOutputResources << std::endl <<
"limites.maxComputeSharedMemorySize: " << p.limits.maxComputeSharedMemorySize << std::endl <<
"limites.maxComputeWorkGroupCount: " << p.limits.maxComputeWorkGroupCount << std::endl <<
"limites.maxComputeWorkGroupInvocations: " << p.limits.maxComputeWorkGroupInvocations << std::endl <<
"limites.maxComputeWorkGroupSize: " << p.limits.maxComputeWorkGroupSize << std::endl <<
"limites.subPixelPrecisionBits: " << p.limits.subPixelPrecisionBits << std::endl <<
"limites.subTexelPrecisionBits: " << p.limits.subTexelPrecisionBits << std::endl <<
"limites.mipmapPrecisionBits: " << p.limits.mipmapPrecisionBits << std::endl <<
"limites.maxDrawIndexedIndexValue: " << p.limits.maxDrawIndexedIndexValue << std::endl <<
"limites.maxDrawIndirectCount: " << p.limits.maxDrawIndirectCount << std::endl <<
"limites.maxSamplerLodBias: " << p.limits.maxSamplerLodBias << std::endl <<
"limites.maxSamplerAnisotropy: " << p.limits.maxSamplerAnisotropy << std::endl <<
"limites.maxViewports: " << p.limits.maxViewports << std::endl <<
"limites.maxViewportDimensions: " << p.limits.maxViewportDimensions << std::endl <<
"limites.viewportBoundsRange: " << p.limits.viewportBoundsRange << std::endl <<
"limites.viewportSubPixelBits: " << p.limits.viewportSubPixelBits << std::endl <<
"limites.minMemoryMapAlignment: " << p.limits.minMemoryMapAlignment << std::endl <<
"limites.minTexelBufferOffsetAlignment: " << p.limits.minTexelBufferOffsetAlignment << std::endl <<
"limites.minUniformBufferOffsetAlignment: " << p.limits.minUniformBufferOffsetAlignment << std::endl <<
"limites.minStorageBufferOffsetAlignment: " << p.limits.minStorageBufferOffsetAlignment << std::endl <<
"limites.minTexelOffset: " << p.limits.minTexelOffset << std::endl <<
"limites.maxTexelOffset: " << p.limits.maxTexelOffset << std::endl <<
"limites.minTexelGatherOffset: " << p.limits.minTexelGatherOffset << std::endl <<
"limites.maxTexelGatherOffset: " << p.limits.maxTexelGatherOffset << std::endl <<
"limites.minInterpolationOffset: " << p.limits.minInterpolationOffset << std::endl <<
"limites.maxInterpolationOffset: " << p.limits.maxInterpolationOffset << std::endl <<
"limites.subPixelInterpolationOffsetBits: " << p.limits.subPixelInterpolationOffsetBits << std::endl <<
"limites.maxFramebufferWidth: " << p.limits.maxFramebufferWidth << std::endl <<
"limites.maxFramebufferHeight: " << p.limits.maxFramebufferHeight << std::endl <<
"limites.maxFramebufferLayers: " << p.limits.maxFramebufferLayers << std::endl <<
"limites.framebufferColorSampleCounts: " << p.limits.framebufferColorSampleCounts << std::endl <<
"limites.framebufferDepthSampleCounts: " << p.limits.framebufferDepthSampleCounts << std::endl <<
"limites.framebufferStencilSampleCounts: " << p.limits.framebufferStencilSampleCounts << std::endl <<
"limites.framebufferNoAttachmentsSampleCounts: " << p.limits.framebufferNoAttachmentsSampleCounts << std::endl <<
"limites.maxColorAttachments: " << p.limits.maxColorAttachments << std::endl <<
"limites.sampledImageColorSampleCounts: " << p.limits.sampledImageColorSampleCounts << std::endl <<
"limites.sampledImageIntegerSampleCounts: " << p.limits.sampledImageIntegerSampleCounts << std::endl <<
"limites.sampledImageDepthSampleCounts: " << p.limits.sampledImageDepthSampleCounts << std::endl <<
"limites.sampledImageStencilSampleCounts: " << p.limits.sampledImageStencilSampleCounts << std::endl <<
"limites.storageImageSampleCounts: " << p.limits.storageImageSampleCounts << std::endl <<
"limites.maxSampleMaskWords: " << p.limits.maxSampleMaskWords << std::endl <<
"limites.timestampComputeAndGraphics: " << p.limits.timestampComputeAndGraphics << std::endl <<
"limites.timestampPeriod: " << p.limits.timestampPeriod << std::endl <<
"limites.maxClipDistances: " << p.limits.maxClipDistances << std::endl <<
"limites.maxCullDistances: " << p.limits.maxCullDistances << std::endl <<
"limites.maxCombinedClipAndCullDistances: " << p.limits.maxCombinedClipAndCullDistances << std::endl <<
"limites.discreteQueuePriorities: " << p.limits.discreteQueuePriorities << std::endl <<
"limites.pointSizeRange: " << p.limits.pointSizeRange << std::endl <<
"limites.lineWidthRange: " << p.limits.lineWidthRange << std::endl <<
"limites.pointSizeGranularity: " << p.limits.pointSizeGranularity << std::endl <<
"limites.lineWidthGranularity: " << p.limits.lineWidthGranularity << std::endl <<
"limites.strictLines: " << p.limits.strictLines << std::endl <<
"limites.standardSampleLocations: " << p.limits.standardSampleLocations << std::endl <<
"limites.optimalBufferCopyOffsetAlignment: " << p.limits.optimalBufferCopyOffsetAlignment << std::endl <<
"limites.optimalBufferCopyRowPitchAlignment: " << p.limits.optimalBufferCopyRowPitchAlignment << std::endl <<
"limites.nonCoherentAtomSize: " << p.limits.nonCoherentAtomSize << std::endl <<
"sparseProperties.residencyStandard2DBlockShape: " << p.sparseProperties.residencyStandard2DBlockShape << std::endl <<
"sparseProperties.residencyStandard2DMultisampleBlockShape: " << p.sparseProperties.residencyStandard2DMultisampleBlockShape << std::endl <<
"sparseProperties.residencyStandard3DBlockShape: " << p.sparseProperties.residencyStandard3DBlockShape << std::endl <<
"sparseProperties.residencyAlignedMipSize: " << p.sparseProperties.residencyAlignedMipSize << std::endl <<
"sparseProperties.residencyNonResidentStrict: " << p.sparseProperties.residencyNonResidentStrict << std::endl;
return out;
}
|
#include<vector>
using std::vector;
#include<iostream>
#include<algorithm>
#include<memory>
using std::shared_ptr;
#include<string>
using std::string;
#include<stack>
using std::stack;
#include<queue>
using std::priority_queue;
/*
Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].
*/
#include<map>
using std::map;
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int l = 0;
int r = nums.size() - 1;
int aimpos = -1;
while (l <= r)
{
int mid = (l + r) / 2;
if (nums[mid] < target) {
l = mid + 1;
}
else if (nums[mid] > target)
{
r = mid - 1;
}
else
{
aimpos = mid;
break;
}
}
if (aimpos != -1)
{
int ansl = aimpos, ansr = aimpos;
while (ansl > 0 && nums[ansl - 1] == nums[ansl])ansl--;
while (ansr + 1 < nums.size() && nums[ansr] == nums[ansr + 1])ansr++;
return vector<int>({ ansl,ansr });
}
return vector<int>({ -1,-1});
}
};
int main()
{
Solution s;
vector<int> i({ 5,7,7,8,8,10});
s.searchRange(i,8);
return 0;
}
|
#include "stdafx.h"
#include "Win32App.h"
HWND Win32App::_hWnd = nullptr;
RECT Win32App::_rect = {0};
int Win32App::Width = 1270;
int Win32App::Height = 720;
int Win32App::_screenWidth = GetSystemMetrics(SM_CXSCREEN);
int Win32App::_screenHeight = GetSystemMetrics(SM_CYSCREEN);
shared_ptr<Renderer> Win32App::_renderer = nullptr;
shared_ptr<Scene> Win32App::_scene = nullptr;
unique_ptr<Keyboard> Win32App::_keyboardEvent = nullptr;
unique_ptr<Mouse> Win32App::_mouseEvent = nullptr;
void Win32App::Init(HINSTANCE hInstance, int nCmdShow) {
InitWindow(hInstance, nCmdShow);
_keyboardEvent = make_unique<Keyboard>();
_mouseEvent = make_unique<Mouse>();
}
int Win32App::Run() {
return MainLoop();
}
void Win32App::InitWindow(HINSTANCE hInstance, int nCmdShow) {
WNDCLASSEXW windowClass = {0};
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = WindowProc;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hInstance = hInstance;
windowClass.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_DIRECTXTEST));
windowClass.hCursor = LoadCursor(nullptr, IDC_ARROW);
windowClass.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
windowClass.lpszClassName = L"DirectXTest";
windowClass.hIconSm = LoadIcon(windowClass.hInstance, MAKEINTRESOURCE(IDI_SMALL));
RegisterClassEx(&windowClass);
_hWnd = CreateWindowW(
windowClass.lpszClassName,
L"DirectX Test",
WS_OVERLAPPEDWINDOW,
(_screenWidth - Width) / 2, (_screenHeight - Height) / 2, Width, Height,
nullptr,
nullptr,
hInstance,
nullptr
);
GetClientRect(_hWnd, &_rect);
ShowWindow(_hWnd, nCmdShow);
}
int Win32App::MainLoop() {
MSG msg = {0};
while (msg.message != WM_QUIT) {
if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
} else {
if (_scene) {
_scene->Update();
}
if (_renderer) {
_renderer->Render();
}
}
}
return (int) msg.wParam;
}
LRESULT CALLBACK Win32App::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_ACTIVATEAPP:
Keyboard::ProcessMessage(message, wParam, lParam);
Mouse::ProcessMessage(message, wParam, lParam);
break;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP:
Keyboard::ProcessMessage(message, wParam, lParam);
break;
case WM_INPUT:
case WM_MOUSEMOVE:
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_MOUSEWHEEL:
case WM_XBUTTONDOWN:
case WM_XBUTTONUP:
case WM_MOUSEHOVER:
Mouse::ProcessMessage(message, wParam, lParam);
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code that uses hdc here...
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
HWND Win32App::GethWnd() {
return _hWnd;
}
RECT Win32App::GetScreenRect() {
return _rect;
}
void Win32App::SetRenderer(shared_ptr<Renderer>& renderer) {
_renderer = renderer;
}
void Win32App::SetScene(shared_ptr<Scene>& scene) {
_scene = scene;
}
|
#pragma once
#include "ray.h"
#include "color.h"
#include <float.h>
#include <string>
class Object;
//------------------------------------------------------------------------------
/**
*/
struct HitResult
{
// hit point
vec3 p;
// normal
vec3 normal;
// hit object, or nullptr
Object* object = nullptr;
// intersection distance
float t = FLT_MAX;
};
//------------------------------------------------------------------------------
/**
*/
class Object
{
public:
Object()
{ }
virtual ~Object()
{ }
virtual bool Intersect(HitResult& hit, const Ray& ray, float maxDist) = 0;
virtual Color GetColor() = 0;
virtual Ray ScatterRay(const Ray& ray, vec3 point, vec3 normal) = 0;
};
|
#ifndef PLAYER_HPP
#define PLAYER_HPP
class Player
{
public:
Player();
};
#endif // PLAYER_HPP
|
#include "Matching.h"
#include "Blending.h"
int main(int argc, char* argv[]){
// Get input images addresses
if(argc < 3){
cout << "Not enough parameters!" << endl;
return -1;
}
// SIFT steps
CImg<float> src1, src2;
src1.load_bmp(argv[1]); src2.load_bmp(argv[2]);
cout << "Begin SIFT" << endl;
SIFT sifter1(src1);
sifter1.SIFT_Start();
sifter1.saveKeyPointsImg("./output/kp1.bmp");
SIFT sifter2(src2);
sifter2.SIFT_Start();
sifter2.saveKeyPointsImg("./output/kp2.bmp");
cout << "End SIFT" << endl;
Matcher matcher(sifter1.GetFirstKeyDescriptor(), sifter2.GetFirstKeyDescriptor());
matcher.matchProcess();
matcher.drawOriKeyPoints(argv[1], argv[2], "./output/kp1_real.bmp", "./output/kp2_real.bmp");
matcher.mixImageAndDrawLine("./output/mixImg.bmp", "./output/mixImgWithLine.bmp");
matcher.RANSAC("./output/fixed_mixLinedImg.bmp");
Blender blender(matcher.getMatchVec().x, matcher.getMatchVec().y);
blender.BlendImages(argv[1], argv[2], "./output/blendedImg.bmp");
return 0;
}
|
#include <QHostAddress>
#include "ShoeManagerTcpServer.hpp"
#include "ShoeManagerTcpServerPrivate.hpp"
ShoeManagerTcpServer::ShoeManagerTcpServer(QObject *parent)
: QObject(parent)
{
d_ptr = new ShoeManagerTcpServerPrivate(this);
}
ShoeManagerTcpServer::~ShoeManagerTcpServer()
{
delete d_ptr;
}
bool ShoeManagerTcpServer::initialize(int port)
{
return d_ptr->initialize(port);
}
bool ShoeManagerTcpServer::finalize()
{
return d_ptr->finalize();
}
bool ShoeManagerTcpServer::sendPacket(const ShoeMessagePacket &packet, const int nDescriptor)
{
return d_ptr->sendPacket(packet, nDescriptor);
}
void ShoeManagerTcpServer::setHeatBeatInterval(const int secs)
{
d_ptr->setHeatBeatInterval(secs);
}
void ShoeManagerTcpServer::heartBeat(const int nDescriptor)
{
d_ptr->heartBeat(nDescriptor);
}
void ShoeManagerTcpServer::closeSocket(int nDescriptor)
{
d_ptr->closeSocket(nDescriptor);
}
|
#ifndef DATABASE_H
#define DATABASE_H
#pragma once
#include "coin.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QtDebug>
#include <QSqlError>
#include <QSqlRecord>
class DbManager
{
public:
// Constructor
DbManager(const QString& path);
// Deconstructor
~DbManager();
// Create Database Structure
bool createTable();
// Add coin to database.
bool addCoin(coin coin);
// Delete coin from database (using coin object)
bool deleteCoin(coin coin);
// Delete a coin based off name
bool deleteCoin(const QString& name);
// Delete all coins
bool deleteAllCoins();
// Check If coin exists in database.
bool coinExists(const QString& name);
// Print all coins in database
bool printAllCoins() const;
// check if DB connection is open
bool isOpen() const;
// Execute query
bool query(const QString &query);
private:
QSqlDatabase m_db;
};
#endif // DATABASE_H
|
/**
******************************************************************************
* Copyright (c) 2019 - ~, SCUT-RobotLab Development Team
* @file mpu6050_config.cpp
* @author YDX 2244907035@qq.com
* @brief Code for MPU6050 config.
* @date 2020-04-02
* @version 1.1
* @par Change Log:
* <table>
* <tr><th>Date <th>Version <th>Author <th>Description
* <tr><td>2018-10-18 <td> 1.0 <td>mannychen <td>Creator
* <tr><td>2019-11-21 <td> 1.1 <td>YDX <td>remove config macro.
* <tr><td>2020-04-02 <td> 1.1 <td>YDX <td>Reduce parameters in initialization function and add notes.
* </table>
*
==============================================================================
How to use this driver
==============================================================================
@note
-# 初始化
调用`MPU6050_Init()`进行初始化
e.g:
MPU6050_Init(GPIOB, GPIO_PIN_6, GPIO_PIN_7);
-# 获取角速度和加速度原始数据
调用`MPU_Get_Gyroscope()`获取角速度
e.g:
if(!MPU_Get_Gyroscope(&MPU6050_IIC_PIN, &MPUData.gx, &MPUData.gy, &MPUData.gz))
{
MPUData.gx -= MPUData.gxoffset;
MPUData.gy -= MPUData.gyoffset;
MPUData.gz -= MPUData.gzoffset;
}
调用`MPU_Get_Accelerometer()`获取加速度
e.g:
MPU_Get_Accelerometer(&MPU6050_IIC_PIN,&MPUData.ax,&MPUData.ay,&MPUData.az);
-# 获取角度
调用`mpu_dmp_get_data()`获取角度
e.g:
mpu_dmp_get_data(&MPUData.roll,&MPUData.pitch,&MPUData.yaw);
@warning
-# 添加预编译宏`USE_FULL_ASSERT`可以启用断言检查。
-# 需要`SRML`的`drv_i2c`支持。
-# 软件IIC的IO口需要配置成:超高速开漏上拉模式。
******************************************************************************
* @attention
*
* if you had modified this file, please make sure your code does not have many
* bugs, update the version Number, write dowm your name and the date, the most
* important is make sure the users will have clear and definite understanding
* through your new brief.
*
* <h2><center>© Copyright (c) 2019 - ~, SCUT-RobotLab Development Team.
* All rights reserved.</center></h2>
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "mpu6050_config.h"
#include "stdio.h"
/* Private define ------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
IIC_PIN_Typedef MPU6050_IIC_PIN;
MPUData_Typedef MPUData;
/* Private type --------------------------------------------------------------*/
/* Private function declarations ---------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/**
* @brief MPU6050 initialization
* @param gpiox: MPU6050 iic gpio port
* @param scl_pinx: MPU6050 iic scl pin
* @param sda_pinx: MPU6050 iic sda pin
* @retval 0:success
* 1:fail
*/
uint8_t MPU6050_Init(GPIO_TypeDef *gpiox, uint32_t scl_pinx, uint32_t sda_pinx)
{
/* MPU6050_IIC initialization */
MPU6050_IIC_PIN.IIC_GPIO_PORT = gpiox;
MPU6050_IIC_PIN.IIC_SCL_PIN = scl_pinx;
MPU6050_IIC_PIN.IIC_SDA_PIN = sda_pinx;
if (scl_pinx == GPIO_PIN_0)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 0;
else if (scl_pinx == GPIO_PIN_1)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 1;
else if (scl_pinx == GPIO_PIN_2)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 2;
else if (scl_pinx == GPIO_PIN_3)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 3;
else if (scl_pinx == GPIO_PIN_4)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 4;
else if (scl_pinx == GPIO_PIN_5)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 5;
else if (scl_pinx == GPIO_PIN_6)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 6;
else if (scl_pinx == GPIO_PIN_7)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 7;
else if (scl_pinx == GPIO_PIN_8)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 8;
else if (scl_pinx == GPIO_PIN_9)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 9;
else if (scl_pinx == GPIO_PIN_10)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 10;
else if (scl_pinx == GPIO_PIN_11)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 11;
else if (scl_pinx == GPIO_PIN_12)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 12;
else if (scl_pinx == GPIO_PIN_13)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 13;
else if (scl_pinx == GPIO_PIN_14)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 14;
else if (scl_pinx == GPIO_PIN_15)
MPU6050_IIC_PIN.IIC_SCL_PIN_NUM = 15;
else
return 1;
if (sda_pinx == GPIO_PIN_0)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 0;
else if (sda_pinx == GPIO_PIN_1)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 1;
else if (sda_pinx == GPIO_PIN_2)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 2;
else if (sda_pinx == GPIO_PIN_3)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 3;
else if (sda_pinx == GPIO_PIN_4)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 4;
else if (sda_pinx == GPIO_PIN_5)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 5;
else if (sda_pinx == GPIO_PIN_6)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 6;
else if (sda_pinx == GPIO_PIN_7)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 7;
else if (sda_pinx == GPIO_PIN_8)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 8;
else if (sda_pinx == GPIO_PIN_9)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 9;
else if (sda_pinx == GPIO_PIN_10)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 10;
else if (sda_pinx == GPIO_PIN_11)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 11;
else if (sda_pinx == GPIO_PIN_12)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 12;
else if (sda_pinx == GPIO_PIN_13)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 13;
else if (sda_pinx == GPIO_PIN_14)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 14;
else if (sda_pinx == GPIO_PIN_15)
MPU6050_IIC_PIN.IIC_SDA_PIN_NUM = 15;
else
return 1;
/* MPU6050 initialization */
MPU_Init(&MPU6050_IIC_PIN);
if (mpu_dmp_init() != 0)
{
HAL_Delay(100);
__set_FAULTMASK(1); //reset
NVIC_SystemReset();
}
MPU_Get_Gyroscope_Init(&MPU6050_IIC_PIN, &MPUData.gxoffset, &MPUData.gyoffset, &MPUData.gzoffset);
return 0;
}
/************************ COPYRIGHT(C) SCUT-ROBOTLAB **************************/
|
#ifndef __CUBEENVTEAPOT_H__
#define __CUBEENVTEAPOT_H__
class CubeEnvTeapot
{
D3DXVECTOR3 m_vPos;
D3DXVECTOR3 m_vRot;
D3DXVECTOR3 m_vScale;
D3DXMATRIX m_mTM;
D3DXMATRIX m_mScale, m_mRot, m_mTrans;
D3DMATERIAL9 m_Mtrl;
LPD3DXMESH m_pTeapot;
LPDIRECT3DCUBETEXTURE9 m_pCubeTexture;
public:
void InitTeapot(void);
void UpdateTeapot(float dTime);
void Control(float dTime);
void RenderTeapot(int LState);
void ReleaseTeapot(void);
public:
CubeEnvTeapot(void);
virtual ~CubeEnvTeapot(void);
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @author Manuela Hutter (manuelah)
*/
#ifndef FAKE_FEATURE_SETTINGS_CONTEXT_H
#define FAKE_FEATURE_SETTINGS_CONTEXT_H
#include "adjunct/quick/controller/FeatureSettingsContext.h"
#include "modules/locale/locale-enum.h"
class FakeFeatureSettingsContext : public FeatureSettingsContext
{
virtual FeatureType GetFeatureType() const { return FeatureTypeSelftest; }
virtual Str::LocaleString GetFeatureStringID() const { return Str::S_OPERA_LINK; } // don't have a fake string here..
virtual Str::LocaleString GetFeatureLongStringID() const { return Str::S_OPERA_LINK; } // don't have a fake string here..
};
#endif // FAKE_FEATURE_SETTINGS_CONTEXT_H
|
/*
* Copyright 2016 Robert Bond
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Reads stdin for lines of the form
* /media/rgb/USB20FD/ants.avi 0 870 680
* <filename> <frame> <x> <y>
* and writes out the ant snapshots
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <iostream>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace std;
using namespace cv;
// constants
const uint32_t snap_size = 20;
const uint32_t search_size = snap_size + snap_size / 2;
const uint32_t ant_pixel = 100;
// options
bool verbose = false;
bool no_ants = false;
struct option {
const char *opt;
bool *vbl;
const char *msg;
} opts[] = {
{ "-v", &verbose, "Verbose logging" },
{ "-n", &no_ants, "No ants" },
{ NULL, NULL, NULL }
};
#define DPRINTF if (verbose) printf
// Need something better than these globals
char *file_name;
uint32_t nframes;
void find_cg(Mat &src, Rect roi, int &xc, int &yc, int thresh)
{
int xtot = 0;
int ytot = 0;
int npix = 0;
for (int y = roi.y; y < roi.y + roi.height; y++) {
for (int x = roi.x; x < roi.x + roi.width; x++) {
if (src.at<uchar>(y, x) < thresh) {
xtot += x;
ytot += y;
npix++;
}
}
}
if (npix > 0) {
xc = xtot / npix;
yc = ytot / npix;
} else {
xc = roi.x + roi.width / 2;
yc = roi.y + roi.height / 2;
}
}
int main(int argc, char* argv[])
{
Mat frame;
printf("snap\n");
++argv;
while (--argc) {
for (struct option *p = opts; p->opt; p++) {
if (strcmp(*argv, p->opt) == 0) {
*p->vbl = true;
printf("%s\n", p->msg);
}
}
argv++;
}
fflush(stdout);
time_t secs = time(NULL);
struct tm *ptm = localtime(&secs);
VideoCapture cap;
namedWindow("snap", CV_WINDOW_AUTOSIZE);
char file_name[500];
char cur_file_name[500];
cur_file_name[0] = 0;
uint32_t frame_index;
uint32_t cur_frame_index;
uint32_t nframes;
uint32_t px;
uint32_t py;
uint32_t snap_half = snap_size / 2;
uint32_t search_half = search_size / 2;
uint32_t snap_num = 0;
const char* tag;
Mat tot = Mat(snap_size, snap_size, CV_32FC1, 0.0);
string dir;
if (no_ants) {
dir = "images/no_ants/";
tag = "not_ant";
} else {
dir = "images/ants/";
tag = "ant";
}
while (scanf("%s %u %u %u\n", file_name, &frame_index, &px, &py) == 4) {
DPRINTF("%s %u %u %u\n", file_name, frame_index, px, py);
if (no_ants)
frame_index += 50;
if (strcmp(file_name, cur_file_name) != 0) {
cap.open(file_name);
if (!cap.isOpened()) {
printf("Can't open %s\n", file_name);
exit(1);
}
nframes = (uint32_t)cap.get(CV_CAP_PROP_FRAME_COUNT);
strcpy(cur_file_name, file_name);
cur_frame_index = ~0;
}
if (frame_index > nframes) {
printf("Invalid frame %u %u, skipping!\n", frame_index, nframes);
continue;
}
if (frame_index != cur_frame_index) {
cap.set(CV_CAP_PROP_POS_FRAMES, (double) frame_index);
cap.read(frame);
if (frame.empty()) {
printf("Empty frame: %s %u %u %u\n",
file_name, frame_index, px, py);
exit(1);
}
cur_frame_index = frame_index;
}
if (px > frame.cols || py > frame.rows) {
printf("Bad xy coord: %s %u %u %u\n",
file_name, frame_index, px, py);
exit(1);
}
int xc, yc;
if (no_ants) {
xc = px;
yc = py;
} else {
// Try to center the ant
if (search_half > px || search_half > py ||
px + search_half > frame.cols || py + search_half > frame.rows) {
printf("Skipping %s %u %u %u\n",
file_name, frame_index, px, py);
continue;
}
Rect search_roi(px - search_half, py - search_half, search_size, search_size);
find_cg(frame, search_roi, xc, yc, ant_pixel);
}
if (snap_half > xc || snap_half > yc ||
xc + snap_half > frame.cols || yc + snap_half > frame.rows) {
printf("Skipping %s %u %u %u\n",
file_name, frame_index, xc, yc);
continue;
}
Rect roi(xc - snap_half, yc - snap_half, snap_size, snap_size);
Mat snap(frame, roi);
if (verbose) {
imshow("snap", snap);
waitKey(3000);
}
char image_name[500];
sprintf(image_name, "%s_%04d%02d%02d%02d%02d_%04u.png", tag,
ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday,
ptm->tm_hour, ptm->tm_min, snap_num++);
imwrite(dir + string(image_name), snap);
printf("%s %u %u %u %s\n",
file_name, frame_index, px, py,
image_name);
Mat tmp;
snap.convertTo(tmp, CV_32FC1);
tot += tmp;
}
cout << tot;
tot /= (float)snap_num * 255.0;
cout << tot;
imshow("snap", tot);
waitKey(0);
exit(0);
}
|
#include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct node
{
int value;
node *next;
};
node *head = NULL;
node *insert(int n)
{
if(head == NULL)
{
node *temp = new node;
temp -> value = n;
temp->next = NULL;
head = temp;
}
else
{
node *temp = new node;
temp -> value = n;
temp->next = NULL;
node *itr = head;
while(itr -> next != NULL)
{
itr = itr->next;
}
itr ->next = temp;
}
}
void show()
{
node *itr = head;
while(itr -> next != NULL)
{
cout << itr -> value;
itr = itr -> next;
}
cout << itr->value;
}
//seperate for first and last
node *insert(int n,int position)
{
if(position == 1)
{
node *temp = new node;
temp->value = n;
temp->next = head;
head = temp;
}
else
{
node *itr = head;
int count = position-2;
while(count--)
{
itr = itr->next;
}
node *temp = new node;
temp->value = n;
temp ->next = itr->next;
itr ->next = temp;
}
}
node *delete1(int position)
{
if(position == 1)
{
head = head->next;
}
else
{
node *itr = head;
int count = position-2;
while(count--)
{
itr = itr->next;
}
itr->next = (itr->next)->next;
}
}
bool search1(int number)
{
node *itr = head;
while(itr -> next != NULL)
{
if(itr->value == number)
return 1;
itr = itr->next;
}
if(itr->value == number)
return 1;
// else
return 0;
}
// linked list in a class
// pass pointer to pointer for head
// pointer defined in main not in global
node* reverse_linked_list()
{
node *prev = NULL;
node *next = NULL;
node *current_iterator = head;
while(current_iterator != NULL)
{
next = current_iterator -> next;
current_iterator -> next = prev;
prev = current_iterator;
current_iterator = next;
}
return prev;
}
// requires an input
// actuall prints in reverse order
void show_recursive(node *temp_head)
{
if(temp_head == NULL)
return;
// print the list till next element untill the last
// i can print the current element
show_recursive(temp_head -> next);
cout << temp_head-> value;
}
void reversell_recursive(node *temp_head)
{
//base case
if(temp_head -> next == NULL)
{
head = temp_head;
// IMP last node = first node ----------------
return;
}
// hypothesis
// reverse ll till second node ie next
reversell_recursive(temp_head -> next);
//assuming ll till second node is reversed
// we can reverse the first link
node *p = temp_head -> next;
p -> next = temp_head;
temp_head -> next = NULL;
}
int main()
{
insert(1);
insert(2);
insert(3);
insert(6);
node *temp_head = head;
reversell_recursive(temp_head);
// head assigned inside function
show();
}
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
//
// Copyright (C) Opera Software AS. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
#ifndef WEBFEED_LOADING_FEED_H_
#define WEBFEED_LOADING_FEED_H_
#include "modules/webfeeds/webfeeds_api.h"
#ifdef WEBFEEDS_BACKEND_SUPPORT
#include "modules/webfeeds/src/webfeedparser.h"
#include "modules/hardcore/mh/messobj.h"
#include "modules/util/adt/opvector.h"
class WebFeed;
class WebFeedParser;
/**
* This class is used to load (and update) feeds.
*
* This class is used internally by the module and should be used for all
* feed loading. It will only load a limited number of feeds at a time, to
* restrict resource usage. If updating a feed it will keep it in disk storage
* until it is needed in memory to limit memory usage.
*/
class WebFeedLoadManager
{
protected:
/** This is a class used from someone requests a feed to be loaded until
* all listeners have been notified. It contains all sorts of meta
* information needed during loading.
*/
class LoadingFeed : public Link, public WebFeedParserListener, public MessageObject {
public:
LoadingFeed();
LoadingFeed(URL& feed_url, WebFeed* feed, OpFeedListener* listener);
LoadingFeed(URL& feed_url, OpFeed::FeedId, OpFeedListener* listener); // Uses id to load feed object on demand (right before parsing)
OP_STATUS Init(BOOL return_unchanged_feeds, time_t last_modified, const char* etag);
~LoadingFeed();
WebFeed* GetFeed();
URL& GetURL() { return m_feed_url; }
OP_STATUS AddListener(OpFeedListener*);
OP_STATUS StartLoading(); ///< must delete this object yourself if method returns an error; otherwise don't delete
void LoadingFinished(); ///< cleans up and notifies all that all loading for this feed is done (but does not notify listeners)
void NotifyListeners(WebFeed*, OpFeed::FeedStatus); ///< Notifies feed listeners
void NotifyListeners(OpFeedEntry*, OpFeedEntry::EntryStatus, BOOL new_entry); ///< Notifies entry listeners
OP_STATUS RemoveListener(OpFeedListener* listener); ///< Make sure this listener won't receive any more callbacks
BOOL IsUpdatingFeed() { return m_feed_id != 0; }
// Callbacks from parser:
void OnEntryLoaded(OpFeedEntry* entry, OpFeedEntry::EntryStatus, BOOL new_entry);
void ParsingDone(WebFeed*, OpFeed::FeedStatus);
void ParsingStarted();
/// override function from MessageObject
void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2);
protected:
OP_STATUS HandleDataLoaded(); ///< Handle Icon data loaded. Finished loading if OP_STATUS is OK, otherwise caller has to do LoadingFinished
#ifdef WEBFEEDS_SAVED_STORE_SUPPORT
BOOL LoadIcon(WebFeed* feed); ///< Starts loading favicon of feed, returns FALSE if icon shouldn't/doesn't need to be loaded
#endif
void UnRegisterCallbacks();
OpVector<OpFeedListener> m_listeners;
URL m_feed_url;
URL m_icon_url;
WebFeed* m_feed;
WebFeedParser* m_parser;
OpFeed::FeedId m_feed_id;
time_t m_last_modified;
OpString8 m_etag;
BOOL m_return_unchanged_feeds;
};
public:
friend class LoadingFeed;
WebFeedLoadManager();
~WebFeedLoadManager();
OP_STATUS Init();
OP_STATUS LoadFeed(WebFeed* feed, URL& feed_url, OpFeedListener* listener, BOOL return_unchanged_feeds, time_t last_modified, const char* etag);
/// Schedule a feed for update, calls UpdatesDone when ALL feeds scheduled have finished updating
/// Assumes at most one update is running, WebFeedsAPI_impl should make sure of that.
OP_STATUS UpdateFeed(URL& feed_url, OpFeed::FeedId, OpFeedListener* listener, BOOL return_unchanged_feeds, time_t last_modified, const char* etag);
OP_STATUS AbortLoading(URL& feed_url);
OP_STATUS AbortAllFeedLoading(BOOL stop_updating_only);
OP_STATUS RemoveListener(OpFeedListener* listener); ///< Make sure this listener won't receive any more callbacks
LoadingFeed* IsLoadingOrQueued(URL& feed_url);
protected:
OP_STATUS LoadFeed(LoadingFeed*); // Takes over ownership of parameter
/* Callbacks by LoadingFeed */
void AddLoadingFeed(LoadingFeed*); ///< this feed has started loading
OP_STATUS RemoveLoadingFeed(LoadingFeed* lf); ///< this feed has finished one way or another
/// List of parsers currently loading. They will remove & delete themselves
/// after last callback, but if any are still loading when api is deleted
/// then the autodelete list should take care of that.
AutoDeleteHead m_loading_feeds;
AutoDeleteHead m_waiting_feeds; ///< Used by LoadFeed, RemoveLoadingParser for not loading too many feeds at once
UINT m_max_loading_feeds;
};
#endif // WEBFEEDS_BACKEND_SUPPORT
#endif /*WEBFEED_LOADING_FEED_H_*/
|
#include "approx_functions.h"
// Xsection
scalar approx_X22(std::vector<double> params){
double sqrts = params[0];
double T = params[1];
return scalar{1.0/T/T};
}
scalar approx_X22QQbar(std::vector<double> params){
double lnsqrts = params[0];
double s = std::exp(2*lnsqrts);
return scalar{std::log(1+s/6.76)/s};
}
scalar approx_dX22_max(std::vector<double> params){
double T = params[1];
return scalar{1.0/std::pow(T, 2)};
}
|
#include <Rcpp.h>
#include <RcppParallel.h>
using namespace RcppParallel;
// [[Rcpp::depends(RcppParallel)]]
/**
* ### Background
*
*
*
*/
/**
* ### The function object
*
* We'll use a [function object](https://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html) (sometimes called a functor) as our worker function.
*
*/
// Our function object
struct getElement : public Worker {
// input vector to read from
// const std::vector< std::string > myVector;
std::vector< std::vector< std::string > > &CppMatrix;
// initialize input and output vectors
getElement(std::vector< std::vector< std::string > > &CppMatrix)
: CppMatrix(CppMatrix) {}
// function call operator that work for the specified range (begin/end)
void operator()(std::size_t begin, std::size_t end) {
// Rcpp::Rcout << "Value: " << begin << "\n";
for (std::size_t i = begin; i < end; i++) {
// retVector[i] = myVector[i];
// myString = myVector[i];
char myDelim = ':';
int element = 2;
// myString = getElement(myString, myDelim, element);
// retVector[i] = myString;
// Don't do the following/
// Rcpp::Rcout << "Value: " << myString << "\n";
// Or this.
// Rcpp::checkUserInterrupt();
}
}
};
// This is what we'll call from R
//
// [[Rcpp::export]]
void stringExtract(Rcpp::StringMatrix RcppMatrix) {
// Because Rcpp data structures are not thread safe
// we'll use std::vector for input and output.
std::vector< std::vector< std::string > > CppMatrix(RcppMatrix.nrow(), std::vector< std::string >(RcppMatrix.ncol()));
// Load C++ data structure from Rcpp.
int i = 0;
int j = 0;
std::string tmpString;
for(i=0; i<CppMatrix.size(); i++){
for(j=0; j<CppMatrix[i].size(); j++){
CppMatrix[i][j] = RcppMatrix(i,j);
}
}
// Create the worker
struct getElement getElement(CppMatrix);
// Call it with parallelFor
unsigned int grainSize = 100;
parallelFor(0, CppMatrix.size(), getElement, grainSize);
}
/**
* ### Fabricate example data
*
*
*/
/*** R
n <- 1e3
myGT <- paste(sample(0:1, size = n, replace = TRUE),
sample(0:1, size = n, replace = TRUE),
sep = "/")
myGT <- paste(myGT, LETTERS, sample(1:20, size = n, replace = TRUE), sep = ":")
myGT <- paste(myGT, LETTERS,
paste(sample(1:200, size = n, replace = TRUE),
sample(1:200, size = n, replace = TRUE), sep=","),
sep = ":")
myGT <- matrix(myGT, nrow=100, ncol = 100)
myGT[1:4,1:5]
*/
/**
* ### Benchmark
*
*
*/
/*** R
library(microbenchmark)
nTimes <- 20
#microbenchmark(gt1 <- delimitString(myGT, ":", 3), times = nTimes)
#head(gt1)
*/
/*** R
#
RcppParallel::setThreadOptions(numThreads = 4)
#microbenchmark(gt2 <- rcpp_parallel_delimitString(myGT), times = nTimes)
#head(gt2)
*/
|
#pragma once
#include <string>
#include <map>
#include <memory>
#include <experimental/filesystem>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include "ApplicationException.h"
#include "Output.h"
#include "Tools.h"
namespace FW
{
class ResourceManager
{
public:
ResourceManager(
const std::string& texture_directory,
const std::string& font_directory,
const std::string& sound_directory,
const std::string& music_directory
);
// takes a resource type (anything but sf::Music) and a directory for where those
// resources are stored. loads in every file in that directory
template <typename ResourceType>
std::map<std::string, ResourceType> loadAllResource(const std::string& resource_directory)
{
namespace fs = std::experimental::filesystem; // shorten namespace
std::map<std::string, ResourceType> resources; // create map for resource
if (fs::exists(resource_directory)) // if the resource directory exists
{
for (auto& path : fs::directory_iterator(resource_directory)) // get the name of every file in the directory
{
std::string path_text = path.path().string();
std::string file = Tools::splitString(path_text, '\\').back();
OUTPUT("Loading file '" << file << "'.");
ResourceType resource; // create a new resource
if (!resource.loadFromFile(path_text)) // load the file
throw ApplicationException("Resource file '" + file + "' could not be loaded.");
resources[file] = resource; // copy it to the map
}
}
return resources; // return the map of resource
}
// have to use a seperate function to load in music due to music using a different function name for loading
void loadAllMusic(const std::string& music_directory);
// a function for getting each kind of resource.
sf::Texture& getTexture(const std::string& filename);
sf::Font& getFont(const std::string& filename);
sf::SoundBuffer& getSoundBuffer(const std::string& filename);
sf::Music& getMusic(const std::string& filename);
private:
// a map for each kind of resource in the game
std::map<std::string, sf::Texture> textures;
std::map<std::string, sf::Font> fonts;
std::map<std::string, sf::SoundBuffer> sound_buffers;
std::map<std::string, std::unique_ptr<sf::Music>> music; // have to use pointers to music because they're non-copyable objects.
};
}
|
#ifndef TENSOR_H
#define TENSOR_H
#include <map>
#include <functional>
#include "Array/Array.h"
typedef std::function<Array(const Array&)> grad_fn;
typedef std::map<const Array*, grad_fn> dependency;
class Tensor
{
private:
int m_row;
int m_col;
Array m_data;
bool m_required_grad;
Array m_grad;
dependency dep;
public:
Tensor(): m_row(0), m_col(0), m_required_grad(false) {}
Tensor(const float &_e, const bool &_required_grad=false, const dependency &_dep=dependency());
Tensor(const Array &_arr, const bool &_required_grad=false, const dependency &_dep=dependency());
Tensor(const int &_row, const int &_col, const float &_e=0, const bool &_required_grad=false);
Tensor(const Tensor &_tensor, const bool &_required_grad=false);
~Tensor();
void release();
int rows() const { return m_row; }
int cols() const { return m_col; }
int num_element() const { return m_row * m_col; }
const Array& data() const { return m_data; }
///********************************************
dependency get_dep()
{
return dep;
}
//*********************************************/
Tensor dot(const Tensor &_t) const;
Tensor sum(int axis=-1) const;
friend Tensor tensor_neg(const Tensor &_t);
friend Tensor tensor_dot(const Tensor &_t1, const Tensor &_t2);
friend Tensor tensor_sum(const Tensor &_t);
protected:
};
Tensor tensor_neg(const Tensor &_t);
Tensor tensor_dot(const Tensor &_t1, const Tensor &_t2);
Tensor tensor_sum(const Tensor &_t);
#endif
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
// Disable warnings in external headers, we can't fix them
PRAGMA_WARNING_PUSH
PRAGMA_WARNING_DISABLE_MSVC(4365) // warning C4365: 'return': conversion from 'int' to 'std::_Rand_urng_from_func::result_type', signed/unsigned mismatch
#include <cassert>
#include <cstring> // For "memcpy()"
#include <iterator> // For "std::back_inserter()"
#include <algorithm> // For "std::copy()"
PRAGMA_WARNING_POP
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace RendererRuntime
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
inline MemoryFile::MemoryFile() :
mNumberOfDecompressedBytes(0),
mCurrentDataPointer(nullptr)
{
// Nothing here
}
inline MemoryFile::MemoryFile(size_t reserveNumberOfCompressedBytes, size_t reserveNumberOfDecompressedBytes) :
mNumberOfDecompressedBytes(0),
mCurrentDataPointer(nullptr)
{
mCompressedData.reserve(reserveNumberOfCompressedBytes);
mDecompressedData.reserve(reserveNumberOfDecompressedBytes);
}
inline MemoryFile::~MemoryFile()
{
// Nothing here
}
inline MemoryFile::ByteVector& MemoryFile::getByteVector()
{
return mDecompressedData;
}
inline const MemoryFile::ByteVector& MemoryFile::getByteVector() const
{
return mDecompressedData;
}
//[-------------------------------------------------------]
//[ Public virtual RendererRuntime::IFile methods ]
//[-------------------------------------------------------]
inline size_t MemoryFile::getNumberOfBytes()
{
return mDecompressedData.size();
}
inline void MemoryFile::read(void* destinationBuffer, size_t numberOfBytes)
{
assert((mCurrentDataPointer - mDecompressedData.data()) + numberOfBytes <= mDecompressedData.size());
memcpy(destinationBuffer, mCurrentDataPointer, numberOfBytes);
mCurrentDataPointer += numberOfBytes;
}
inline void MemoryFile::skip(size_t numberOfBytes)
{
assert((mCurrentDataPointer - mDecompressedData.data()) + numberOfBytes <= mDecompressedData.size());
mCurrentDataPointer += numberOfBytes;
}
inline void MemoryFile::write(const void* sourceBuffer, size_t numberOfBytes)
{
std::copy(static_cast<const uint8_t*>(sourceBuffer), static_cast<const uint8_t*>(sourceBuffer) + numberOfBytes, std::back_inserter(mDecompressedData));
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // RendererRuntime
|
#pragma once
#include "stdafx.h"
#include "TestBase.h"
class Station;
class Ai4wwTests : public TestBase
{
public:
Ai4wwTests();
virtual ~Ai4wwTests();
virtual bool Setup();
virtual void Teardown();
virtual bool RunAllTests();
bool TestLocation();
bool TestInState();
bool TestCallsign();
bool TestNumberOfQsos();
private:
Station *m_station;
// lines from the cabrillo file
vector<string> m_lines;
};
|
#include<bits/stdc++.h>
using namespace std;
#define PI 3.1415926535897932
int main(){
char fox[]="The quick brown fox jumps over the lazy dog.";
int n = strlen(fox);
for (int i=0;i<n;++i) {
if ('o' == fox[i]) {
printf("find 'o'!!! fox[%d]\n",i);
}
}
return 0;
}
|
/* The integer 36 has a peculiar property: it is a perfect square, and is also the sum of the integers from 1 through 8. The next such number is 1225 which is 352, and the sum of the integers from 1 through 49. Find the next number (or numbers) that is a perfect square and also the sum of a series 1...n. This next number may be greater than 32767 (range of int, so use long). You may use library functions that you know of, (or mathematical formulas) to make your program run faster. (Note: depending on your machine and your program, it can take quite a while to find this number.) */
#include<iostream>
#include<cmath>
using namespace std;
int sum(int n){
if(n==1){
return 1;
}
else{
return (n + sum(n-1)); //sum(n)=n+sum(n-1)
}
}
int main()
{
for(long i=0; i<100000; i++){
for(long n=1; n<10000; n++){
if(sqrt(i)==int(sqrt(i))){
if(i==sum(n)){
cout << i <<endl;
}
}
}
}
return 0;
}
|
/****************************************************************************
** Copyright (C) 2017 Olaf Japp
**
** This file is part of FlatSiteBuilder.
**
** FlatSiteBuilder is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** FlatSiteBuilder 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 FlatSiteBuilder. If not, see <http://www.gnu.org/licenses/>.
**
****************************************************************************/
#ifndef EXPANDER_H
#define EXPANDER_H
#include <QLayout>
#include <QVBoxLayout>
#include <QToolButton>
#include <QScrollArea>
#include <QPropertyAnimation>
#include <QParallelAnimationGroup>
#include "hyperlink.h"
class Expander : public QWidget
{
Q_OBJECT
Q_PROPERTY(QColor color READ color WRITE setColor)
public:
Expander(QString header, QString normalIcon = "", QString hoveredIcon = "", QString selectedIcon = "");
void addLayout(QLayout *l);
void enterEvent(QEvent * event);
void leaveEvent(QEvent * event);
void setExpanded(bool value);
void setColor(QColor color);
QColor color() {return Qt::black;} // not really needed now,
protected:
virtual void mouseReleaseEvent(QMouseEvent *event);
public slots:
void buttonClicked();
signals:
void expanded(bool value);
void clicked();
private:
QWidget *m_content;
QLabel *m_icon;
QLabel *m_hyper;
QString m_labelNormalColor;
QString m_labelHoveredColor;
QString m_labelSelectedColor;
QImage m_normalIcon;
QImage m_hoveredIcon;
QImage m_selectedIcon;
QString m_text;
QPropertyAnimation *heightAnim;
QPropertyAnimation *colorAnim;
QParallelAnimationGroup *anim;
QColor m_normalColor;
QColor m_selectedColor;
QColor m_hoveredColor;
bool m_isExpanded;
void expandContent();
void collapseContent();
};
#endif // EXPANDER_H
|
#include "sort.h"
void sort::insertion_sort(vector<int> &data)
{
for (int j = 1; j < data.size(); ++j)
{
int temp = data[j], i = j-1;
while( i>=0 && data[i]> temp )
{
data[i + 1] = data[i];
--i;
}
data[i + 1] = temp;
}
}
void sort::merge(vector<int> &data, int beg, int mid, int end)
{
vector<int> temp;
temp.reserve(end - beg + 1);
int i = beg, j = mid + 1;
while ( i <= mid && j <= end )
{
if (data[i] > data[j])
temp.push_back(data[j++]);
else
temp.push_back(data[i++]);
}
while (i <= mid)
temp.push_back(data[i++]);
while (j <= end)
temp.push_back(data[j++]);
for (int i = beg, j = 0; i <= end; ++i, ++j)
data[i] = temp[j];
}
void sort::mergeSort(vector<int> &data, int beg, int end)
{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(data, beg, mid);
mergeSort(data, mid+1, end);
merge(data, beg, mid, end);
}
}
void sort::merge_sort(vector<int> &data)
{
mergeSort(data, 0, data.size()-1);
}
void sort::heap_sort(vector<int> &data)
{
}
void sort::quick_sort(vector<int> &data)
{
}
void sort::counting_sort(vector<int> &data)
{
}
|
/*
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 "Core/Path.hpp"
#include "Core/Settings.hpp"
#include "Serialization/Serializer.hpp"
#include <ostream>
namespace Push
{
void Write(const Serializer& serializer, std::ostream& stream);
void Write(const Serializer& serializer, const Path& fullPath);
void Write(const Serializer& serializer, const Path& file, BundleType bundleType);
}
|
#pragma once
#include "GDISetup.h"
#include <Interfaces.h>
#include <wil\win32_helpers.h>
class VSwapChain : public wrl::RuntimeClass<wrl::RuntimeClassFlags<wrl::ClassicCom>, IVSwapChain>
{
class VFrame
{
using unique_gdi = wil::unique_any<Gdiplus::GpGraphics*, decltype(&Gdiplus::DllExports::GdipDeleteGraphics), Gdiplus::DllExports::GdipDeleteGraphics>;
using unique_image = wil::unique_any<Gdiplus::GpBitmap*, decltype(&Gdiplus::DllExports::GdipDisposeImage), Gdiplus::DllExports::GdipDisposeImage>;
using unique_cached_bitmap = wil::unique_any<Gdiplus::GpCachedBitmap*, decltype(&Gdiplus::DllExports::GdipDeleteCachedBitmap), Gdiplus::DllExports::GdipDeleteCachedBitmap>;
public:
VFrame(int width, int height, HWND hwnd, bool ICCColorAdjustment = false);
public:
void LockImage(VRTV_DESC& _out_view, Gdiplus::Rect lockArea, Gdiplus::ImageLockMode mode);
void LockFullImage(VRTV_DESC& _out_view, Gdiplus::ImageLockMode mode);
void UnlockImage(VRTV_DESC& view);
void Draw()const;
VPIXEL_FORMAT GetPixelFormat()const noexcept;
private:
mutable unique_cached_bitmap output;
unique_image image;
unique_gdi pGfx;
Gdiplus::Rect frameArea;
VPIXEL_FORMAT format = VPIXEL_FORMAT::PARGB32bpp;
};
public:
VSwapChain(const VSWAP_CHAIN_DESC* desc, IVDevice* gfx, HWND hwnd);
public:
void __stdcall Present()override;
void __stdcall GetRenderTarget(uint32_t number, VRTV_DESC* _out_buf)override;
private:
~VSwapChain() = default;
private:
VFrame Frame;
VRTV_DESC BackBuffer{ 0 };
wrl::ComPtr<IVTexture> RenderBuffer;
};
|
//Database.cpp
#include<iostream>
#include<stdexcept>
#include"Database.h"
using namespace std;
Database::Database()
{
mNextSlot=0;
mNextEmployeeNumber=kFirstEmployeeNumber;
}
Database::~Database()
{
//Noting need to do.
}
Employee& Database::addEmployee(string inFirstName,string inLastName)
{
if(mNextSlot>=kMaxEmployees)
{
cerr<<"There is no more room to add in an employee. "<<endl;
throw exception();
}
Employee& theEmployee=mEmployees[mNextSlot++];
theEmployee.setFirstName(inFirstName);
theEmployee.setLastName(inLastName);
theEmployee.setEmployeeNumber(mNextEmployeeNumber++);
theEmployee.hire();
return theEmployee;
}
Employee& Database::getEmployee(int inEmployeeNumber)
{
for (int i=0;i<mNextSlot;i++)
{
if(mEmployees[i].getEmployeeNumber()==inEmployeeNumber)
{
return mEmployees[i];
}
}
cerr<<"No employee with employeenumber "<<inEmployeeNumber<<endl;
throw exception();
}
Employee& Database::getEmployee(string inFirstName,string inLastName)
{
for(int i=0;i<mNextSlot;i++)
{
if(mEmployees[i].getFirstName()==inFirstName &&
mEmployees[i].getLastName()==inLastName)
{
return mEmployees[i];
}
}
cerr<<"No match with name "<<inFirstName<<" "<<inLastName<<endl;
throw exception();
}
void Database::displayAll()
{
for(int i=0;i<mNextSlot;i++)
{
mEmployees[i].display();
}
}
void Database::displayCurrent()
{
for(int i=0;i<mNextSlot;i++)
{
if(mEmployees[i].getIsHired())
{
mEmployees[i].display();
}
}
}
void Database::displayFormer()
{
for(int i=0;i<mNextSlot;i++)
{
if(!mEmployees[i].getIsHired())
{
mEmployees[i].display();
}
}
}
|
//
// Game.hpp
// GAME2
//
// Created by ruby on 2017. 11. 11..
// Copyright © 2017년 ruby. All rights reserved.
//
#ifndef Game_hpp
#define Game_hpp
#include <iostream>
using namespace std;
class Boat;
class Torpedo;
class BoatAList;
class BoatBList;
class BoatCList;
class Game {
private:
enum SCORE { TURN=500, TORPEDO=400, BOAT_A=100, BOAT_B=200, BOAT_C=300 };
Boat* user;
Boat* b_ptr[100];
BoatAList* boatAList;
BoatBList* boatBList;
BoatCList* boatCList;
Torpedo* t_ptr[300];
int n_turn;
int init_boat;
int init_boatA;
int init_boatB;
int init_boatC;
int init_torpedo;
int n_boat;
int n_boatA;
int n_boatB;
int n_boatC;
int n_torpedo;
int indexOfTorpedo;
int score;
int boundX;
int boundY;
bool again;
public:
Game() {}
bool isOverlapped();
void checkHit();
void show_initMenu();
bool make_boats();
void shot_torpedo();
void show_result();
void show_state();
void play_game();
bool get_again();
void delete_objects();
};
#endif /* Game_hpp */
|
// Build and return the stencil (look in the stencil directory) for a U(1) operator.
// Depends on the lattice class and the staggered_u1_op struct.
#include <complex>
using std::complex;
#include "operators.h"
#include "lattice.h"
#include "coarse_stencil.h"
#include "operators_stencil.h"
// Given an allocated but otherwise empty stencil, appropriately fill it with the 2d staggered links.
void get_square_staggered_u1_stencil(stencil_2d* stenc, staggered_u1_op* stagif)
{
if (stenc->generated) // If it's already generated, leave!
{
return;
}
if (stenc->lat->get_nc() != 1) // If it's not an nc = 1 lattice, leave!
{
return;
}
// Loop over all sites.
int i;
int lattice_size = stenc->lat->get_lattice_size();
int coords[2], color; // color is always 0.
int coords_tmp[2];
int eta1;
for (i = 0; i < lattice_size; i++)
{
stenc->lat->index_to_coord(i, coords, color);
eta1 = 1 - 2*(coords[0]%2);
// Clover is the mass.
//stenc->clover[i] = stagif->mass;
// +x
stenc->hopping[i] = -0.5*stagif->lattice[2*i];
// +y
stenc->hopping[i+lattice_size] = -0.5*eta1*stagif->lattice[2*i+1];
// -x
coords_tmp[0] = (coords[0]-1+stenc->lat->get_lattice_dimension(0))%stenc->lat->get_lattice_dimension(0);
coords_tmp[1] = coords[1];
stenc->hopping[i+2*lattice_size] = 0.5*conj(stagif->lattice[2*stenc->lat->coord_to_index(coords_tmp, 0)]);
// -y
coords_tmp[0] = coords[0];
coords_tmp[1] = (coords[1]-1+stenc->lat->get_lattice_dimension(1))%stenc->lat->get_lattice_dimension(1);
stenc->hopping[i+3*lattice_size] = 0.5*eta1*conj(stagif->lattice[2*stenc->lat->coord_to_index(coords_tmp, 0)+1]);
}
stenc->shift = stagif->mass;
stenc->eo_shift = 0.0;
stenc->dof_shift = 0.0;
stenc->generated = true;
}
void get_square_staggered_gamma5_u1_stencil(stencil_2d* stenc, staggered_u1_op* stagif)
{
if (stenc->generated) // If it's already generated, leave!
{
return;
}
if (stenc->lat->get_nc() != 1) // If it's not an nc = 1 lattice, leave!
{
return;
}
// Loop over all sites.
int i;
int eo_sign;
int lattice_size = stenc->lat->get_lattice_size();
int coords[2], color; // color is always 0.
int coords_tmp[2];
int eta1;
for (i = 0; i < lattice_size; i++)
{
stenc->lat->index_to_coord(i, coords, color);
eta1 = 1 - 2*(coords[0]%2);
eo_sign = stenc->lat->index_is_even(i) ? 1.0 : -1.0;
// Clover is the mass.
//stenc->clover[i] = eo_sign*stagif->mass;
// +x
stenc->hopping[i] = -0.5*eo_sign*stagif->lattice[2*i];
// +y
stenc->hopping[i+lattice_size] = -0.5*eo_sign*eta1*stagif->lattice[2*i+1];
// -x
coords_tmp[0] = (coords[0]-1+stenc->lat->get_lattice_dimension(0))%stenc->lat->get_lattice_dimension(0);
coords_tmp[1] = coords[1];
stenc->hopping[i+2*lattice_size] = 0.5*eo_sign*conj(stagif->lattice[2*stenc->lat->coord_to_index(coords_tmp, 0)]);
// -y
coords_tmp[0] = coords[0];
coords_tmp[1] = (coords[1]-1+stenc->lat->get_lattice_dimension(1))%stenc->lat->get_lattice_dimension(1);
stenc->hopping[i+3*lattice_size] = 0.5*eo_sign*eta1*conj(stagif->lattice[2*stenc->lat->coord_to_index(coords_tmp, 0)+1]);
}
stenc->shift = 0.0;
stenc->eo_shift = stagif->mass;
stenc->dof_shift = 0.0;
stenc->generated = true;
}
// Given an allocated but otherwise empty stencil, appropriately fill it with staggered dagger links.
// Same as staggered, but with the negative of the hopping term.
void get_square_staggered_dagger_u1_stencil(stencil_2d* stenc, staggered_u1_op* stagif)
{
if (stenc->generated) // If it's already generated, leave!
{
return;
}
if (stenc->lat->get_nc() != 1) // If it's not an nc = 1 lattice, leave!
{
return;
}
// Loop over all sites.
int i;
int lattice_size = stenc->lat->get_lattice_size();
int coords[2], color; // color is always 0.
int coords_tmp[2];
int eta1;
for (i = 0; i < lattice_size; i++)
{
stenc->lat->index_to_coord(i, coords, color);
eta1 = 1 - 2*(coords[0]%2);
// Clover is the mass.
//stenc->clover[i] = stagif->mass;
// +x
stenc->hopping[i] = 0.5*stagif->lattice[2*i];
// +y
stenc->hopping[i+lattice_size] = 0.5*eta1*stagif->lattice[2*i+1];
// -x
coords_tmp[0] = (coords[0]-1+stenc->lat->get_lattice_dimension(0))%stenc->lat->get_lattice_dimension(0);
coords_tmp[1] = coords[1];
stenc->hopping[i+2*lattice_size] = -0.5*conj(stagif->lattice[2*stenc->lat->coord_to_index(coords_tmp, 0)]);
// -y
coords_tmp[0] = coords[0];
coords_tmp[1] = (coords[1]-1+stenc->lat->get_lattice_dimension(1))%stenc->lat->get_lattice_dimension(1);
stenc->hopping[i+3*lattice_size] = -0.5*eta1*conj(stagif->lattice[2*stenc->lat->coord_to_index(coords_tmp, 0)+1]);
}
stenc->shift = stagif->mass;
stenc->eo_shift = 0.0;
stenc->dof_shift = 0.0;
stenc->generated = true;
}
/////////////
// Functions for applying specialized operator stencils.
/////////////
// Prepare an even rhs for an even/odd preconditioned solve.
// Takes in rhs_orig, returns rhs_e.
void apply_square_staggered_eoprec_prepare_stencil(complex<double>* rhs_e, complex<double>* rhs_orig, stencil_2d* stenc)
{
int lattice_size = stenc->lat->get_lattice_size();
// Prepare rhs: m rhs_e - D_{eo} rhs_o
apply_stencil_2d_eo(rhs_e, rhs_orig, stenc); // zeroes odd sites in rhs_e.
for (int i = 0; i < lattice_size; i++)
{
if (stenc->lat->index_is_even(i))
{
rhs_e[i] = stenc->shift*rhs_orig[i] - rhs_e[i];
}
}
}
// Square staggered 2d operator w/ u1 function, m^2 - D_{eo} D_{oe} [zeroes odd explicitly]
void apply_square_staggered_m2mdeodoe_stencil(complex<double>* lhs, complex<double>* rhs, void* extra_data)
{
stencil_2d* stenc = (stencil_2d*)extra_data;
int lattice_size = stenc->lat->get_lattice_size();
complex<double>* tmp = new complex<double>[lattice_size];
apply_stencil_2d_oe(tmp, rhs, extra_data);
apply_stencil_2d_eo(lhs, tmp, extra_data);
for (int i = 0; i < lattice_size; i++)
{
if (stenc->lat->index_is_even(i))
{
lhs[i] = stenc->shift*stenc->shift*rhs[i] - lhs[i];
}
}
delete[] tmp;
}
// Reconstruct the full solution for an even/odd preconditioned solve.
// Takes in lhs_e, rhs_o, returns lhs_full (copying over the even part from lhs_e)
void apply_square_staggered_eoprec_reconstruct_stencil(complex<double>* lhs_full, complex<double>* lhs_e, complex<double>* rhs_o, stencil_2d* stenc)
{
int lattice_size = stenc->lat->get_lattice_size();
double inv_mass = 1.0/real(stenc->shift);
// Reconstruct odd: m^{-1}*(rhs_o - D_{oe} lhs2_e)
apply_stencil_2d_oe(lhs_full, lhs_e, stenc);
for (int i = 0; i < lattice_size; i++)
{
if (!stenc->lat->index_is_even(i)) // odd
{
lhs_full[i] = inv_mass*(rhs_o[i] - lhs_full[i]);
}
else
{
lhs_full[i] = lhs_e[i];
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.