blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ca9adf3ba8e223afdac93e9a12897d30c7e78c4f | b8df2e8544d095e70beed9e87460635007bcd6ed | /MultiTrackVideoPlayer/Backend/StateHistory.cpp | e0cf6d33564bb94d75cf1bbc706e38fd4cfc25e1 | [] | no_license | koala24/MultiTrackVideoPlayer | 656ee7160548cb15a0ec27e02ec0a0e9866ad31a | 4b62ba149e1878a9aafa3232e6ff9e7ee302abb9 | refs/heads/master | 2020-06-05T12:14:24.897164 | 2015-02-16T06:44:49 | 2015-02-16T06:44:49 | 30,856,946 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 764 | cpp | #include "StateHistory.h"
StateHistory::StateHistory() : _historyList(), _mutex() {
}
void StateHistory::add( const StateEnum::StateValue &value ) {
_mutex.lock();
_historyList.prepend( value );
if ( _historyList.size() > 5 )
_historyList.removeLast();
_mutex.unlock();
}
StateEnum::StateValue StateHistory::current() {
_mutex.lock();
StateEnum::StateValue val = StateEnum::Stopped;
if ( _historyList.size() != 0 )
val = _historyList.first();
_mutex.unlock();
return val;
}
StateEnum::StateValue StateHistory::previous() {
_mutex.lock();
StateEnum::StateValue val = StateEnum::Stopped;
if ( _historyList.size() >= 2 )
val = _historyList.at( 1 );
_mutex.unlock();
return val;
}
| [
"adziu24@outlook.de"
] | adziu24@outlook.de |
2e2c115737a990f8f1b9382be0873e9630e3f481 | a0392240c172248b9648b8a62938d900ed8b66d4 | /include/factory.hpp | 131aae3aca0d14955aef2ea5fd34d4ba39c27473 | [] | no_license | AdiAlgrabli/NAS-Project | b3b571931614fd3c6ab69f6678883c7f9f624509 | 5e42d3cf77abf9160b7b7de646cbd2d7dfc2321d | refs/heads/master | 2022-05-29T08:40:50.034518 | 2020-05-01T12:14:37 | 2020-05-01T12:14:37 | 260,450,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 134 | hpp | #ifndef RD70_INCLUDE_FACTORY
#define RD70_INCLUDE_FACTORY
#include "../framework/factory/factory.hpp"
#endif // RD70_INCLUDE_FACTORY | [
"adialgrabli@gmail.com"
] | adialgrabli@gmail.com |
90694096735b00ecaebf2a37203a834624496b40 | 3dd312fc24543066e317d3e35c5eac1a46ce00f6 | /include/samurai/io/net/dns/resolver-fork.h | 2aee224bf3dc2e368ff7f66441ffccad449c2321 | [] | no_license | janvidar/samurai | b6dfcd577280d15dabda20f27cec577b9f730351 | 15af0285100258e5ed8eeb72afa2f72612588708 | refs/heads/master | 2016-09-05T20:04:56.557742 | 2011-09-15T08:35:12 | 2011-09-15T08:36:46 | 147,481 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 690 | h | /*
* Copyright (C) 2001-2007 Jan Vidar Krey, janvidar@extatic.org
* See the file "COPYING" for licensing details.
*/
#ifndef HAVE_QUICKDC_DNSRESOLVER_FORKED_H
#define HAVE_QUICKDC_DNSRESOLVER_FORKED_H
#include <samurai/io/net/dns/resolver.h>
#ifdef SAMURAI_POSIX
namespace Samurai {
namespace IO {
namespace Net {
namespace DNS {
class ForkResolver : public Resolver {
public:
virtual ~ForkResolver();
ForkResolver(ResolveEventHandler* eventHandler);
void lookup(const char* addr);
protected:
int childPid;
int sd;
void internal_lookup();
friend class SocketMonitor;
char* ipaddr;
};
}
}
}
}
#endif // SAMURAI_POSIX
#endif // HAVE_QUICKDC_DNSRESOLVER_FORKED_H
| [
"janvidar@extatic.org"
] | janvidar@extatic.org |
79840d41b445dd3079d23b0bf287644a54b080a5 | 48d84159338d428fca8ba486aab0c6ef4c9a7df7 | /sources/aruco-3.0.11/utils_calibration/dirreader.h | 7d4067fd85bbcb59d139ff8a7b3b5dd1f283f870 | [
"BSD-2-Clause"
] | permissive | timotheos/ArUco | 290dbbc6cfa2233b15af417a3963acbed2109f79 | b44eb10905ebc68e6fa7b3c43c93a3eac1cd7569 | refs/heads/master | 2021-01-06T07:59:45.560655 | 2019-06-23T09:52:15 | 2019-06-23T09:52:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,933 | h | #ifndef _DIR_READER_H
#define _DIR_READER_H
#include <vector>
#include <string>
#ifdef WIN32
/*
* Dirent interface for Microsoft Visual Studio
*
* Copyright (C) 2006-2012 Toni Ronkko
* This file is part of dirent. Dirent may be freely distributed
* under the MIT license. For all details and documentation, see
* https://github.com/tronkko/dirent
*/
#ifndef DIRENT_H
#define DIRENT_H
/*
* Include windows.h without Windows Sockets 1.1 to prevent conflicts with
* Windows Sockets 2.0.
*/
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <stdio.h>
#include <stdarg.h>
#include <wchar.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
/* Indicates that d_type field is available in dirent structure */
#define _DIRENT_HAVE_D_TYPE
/* Indicates that d_namlen field is available in dirent structure */
#define _DIRENT_HAVE_D_NAMLEN
/* Entries missing from MSVC 6.0 */
#if !defined(FILE_ATTRIBUTE_DEVICE)
# define FILE_ATTRIBUTE_DEVICE 0x40
#endif
/* File type and permission flags for stat(), general mask */
#if !defined(S_IFMT)
# define S_IFMT _S_IFMT
#endif
/* Directory bit */
#if !defined(S_IFDIR)
# define S_IFDIR _S_IFDIR
#endif
/* Character device bit */
#if !defined(S_IFCHR)
# define S_IFCHR _S_IFCHR
#endif
/* Pipe bit */
#if !defined(S_IFFIFO)
# define S_IFFIFO _S_IFFIFO
#endif
/* Regular file bit */
#if !defined(S_IFREG)
# define S_IFREG _S_IFREG
#endif
/* Read permission */
#if !defined(S_IREAD)
# define S_IREAD _S_IREAD
#endif
/* Write permission */
#if !defined(S_IWRITE)
# define S_IWRITE _S_IWRITE
#endif
/* Execute permission */
#if !defined(S_IEXEC)
# define S_IEXEC _S_IEXEC
#endif
/* Pipe */
#if !defined(S_IFIFO)
# define S_IFIFO _S_IFIFO
#endif
/* Block device */
#if !defined(S_IFBLK)
# define S_IFBLK 0
#endif
/* Link */
#if !defined(S_IFLNK)
# define S_IFLNK 0
#endif
/* Socket */
#if !defined(S_IFSOCK)
# define S_IFSOCK 0
#endif
/* Read user permission */
#if !defined(S_IRUSR)
# define S_IRUSR S_IREAD
#endif
/* Write user permission */
#if !defined(S_IWUSR)
# define S_IWUSR S_IWRITE
#endif
/* Execute user permission */
#if !defined(S_IXUSR)
# define S_IXUSR 0
#endif
/* Read group permission */
#if !defined(S_IRGRP)
# define S_IRGRP 0
#endif
/* Write group permission */
#if !defined(S_IWGRP)
# define S_IWGRP 0
#endif
/* Execute group permission */
#if !defined(S_IXGRP)
# define S_IXGRP 0
#endif
/* Read others permission */
#if !defined(S_IROTH)
# define S_IROTH 0
#endif
/* Write others permission */
#if !defined(S_IWOTH)
# define S_IWOTH 0
#endif
/* Execute others permission */
#if !defined(S_IXOTH)
# define S_IXOTH 0
#endif
/* Maximum length of file name */
#if !defined(PATH_MAX)
# define PATH_MAX MAX_PATH
#endif
#if !defined(FILENAME_MAX)
# define FILENAME_MAX MAX_PATH
#endif
#if !defined(NAME_MAX)
# define NAME_MAX FILENAME_MAX
#endif
/* File type flags for d_type */
#define DT_ALL_DICTS 0
#define DT_REG S_IFREG
#define DT_DIR S_IFDIR
#define DT_FIFO S_IFIFO
#define DT_SOCK S_IFSOCK
#define DT_CHR S_IFCHR
#define DT_BLK S_IFBLK
#define DT_LNK S_IFLNK
/* Macros for converting between st_mode and d_type */
#define IFTODT(mode) ((mode) & S_IFMT)
#define DTTOIF(type) (type)
/*
* File type macros. Note that block devices, sockets and links cannot be
* distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are
* only defined for compatibility. These macros should always return false
* on Windows.
*/
#if !defined(S_ISFIFO)
# define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO)
#endif
#if !defined(S_ISDIR)
# define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
#endif
#if !defined(S_ISREG)
# define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
#endif
#if !defined(S_ISLNK)
# define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
#endif
#if !defined(S_ISSOCK)
# define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK)
#endif
#if !defined(S_ISCHR)
# define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR)
#endif
#if !defined(S_ISBLK)
# define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK)
#endif
/* Return the exact length of the file name without zero terminator */
#define _D_EXACT_NAMLEN(p) ((p)->d_namlen)
/* Return the maximum size of a file name */
#define _D_ALLOC_NAMLEN(p) ((PATH_MAX)+1)
#ifdef __cplusplus
extern "C" {
#endif
/* Wide-character version */
struct _wdirent {
/* Always zero */
long d_ino;
/* File position within stream */
long d_off;
/* Structure size */
unsigned short d_reclen;
/* Length of name without \0 */
size_t d_namlen;
/* File type */
int d_type;
/* File name */
wchar_t d_name[PATH_MAX+1];
};
typedef struct _wdirent _wdirent;
struct _WDIR {
/* Current directory entry */
struct _wdirent ent;
/* Private file data */
WIN32_FIND_DATAW data;
/* True if data is valid */
int cached;
/* Win32 search handle */
HANDLE handle;
/* Initial directory name */
wchar_t *patt;
};
typedef struct _WDIR _WDIR;
/* Multi-byte character version */
struct dirent {
/* Always zero */
long d_ino;
/* File position within stream */
long d_off;
/* Structure size */
unsigned short d_reclen;
/* Length of name without \0 */
size_t d_namlen;
/* File type */
int d_type;
/* File name */
char d_name[PATH_MAX+1];
};
typedef struct dirent dirent;
struct DIR {
struct dirent ent;
struct _WDIR *wdirp;
};
typedef struct DIR DIR;
/* Dirent functions */
static DIR *opendir (const char *dirname);
static _WDIR *_wopendir (const wchar_t *dirname);
static struct dirent *readdir (DIR *dirp);
static struct _wdirent *_wreaddir (_WDIR *dirp);
static int readdir_r(
DIR *dirp, struct dirent *entry, struct dirent **result);
static int _wreaddir_r(
_WDIR *dirp, struct _wdirent *entry, struct _wdirent **result);
static int closedir (DIR *dirp);
static int _wclosedir (_WDIR *dirp);
static void rewinddir (DIR* dirp);
static void _wrewinddir (_WDIR* dirp);
static int scandir (const char *dirname, struct dirent ***namelist,
int (*filter)(const struct dirent*),
int (*compare)(const void *, const void *));
static int alphasort (const struct dirent **a, const struct dirent **b);
static int versionsort (const struct dirent **a, const struct dirent **b);
/* For compatibility with Symbian */
#define wdirent _wdirent
#define WDIR _WDIR
#define wopendir _wopendir
#define wreaddir _wreaddir
#define wclosedir _wclosedir
#define wrewinddir _wrewinddir
/* Internal utility functions */
static WIN32_FIND_DATAW *dirent_first (_WDIR *dirp);
static WIN32_FIND_DATAW *dirent_next (_WDIR *dirp);
static int dirent_mbstowcs_s(
size_t *pReturnValue,
wchar_t *wcstr,
size_t sizeInWords,
const char *mbstr,
size_t count);
static int dirent_wcstombs_s(
size_t *pReturnValue,
char *mbstr,
size_t sizeInBytes,
const wchar_t *wcstr,
size_t count);
static void dirent_set_errno (int error);
/*
* Open directory stream DIRNAME for read and return a pointer to the
* internal working area that is used to retrieve individual directory
* entries.
*/
static _WDIR*
_wopendir(
const wchar_t *dirname)
{
_WDIR *dirp = NULL;
int error;
/* Must have directory name */
if (dirname == NULL || dirname[0] == '\0') {
dirent_set_errno (ENOENT);
return NULL;
}
/* Allocate new _WDIR structure */
dirp = (_WDIR*) malloc (sizeof (struct _WDIR));
if (dirp != NULL) {
DWORD n;
/* Reset _WDIR structure */
dirp->handle = INVALID_HANDLE_VALUE;
dirp->patt = NULL;
dirp->cached = 0;
/* Compute the length of full path plus zero terminator
*
* Note that on WinRT there's no way to convert relative paths
* into absolute paths, so just assume its an absolute path.
*/
# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
n = wcslen(dirname);
# else
n = GetFullPathNameW (dirname, 0, NULL, NULL);
# endif
/* Allocate room for absolute directory name and search pattern */
dirp->patt = (wchar_t*) malloc (sizeof (wchar_t) * n + 16);
if (dirp->patt) {
/*
* Convert relative directory name to an absolute one. This
* allows rewinddir() to function correctly even when current
* working directory is changed between opendir() and rewinddir().
*
* Note that on WinRT there's no way to convert relative paths
* into absolute paths, so just assume its an absolute path.
*/
# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP)
wcsncpy_s(dirp->patt, n+1, dirname, n);
# else
n = GetFullPathNameW (dirname, n, dirp->patt, NULL);
# endif
if (n > 0) {
wchar_t *p;
/* Append search pattern \* to the directory name */
p = dirp->patt + n;
if (dirp->patt < p) {
switch (p[-1]) {
case '\\':
case '/':
case ':':
/* Directory ends in path separator, e.g. c:\temp\ */
/*NOP*/;
break;
default:
/* Directory name doesn't end in path separator */
*p++ = '\\';
}
}
*p++ = '*';
*p = '\0';
/* Open directory stream and retrieve the first entry */
if (dirent_first (dirp)) {
/* Directory stream opened successfully */
error = 0;
} else {
/* Cannot retrieve first entry */
error = 1;
dirent_set_errno (ENOENT);
}
} else {
/* Cannot retrieve full path name */
dirent_set_errno (ENOENT);
error = 1;
}
} else {
/* Cannot allocate memory for search pattern */
error = 1;
}
} else {
/* Cannot allocate _WDIR structure */
error = 1;
}
/* Clean up in case of error */
if (error && dirp) {
_wclosedir (dirp);
dirp = NULL;
}
return dirp;
}
/*
* Read next directory entry.
*
* Returns pointer to static directory entry which may be overwritted by
* subsequent calls to _wreaddir().
*/
static struct _wdirent*
_wreaddir(
_WDIR *dirp)
{
struct _wdirent *entry;
/*
* Read directory entry to buffer. We can safely ignore the return value
* as entry will be set to NULL in case of error.
*/
(void) _wreaddir_r (dirp, &dirp->ent, &entry);
/* Return pointer to statically allocated directory entry */
return entry;
}
/*
* Read next directory entry.
*
* Returns zero on success. If end of directory stream is reached, then sets
* result to NULL and returns zero.
*/
static int
_wreaddir_r(
_WDIR *dirp,
struct _wdirent *entry,
struct _wdirent **result)
{
WIN32_FIND_DATAW *datap;
/* Read next directory entry */
datap = dirent_next (dirp);
if (datap) {
size_t n;
DWORD attr;
/*
* Copy file name as wide-character string. If the file name is too
* long to fit in to the destination buffer, then truncate file name
* to PATH_MAX characters and zero-terminate the buffer.
*/
n = 0;
while (n < PATH_MAX && datap->cFileName[n] != 0) {
entry->d_name[n] = datap->cFileName[n];
n++;
}
entry->d_name[n] = 0;
/* Length of file name excluding zero terminator */
entry->d_namlen = n;
/* File type */
attr = datap->dwFileAttributes;
if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
entry->d_type = DT_CHR;
} else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
entry->d_type = DT_DIR;
} else {
entry->d_type = DT_REG;
}
/* Reset dummy fields */
entry->d_ino = 0;
entry->d_off = 0;
entry->d_reclen = sizeof (struct _wdirent);
/* Set result address */
*result = entry;
} else {
/* Return NULL to indicate end of directory */
*result = NULL;
}
return /*OK*/0;
}
/*
* Close directory stream opened by opendir() function. This invalidates the
* DIR structure as well as any directory entry read previously by
* _wreaddir().
*/
static int
_wclosedir(
_WDIR *dirp)
{
int ok;
if (dirp) {
/* Release search handle */
if (dirp->handle != INVALID_HANDLE_VALUE) {
FindClose (dirp->handle);
dirp->handle = INVALID_HANDLE_VALUE;
}
/* Release search pattern */
if (dirp->patt) {
free (dirp->patt);
dirp->patt = NULL;
}
/* Release directory structure */
free (dirp);
ok = /*success*/0;
} else {
/* Invalid directory stream */
dirent_set_errno (EBADF);
ok = /*failure*/-1;
}
return ok;
}
/*
* Rewind directory stream such that _wreaddir() returns the very first
* file name again.
*/
static void
_wrewinddir(
_WDIR* dirp)
{
if (dirp) {
/* Release existing search handle */
if (dirp->handle != INVALID_HANDLE_VALUE) {
FindClose (dirp->handle);
}
/* Open new search handle */
dirent_first (dirp);
}
}
/* Get first directory entry (internal) */
static WIN32_FIND_DATAW*
dirent_first(
_WDIR *dirp)
{
WIN32_FIND_DATAW *datap;
/* Open directory and retrieve the first entry */
dirp->handle = FindFirstFileExW(
dirp->patt, FindExInfoStandard, &dirp->data,
FindExSearchNameMatch, NULL, 0);
if (dirp->handle != INVALID_HANDLE_VALUE) {
/* a directory entry is now waiting in memory */
datap = &dirp->data;
dirp->cached = 1;
} else {
/* Failed to re-open directory: no directory entry in memory */
dirp->cached = 0;
datap = NULL;
}
return datap;
}
/*
* Get next directory entry (internal).
*
* Returns
*/
static WIN32_FIND_DATAW*
dirent_next(
_WDIR *dirp)
{
WIN32_FIND_DATAW *p;
/* Get next directory entry */
if (dirp->cached != 0) {
/* A valid directory entry already in memory */
p = &dirp->data;
dirp->cached = 0;
} else if (dirp->handle != INVALID_HANDLE_VALUE) {
/* Get the next directory entry from stream */
if (FindNextFileW (dirp->handle, &dirp->data) != FALSE) {
/* Got a file */
p = &dirp->data;
} else {
/* The very last entry has been processed or an error occured */
FindClose (dirp->handle);
dirp->handle = INVALID_HANDLE_VALUE;
p = NULL;
}
} else {
/* End of directory stream reached */
p = NULL;
}
return p;
}
/*
* Open directory stream using plain old C-string.
*/
static DIR*
opendir(
const char *dirname)
{
struct DIR *dirp;
int error;
/* Must have directory name */
if (dirname == NULL || dirname[0] == '\0') {
dirent_set_errno (ENOENT);
return NULL;
}
/* Allocate memory for DIR structure */
dirp = (DIR*) malloc (sizeof (struct DIR));
if (dirp) {
wchar_t wname[PATH_MAX + 1];
size_t n;
/* Convert directory name to wide-character string */
error = dirent_mbstowcs_s(
&n, wname, PATH_MAX + 1, dirname, PATH_MAX + 1);
if (!error) {
/* Open directory stream using wide-character name */
dirp->wdirp = _wopendir (wname);
if (dirp->wdirp) {
/* Directory stream opened */
error = 0;
} else {
/* Failed to open directory stream */
error = 1;
}
} else {
/*
* Cannot convert file name to wide-character string. This
* occurs if the string contains invalid multi-byte sequences or
* the output buffer is too small to contain the resulting
* string.
*/
error = 1;
}
} else {
/* Cannot allocate DIR structure */
error = 1;
}
/* Clean up in case of error */
if (error && dirp) {
free (dirp);
dirp = NULL;
}
return dirp;
}
/*
* Read next directory entry.
*/
static struct dirent*
readdir(
DIR *dirp)
{
struct dirent *entry;
/*
* Read directory entry to buffer. We can safely ignore the return value
* as entry will be set to NULL in case of error.
*/
(void) readdir_r (dirp, &dirp->ent, &entry);
/* Return pointer to statically allocated directory entry */
return entry;
}
/*
* Read next directory entry into called-allocated buffer.
*
* Returns zero on sucess. If the end of directory stream is reached, then
* sets result to NULL and returns zero.
*/
static int
readdir_r(
DIR *dirp,
struct dirent *entry,
struct dirent **result)
{
WIN32_FIND_DATAW *datap;
/* Read next directory entry */
datap = dirent_next (dirp->wdirp);
if (datap) {
size_t n;
int error;
/* Attempt to convert file name to multi-byte string */
error = dirent_wcstombs_s(
&n, entry->d_name, PATH_MAX + 1, datap->cFileName, PATH_MAX + 1);
/*
* If the file name cannot be represented by a multi-byte string,
* then attempt to use old 8+3 file name. This allows traditional
* Unix-code to access some file names despite of unicode
* characters, although file names may seem unfamiliar to the user.
*
* Be ware that the code below cannot come up with a short file
* name unless the file system provides one. At least
* VirtualBox shared folders fail to do this.
*/
if (error && datap->cAlternateFileName[0] != '\0') {
error = dirent_wcstombs_s(
&n, entry->d_name, PATH_MAX + 1,
datap->cAlternateFileName, PATH_MAX + 1);
}
if (!error) {
DWORD attr;
/* Length of file name excluding zero terminator */
entry->d_namlen = n - 1;
/* File attributes */
attr = datap->dwFileAttributes;
if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) {
entry->d_type = DT_CHR;
} else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) {
entry->d_type = DT_DIR;
} else {
entry->d_type = DT_REG;
}
/* Reset dummy fields */
entry->d_ino = 0;
entry->d_off = 0;
entry->d_reclen = sizeof (struct dirent);
} else {
/*
* Cannot convert file name to multi-byte string so construct
* an errornous directory entry and return that. Note that
* we cannot return NULL as that would stop the processing
* of directory entries completely.
*/
entry->d_name[0] = '?';
entry->d_name[1] = '\0';
entry->d_namlen = 1;
entry->d_type = DT_ALL_DICTS;
entry->d_ino = 0;
entry->d_off = -1;
entry->d_reclen = 0;
}
/* Return pointer to directory entry */
*result = entry;
} else {
/* No more directory entries */
*result = NULL;
}
return /*OK*/0;
}
/*
* Close directory stream.
*/
static int
closedir(
DIR *dirp)
{
int ok;
if (dirp) {
/* Close wide-character directory stream */
ok = _wclosedir (dirp->wdirp);
dirp->wdirp = NULL;
/* Release multi-byte character version */
free (dirp);
} else {
/* Invalid directory stream */
dirent_set_errno (EBADF);
ok = /*failure*/-1;
}
return ok;
}
/*
* Rewind directory stream to beginning.
*/
static void
rewinddir(
DIR* dirp)
{
/* Rewind wide-character string directory stream */
_wrewinddir (dirp->wdirp);
}
/*
* Scan directory for entries.
*/
static int
scandir(
const char *dirname,
struct dirent ***namelist,
int (*filter)(const struct dirent*),
int (*compare)(const void*, const void*))
{
struct dirent **files = NULL;
size_t size = 0;
size_t allocated = 0;
const size_t init_size = 1;
DIR *dir = NULL;
struct dirent *entry;
struct dirent *tmp = NULL;
size_t i;
int result = 0;
/* Open directory stream */
dir = opendir (dirname);
if (dir) {
/* Read directory entries to memory */
while (1) {
/* Enlarge pointer table to make room for another pointer */
if (size >= allocated) {
void *p;
size_t num_entries;
/* Compute number of entries in the enlarged pointer table */
if (size < init_size) {
/* Allocate initial pointer table */
num_entries = init_size;
} else {
/* Double the size */
num_entries = size * 2;
}
/* Allocate first pointer table or enlarge existing table */
p = realloc (files, sizeof (void*) * num_entries);
if (p != NULL) {
/* Got the memory */
files = (dirent**) p;
allocated = num_entries;
} else {
/* Out of memory */
result = -1;
break;
}
}
/* Allocate room for temporary directory entry */
if (tmp == NULL) {
tmp = (struct dirent*) malloc (sizeof (struct dirent));
if (tmp == NULL) {
/* Cannot allocate temporary directory entry */
result = -1;
break;
}
}
/* Read directory entry to temporary area */
if (readdir_r (dir, tmp, &entry) == /*OK*/0) {
/* Did we got an entry? */
if (entry != NULL) {
int pass;
/* Determine whether to include the entry in result */
if (filter) {
/* Let the filter function decide */
pass = filter (tmp);
} else {
/* No filter function, include everything */
pass = 1;
}
if (pass) {
/* Store the temporary entry to pointer table */
files[size++] = tmp;
tmp = NULL;
/* Keep up with the number of files */
result++;
}
} else {
/*
* End of directory stream reached => sort entries and
* exit.
*/
qsort (files, size, sizeof (void*), compare);
break;
}
} else {
/* Error reading directory entry */
result = /*Error*/ -1;
break;
}
}
} else {
/* Cannot open directory */
result = /*Error*/ -1;
}
/* Release temporary directory entry */
if (tmp) {
free (tmp);
}
/* Release allocated memory on error */
if (result < 0) {
for (i = 0; i < size; i++) {
free (files[i]);
}
free (files);
files = NULL;
}
/* Close directory stream */
if (dir) {
closedir (dir);
}
/* Pass pointer table to caller */
if (namelist) {
*namelist = files;
}
return result;
}
/* Alphabetical sorting */
static int
alphasort(
const struct dirent **a, const struct dirent **b)
{
return strcoll ((*a)->d_name, (*b)->d_name);
}
/* Sort versions */
static int
versionsort(
const struct dirent **a, const struct dirent **b)
{
/* FIXME: implement strverscmp and use that */
return alphasort (a, b);
}
/* Convert multi-byte string to wide character string */
static int
dirent_mbstowcs_s(
size_t *pReturnValue,
wchar_t *wcstr,
size_t sizeInWords,
const char *mbstr,
size_t count)
{
int error;
#if defined(_MSC_VER) && _MSC_VER >= 1400
/* Microsoft Visual Studio 2005 or later */
error = mbstowcs_s (pReturnValue, wcstr, sizeInWords, mbstr, count);
#else
/* Older Visual Studio or non-Microsoft compiler */
size_t n;
/* Convert to wide-character string (or count characters) */
n = mbstowcs (wcstr, mbstr, sizeInWords);
if (!wcstr || n < count) {
/* Zero-terminate output buffer */
if (wcstr && sizeInWords) {
if (n >= sizeInWords) {
n = sizeInWords - 1;
}
wcstr[n] = 0;
}
/* Length of resuting multi-byte string WITH zero terminator */
if (pReturnValue) {
*pReturnValue = n + 1;
}
/* Success */
error = 0;
} else {
/* Could not convert string */
error = 1;
}
#endif
return error;
}
/* Convert wide-character string to multi-byte string */
static int
dirent_wcstombs_s(
size_t *pReturnValue,
char *mbstr,
size_t sizeInBytes, /* max size of mbstr */
const wchar_t *wcstr,
size_t count)
{
int error;
#if defined(_MSC_VER) && _MSC_VER >= 1400
/* Microsoft Visual Studio 2005 or later */
error = wcstombs_s (pReturnValue, mbstr, sizeInBytes, wcstr, count);
#else
/* Older Visual Studio or non-Microsoft compiler */
size_t n;
/* Convert to multi-byte string (or count the number of bytes needed) */
n = wcstombs (mbstr, wcstr, sizeInBytes);
if (!mbstr || n < count) {
/* Zero-terminate output buffer */
if (mbstr && sizeInBytes) {
if (n >= sizeInBytes) {
n = sizeInBytes - 1;
}
mbstr[n] = '\0';
}
/* Length of resulting multi-bytes string WITH zero-terminator */
if (pReturnValue) {
*pReturnValue = n + 1;
}
/* Success */
error = 0;
} else {
/* Cannot convert string */
error = 1;
}
#endif
return error;
}
/* Set errno variable */
static void
dirent_set_errno(
int error)
{
#if defined(_MSC_VER) && _MSC_VER >= 1400
/* Microsoft Visual Studio 2005 and later */
_set_errno (error);
#else
/* Non-Microsoft compiler or older Microsoft compiler */
errno = error;
#endif
}
#ifdef __cplusplus
}
#endif
#endif /*DIRENT_H*/
#else
#include <dirent.h>
#endif
// #endifxx
class DirReader{
public:
static std::vector<std::string> read(std::string path){
DIR *dir;
struct dirent *ent;
std::vector<std::string> res;
if ((dir = opendir (path.c_str())) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL)
res.push_back(path+std::string("/")+std::string(ent->d_name));
closedir (dir);
}
//check
return res;
}
};
#endif
| [
"1808511884@qq.com"
] | 1808511884@qq.com |
9c0f9d20ffd85cb428f36eb6bdc36c2c3ccf3875 | 00ae45df298f0fde0840ecbc8f4b633d5d1f380d | /linestyle.h | 2379ef9a80dc0d5f82f851db8d1be177afb91ad8 | [] | no_license | sh894/Bresenham_Draw_Line_Algorithm | 9dcde8845acbb399a3b6df286279441ae7bfc3c8 | 5b24cdebe39d723db24fbcf28d47271369cdfbab | refs/heads/master | 2020-05-20T09:29:34.604204 | 2015-02-09T02:53:37 | 2015-02-09T02:53:37 | 30,430,212 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 403 | h | #ifndef LINESTYLE_H
#define LINESTYLE_H
#include <QLineEdit>
#include <QDialog>
class LineStyle : public QDialog
{
Q_OBJECT
public:
LineStyle(QWidget *parent = 0);
~LineStyle();
signals:
/*
A signal to indicate when the values are updated
*/
void stylevaluesUpdated(int x);
private:
QLineEdit *editX;
private slots:
void getValues();
};
#endif // LINESTYLE_H
| [
"sh894@mail.missouri.edu"
] | sh894@mail.missouri.edu |
2ba8747c26f13c9c33896d0b139249ac93b5cf9e | 728e57a80995d7be98d46295b780d0b433c9e62a | /src/rewriter/symbol_rewriter_test.cc | d730441e42780ad506163844608055297c0a9949 | [
"Apache-2.0",
"MIT",
"BSD-3-Clause",
"GPL-1.0-or-later"
] | permissive | SNQ-2001/Mozc-for-iOS | 7936bfd9ff024faacfd2d96af3ec15a2000378a1 | 45b0856ed8a22d5fa6b4471548389cbde4abcf10 | refs/heads/master | 2023-03-17T22:19:15.843107 | 2014-10-04T05:48:29 | 2014-10-04T05:48:42 | 574,371,060 | 0 | 0 | Apache-2.0 | 2022-12-05T06:48:07 | 2022-12-05T06:48:06 | null | UTF-8 | C++ | false | false | 10,549 | cc | // Copyright 2010-2014, Google Inc.
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "rewriter/symbol_rewriter.h"
#include <string>
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "base/system_util.h"
#include "base/util.h"
#include "config/config.pb.h"
#include "config/config_handler.h"
#include "converter/conversion_request.h"
#include "converter/segments.h"
#include "data_manager/testing/mock_data_manager.h"
#include "engine/engine_interface.h"
#include "engine/mock_data_engine_factory.h"
#include "session/commands.pb.h"
#include "testing/base/public/gunit.h"
DECLARE_string(test_tmpdir);
namespace mozc {
namespace {
void AddSegment(const string &key, const string &value,
Segments *segments) {
Segment *seg = segments->push_back_segment();
seg->set_key(key);
Segment::Candidate *candidate = seg->add_candidate();
candidate->Init();
candidate->value = key;
candidate->content_key = key;
candidate->content_value = value;
}
void AddCandidate(const string &value, Segment *segment) {
Segment::Candidate *candidate = segment->add_candidate();
candidate->Init();
candidate->value = value;
candidate->content_key = segment->key();
candidate->content_value = value;
}
bool HasCandidateAndDescription(const Segments &segments,
int index,
const string &key,
const string &description) {
CHECK_GT(segments.segments_size(), index);
bool check_description = !description.empty();
for (size_t i = 0; i < segments.segment(index).candidates_size(); ++i) {
const Segment::Candidate &candidate = segments.segment(index).candidate(i);
if (candidate.value == key) {
if (check_description) {
bool result = candidate.description == description;
return result;
} else {
return true;
}
}
}
return false;
}
bool HasCandidate(const Segments &segments, int index, const string &value) {
return HasCandidateAndDescription(segments, index, value, "");
}
} // namespace
class SymbolRewriterTest : public ::testing::Test {
protected:
SymbolRewriterTest() {}
~SymbolRewriterTest() {}
virtual void SetUp() {
SystemUtil::SetUserProfileDirectory(FLAGS_test_tmpdir);
config::Config config;
config::ConfigHandler::GetDefaultConfig(&config);
config::ConfigHandler::SetConfig(config);
// We cannot use mock converter here because SymbolRewriter uses
// ResizeSegment of converter implementation. However, SymbolRewriter is
// independent of underlying dictionary and, hence, we can use a converter
// with mock data.
engine_.reset(MockDataEngineFactory::Create());
converter_ = engine_->GetConverter();
data_manager_.reset(new testing::MockDataManager);
}
virtual void TearDown() {
// Just in case, reset the config in test_tmpdir
config::Config config;
config::ConfigHandler::GetDefaultConfig(&config);
config::ConfigHandler::SetConfig(config);
}
scoped_ptr<EngineInterface> engine_;
const ConverterInterface *converter_;
scoped_ptr<testing::MockDataManager> data_manager_;
};
// Note that these tests are using default symbol dictionary.
// Test result can be changed if symbol dictionary is modified.
// TODO(toshiyuki): Modify symbol rewriter so that we can use symbol dictionary
// for testing.
TEST_F(SymbolRewriterTest, TriggerRewriteTest) {
SymbolRewriter symbol_rewriter(converter_, data_manager_.get());
const ConversionRequest request;
{
Segments segments;
// "ー"
AddSegment("\xe3\x83\xbc", "test", &segments);
// ">"
AddSegment("\x3e", "test", &segments);
EXPECT_TRUE(symbol_rewriter.Rewrite(request, &segments));
// "→"
EXPECT_TRUE(HasCandidate(segments, 0, "\xe2\x86\x92"));
}
{
Segments segments;
// "ー"
AddSegment("\xe3\x83\xbc", "test", &segments);
// "ー"
AddSegment("\xe3\x83\xbc", "test", &segments);
EXPECT_TRUE(symbol_rewriter.Rewrite(request, &segments));
// "―"
EXPECT_TRUE(HasCandidate(segments, 0, "\xe2\x80\x95"));
// "―"
EXPECT_TRUE(HasCandidate(segments, 1, "\xe2\x80\x95"));
}
}
TEST_F(SymbolRewriterTest, TriggerRewriteEntireTest) {
SymbolRewriter symbol_rewriter(converter_, data_manager_.get());
const ConversionRequest request;
{
Segments segments;
// "ー"
AddSegment("\xe3\x83\xbc", "test", &segments);
// ">"
AddSegment("\x3e", "test", &segments);
EXPECT_TRUE(symbol_rewriter.RewriteEntireCandidate(request, &segments));
// "→"
EXPECT_TRUE(HasCandidate(segments, 0, "\xe2\x86\x92"));
}
{
Segments segments;
// "ー"
AddSegment("\xe3\x83\xbc", "test", &segments);
// "ー"
AddSegment("\xe3\x83\xbc", "test", &segments);
EXPECT_FALSE(symbol_rewriter.RewriteEntireCandidate(request, &segments));
}
}
TEST_F(SymbolRewriterTest, TriggerRewriteEachTest) {
SymbolRewriter symbol_rewriter(converter_, data_manager_.get());
{
Segments segments;
// "ー"
AddSegment("\xe3\x83\xbc", "test", &segments);
// ">"
AddSegment("\x3e", "test", &segments);
EXPECT_TRUE(symbol_rewriter.RewriteEachCandidate(&segments));
EXPECT_EQ(2, segments.segments_size());
// "―"
EXPECT_TRUE(HasCandidate(segments, 0, "\xe2\x80\x95"));
// "→"
EXPECT_FALSE(HasCandidate(segments, 0, "\xe2\x86\x92"));
// "〉"
EXPECT_TRUE(HasCandidate(segments, 1, "\xe3\x80\x89"));
}
}
TEST_F(SymbolRewriterTest, TriggerRewriteDescriptionTest) {
SymbolRewriter symbol_rewriter(converter_, data_manager_.get());
{
Segments segments;
// "したつき"
AddSegment("\xE3\x81\x97\xE3\x81\x9F\xE3\x81\xA4\xE3\x81\x8D",
"test", &segments);
EXPECT_TRUE(symbol_rewriter.RewriteEachCandidate(&segments));
EXPECT_EQ(1, segments.segments_size());
// "₍"
EXPECT_TRUE(HasCandidateAndDescription(segments, 0, "\xE2\x82\x8D",
// "下付き文字(始め丸括弧)"
"\xE4\xB8\x8B\xE4\xBB\x98\xE3\x81\x8D\xE6\x96\x87\xE5\xAD\x97"
"("
"\xE5\xA7\x8B\xE3\x82\x81\xE4\xB8\xB8\xE6\x8B\xAC\xE5\xBC\xA7"
")"));
}
}
TEST_F(SymbolRewriterTest, InsertAfterSingleKanjiAndT13n) {
SymbolRewriter symbol_rewriter(converter_, data_manager_.get());
const ConversionRequest request;
{
Segments segments;
// "てん", "てん"
AddSegment("\xe3\x81\xa6\xe3\x82\x93", "\xe3\x81\xa6\xe3\x82\x93",
&segments);
Segment *seg = segments.mutable_segment(0);
// Add 15 single-kanji and transliterated candidates
// "点"
AddCandidate("\xe7\x82\xb9", seg);
// "転"
AddCandidate("\xe8\xbb\xa2", seg);
// "天"
AddCandidate("\xe5\xa4\xa9", seg);
// "てん"
AddCandidate("\xe3\x81\xa6\xe3\x82\x93", seg);
// "テン"
AddCandidate("\xe3\x83\x86\xe3\x83\xb3", seg);
// "展"
AddCandidate("\xe5\xb1\x95", seg);
// "店"
AddCandidate("\xe5\xba\x97", seg);
// "典"
AddCandidate("\xe5\x85\xb8", seg);
// "添"
AddCandidate("\xe6\xb7\xbb", seg);
// "填"
AddCandidate("\xe5\xa1\xab", seg);
// "顛"
AddCandidate("\xe9\xa1\x9b", seg);
// "辿"
AddCandidate("\xe8\xbe\xbf", seg);
// "纏"
AddCandidate("\xe7\xba\x8f", seg);
// "甜"
AddCandidate("\xe7\x94\x9c", seg);
// "貼"
AddCandidate("\xe8\xb2\xbc", seg);
EXPECT_TRUE(symbol_rewriter.Rewrite(request, &segments));
EXPECT_GT(segments.segment(0).candidates_size(), 16);
for (int i = 0; i < 16; ++i) {
const string &value = segments.segment(0).candidate(i).value;
EXPECT_FALSE(Util::IsScriptType(value, Util::UNKNOWN_SCRIPT))
<< i << ": " << value;
}
}
}
TEST_F(SymbolRewriterTest, SetKey) {
SymbolRewriter symbol_rewriter(converter_, data_manager_.get());
Segments segments;
const ConversionRequest request;
Segment *segment = segments.push_back_segment();
// "てん"
const string kKey = "\xe3\x81\xa6\xe3\x82\x93";
segment->set_key(kKey);
Segment::Candidate *candidate = segment->add_candidate();
candidate->Init();
candidate->key = "strange key";
candidate->value = "strange value";
candidate->content_key = "strange key";
candidate->content_value = "strange value";
EXPECT_EQ(1, segment->candidates_size());
EXPECT_TRUE(symbol_rewriter.Rewrite(request, &segments));
EXPECT_GT(segment->candidates_size(), 1);
for (size_t i = 1; i < segment->candidates_size(); ++i) {
EXPECT_EQ(kKey, segment->candidate(i).key);
}
}
TEST_F(SymbolRewriterTest, MobileEnvironmentTest) {
commands::Request input;
SymbolRewriter rewriter(converter_, data_manager_.get());
{
input.set_mixed_conversion(true);
const ConversionRequest request(NULL, &input);
EXPECT_EQ(RewriterInterface::ALL, rewriter.capability(request));
}
{
input.set_mixed_conversion(false);
const ConversionRequest request(NULL, &input);
EXPECT_EQ(RewriterInterface::CONVERSION, rewriter.capability(request));
}
}
} // namespace mozc
| [
"kishikawakatsumi@mac.com"
] | kishikawakatsumi@mac.com |
cce7edf451a3433fc1a378a7f536a22b8a192a30 | df35c3b9370c03b69d554f268ac503122f51fa4d | /uva/11902-Dominator.cpp | 508c645b8bdc59a0bb97422d0839b656606472ad | [] | no_license | avijit1258/CompetitiveProgramming | 04715b7e55d2ecfcf43b5856f714c6e7f908b2ec | b79a5dabddb016a12a74a7990ae262333f64821b | refs/heads/master | 2021-06-26T16:06:40.684698 | 2017-12-26T08:30:45 | 2017-12-26T08:30:45 | 97,233,852 | 0 | 3 | null | 2020-10-01T16:36:55 | 2017-07-14T12:56:31 | C++ | UTF-8 | C++ | false | false | 3,179 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
int V;
vector<vii> AdjList;
bitset<105> initVisited, curVisited;
bool first;
void graph_input()
{
int choice;
cin >> V;
AdjList.assign(V, vii());
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
cin >> choice;
if(choice == 1)
{
AdjList[i].push_back(ii(j, 1));
}
}
}
}
void dfs(int u, int del)
{
bitset<105> *visited;
if(first)
visited = &initVisited;
else
visited = &curVisited;
visited->set(u);
if(u == del)
return;
for(int i = 0; i < (int)AdjList[u].size() ; i++)
{
pair<int,int> v = AdjList[u][i];
if(!visited->test(v.first))
{
dfs(v.first, del);
}
}
}
int main(int argc, char const *argv[]) {
int tc, count = 1;
cin >> tc;
while(tc--)
{
graph_input();
first = true;
for(int k = 0; k < V ; k++)
initVisited.reset(k);
dfs(0, V);
first = false;
printf("Case %d:\n", count++);
for(int l = 0; l < V; l++)
{
for(int k = 0; k < V ; k++)
curVisited.reset(k);
dfs(0, l);
printf("+" );
for(int j = 0; j < 2 * V - 1 ; j++)
printf("-");
printf("+\n|");
for(int j = 0; j < V ; j++)
if(initVisited.test(j) && ((l == j) || (!curVisited.test(j))))
printf("Y|");
else
printf("N|");
printf("\n");
}
printf("+" );
for(int j = 0; j < 2 * V - 1 ; j++)
printf("-" );
printf("+\n");
}
int c;
cin >> c;
return 0;
}
// code to learn from
/*
#include <cstdio>
#include <bitset>
#include <vector>
#include <cstring>
using namespace std;
typedef vector<int> vi;
int V, tc, count = 1;
vector<vi> AdjList;
bitset<105> initVisited, curVisited;
bool first;
void dfs(int u, int del) {
bitset<105> *visited;
if (first)
visited = &initVisited;
else
visited = &curVisited;
visited->set(u);
if (u == del)
return;
for (int i = 0; i < (int) AdjList[u].size(); i++) {
int v = AdjList[u][i];
if (!visited->test(v))
dfs(v, del);
}
}
int main() {
scanf("%d", &tc);
while (tc--) {
scanf("%d", &V);
AdjList.assign(V, vi());
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
int e;
scanf("%d", &e);
if (e)
AdjList[i].push_back(j);
}
}
first = true;
for (int i = 0; i < V; i++)
initVisited.reset(i);
dfs(0, V);
first = false;
printf("Case %d:", count++);
for (int i = 0; i < V; i++) {
for (int k = 0; k < V; k++)
curVisited.reset(k);
dfs(0, i);
printf("\n+");
for (int j = 0; j < V * 2 - 1; j++) {
printf("-");
}
printf("+\n|");
for (int j = 0; j < V; j++) {
if (initVisited.test(j) && (i == j || !curVisited.test(j)))
printf("Y");
else
printf("N");
printf("|");
}
}
printf("\n+");
for (int j = 0; j < V * 2 - 1; j++) {
printf("-");
}
printf("+\n");
}
return 0;
}
*/
| [
"avijitbhatt1258@gmail.com"
] | avijitbhatt1258@gmail.com |
389734510d9f84ff0b6b9256f329b68acb61c583 | 7385ebf2885605dd5e2af634328d8f46355701cd | /applications/Backtracking/NQueens/src/main.cpp | 4542930677583a799d4d15ab1d9fd38fbd554cad | [] | no_license | purplebrain/cplusplus | 2479df4cbb425813f776347b7f68e207ef6f28dd | b79459c763b9267fcd237a4ef03d18e3ab3dfc48 | refs/heads/master | 2021-07-21T01:34:22.130186 | 2020-04-29T05:24:20 | 2020-04-29T05:24:20 | 135,749,971 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,898 | cpp | #include <iostream>
#include <cmath>
#include <vector>
using namespace std;
unsigned int gN;
unsigned int **gArrBoard;
typedef struct POINT {
public:
int X;
int Y;
POINT (int X, int Y)
{
this->X = X;
this->Y = Y;
}
} POINT;
void
printPartialVector (vector<POINT>& vecPartial)
{
cout << " vecPartial = [";
for (vector<POINT>::iterator itr = vecPartial.begin();
itr != vecPartial.end();
itr++) {
cout << " (" << itr->X << "," << itr->Y << ")";
}
cout << "]";
}
void
cleanup (void)
{
for (int i = 0; i < gN; i++) {
delete [] gArrBoard[i];
}
}
void
init (void)
{
gArrBoard = new unsigned int*[gN];
for (int i = 0; i < gN; i++) {
gArrBoard[i] = new unsigned int[gN];
fill_n(gArrBoard[i], gN, 0);
}
return;
}
void
printSolution (void)
{
cout << "########" << endl;
for (int i = 0; i < gN; i++) {
for (int j = 0; j < gN; j++) {
cout << gArrBoard[i][j] << " ";
}
cout << endl;
}
cout << "########" << endl;
}
bool
isConstraintSatisfied (vector<POINT>& vecPartial)
{
if (vecPartial.size() == gN) {
return (true);
} else {
return (false);
}
}
bool
NQueen (int idxRow, int idxCol, vector<POINT> vecPartial)
{
// [ EXIT CONDITION ]
if ((idxRow == gN) || (idxCol == gN)) {
return (true);
}
// [ UPDATE PARTIALS ]
POINT tmp(-1,-1);
tmp.X = idxRow;
tmp.Y = idxCol;
vecPartial.push_back(tmp);
gArrBoard[tmp.X][tmp.Y] = 1;
// [ CONSTRAINT CHECK ]
if (isConstraintSatisfied(vecPartial)) {
// SUCCESS
return (true);
} else {
// FAILURE (go to next state)
// CONDITION CHECK TO PICK NEXT STATE
for (int col = 0; col < gN; col++) {
POINT tmp(idxRow+1, col);
bool isGood2Pick = false;
for (int i = 0; i < vecPartial.size(); i++) {
if (!(((vecPartial[i].X == tmp.X) || (vecPartial[i].Y == tmp.Y)) ||
(abs(vecPartial[i].X-tmp.X) == abs(vecPartial[i].Y-tmp.Y)))) {
isGood2Pick = true;
continue;
} else {
isGood2Pick = false;
break;
}
}
if (isGood2Pick) {
// GO TO NEXT STATE
if (!NQueen(idxRow+1, col, vecPartial)) {
continue;
} else {
return (true);
}
}
}
POINT tmp1 = vecPartial[vecPartial.size() - 1];
vecPartial.pop_back();
gArrBoard[tmp1.X][tmp1.Y] = 0;
return (false);
}
}
void
NQueen (void)
{
vector<POINT> vecPartial;
// [ LOOP OVER BASE STATES ]
for (int j = 0; j < gN; j++) {
if (!NQueen(0, j, vecPartial)) {
continue;
} else {
return;
}
}
}
int
main (int argc, char *argv[])
{
while (1) {
cout << endl;
cout << "====================================" << endl;
cout << "Enter number of Queens : "; cin >> gN;
init();
NQueen();
printSolution();
cleanup();
}
return (0);
}
| [
"reach4msd@gmail.com"
] | reach4msd@gmail.com |
4941282447739fa3ad7dfe320f469740608776a6 | 6484dc45cfadb1048a3a02cf8790794032404bdc | /cpp/ThingThroughput/src/ThroughputWriter.cpp | f86ce47f316df46c0caba4e2acf6e786442cf922 | [] | no_license | aswinvk28/edge_sdk_examples | fd8cb70463eebeed5d11894eae2f27f93ef7480d | 354c0b526d3dbaf49281d26668f6d6e55d1b3154 | refs/heads/main | 2023-03-12T13:18:27.162609 | 2021-02-28T17:38:22 | 2021-02-28T17:38:22 | 343,169,460 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,955 | cpp | /* ADLINK Edge SDK
*
* This software and documentation are Copyright 2018 to 2020 ADLINK
* Technology Limited, its affiliated companies and licensors. 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.
*
*/
/**
* This is a simple throughput application measuring obtainable throughput using the thingSDK
*/
#include <atomic>
#include <chrono>
#include <cstring>
#include <iostream>
#include <signal.h>
#include <sstream>
#include <stdlib.h>
#include <thread>
#include <time.h>
#ifdef _WIN32
#include <Windows.h>
#endif
#include <IoTDataThing.hpp>
#include <JSonThingAPI.hpp>
#include <ThingAPIException.hpp>
#include "include/cxxopts.hpp"
#include "include/utilities.h"
using namespace std;
using namespace com::adlinktech::datariver;
using namespace com::adlinktech::iot;
#ifdef _WIN32
static bool ctrlHandler(DWORD fdwCtrlType)
{
stop = true;
return true;
}
#else
static void ctrlHandler(int fdwCtrlType)
{
stop = true;
}
#endif
// Writer mode:
// standard = use default write function
// outputHandler = use output handler for writing
// outputHandlerNotThreadSafe = use non-thread-safe write method for output handler
enum WriterMode {
standard,
outputHandler,
outputHandlerNotThreadSafe
};
class ThroughputWriter {
private:
string m_thingPropertiesUri;
DataRiver m_dataRiver = createDataRiver();
Thing m_thing = createThing();
IOT_NVP_SEQ m_sample;
DataRiver createDataRiver() {
return DataRiver::getInstance();
}
Thing createThing() {
// Create and Populate the TagGroup registry with JSON resource files.
JSonTagGroupRegistry tgr;
tgr.registerTagGroupsFromURI("file://definitions/TagGroup/com.adlinktech.example/ThroughputTagGroup.json");
m_dataRiver.addTagGroupRegistry(tgr);
// Create and Populate the ThingClass registry with JSON resource files.
JSonThingClassRegistry tcr;
tcr.registerThingClassesFromURI("file://definitions/ThingClass/com.adlinktech.example/ThroughputWriterThingClass.json");
m_dataRiver.addThingClassRegistry(tcr);
// Create a Thing based on properties specified in a JSON resource file.
JSonThingProperties tp;
tp.readPropertiesFromURI(m_thingPropertiesUri);
return m_dataRiver.createThing(tp);
}
void setupMessage(unsigned long payloadSize) {
IOT_VALUE sequencenumber_v;
IOT_VALUE sequencedata_v;
// Init sequence number and size Tags
sequencenumber_v.iotv_uint64(0);
// Init data Tag
IOT_BYTE_SEQ sequencedata = IOT_BYTE_SEQ();
for(unsigned long i = 0; i < payloadSize; i++)
{
sequencedata.push_back('a');
}
sequencedata_v.iotv_byte_seq(sequencedata);
// Create sample
m_sample = {
IOT_NVP("sequencenumber", sequencenumber_v),
IOT_NVP("sequencedata", sequencedata_v)
};
}
void waitForReader() {
// wait for throughputreader to appear by discovering its thingId and thingClass
cout << "Waiting for Throughput reader.. " << endl;
DiscoveredThingRegistry discoveredThingRegistry = m_dataRiver.getDiscoveredThingRegistry();
bool readerFound = false;
while (!readerFound && !stop)
{
try
{
auto thing = discoveredThingRegistry.findDiscoveredThing("*", "ThroughputReader:com.adlinktech.example:v1.0");
readerFound = true;
}
catch (...)
{
// Thing not available yet
}
this_thread::sleep_for(chrono::milliseconds(100));
}
if (!stop) {
cout << "Throughput reader found" << endl;
} else {
cout << "Terminated" << endl;
exit(1);
}
}
void write(unsigned long burstInterval, unsigned long burstSize, unsigned long runningTime, WriterMode mode) {
unsigned long burstCount = 0;
unsigned long count = 0;
bool timedOut = false;
unsigned long long deltaTime;
Timepoint pubStart = Clock::now();
Timepoint burstStart = Clock::now();
Timepoint currentTime = Clock::now();
Thing::OutputHandler outputHandler = m_thing.getOutputHandler("ThroughputOutput");
IOT_VALUE *internal_sequencenumber_v;
if (mode == WriterMode::outputHandlerNotThreadSafe) {
outputHandler.setNonReentrantFlowID(m_thing.getContextId());
IOT_NVP_SEQ &internal_nvp_seq = outputHandler.setupNonReentrantNVPSeq(m_sample);
IOT_NVP &internal_sequencenumber_nvp = internal_nvp_seq[0];
internal_sequencenumber_v = &internal_sequencenumber_nvp.value();
}
while (!stop && !timedOut)
{
// Write data until burst size has been reached
if (burstCount++ < burstSize) {
if (mode == WriterMode::outputHandler) {
// Fill the nvp_seq with updated sequencenr
m_sample[0].value().iotv_uint64(count++);
// Write the data using output handler
outputHandler.write(m_sample);
} else if (mode == WriterMode::outputHandlerNotThreadSafe) {
// Fill the nvp_seq with updated sequencenr
internal_sequencenumber_v->iotv_uint64(count++);
// Write the data using non-reentrant write on output handler
outputHandler.writeNonReentrant();
} else {
// Fill the nvp_seq with updated sequencenr
m_sample[0].value().iotv_uint64(count++);
// Write the data
m_thing.write("ThroughputOutput", m_sample);
}
} else if (burstInterval != 0) {
// Sleep until burst interval has passed
currentTime = Clock::now();
deltaTime = Duration<Milliseconds>(currentTime - burstStart);
if (deltaTime < burstInterval)
{
this_thread::sleep_for(chrono::milliseconds(burstInterval - deltaTime));
}
burstStart = Clock::now();
burstCount = 0;
} else {
burstCount = 0;
}
// Check of timeout
if (runningTime != 0) {
currentTime = Clock::now();
if (Duration<Seconds>(currentTime - pubStart) > runningTime) {
timedOut = true;
}
}
}
// Show stats
if (stop) {
std::cout << "Terminated: " << count << " samples written" << std::endl;
} else {
std::cout << "Timed out: " << count << " samples written" << std::endl;
}
}
public:
ThroughputWriter(string thingPropertiesUri) :
m_thingPropertiesUri(thingPropertiesUri)
{
cout << "Throughput writer started" << endl;
}
~ThroughputWriter() {
m_dataRiver.close();
cout << "Throughput writer stopped" << endl;
}
int run(unsigned long payloadSize, unsigned long burstInterval, unsigned long burstSize, unsigned long runningTime, WriterMode writerMode) {
string writerModeStr = (writerMode == WriterMode::outputHandler) ?
"outputHandler" : ((writerMode == WriterMode::outputHandlerNotThreadSafe) ?
"outputHandlerNotThreadSafe" : "standard");
cout << "payloadSize: " << payloadSize << " | burstInterval: " << burstInterval
<< " | burstSize: " << burstSize << " | runningTime: " << runningTime
<< " | writer-mode: " << writerModeStr << endl;
// Wait for reader to be discovered
waitForReader();
// Create the message that is sent
setupMessage(payloadSize);
// Write data
write(burstInterval, burstSize, runningTime, writerMode);
// Give middleware some time to finish writing samples
this_thread::sleep_for(chrono::seconds(2));
return 0;
}
};
static void GetCommandLineParameters(int argc, char *argv[],
unsigned long& payloadSize,
unsigned long& burstInterval,
unsigned long& burstSize,
unsigned long& runningTime,
WriterMode& writerMode
) {
cxxopts::Options options("ThroughputWriter", "ADLINK ThingSDK ThroughputWriter");
try {
options.add_options()
("p,payload-size", "Payload size", cxxopts::value<unsigned long>()->default_value("4096"))
("b,burst-interval", "Burst interval in milliseconds", cxxopts::value<unsigned long>()->default_value("0"))
("s,burst-size", "Burst size", cxxopts::value<unsigned long>()->default_value("1"))
("r,running-time", "Running Time in seconds (0 is infinite)", cxxopts::value<unsigned long>()->default_value("0"))
("w,writer-mode", "Writer mode (standard, outputHandler, outputHandlerNotThreadSafe)", cxxopts::value<string>()->default_value("standard"))
("h,help", "Print help")
;
options.parse_positional({"payload-size", "burst-interval", "burst-size", "running-time", "writer-mode", "other"});
options.positional_help("[payload-size] [burst-interval] [burst-size] [running-time]");
auto cmdLineOptions = options.parse(argc, argv);
if (cmdLineOptions.count("help")) {
cout << options.help({""}) << endl;
exit(0);
}
payloadSize = cmdLineOptions["p"].as<unsigned long>();
burstInterval = cmdLineOptions["b"].as<unsigned long>();
burstSize = cmdLineOptions["s"].as<unsigned long>();
runningTime = cmdLineOptions["r"].as<unsigned long>();
if (cmdLineOptions["w"].as<string>() == "outputHandler") {
writerMode = WriterMode::outputHandler;
} else if (cmdLineOptions["w"].as<string>() == "outputHandlerNotThreadSafe") {
writerMode = WriterMode::outputHandlerNotThreadSafe;
} else if (cmdLineOptions["w"].as<string>() == "standard") {
writerMode = WriterMode::standard;
} else {
cerr << "Invalid writer-mode" << endl << endl;
cout << options.help({""}) << endl;
exit(1);
}
}
catch (cxxopts::OptionException e) {
cerr << e.what() << endl << endl;
cout << options.help({""}) << endl;
exit(1);
}catch(std::exception& e1){
cerr << "An unexpected error occurred: " << e1.what() << endl;
}
}
int main(int argc, char *argv[]) {
// Get command line parameters
unsigned long payloadSize;
unsigned long burstInterval;
unsigned long burstSize;
unsigned long runningTime;
WriterMode writerMode = WriterMode::standard;
GetCommandLineParameters(argc, argv, payloadSize, burstInterval, burstSize, runningTime, writerMode);
// Register handler for Ctrl-C
registerControlHandler();
try
{
return ThroughputWriter("file://./config/ThroughputWriterProperties.json")
.run(payloadSize, burstInterval, burstSize, runningTime, writerMode);
}
catch (ThingAPIException e)
{
cerr << "An unexpected error occurred: " << e.what() << endl;
}
unregisterControlHandler();
}
| [
"aswinkvj@gmail.com"
] | aswinkvj@gmail.com |
43b97ac5f6f4518ffb5eb22c2a6c3fb5812c446f | cf8ddfc720bf6451c4ef4fa01684327431db1919 | /SDK/ARKSurvivalEvolved_PrimalItemSkin_CorruptedHelmet_classes.hpp | 47a2eba3670cb1d3340abfb9c603addeb4b82b1e | [
"MIT"
] | permissive | git-Charlie/ARK-SDK | 75337684b11e7b9f668da1f15e8054052a3b600f | c38ca9925309516b2093ad8c3a70ed9489e1d573 | refs/heads/master | 2023-06-20T06:30:33.550123 | 2021-07-11T13:41:45 | 2021-07-11T13:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 863 | hpp | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PrimalItemSkin_CorruptedHelmet_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass PrimalItemSkin_CorruptedHelmet.PrimalItemSkin_CorruptedHelmet_C
// 0x0000 (0x0AE0 - 0x0AE0)
class UPrimalItemSkin_CorruptedHelmet_C : public UPrimalItemSkinGeneric_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass PrimalItemSkin_CorruptedHelmet.PrimalItemSkin_CorruptedHelmet_C");
return ptr;
}
void ExecuteUbergraph_PrimalItemSkin_CorruptedHelmet(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
690d6df71a673ba71481f08f68d18ae06201fb97 | 5cd0b6d481170656e7046abafa891ed30058b8b6 | /UnitTest_RayTracer/vector_tests.cc | 31d7f810a090a6dc14d7b471c69986213f841743 | [] | no_license | JabberSnatch/pbr_pathtracer | c815c65e45e4c707478a3475356017155fc9ad36 | 0d82f40cb2e00e6767df270e266010840a7aee75 | refs/heads/master | 2021-01-19T02:47:04.157734 | 2018-03-02T18:35:36 | 2018-03-02T18:35:36 | 87,292,622 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,395 | cc | #include "gtest/gtest.h"
#include "maths/vector.h"
#include "global_definitions.h"
template <typename T>
class FloatVectorTest : public ::testing::Test
{
protected:
FloatVectorTest()
: scalar{ 3._d }
{
for (uint32_t i = 0; i < test_vector.size; ++i)
{
test_vector[i] = maths::Decimal(i + 1);
vector[i] = maths::Decimal(i + 1) * 2;
}
}
using tested_type = T;
T test_vector;
maths::Decimal scalar;
T vector;
};
typedef ::testing::Types<maths::Vector<maths::Decimal, 2>, maths::Vec3f, maths::Vec4f, maths::Vector<maths::Decimal, 50>> vector_types;
TYPED_TEST_CASE(FloatVectorTest, vector_types);
TYPED_TEST(FloatVectorTest, ScalarMultiplication)
{
test_vector *= scalar;
for (uint32_t i = 1; i <= test_vector.size; ++i)
EXPECT_DECIMAL_EQ(test_vector[i - 1], i * scalar);
}
TYPED_TEST(FloatVectorTest, ScalarDivision)
{
test_vector /= scalar;
for (uint32_t i = 1; i <= test_vector.size; ++i)
EXPECT_DECIMAL_EQ(test_vector[i - 1], i / scalar);
}
TYPED_TEST(FloatVectorTest, VectorMultiplication)
{
test_vector *= vector;
for (uint32_t i = 1; i <= test_vector.size; ++i)
EXPECT_DECIMAL_EQ(test_vector[i - 1], 2 * i * i);
}
TYPED_TEST(FloatVectorTest, VectorDivision)
{
test_vector /= vector;
for (uint32_t i = 1; i <= test_vector.size; ++i)
EXPECT_DECIMAL_EQ(test_vector[i - 1], 0.5_d);
}
TYPED_TEST(FloatVectorTest, VectorMin)
{
tested_type min = maths::Min(test_vector, vector);
for (uint32_t i = 0; i < min.size; ++i)
EXPECT_DECIMAL_EQ(min[i], test_vector[i]);
}
TYPED_TEST(FloatVectorTest, VectorMax)
{
auto max = maths::Max(test_vector, vector);
for (uint32_t i = 0; i < max.size; ++i)
EXPECT_DECIMAL_EQ(max[i], vector[i]);
}
TYPED_TEST(FloatVectorTest, EqualOp)
{
EXPECT_TRUE(test_vector == test_vector);
EXPECT_FALSE(test_vector != test_vector);
EXPECT_FALSE(test_vector == vector);
EXPECT_TRUE(test_vector != vector);
}
TYPED_TEST(FloatVectorTest, MinMaxDimension)
{
EXPECT_EQ(maths::MaximumDimension(vector), vector.size - 1u);
EXPECT_EQ(maths::MinimumDimension(vector), 0u);
}
class Vec3fTest : public ::testing::Test
{
protected:
Vec3fTest() :
vector{ 1._d, 2._d, 3._d },
x{ 1._d, 0._d, 0._d },
y{ 0._d, 1._d, 0._d },
z{ 0._d, 0._d, 1._d }
{}
maths::Vec3f vector;
maths::Vec3f x;
maths::Vec3f y;
maths::Vec3f z;
};
TEST_F(Vec3fTest, DotProduct)
{
EXPECT_DECIMAL_EQ(maths::Dot(x, y), 0._d);
EXPECT_DECIMAL_EQ(maths::Dot(x, x), 1._d);
EXPECT_TRUE(maths::Dot(vector, x) > 0._d);
}
TEST_F(Vec3fTest, CrossProduct)
{
EXPECT_TRUE(maths::Cross(x, y) == z);
EXPECT_DECIMAL_EQ(maths::SqrLength(maths::Cross(x, y)), 1._d);
maths::Vec3f cross{ maths::Cross(vector, x) };
EXPECT_DECIMAL_EQ(maths::Dot(cross, vector), 0._d);
EXPECT_DECIMAL_EQ(maths::Dot(cross, x), 0._d);
EXPECT_DECIMAL_EQ(maths::Dot(maths::Cross(y, x), z), -1._d);
}
TEST_F(Vec3fTest, Reflect)
{
maths::Vec3f direction = maths::Normalized(vector);
maths::Vec3f reflected = maths::Reflect(direction, x);
EXPECT_DECIMAL_EQ(maths::Dot(direction, x), maths::Dot(reflected, x));
EXPECT_DECIMAL_EQ(maths::Dot(direction, y), -maths::Dot(reflected, y));
EXPECT_DECIMAL_EQ(maths::Dot(direction, z), -maths::Dot(reflected, z));
}
typedef ::testing::Types<maths::Norm3f> normal_types;
template <typename T>
class NormalTest : public ::testing::Test
{
protected:
NormalTest() :
x(0._d), y(0._d), z(0._d)
{
for (uint32_t i = 1; i <= normalA.size; ++i)
{
normalA[i - 1] = maths::Decimal(i);
normalB[i - 1] = maths::Decimal(i) * 2._d;
}
x[0] = 1._d;
y[1] = 1._d;
z[2] = 1._d;
}
T normalA;
T normalB;
T x;
T y;
T z;
};
TYPED_TEST_CASE(NormalTest, normal_types);
TYPED_TEST(NormalTest, Normalization)
{
EXPECT_GT(maths::Length(normalA), 1._d);
auto normalized = maths::Normalized(normalA);
EXPECT_DECIMAL_EQ(maths::Length(normalized), 1._d);
}
TYPED_TEST(NormalTest, Directions)
{
auto x_facing = maths::FaceForward(normalA, x);
auto normalized = maths::Normalized(normalA);
auto z_facing = maths::FaceForward(normalized, z);
auto minusZ_facing = maths::FaceForward(normalized, -z);
EXPECT_GT(maths::Dot(x_facing, x), 0._d);
EXPECT_GT(maths::Dot(x_facing, normalA), 0._d);
EXPECT_DECIMAL_EQ(maths::Dot(z_facing, minusZ_facing), -1._d);
EXPECT_GT(maths::Dot(z_facing, z), 0._d);
EXPECT_GT(maths::Dot(z_facing, normalized), 0._d);
EXPECT_LT(maths::Dot(minusZ_facing, normalized), 0._d);
}
| [
"samuel.bourasseau@gmail.com"
] | samuel.bourasseau@gmail.com |
5da5dd64b2a258ff677aae1b5ab61256d41cf9fe | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/windows/advcore/gdiplus/engine/imaging/api/basicops.cpp | 0d1c34901f048863d10efeeb049927f1df6b1f6a | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 40,111 | cpp | /**************************************************************************\
*
* Copyright (c) 1999 Microsoft Corporation
*
* Module Name:
*
* basicops.cpp
*
* Abstract:
*
* Implementation of IBasicImageOps interface
*
* Revision History:
*
* 05/10/1999 davidx
* Created it.
*
\**************************************************************************/
#include "precomp.hpp"
/**************************************************************************\
*
* Function Description:
*
* Clone image property items from current object to the destination object
*
* Arguments:
*
* dstBmp --- [IN]Pointer to the destination GpMemoryBitmap object
*
* Return Value:
*
* Status code
*
* Note:
* This is a private method. So we don't need to do input parameter
* validation since the caller should do this for us.
*
* Revision History:
*
* 09/08/2000 minliu
* Created it.
*
\**************************************************************************/
HRESULT
GpMemoryBitmap::ClonePropertyItems(
IN GpMemoryBitmap* dstBmp
)
{
if ( PropertyNumOfItems < 1 )
{
// No property
return S_OK;
}
// PropertyListHead and PropertyListTail are always uninitialized and
// therefore we have to skip the first one and make the loop skip the
// last one.
InternalPropertyItem* pTemp = PropertyListHead.pNext;
while ( pTemp->pNext != NULL )
{
// Add current item into the destination property item list
if ( AddPropertyList(&(dstBmp->PropertyListTail),
pTemp->id,
pTemp->length,
pTemp->type,
pTemp->value) != S_OK )
{
WARNING(("MemBitmap::ClonePropertyItems-AddPropertyList() failed"));
return E_FAIL;
}
pTemp = pTemp->pNext;
}
dstBmp->PropertyNumOfItems = PropertyNumOfItems;
dstBmp->PropertyListSize = PropertyListSize;
return S_OK;
}// ClonePropertyItems()
/**************************************************************************\
*
* Function Description:
*
* Clone an area of the bitmap image
*
* Arguments:
*
* rect - Specifies the image area to be cloned
* NULL means the entire image
* outbmp - Returns a pointer to the cloned bitmap image
* bNeedCloneProperty--Flag caller passes in to indicate if this method
* should clone property or not
*
* Return Value:
*
* Status code
*
* Note: if it is a partial clone, the caller should not ask cloning
* property items. Otherwise, there will be inconsistency in the image
*
\**************************************************************************/
HRESULT
GpMemoryBitmap::Clone(
IN OPTIONAL const RECT* rect,
OUT IBitmapImage** outbmp,
BOOL bNeedCloneProperty
)
{
ASSERT(IsValid());
*outbmp = NULL;
// Lock the current bitmap object and validate source rectangle
GpLock lock(&objectLock);
HRESULT hr;
RECT area;
GpMemoryBitmap* bmp;
if (lock.LockFailed())
{
WARNING(("GpMemoryBitmap::Clone---Object busy"));
hr = IMGERR_OBJECTBUSY;
}
else if (!ValidateImageArea(&area, rect))
{
WARNING(("GpMemoryBitmap::Clone---Invalid clone area"));
hr = E_INVALIDARG;
}
else if ((bmp = new GpMemoryBitmap()) == NULL)
{
WARNING(("GpMemoryBitmap::Clone---Out of memory"));
hr = E_OUTOFMEMORY;
}
else
{
UINT w = area.right - area.left;
UINT h = area.bottom - area.top;
RECT r = { 0, 0, w, h };
BitmapData bmpdata;
// Initialize the new bitmap image object
hr = bmp->InitNewBitmap(w, h, PixelFormat);
if (SUCCEEDED(hr))
{
// Copy pixel data from the current bitmap image object
// to the new bitmap image object.
bmp->GetBitmapAreaData(&r, &bmpdata);
hr = InternalLockBits(&area,
IMGLOCK_READ|IMGLOCK_USERINPUTBUF,
PixelFormat,
&bmpdata);
if (SUCCEEDED(hr))
{
InternalUnlockBits(&r, &bmpdata);
}
// Clone color palettes, flags, etc.
if (SUCCEEDED(hr))
{
// Copy DPI info.
bmp->xdpi = this->xdpi;
bmp->ydpi = this->ydpi;
hr = bmp->CopyPaletteFlagsEtc(this);
}
// Clone all the property items if there is any and the caller wants
// to
if ( SUCCEEDED(hr)
&&(bNeedCloneProperty == TRUE)
&&(PropertyNumOfItems > 0) )
{
hr = ClonePropertyItems(bmp);
}
}
if (SUCCEEDED(hr))
{
*outbmp = bmp;
}
else
{
delete bmp;
}
}
return hr;
}// Clone()
/**************************************************************************\
*
* Function Description:
*
* Functions for flipping a scanline
*
* Arguments:
*
* dst - Pointer to the destination scanline
* src - Pointer to the source scanline
* count - Number of pixels
*
* Return Value:
*
* NONE
*
\**************************************************************************/
VOID _FlipXNone(BYTE* dst, const BYTE* src, UINT count)
{
memcpy(dst, src, count);
}
BYTE byteRev[] = {0x0, 0x8, 0x4, 0xc,
0x2, 0xa, 0x6, 0xe,
0x1, 0x9, 0x5, 0xd,
0x3, 0xb, 0x7, 0xf};
// Given a byte as input, return the byte resulting from reversing the bits
// of the input byte.
BYTE ByteReverse (BYTE bIn)
{
BYTE bOut; // return value
bOut =
(byteRev[ (bIn & 0xf0) >> 4 ]) |
(byteRev[ (bIn & 0x0f)] << 4) ;
return bOut;
}
// these masks are used in the shift left phase of FlipX1bpp
BYTE maskLeft[] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f};
BYTE maskRight[] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80};
VOID _FlipX1bpp(BYTE* dst, const BYTE* src, UINT count)
{
UINT iByte; // byte within the scan line
if (count == 0)
{
return;
}
// The algorithm for 1 bpp flip is:
// 1. Reverse the order of the bytes in the scan line.
// 2. Reverse the bits within each byte of the scan line.
// 3. Shift the bits of the scan line to be aligned on the left.
UINT numBytes = (count + 7) / 8; // number of bytes in the scan line
// Step 1
for (iByte = 0; iByte < numBytes; iByte++)
{
dst[iByte] = src[numBytes - 1 - iByte];
}
// Step 2
for (iByte = 0; iByte < numBytes; iByte++)
{
dst[iByte] = ByteReverse(dst[iByte]);
}
// Step 3
UINT extraBits = count & 0x07; // count mod 8
BYTE maskL = maskLeft[extraBits];
BYTE maskR = maskRight[extraBits];
for (iByte = 0; iByte < numBytes - 1; iByte++)
{
dst[iByte] =
((dst[iByte] & maskL) << (8 - extraBits)) |
((dst[iByte+1] & maskR) >> (extraBits)) ;
}
// last byte: iByte = numBytes-1
dst[iByte] = ((dst[iByte] & maskL) << (8 - extraBits));
}
VOID _FlipX4bpp(BYTE* dst, const BYTE* src, UINT count)
{
// if the number of pixels in the scanline is odd, we have to deal with
// nibbles across byte boundaries.
if (count % 2)
{
BYTE temp;
dst += (count / 2);
// Handle the last dst byte
*dst = *src & 0xf0;
dst--;
count--;
// ASSERT: count is now even.
while (count)
{
*dst = (*src & 0x0f) | (*(src+1) & 0xf0);
src++;
dst--;
count -= 2;
}
}
else
{
dst += (count / 2) - 1;
// ASSERT: count is even.
while (count)
{
*dst = *src;
*dst = ((*dst & 0xf0) >> 4) | ((*dst & 0x0f) << 4);
dst--;
src++;
count -= 2;
}
}
}
VOID _FlipX8bpp(BYTE* dst, const BYTE* src, UINT count)
{
dst += count;
while (count--)
*--dst = *src++;
}
VOID _FlipX16bpp(BYTE* dst, const BYTE* src, UINT count)
{
WORD* d = (WORD*) dst;
const WORD* s = (const WORD*) src;
d += count;
while (count--)
*--d = *s++;
}
VOID _FlipX24bpp(BYTE* dst, const BYTE* src, UINT count)
{
dst += 3 * (count-1);
while (count--)
{
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
src += 3;
dst -= 3;
}
}
VOID _FlipX32bpp(BYTE* dst, const BYTE* src, UINT count)
{
DWORD* d = (DWORD*) dst;
const DWORD* s = (const DWORD*) src;
d += count;
while (count--)
*--d = *s++;
}
/**************************************************************************\
*
* Function Description:
*
* Flip a 48 BPP bitmap horizontally
*
* Arguments:
*
* dst ----------- Pointer to destination image data
* src ----------- Pointer to source image data
* count --------- Number of pixels in a line
*
* Return Value:
*
* NONE
*
* Revision History:
*
* 10/10/2000 minliu
* Wrote it.
*
\**************************************************************************/
VOID
_FlipX48bpp(
BYTE* dst,
const BYTE* src,
UINT count
)
{
// dst pointer points to the last pixel in the line
dst += 6 * (count - 1);
// Loop through each pixel in this line
while (count--)
{
GpMemcpy(dst, src, 6);
// Each pixel takes 6 bytes. Move to next pixel. src move left to right
// and dst move right to left
src += 6;
dst -= 6;
}
}// _FlipX48bpp()
/**************************************************************************\
*
* Function Description:
*
* Flip a 64 BPP bitmap horizontally
*
* Arguments:
*
* dst ----------- Pointer to destination image data
* src ----------- Pointer to source image data
* count --------- Number of pixels in a line
*
* Return Value:
*
* NONE
*
* Revision History:
*
* 10/10/2000 minliu
* Wrote it.
*
\**************************************************************************/
VOID
_FlipX64bpp(
BYTE* dst,
const BYTE* src,
UINT count
)
{
// dst pointer points to the last pixel in the line
dst += 8 * (count - 1);
// Loop through each pixel in this line
while (count--)
{
GpMemcpy(dst, src, 8);
// Each pixel takes 8 bytes. Move to next pixel. src move left to right
// and dst move right to left
src += 8;
dst -= 8;
}
}// _FlipX64bpp()
/**************************************************************************\
*
* Function Description:
*
* Flip the bitmap image in x- and/or y-direction
*
* Arguments:
*
* flipX - Whether to flip horizontally
* flipY - Whether to flip vertically
* outbmp - Returns a pointer to the flipped bitmap image
*
* Return Value:
*
* Status code
*
\**************************************************************************/
HRESULT
GpMemoryBitmap::Flip(
IN BOOL flipX,
IN BOOL flipY,
OUT IBitmapImage** outbmp
)
{
// If no flipping is involved, just call Clone (including the property)
if ( !flipX && !flipY )
{
return this->Clone(NULL, outbmp, TRUE);
}
ASSERT(IsValid());
*outbmp = NULL;
// Lock the current bitmap object
// and validate source rectangle
GpLock lock(&objectLock);
HRESULT hr;
GpMemoryBitmap* bmp = NULL;
if (lock.LockFailed())
{
hr = IMGERR_OBJECTBUSY;
}
else if ((bmp = new GpMemoryBitmap()) == NULL)
{
hr = E_OUTOFMEMORY;
}
else
{
hr = bmp->InitNewBitmap(Width, Height, PixelFormat);
if (FAILED(hr))
{
goto exitFlip;
}
UINT pixsize = GetPixelFormatSize(PixelFormat);
UINT count = Width;
VOID (*flipxProc)(BYTE*, const BYTE*, UINT);
if (!flipX)
{
count = (Width * pixsize + 7) / 8;
flipxProc = _FlipXNone;
}
else switch (pixsize)
{
case 1:
flipxProc = _FlipX1bpp;
break;
case 4:
flipxProc = _FlipX4bpp;
break;
case 8:
flipxProc = _FlipX8bpp;
break;
case 16:
flipxProc = _FlipX16bpp;
break;
case 24:
flipxProc = _FlipX24bpp;
break;
case 32:
flipxProc = _FlipX32bpp;
break;
case 48:
flipxProc = _FlipX48bpp;
break;
case 64:
flipxProc = _FlipX64bpp;
break;
default:
WARNING(("Flip: pixel format not yet supported"));
hr = E_NOTIMPL;
goto exitFlip;
}
// Do the flipping
const BYTE* src = (const BYTE*) this->Scan0;
BYTE* dst = (BYTE*) bmp->Scan0;
INT dstinc = bmp->Stride;
if (flipY)
{
dst += (Height - 1) * dstinc;
dstinc = -dstinc;
}
for (UINT y = 0; y < Height; y++ )
{
flipxProc(dst, src, count);
src += this->Stride;
dst += dstinc;
}
// Clone color palettes, flags, etc.
// Copy DPI info.
bmp->xdpi = this->xdpi;
bmp->ydpi = this->ydpi;
hr = bmp->CopyPaletteFlagsEtc(this);
}
exitFlip:
if ( SUCCEEDED(hr) )
{
*outbmp = bmp;
}
else
{
delete bmp;
}
return hr;
}// Flip()
/**************************************************************************\
*
* Function Description:
*
* Resize the bitmap image
*
* Arguments:
*
* newWidth - Specifies the new bitmap width
* newHeight - Specifies the new bitmap height
* pixfmt - Specifies the new bitmap pixel format
* hints - Specifies which interpolation method to use
* outbmp - Returns a pointer to the resized bitmap image
*
* Return Value:
*
* Status code
*
\**************************************************************************/
HRESULT
GpMemoryBitmap::Resize(
IN UINT newWidth,
IN UINT newHeight,
IN PixelFormatID pixfmt,
IN InterpolationHint hints,
OUT IBitmapImage** outbmp
)
{
ASSERT(IsValid());
*outbmp = NULL;
// Validate input parameters
if (newWidth == 0 || newHeight == 0)
return E_INVALIDARG;
HRESULT hr;
GpMemoryBitmap* bmp;
hr = GpMemoryBitmap::CreateFromImage(
this,
newWidth,
newHeight,
pixfmt,
hints,
&bmp);
if (SUCCEEDED(hr))
*outbmp = bmp;
return hr;
}
/**************************************************************************\
*
* Function Description:
*
* Functions for rotating bitmap 90 degrees or 270 degrees
*
* Arguments:
*
* dst - Destination bitmap image data
* src - Source bitmap image data
* Sinc - direction to increment the source within a scanline (+1 or -1)
* sinc - direction and amount to increment the source per scanline
*
* For a rotation of 90 degrees, src should be set to the beginning of the last
* scanline, Sinc should be set to +1, and sinc should be set to -Stride of a src scanline.
*
* For a rotation of 270 degrees, src should be set to the beginning of scanline 0,
* Sinc should be set to -1, and sinc should be set to +Stride of a src scanline.
*
* Return Value:
*
* NONE
*
\**************************************************************************/
#define _ROTATETMPL(name, T) \
\
VOID \
name( \
BitmapData* dst, \
const BYTE UNALIGNED* src, \
INT Sinc, \
INT sinc \
) \
{ \
T* D = (T*) dst->Scan0; \
const T* S = (const T*) src; \
UINT y = dst->Height; \
INT Dinc = dst->Stride / sizeof(T); \
\
sinc /= sizeof(T); \
\
if (Sinc < 0) \
S += (y - 1); \
\
while (y--) \
{ \
T* d = D; \
const T* s = S; \
UINT x = dst->Width; \
\
while (x--) \
{ \
*d++ = *s; \
s += sinc; \
} \
\
D += Dinc; \
S += Sinc; \
} \
}
_ROTATETMPL(_Rotate8bpp, BYTE)
_ROTATETMPL(_Rotate16bpp, WORD)
_ROTATETMPL(_Rotate32bpp, DWORD)
VOID
_Rotate1bpp(
BitmapData* dst,
const BYTE UNALIGNED* src,
INT Sinc,
INT sinc
)
{
UINT iAngle = 0;
BYTE UNALIGNED* dstRowTemp = static_cast<BYTE UNALIGNED*>(dst->Scan0);
BYTE UNALIGNED* dstColTemp = static_cast<BYTE UNALIGNED*>(dst->Scan0);
UINT dstY = dst->Height; // number of destination rows we need to output
UINT dstX = dst->Width / 8;
UINT extraDstRowBits = dst->Width % 8;
UINT dstRow = 0; // the destination row we are working on
UINT dstColByte = 0; // the byte within the destination row we are working on
BYTE UNALIGNED* topSrc; // the top of the source bitmap
INT srcStride = abs(sinc);
UINT srcRow; // which source row we are reading
UINT srcByte; // which byte within the source row we are reading
UINT srcBit; // which bit within the source byte we are reading
if (Sinc == 1)
{
iAngle = 90;
}
else
{
ASSERT (Sinc == -1);
iAngle = 270;
}
topSrc = const_cast<BYTE UNALIGNED*>(src);
topSrc = (iAngle == 270) ? topSrc : (topSrc + sinc * ((INT)dst->Width - 1));
// This code is pretty brute force, but it is fairly simple.
// We should change the algorithm if performance is a problem.
// The algorithm is: for each destination byte (starting at the upper
// left corner of the destination and moving left to right, top to bottom),
// grab the appropriate bytes from the source. To avoid accessing memory
// out of bounds of the source, we need to handle the last x mod 8 bits
// at the end of the destination row.
if (iAngle == 90)
{
for (dstRow = 0; dstRow < dstY; dstRow++)
{
srcByte = dstRow / 8; // byte within the source row
srcBit = 7 - (dstRow & 0x07); // which source bit we need to mask
for (dstColByte = 0; dstColByte < dstX; dstColByte++)
{
srcRow = (dst->Width - 1) - (dstColByte * 8); // the first source row corresponding to the dest byte
*dstColTemp =
(((topSrc[(srcRow - 0) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 7) |
(((topSrc[(srcRow - 1) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 6) |
(((topSrc[(srcRow - 2) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 5) |
(((topSrc[(srcRow - 3) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 4) |
(((topSrc[(srcRow - 4) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 3) |
(((topSrc[(srcRow - 5) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 2) |
(((topSrc[(srcRow - 6) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 1) |
(((topSrc[(srcRow - 7) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 0)
;
dstColTemp++;
}
// Handle the last few bits on the row
// ASSERT: dstColTemp is pointing to the last byte on the destination row
if (extraDstRowBits)
{
UINT extraBit;
*dstColTemp = 0;
srcRow = (dst->Width - 1) - (dstColByte * 8); // the first source row corresponding to the dest byte
for (extraBit = 0 ; extraBit < extraDstRowBits; extraBit++)
{
*dstColTemp |=
(((topSrc[(srcRow - extraBit) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << (7 - extraBit))
;
}
}
dstRowTemp += dst->Stride;
dstColTemp = dstRowTemp;
}
}
else
{
ASSERT (iAngle == 270);
for (dstRow = 0; dstRow < dstY; dstRow++)
{
srcByte = ((dstY - 1) - dstRow) / 8; // byte within the source row
srcBit = 7 - (((dstY - 1) - dstRow) & 0x07); // which source bit we need to mask
for (dstColByte = 0; dstColByte < dstX; dstColByte++)
{
srcRow = dstColByte * 8; // the first source row corresponding to the dest byte
*dstColTemp =
(((topSrc[(srcRow + 0) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 7) |
(((topSrc[(srcRow + 1) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 6) |
(((topSrc[(srcRow + 2) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 5) |
(((topSrc[(srcRow + 3) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 4) |
(((topSrc[(srcRow + 4) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 3) |
(((topSrc[(srcRow + 5) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 2) |
(((topSrc[(srcRow + 6) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 1) |
(((topSrc[(srcRow + 7) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << 0)
;
dstColTemp++;
}
// Handle the last few bits on the row
// ASSERT: dstColTemp is pointing to the last byte on the destination row
if (extraDstRowBits)
{
UINT extraBit;
*dstColTemp = 0;
srcRow = dstColByte * 8; // the first source row corresponding to the dest byte
for (extraBit = 0 ; extraBit < extraDstRowBits; extraBit++)
{
*dstColTemp |=
(((topSrc[(srcRow + extraBit) * srcStride + srcByte] & (1 << srcBit)) >> srcBit) << (7 - extraBit))
;
}
}
dstRowTemp += dst->Stride;
dstColTemp = dstRowTemp;
}
}
}
VOID
_Rotate4bpp(
BitmapData* dst,
const BYTE UNALIGNED* src,
INT Sinc,
INT sinc
)
{
const BYTE* tempSrc;
BYTE UNALIGNED* Dst;
UINT dstY = dst->Height;
UINT dstX; // used to hold the current pixel of the dst;
BOOL bOddPixelsInScanline = (dstY % 2);
UINT iAngle = (Sinc > 0) ? 90 : 270;
// if the number of pixels in a src scanline is odd, handle the last
// src nibble separately.
if (bOddPixelsInScanline)
{
tempSrc = src + (dstY / 2); // point to the byte that contains the "odd" nibble.
Dst = (BYTE UNALIGNED*) dst->Scan0;
if (iAngle == 90)
{
Dst += (((INT)dstY - 1) * dst->Stride);
}
// ASSERT:
// if we process src pixels backwards in the scanline (i.e., we are
// rotating 270 degrees), then dst points to the first scanline.
// if we process src pixels forwards in the scanline (i.e., we are
// rotating 90 degrees), then dst points to the last scanline.
dstX = dst->Width;
while (dstX)
{
// take the high order nibble of the Src and deposit it
// into the high order nibble of the Dst
*Dst = *tempSrc & 0xf0;
tempSrc += sinc;
dstX--;
if (!dstX)
break;
// take the high order nibble of the Src and deposit it
// into the low order nibble of the Dst
*Dst |= (*tempSrc & 0xf0) >> 4;
tempSrc += sinc;
dstX--;
Dst++;
}
dstY--;
}
tempSrc = src;
Dst = (BYTE UNALIGNED*) dst->Scan0;
// start at the end of src scanline if the angle is 270,
// excluding the last nibble if dstY is odd.
// Also, if we have an odd number of pixels in a src scanline, start Dst
// at the second scanline, since the first dst scanline was handled above.
if (iAngle == 270)
{
tempSrc = src + (dstY / 2) - 1;
if (bOddPixelsInScanline)
{
Dst += dst->Stride;
}
}
// Handle the rest of the scanlines. The following code is pretty brute force.
// It handles 90 degrees and 270 degrees separately, because in the 90 degree
// case, we need to process the high src nibbles within a src byte first, whereas
// in the 270 case, we need to process the low nibbles first.
if (iAngle == 90)
{
while (dstY)
{
BYTE* d = Dst;
const BYTE* s = tempSrc;
dstX = dst->Width;
while (dstX)
{
// take the high order nibble of the Src and deposit it
// into the high order nibble of the Dst
*d = *s & 0xf0;
s += sinc;
dstX--;
if (!dstX)
break;
// take the high order nibble of the Src and deposit it
// into the low order nibble of the Dst
*d |= (*s & 0xf0) >> 4;
s += sinc;
dstX--;
d++;
}
dstY--;
if (!dstY)
break;
Dst += dst->Stride;
d = Dst;
s = tempSrc;
dstX = dst->Width;
while (dstX)
{
// take the low order nibble of the Src and deposit it
// into the high order nibble of the Dst
*d = (*s & 0x0f) << 4;
s += sinc;
dstX--;
if (!dstX)
break;
// take the low order nibble of the Src and deposit it
// into the low order nibble of the Dst
*d |= *s & 0x0f;
s += sinc;
dstX--;
d++;
}
dstY--;
Dst += dst->Stride;
tempSrc += Sinc;
}
}
else
{
// ASSERT: iAngle == 270
while (dstY)
{
BYTE* d = Dst;
const BYTE* s = tempSrc;
dstX = dst->Width;
while (dstX)
{
// take the low order nibble of the Src and deposit it
// into the high order nibble of the Dst
*d = (*s & 0x0f) << 4;
s += sinc;
dstX--;
if (!dstX)
break;
// take the low order nibble of the Src and deposit it
// into the low order nibble of the Dst
*d |= *s & 0x0f;
s += sinc;
dstX--;
d++;
}
dstY--;
if (!dstY)
break;
Dst += dst->Stride;
d = Dst;
s = tempSrc;
dstX = dst->Width;
while (dstX)
{
// take the high order nibble of the Src and deposit it
// into the high order nibble of the Dst
*d = *s & 0xf0;
s += sinc;
dstX--;
if (!dstX)
break;
// take the high order nibble of the Src and deposit it
// into the low order nibble of the Dst
*d |= (*s & 0xf0) >> 4;
s += sinc;
dstX--;
d++;
}
dstY--;
Dst += dst->Stride;
tempSrc += Sinc;
}
}
}
VOID
_Rotate24bpp(
BitmapData* dst,
const BYTE UNALIGNED* S,
INT Sinc,
INT sinc
)
{
BYTE UNALIGNED* D = (BYTE UNALIGNED*) dst->Scan0;
UINT y = dst->Height;
// start at the end of src scanline if direction is -1 within a scanline
if (Sinc < 0)
S += 3 * (y - 1);
Sinc *= 3;
while (y--)
{
BYTE* d = D;
const BYTE UNALIGNED* s = S;
UINT x = dst->Width;
while (x--)
{
d[0] = s[0];
d[1] = s[1];
d[2] = s[2];
d += 3;
s += sinc;
}
D += dst->Stride;
S += Sinc;
}
}
/**************************************************************************\
*
* Function Description:
*
* Functions for rotating a 48 BPP bitmap 90 degrees or 270 degrees
*
* Arguments:
*
* dstBmp ----------- Destination bitmap image data
* srcData ----------- Source bitmap image data
* iLineIncDirection - Direction to increment the source (+1 or -1)
* iSrcStride -------- Direction and amount to increment the source per
* scanline. If the stride is negative, it means we are
* moving bottom up
*
* Note to caller:
* For a rotation of 90 degrees, "srcData" should be set to the beginning
* of the last scanline, "iLineIncDirection" should be set to +1, and
* "iSrcStride" should be set to -Stride of a src scanline.
*
* For a rotation of 270 degrees, "srcData" should be set to the beginning of
* scanline 0, "iLineIncDirection" should be set to -1, and "iSrcStride" should
* be set to +Stride of a src scanline.
*
* Return Value:
*
* NONE
*
* Revision History:
*
* 10/10/2000 minliu
* Wrote it.
*
\**************************************************************************/
VOID
_Rotate48bpp(
BitmapData* dstBmp,
const BYTE UNALIGNED* srcData,
INT iLineIncDirection,
INT iSrcStride
)
{
UINT uiCurrentLine = dstBmp->Height;
const BYTE UNALIGNED* pSrcData = srcData;
// Start at the end of src scanline if direction is < 0 (rotate 270)
if ( iLineIncDirection < 0 )
{
pSrcData += 6 * (uiCurrentLine - 1);
}
iLineIncDirection *= 6; // 6 bytes for each 48 bpp pixel
BYTE* pDstLine = (BYTE UNALIGNED*)dstBmp->Scan0;
// Rotate line by line
while ( uiCurrentLine-- )
{
BYTE* dstPixel = pDstLine;
const BYTE UNALIGNED* srcPixel = pSrcData;
UINT x = dstBmp->Width;
// Move one pixel at a time horizontally
while ( x-- )
{
// Copy 6 bytes from source to dest
GpMemcpy(dstPixel, srcPixel, 6);
// Move dst one pixel to the next (6 bytes)
dstPixel += 6;
// Move src pointer to the next line
srcPixel += iSrcStride;
}
// Move dest to the next line
pDstLine += dstBmp->Stride;
// Move src to one pixel to the right (rotate 90) or to the left (270)
pSrcData += iLineIncDirection;
}
}// _Rotate48bpp()
/**************************************************************************\
*
* Function Description:
*
* Functions for rotating a 64 BPP bitmap 90 degrees or 270 degrees
*
* Arguments:
*
* dstBmp ----------- Destination bitmap image data
* srcData ----------- Source bitmap image data
* iLineIncDirection - Direction to increment the source (+1 or -1)
* iSrcStride -------- Direction and amount to increment the source per
* scanline. If the stride is negative, it means we are
* moving bottom up
*
* Note to caller:
* For a rotation of 90 degrees, "srcData" should be set to the beginning
* of the last scanline, "iLineIncDirection" should be set to +1, and
* "iSrcStride" should be set to -Stride of a src scanline.
*
* For a rotation of 270 degrees, "srcData" should be set to the beginning of
* scanline 0, "iLineIncDirection" should be set to -1, and "iSrcStride" should
* be set to +Stride of a src scanline.
*
* Return Value:
*
* NONE
*
* Revision History:
*
* 10/10/2000 minliu
* Wrote it.
*
\**************************************************************************/
VOID
_Rotate64bpp(
BitmapData* dstBmp,
const BYTE UNALIGNED* srcData,
INT iLineIncDirection,
INT iSrcStride
)
{
UINT uiCurrentLine = dstBmp->Height;
const BYTE UNALIGNED* pSrcData = srcData;
// Start at the end of src scanline if direction is < 0, (rotate 270)
if ( iLineIncDirection < 0 )
{
pSrcData += 8 * (uiCurrentLine - 1);
}
iLineIncDirection *= 8; // 8 bytes for each 64 bpp pixel
BYTE UNALIGNED* pDstLine = (BYTE UNALIGNED*)dstBmp->Scan0;
// Rotate line by line
while ( uiCurrentLine-- )
{
BYTE* dstPixel = pDstLine;
const BYTE UNALIGNED* srcPixel = pSrcData;
UINT x = dstBmp->Width;
// Move one pixel at a time horizontally
while ( x-- )
{
// Copy 8 bytes from source to dest
GpMemcpy(dstPixel, srcPixel, 8);
// Move dst one pixel to the next (8 bytes)
dstPixel += 8;
// Move src pointer to the next line
srcPixel += iSrcStride;
}
// Move dest to the next line
pDstLine += dstBmp->Stride;
// Move src to one pixel to the right (rotate 90) or to the left (270)
pSrcData += iLineIncDirection;
}
}// _Rotate64bpp()
/**************************************************************************\
*
* Function Description:
*
* Rotate the bitmap image by the specified angle
*
* Arguments:
*
* angle - Specifies the rotation angle, in degrees
* hints - Specifies which interpolation method to use
* outbmp - Returns a pointer to the rotated bitmap image
*
* Return Value:
*
* Status code
*
* Notes:
*
* Currently we only support 90-degree rotations.
*
\**************************************************************************/
HRESULT
GpMemoryBitmap::Rotate(
IN FLOAT angle,
IN InterpolationHint hints,
OUT IBitmapImage** outbmp
)
{
// Get the integer angle
INT iAngle = (INT) angle;
iAngle %= 360;
if ( iAngle < 0 )
{
iAngle += 360;
}
switch (iAngle)
{
case 0:
case 360:
return this->Clone(NULL, outbmp, TRUE);
break;
case 180:
return this->Flip(TRUE, TRUE, outbmp);
break;
case 90:
case 270:
break;
default:
return E_NOTIMPL;
}
// Lock the current bitmap image
// and create the new bitmap image
ASSERT(IsValid());
*outbmp = NULL;
GpLock lock(&objectLock);
HRESULT hr;
GpMemoryBitmap* bmp = NULL;
if ( lock.LockFailed() )
{
hr = IMGERR_OBJECTBUSY;
}
else if ((bmp = new GpMemoryBitmap()) == NULL)
{
hr = E_OUTOFMEMORY;
}
else
{
hr = bmp->InitNewBitmap(Height, Width, PixelFormat);
if (FAILED(hr))
{
goto exitRotate;
}
ASSERT(bmp->Width == this->Height &&
bmp->Height == this->Width);
VOID (*rotateProc)(BitmapData*, const BYTE UNALIGNED*, INT, INT);
switch (GetPixelFormatSize(PixelFormat))
{
case 1:
rotateProc = _Rotate1bpp;
break;
case 4:
rotateProc = _Rotate4bpp;
break;
case 8:
rotateProc = _Rotate8bpp;
break;
case 16:
rotateProc = _Rotate16bpp;
break;
case 24:
rotateProc = _Rotate24bpp;
break;
case 32:
rotateProc = _Rotate32bpp;
break;
case 48:
rotateProc = _Rotate48bpp;
break;
case 64:
rotateProc = _Rotate64bpp;
break;
default:
WARNING(("Rotate: pixel format not yet supported"));
hr = E_NOTIMPL;
goto exitRotate;
}
// Do the rotation
const BYTE UNALIGNED* src = (const BYTE UNALIGNED*) this->Scan0;
INT sinc = this->Stride;
INT Sinc;
if ( iAngle == 90 )
{
// clockwise
src += sinc * ((INT)this->Height - 1);
Sinc = 1;
sinc = -sinc;
}
else
{
Sinc = -1;
}
rotateProc(bmp, src, Sinc, sinc);
// Copy DPI info.
// Note: when the code falls here, we know it is either 90 or -90 degree
// rotation. So the DPI value should be swapped
bmp->xdpi = this->ydpi;
bmp->ydpi = this->xdpi;
// Clone color palettes, flags, etc.
hr = bmp->CopyPaletteFlagsEtc(this);
}
exitRotate:
if ( SUCCEEDED(hr) )
{
*outbmp = bmp;
}
else
{
delete bmp;
}
return hr;
}// Rotate()
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
40824d2f98ee4a26c64c1890288a2a59aecdd2df | aaa60b19f500fc49dbaac1ec87e9c535a66b4ff5 | /0-OJ/longest_continuous_ones.cc | 8708fe8f43cfe06bbf24e926787d036e2f1cb885 | [] | no_license | younger-1/leetcode-younger | c24e4a2a77c2f226c064c4eaf61e7f47d7e98d74 | a6dc92bbb90c5a095ac405476aeae6690e204b6b | refs/heads/master | 2023-07-25T02:31:42.430740 | 2021-09-09T08:06:05 | 2021-09-09T08:06:05 | 334,441,040 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,090 | cc | #include <stdio.h>
#include <vector>
using namespace std;
int longest_continuous_ones(vector<int>& nums) {
int n = nums.size();
vector<int> zeros;
for (int i = 0; i < n; i++) {
if (nums[i] == 0) {
zeros.push_back(i);
}
}
if (zeros.size() == n) {
return 0;
}
if (zeros.size() < 2) {
return n - 1;
}
int m = zeros.size();
int res = max(zeros[1] - 1, n - zeros[m - 2] - 2);
for (int i = 1; i < m - 1; i++) {
res = max(res, zeros[i + 1] - zeros[i - 1] - 2);
}
return res;
}
/*
* 输入:T 组, 每组 n 个数, 都是由 0,1 组成
* 输出:每组数去掉任何一个 0 后,找到最长的连续的 1,打印其长度
*/
int main() {
int T, n;
scanf("%d", &T);
for (int i = 0; i < T; i++) {
scanf("%d", &n);
vector<int> nums;
int num;
for (int j = 0; j < n; j++) {
scanf("%d", &num);
nums.push_back(num);
}
int res = longest_continuous_ones(nums);
printf("%d\n", res);
}
} | [
"45989017+younger-1@users.noreply.github.com"
] | 45989017+younger-1@users.noreply.github.com |
07123c951b3b562c97362de83d8a8fdf60bbe9b9 | e0b4fc8aaf60ff3c4187646ab132027b603da0be | /Rockethon_2014/Rockethon_2014_A/main.cpp | f39370a2abdae0a7264b7c099c4f87f48a218d96 | [] | no_license | tupieurods/SportProgramming | c886a2b3759d43d1ec52e949c7027c9c43bf6ef1 | 9f2362e14b51f249141166c1867d081f125e7358 | refs/heads/master | 2021-01-23T22:53:20.521768 | 2014-10-29T16:27:13 | 2014-10-29T16:27:13 | 15,796,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 785 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
char str[109];
int len;
void ReadData()
{
scanf("%s%*c", str);
len = strlen(str);
}
int answer;
void Solve()
{
answer = 0;
int cnt = 0;
char current = str[0];
for(int i = 0; i < len; i++)
{
if(str[i] == current)
{
cnt++;
}
else
{
if(cnt % 2 == 0)
{
answer++;
}
current = str[i];
cnt = 1;
}
}
if(cnt % 2 == 0)
{
answer++;
}
}
void WriteData()
{
printf("%d\n", answer);
}
int main()
{
int QWE;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
scanf("%d%*c", &QWE);
#else
QWE = 1;
#endif
for(int T = 0; T < QWE; T++)
{
ReadData();
Solve();
WriteData();
}
return 0;
} | [
"tupieurods@gmail.com"
] | tupieurods@gmail.com |
afef6a1f086b01a9e75debfae0fbb1944d6e4f71 | fdfe4c22d3520aa1a74a175d5df4d871ed29a2f6 | /threading/threadpool.hpp | 0aef9b084dce94ceee5c4267cc60cfccdedf216d | [
"MIT"
] | permissive | firngrod/firnlibs | e60f6556e4eec80a1e83122af8b2cab60c56966f | a8fbdd22ec3b0a9497b809e8b86092e0affea995 | refs/heads/master | 2020-07-13T12:52:04.079564 | 2019-06-15T20:45:46 | 2019-06-15T20:45:46 | 67,539,812 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,916 | hpp | #pragma once
#include "queue.hpp"
#include "guardedvar.hpp"
#include <thread>
#include <map>
#include <condition_variable>
#include <functional>
namespace FirnLibs
{
namespace Threading
{
class Threadpool
{
public:
// Initialize the threadpool with a number of slave threads.
// count of -1 (yes, I know, unsigned size, just go with it) sets thread count to processor count
Threadpool(const size_t &threadCount = -1);
// Beware when deconstructing the threadpool since this will leak all unfinished queued jobs.
// It is recommended to do a FinishUp() first, although if terminating the program, you may not care.
~Threadpool();
// Update the amount of available threads.
// count of -1 (yes, I know, unsigned size, just go with it) sets thread count to processor count
void SetThreadCount(const size_t &threadCount = -1);
// Push another job to the threadpool.
// Returns false if the threadpool is trying to wind down.
// Check for this case and be sure to clean up since the child thread won't run.
bool Push(std::function<void()> func);
// Prevents further jobs from being added to the queue and blocks until all jobs have finished.
void FinishUp();
protected:
class ThreadParams
{
public:
bool *stopSignal;
FirnLibs::Threading::Queue<std::function<void()> > *queue;
std::condition_variable *cv;
std::mutex *mutex;
};
class ThreadPackage
{
public:
std::thread * thread;
bool * stopSignal;
};
std::list<ThreadPackage> threadList;
FirnLibs::Threading::Queue<std::function<void()> > queue;
std::condition_variable cv;
std::mutex mutex, threadMutex;
static void RunnerFunc(ThreadParams * params);
FirnLibs::Threading::GuardedVar<bool> finishing;
};
}
}
| [
"firngrod@hotmail.com"
] | firngrod@hotmail.com |
0e28875aa9c333ac621253ea07b6e625cde8c25c | c9e0227c3958db89747488328bd2b255e54f008f | /solutions/1029. Two City Scheduling/1029.cpp | ded4b380b2e184325463af4e4d3742f44fd5352e | [] | no_license | XkhldY/LeetCode | 2deba28b7491c36b4f224c3132fb89feea318832 | 94e23db2668615d9fe09e129a96c22ae4e83b9c8 | refs/heads/main | 2023-04-03T08:17:30.743071 | 2021-04-14T23:34:03 | 2021-04-14T23:34:03 | 358,136,537 | 1 | 0 | null | 2021-04-15T05:20:21 | 2021-04-15T05:20:21 | null | UTF-8 | C++ | false | false | 593 | cpp | class Solution {
public:
int twoCitySchedCost(vector<vector<int>>& costs) {
const int n = costs.size() / 2;
int ans = 0;
// assume send 2n people to city b at first, but actually we have to send n
// people to city a as well, so we sort by "how much will be refunded" if we
// send a person to city a instead of city b, i.e., -(costs[1] - costs[0])
sort(begin(costs), end(costs), [](const auto& a, const auto& b) {
return a[0] - a[1] < b[0] - b[1];
});
for (int i = 0; i < n; ++i)
ans += costs[i][0] + costs[i + n][1];
return ans;
}
};
| [
"walkccray@gmail.com"
] | walkccray@gmail.com |
7129055551e36731c3bc2e17d7427cc57151299b | e42035875cfa415e7bfcfd36975f992ab78122d7 | /Point of Sale/Untitled2.cpp | 7af760ac740e5d92afe1bf802e7cba0cee41de3f | [] | no_license | mackrugeri/C- | 553795c85fa7ae0ec920b7fb4f73ece14e1e99b8 | 882a981dfe92fbcbe9243f823fc2706854471a93 | refs/heads/main | 2023-05-29T23:56:29.480549 | 2021-06-04T16:28:40 | 2021-06-04T16:28:40 | 373,884,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 439 | cpp | #include <iostream>
#include <cstdlib>
using namespace std;
struct coord_struct {
double x;
double y;
};
typedef struct coord_struct coord;
int main() {
char *s;
coord *c = (coord *)malloc(sizeof(coord));
printf("Enter x: ");
fgets(s, 79, stdin);
c->x = atof(s);
printf("Enter y: ");
fgets(s, 79, stdin);
c->y = atof(s);
printf("Coords are (%lf, %lf).\n", c->x, c->y);
free(c);
free(s);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
95f6100376212c2834cb548db05f9823cfb84384 | bdff77da36bd24b4a9c3233d20419b62146ae15c | /lab6/task.cpp | b2e869b9dc8a67627f4e012e8d3da9d555267e4e | [] | no_license | bewithforce/OperatingSystems | 7764f003ef78e1c7019fef3c6cb0fb51e03922a6 | e4028e0ebbba745f4ee9a8b839c2e813af766b53 | refs/heads/master | 2022-08-24T03:08:17.779396 | 2020-05-19T07:14:08 | 2020-05-19T07:14:08 | 246,387,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 473 | cpp | #include <dirent.h>
#include <iostream>
#include <set>
using namespace std;
int main() {
DIR *d;
struct dirent *dir;
set<string> files;
d = opendir("../");
if (d) {
while ((dir = readdir(d)) != nullptr) {
if(dir->d_type != DT_LNK && dir->d_type != DT_DIR){
files.insert(dir->d_name);
}
}
closedir(d);
}
for(auto& item : files){
cout << item << endl;
}
return 0;
} | [
"somniummisellus@gmail.com"
] | somniummisellus@gmail.com |
63c708e95a1bd49e59b5b747cc10de731593de34 | 9b5b69a2fcb9db79ca8a4d96c8dc445fb32814cd | /src/selfie_stm32_bridge/src/main.cpp | a11af75c56e118118feed710d3087a984a127ec4 | [] | no_license | KNR-Selfie/selfie_carolocup2019 | a86e88c0499707f936b1830bcc956bb472d22cd9 | d293ec8259e0af8eb640cbb633c9afc7cad69bc8 | refs/heads/master | 2020-04-01T21:02:55.647017 | 2019-02-13T20:38:36 | 2019-02-13T20:38:36 | 153,634,827 | 2 | 1 | null | 2019-02-05T15:10:51 | 2018-10-18T14:11:19 | C++ | UTF-8 | C++ | false | false | 5,247 | cpp | #include "ros/ros.h"
#include "sensor_msgs/Imu.h"
#include "std_msgs/Float32.h"
#include "std_msgs/UInt8.h"
#include "std_msgs/Bool.h"
#include "ackermann_msgs/AckermannDriveStamped.h"
#include "usb.hpp"
#include <sstream>
USB_STM Usb;
void ackermanCallback(const ackermann_msgs::AckermannDriveStamped::ConstPtr& msg);
void left_turn_indicatorCallback(const std_msgs::Bool::ConstPtr& msg);
void right_turn_indicatorCallback(const std_msgs::Bool::ConstPtr& msg);
int main(int argc, char **argv)
{
ros::init(argc, argv, "selfie_stm32_bridge");
ros::NodeHandle n;
ros::Publisher imu_publisher = n.advertise<sensor_msgs::Imu>("imu", 100);
ros::Publisher velo_publisher = n.advertise<std_msgs::Float32>("speed", 50);
ros::Publisher dis_publisher = n.advertise<std_msgs::Float32>("distance", 50);
ros::Publisher button1_publisher = n.advertise<std_msgs::Bool>("start_button1", 50);
ros::Publisher button2_publisher = n.advertise<std_msgs::Bool>("start_button2", 50);
ros::Publisher reset_vision_publisher = n.advertise<std_msgs::Bool>("reset_vision", 50);
ros::Publisher switch_state_publisher = n.advertise<std_msgs::UInt8>("switch_state", 50);
ros::Subscriber ackerman_subscriber = n.subscribe("drive", 1, ackermanCallback);
ros::Subscriber left_turn_indicator_subscriber = n.subscribe("left_turn_indicator", 1, left_turn_indicatorCallback);
ros::Subscriber right_turn_indicator_subscriber = n.subscribe("right_turn_indicator", 1, right_turn_indicatorCallback);
//usb communication - read
uint32_t timestamp = 1;
int16_t velocity = 1;
int32_t distance = 1;
int16_t quaternion_x = 1;
int16_t quaternion_y = 1;
int16_t quaternion_z = 1;
int16_t quaternion_w = 1;
uint16_t yaw = 1;
int16_t ang_vel_x = 1;
int16_t ang_vel_y = 1;
int16_t ang_vel_z = 1;
int16_t lin_acc_x = 1;
int16_t lin_acc_y = 1;
int16_t lin_acc_z = 1;
uint8_t start_button1 = 0;
uint8_t start_button2 = 0;
uint8_t reset_vision = 0;
uint8_t switch_state = 0;
Usb.init();
ros::Time begin = ros::Time::now();
Usb.indicators.left = 0;
Usb.indicators.right = 0;
Usb.control.steering_angle = 0;
Usb.control.steering_angle_velocity = 0;
Usb.control.speed = 0;
Usb.control.acceleration = 0;
Usb.control.jerk = 0;
while (ros::ok())
{
ros::Time now = ros::Time::now();
uint32_t send_ms = (now.sec - begin.sec) * 1000 + (now.nsec / 1000000);
Usb.usb_read_buffer(128, timestamp, distance, velocity, quaternion_x, quaternion_y, quaternion_z, quaternion_w, yaw, ang_vel_x, ang_vel_y, ang_vel_z, lin_acc_x, lin_acc_y, lin_acc_z, start_button1, start_button2, reset_vision, switch_state);
Usb.usb_send_buffer(send_ms, Usb.control.steering_angle, Usb.control.steering_angle_velocity, Usb.control.speed, Usb.control.acceleration, Usb.control.jerk, Usb.indicators.left, Usb.indicators.right);
//send imu to msg
static sensor_msgs::Imu imu_msg;
imu_msg.header.frame_id = "imu";
imu_msg.header.stamp = ros::Time::now();
imu_msg.orientation.x = (float)(quaternion_x / 32767.f);
imu_msg.orientation.y = (float)(quaternion_y / 32767.f);
imu_msg.orientation.z = (float)(quaternion_z / 32767.f);
imu_msg.orientation.w = (float)(quaternion_w / 32767.f);
imu_msg.linear_acceleration.x = (float)(lin_acc_x / 8192.f * 9.80655f);
imu_msg.linear_acceleration.y = (float)(lin_acc_y / 8192.f * 9.80655f);
imu_msg.linear_acceleration.z = (float)(lin_acc_z / 8192.f * 9.80655f);
imu_msg.angular_velocity.x = (float)(ang_vel_x / 65.535f);
imu_msg.angular_velocity.y = (float)(ang_vel_y / 65.535f);
imu_msg.angular_velocity.z = (float)(ang_vel_z / 65.535f);
//send velocity to msg
static std_msgs::Float32 velo_msg;
velo_msg.data = (float)velocity / 1000;
//send distance to msg
static std_msgs::Float32 dis_msg;
dis_msg.data = (float)distance / 1000;
//send status button status to msg
static std_msgs::Bool button1_msg;
button1_msg.data = start_button1;
static std_msgs::Bool button2_msg;
button2_msg.data = start_button2;
//send status button status to msg
static std_msgs::Bool reset_vision_msg;
reset_vision_msg.data = reset_vision;
static std_msgs::UInt8 switch_state_msg;
switch_state_msg.data = switch_state;
//publishing msg
imu_publisher.publish(imu_msg);
velo_publisher.publish(velo_msg);
dis_publisher.publish(dis_msg);
button1_publisher.publish(button1_msg);
button2_publisher.publish(button2_msg);
reset_vision_publisher.publish(reset_vision_msg);
switch_state_publisher.publish(switch_state_msg);
ros::spinOnce();
}
}
void ackermanCallback(const ackermann_msgs::AckermannDriveStamped::ConstPtr& msg)
{
Usb.control.steering_angle = -msg->drive.steering_angle;
Usb.control.steering_angle_velocity = msg->drive.steering_angle_velocity;
Usb.control.speed = msg->drive.speed;
Usb.control.acceleration = msg->drive.acceleration;
Usb.control.jerk = msg->drive.jerk;
}
void left_turn_indicatorCallback(const std_msgs::Bool::ConstPtr& msg)
{
Usb.indicators.left = (int8_t) msg->data;
}
void right_turn_indicatorCallback(const std_msgs::Bool::ConstPtr& msg)
{
Usb.indicators.right = (int8_t) msg->data;
}
| [
"gotlib.adam+dev@gmail.com"
] | gotlib.adam+dev@gmail.com |
bd6a42416057b3fc75ec6215b11a2cc09c18cb8e | 8676f6da8a8ccc67502b7e46ef5946e73a2f464e | /whiteBelt/week1/greatest_common_divisor.cpp | 7e22a740e084adf8347842aed590c21fddf74e0a | [] | no_license | sakekoke/cpp_projects | 8f37f338a748c6d7db0e22a41164917c9eae8186 | 23b52e710364e5f1e381cb0cf97de130d25e5954 | refs/heads/main | 2023-02-05T16:22:30.538798 | 2021-01-01T04:43:03 | 2021-01-01T04:43:03 | 321,422,522 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 293 | cpp | #include <iostream>
int main() {
int index, a, b, max, ans;
std::cin >> a >> b;
while (a > 0 && b > 0)
{
if (a > b)
{
a %= b;
}
else
{
b %= a;
}
}
std::cout << a + b << std::endl;
return 0;
} | [
"sakekoke42@gmail.com"
] | sakekoke42@gmail.com |
8fb36a671e2e2a52bbc97f9ac2e2488a07933e67 | 882d3591752a93792bd8c734dd91b1e5439c5ffe | /android/QNLiveShow/liveshowApp/src/main/jni/crashhandler/com_qpidnetwork_livemodule_utils_CrashHandlerJni.cpp | 6f76559fadbe43c25a22fbbeedd4e7d6c954fafc | [] | no_license | KingsleyYau/LiveClient | f4d4d2ae23cbad565668b1c4d9cd849ea5ca2231 | cdd2694ddb4f1933bef40c5da3cc7d1de8249ae2 | refs/heads/master | 2022-10-15T13:01:57.566157 | 2022-09-22T07:37:05 | 2022-09-22T07:37:05 | 93,734,517 | 27 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 717 | cpp | #include "com_qpidnetwork_livemodule_utils_CrashHandlerJni.h"
#include <crashhandler/CrashHandler.h>
#include <common/command.h>
/*
* Class: com_qpidnetwork_utils_CrashHandlerJni
* Method: SetCrashLogDirectory
* Signature: (Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_qpidnetwork_livemodule_utils_CrashHandlerJni_SetCrashLogDirectory
(JNIEnv *env, jclass cls, jstring directory){
string strDirectory("");
if (directory != NULL) {
const char *cpDirectory = env->GetStringUTFChars(directory, 0);
strDirectory = cpDirectory;
env->ReleaseStringUTFChars(directory, cpDirectory);
}
CrashHandler::GetInstance()->SetCrashLogDirectory(strDirectory);
}
| [
"Kingsleyyau@gmail.com"
] | Kingsleyyau@gmail.com |
b12a62432bfc64336e2e4f4c0de7e100027d5851 | 8af5a214f3ee7df4a048f3ba0ed37ba8acbb1d8e | /smeint.cpp | db9b5001a9f57070255bb8258841ea7042ad7ef3 | [] | no_license | gaze/smeint | 9c705d9002f6d51d99886aab0fdfb19ee922ac5b | c5a3942916f59d4d677ff9313a577b8b98935683 | refs/heads/master | 2021-01-21T11:08:32.148725 | 2017-05-19T14:25:29 | 2017-05-19T14:25:29 | 91,727,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,226 | cpp | #include <iostream>
#include <tuple>
#include <vector>
#include <Eigen/Core>
#include <memory>
#include <pybind11/pybind11.h>
#include <pybind11/eigen.h>
#include <complex>
#include <cmath>
#include <assert.h>
#include <random>
namespace py = pybind11;
#if 0
typedef std::complex<double> dtype;
typedef Eigen::SparseMatrix<dtype> SpMat;
typedef Eigen::MatrixXcd DMat;
#else
typedef double dtype;
typedef Eigen::SparseMatrix<dtype> SpMat;
typedef Eigen::MatrixXd DMat;
typedef Eigen::RowVectorXd RVec;
#endif
struct SMESolver {
SMESolver(
SpMat hamiltonian
) : hamiltonian(hamiltonian) {}
enum TermCond {
kGreaterThanOrEqualTo,
kLessThan,
kStepLimitReached
};
SpMat hamiltonian;
DMat rho0;
std::vector<SpMat> collapse;
// Observed operator and the efficiency it comes in with
std::vector<SpMat> measurement;
std::vector<double> etas;
// All expectation values of interest
std::vector<SpMat> ev_ops;
// Key from names of expectation values to their index
std::unordered_map<std::string, int> ev_names;
// Termination condition (expval index, condition, value)
std::vector<std::tuple<int, TermCond, dtype>> term_conds;
void AddCollapse(SpMat op);
void AddMeasurement(SpMat op, double eta);
void AddExpectationValue(std::string name, SpMat op);
void AddTerminationCondition(std::string name, TermCond tc, dtype value);
std::tuple<DMat,DMat> Run(DMat rho0, int N, double dt);
};
void SMESolver::AddExpectationValue(std::string name, SpMat op){
ev_ops.push_back(op);
ev_names[name] = ev_ops.size() - 1;
}
void SMESolver::AddTerminationCondition(
std::string name,
SMESolver::TermCond tc,
dtype value){
int idx = ev_names[name];
term_conds.push_back(std::tie(idx, tc, value));
}
void SMESolver::AddCollapse(SpMat op){
collapse.push_back(op);
}
void SMESolver::AddMeasurement(SpMat op, double eta){
measurement.push_back(op);
etas.push_back(eta);
}
std::tuple<DMat,DMat> SMESolver::Run(DMat rho0, int N, double dt){
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<> d;
double rtdt = sqrt(dt);
unsigned long M = measurement.size();
// Domain checks
if(hamiltonian.rows() != hamiltonian.cols()){
std::cout<<"Hamiltonian not square"<<std::endl;
throw new std::domain_error("Hamiltonian not square");
}
long D = hamiltonian.rows();
if(rho0.rows() != D || rho0.cols() != D){
std::cout<<"rho0"<<std::endl;
throw new
std::domain_error("rho0 shape doesn't match system dimension");
}
for( auto &v : collapse )
if(v.rows() != D || v.cols() != D) {
std::cout<<"collapse ops"<<std::endl;
throw new std::domain_error("Collapse operator has wrong dimension");
}
for( auto &l : measurement )
if(l.rows() != D || l.cols() != D) {
std::cout<<"msmt ops"<<std::endl;
throw new
std::domain_error("Measurement operator has wrong dimension");
}
DMat dy(N,M);
DMat rhos(N,D*D);
DMat rho(rho0);
// Deterministic part of the evolution
// SpMat mdet = dtype{0.0,1.0} * hamiltonian;
SpMat mdet = 0.0 * hamiltonian;
for( auto &v : collapse ) mdet += 0.5*v.adjoint()*v;
for( auto &l : measurement ) mdet += 0.5*l.adjoint()*l;
for(int i=0;i<N;i++){
// Measurement record
for(int r=0;r<M;r++) {
dtype a = (measurement[r] * rho \
+ rho * (measurement[r].adjoint())).trace();
dy(i,r) = sqrt(etas[r]) * a * dt + d(gen)*rtdt;
}
DMat m = DMat::Identity(D,D) - mdet*dt;
for(int r=0;r<M;r++){
m += (sqrt(etas[r])*dy(i,r))*measurement[r];
for(int s=0;s<M;s++){
dtype f = dy(i,r)*dy(i,s);
if(r == s) f -= dt;
m += 0.5*sqrt(etas[r]*etas[s])*measurement[r]*measurement[s]*f;
}
}
DMat rhonext = m*rho*m.adjoint();
for( auto &v : collapse ) rhonext += v*rho*v.adjoint()*dt;
for(int j=0;j<measurement.size();j++)
rhonext += \
(1-etas[j])*measurement[j]*rho*measurement[j].adjoint()*dt;
rhonext /= rhonext.trace();
Eigen::Map<RVec> rhocol(rhonext.data(),rhonext.size());
rhos.row(i) = rhocol;
rho = rhonext;
}
return std::tie(dy,rhos);
}
PYBIND11_PLUGIN(smeint) {
py::module m("smeint", "SME Solver");
py::class_<SMESolver> solver(m, "Solver");
solver.def(py::init<SpMat>())
.def("add_collapse", &SMESolver::AddCollapse)
.def("add_measurement", &SMESolver::AddMeasurement)
.def("add_expectation_value", &SMESolver::AddExpectationValue)
.def("add_termination_condition", &SMESolver::AddTerminationCondition)
.def("run", &SMESolver::Run);
py::enum_<SMESolver::TermCond>(solver, "TermCond")
.value("LessThan", SMESolver::TermCond::kLessThan)
.value("LessThanOrEqualTo", SMESolver::TermCond::kGreaterThanOrEqualTo);
return m.ptr();
}
| [
"gaze@bea.ms"
] | gaze@bea.ms |
f0ca2ca0af2c510adc3a136f81ec4726784c5d89 | 3054ded5d75ec90aac29ca5d601e726cf835f76c | /Training/ITMOx Course/Semana 2/C.c++ | 95fab444bf41cd44634e6eb5a4b8bfcf9b02c300 | [] | no_license | Yefri97/Competitive-Programming | ef8c5806881bee797deeb2ef12416eee83c03add | 2b267ded55d94c819e720281805fb75696bed311 | refs/heads/master | 2022-11-09T20:19:00.983516 | 2022-04-29T21:29:45 | 2022-04-29T21:29:45 | 60,136,956 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 950 | /*
* ITMOx Course - 1st Week Problems
* Problem: Prepare Yourself to Competitions!
* Level: Easy
*/
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
const int kInf = 1e6;
int main() {
ios::sync_with_stdio(false); // Fast input - output
ifstream fin("input.txt"); // File Input
ofstream fout("output.txt"); // File Output
/*** Code ***/
int n; fin >> n;
vector<int> practice(n);
for (int i = 0; i < n; i++)
fin >> practice[i];
vector<int> theory(n);
for (int i = 0; i < n; i++)
fin >> theory[i];
int ans = 0;
bool p = false, t = false;
for (int i = 0; i < n; i++) {
if (practice[i] > theory[i]) {
ans += practice[i];
p = true;
} else {
ans += theory[i];
t = true;
}
}
if (!p or !t) {
int mmin = kInf;
for (int i = 0; i < n; i++)
mmin = min(mmin, abs(practice[i] - theory[i]));
ans -= mmin;
}
fout << ans << endl;
return 0;
} | [
"yefri.gaitan97@gmail.com"
] | yefri.gaitan97@gmail.com | |
219157ebd25030650daef9e0f0a2cce7ae5ffa2c | 00053952c44756c3f0a7abd0d9c48c09a019f676 | /base/file.cpp | 70d0a59a78d3cc2560638a7bb73bd3804772f42b | [] | no_license | xlmshack/kvnsfer | e946704d703d689b2abdb51696333d5e33884fae | dbaafe9180587f56073bffa36645bb9b7e35c24d | refs/heads/master | 2020-03-23T23:29:20.759764 | 2018-08-29T15:50:21 | 2018-08-29T15:50:21 | 142,237,315 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,273 | cpp | #include "file.h"
#include <assert.h>
#include "apr.h"
#include "apr_general.h"
#include "apr_errno.h"
namespace base {
File::File()
:file_(nullptr) {
apr_status_t status = APR_SUCCESS;
status = apr_pool_create(&pool_, NULL);
assert(status == APR_SUCCESS);
}
File::File(const char* fname, apr_int32_t flag)
:File() {
Open(fname, flag);
}
File::~File() {
if (file_) {
apr_file_close(file_);
}
if (pool_) {
apr_pool_destroy(pool_);
}
}
void File::Open(const char* fname, apr_int32_t flag) {
assert(file_ == nullptr);
apr_status_t status = APR_SUCCESS;
apr_fileperms_t perms = APR_FPROT_OS_DEFAULT;
status = apr_file_open(&file_, fname, flag, perms, pool_);
}
void File::Close() {
assert(file_);
apr_file_close(file_);
file_ = nullptr;
}
void File::Flush() {
assert(file_);
apr_file_flush(file_);
}
void File::Seek(apr_seek_where_t where, apr_off_t *offset) {
assert(file_);
apr_file_seek(file_, where, offset);
}
void File::Read(void* buf, apr_size_t *nbytes) {
assert(file_);
apr_file_read(file_, buf, nbytes);
}
void File::Write(const void *buf, apr_size_t *nbytes) {
assert(file_);
apr_file_write(file_, buf, nbytes);
}
} // namespace base | [
"xlmshack@gmail.com"
] | xlmshack@gmail.com |
dfe6509f94126dec09ed21c73885374275e4a952 | cb8042aeb1f7829017513bf64911076b7bc9e954 | /Codeup_BasicLevel-100/Q06_/main.cpp | f3055f359da21a70d4e9f7bc33a753558a859f8e | [] | no_license | Heongilee/CodeUp_Challenge | a81249925d4b95707f51f2415659051a7eb12303 | 719d7a2e24ce60b6214145c400e9b82e6ec437d8 | refs/heads/master | 2021-01-02T17:23:41.039957 | 2020-02-19T06:32:15 | 2020-02-19T06:32:15 | 239,714,427 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 104 | cpp | #include <iostream>
using namespace std;
int main()
{
cout << "\"!@#$%^&*()\"" << endl;
return 0;
} | [
"gjsrl1@gmail.com"
] | gjsrl1@gmail.com |
0f62af5fa58ab47766fc728452bd9fb4ff78aed0 | dcfdad4ce2289af76fc1ca2a9f593a13a79b390d | /CS154_Labs_2ndSem/Lab9/trythis2.cpp | b395f1b17b3ad7846740571a2f046ddd028073d0 | [] | no_license | arponbasu/CS154_Labs_2ndSem | ee2b4b02ea13028d59236cf51a64ca89505a9fd0 | f48b016776a57435f050fe6babac1fc90ac3d85e | refs/heads/main | 2023-07-05T01:20:14.895773 | 2021-09-01T16:32:58 | 2021-09-01T16:32:58 | 392,825,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 248 | cpp | #include <iostream>
using namespace std;
void f(int x, int y, int z) {
cout << x << " " << y << " " << z << endl;
}
int main () {
int i=10;
f(i, i++, ++i);
cout << i << endl;//New line added by me
f(++i, i++, ++i);
cout << i << endl;
}
| [
"noreply@github.com"
] | noreply@github.com |
c257166823dd854660ae387560be420e054436f6 | 83523fbc65ae3df4ccac9fee7e035cb07922a3e0 | /RZExternal/src/FitSDKRelease_20/fit_mesg_capabilities_mesg_listener.hpp | 912525422247426912f6dd867d0eb3e5421c43e4 | [
"MIT"
] | permissive | swifter-motion/iossimfinder | 0aedb01ae0e5bd64b4122f4b8b389bbca54a4aa3 | 810434d87e44c242ae1386b9da15b45de5426383 | refs/heads/master | 2020-05-31T15:23:33.288075 | 2018-06-24T16:13:54 | 2018-06-24T16:13:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,388 | hpp | ////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2018 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 20.56Release
// Tag = production/akw/20.56.00-0-g20d5d53
////////////////////////////////////////////////////////////////////////////////
#if !defined(FIT_MESG_CAPABILITIES_MESG_LISTENER_HPP)
#define FIT_MESG_CAPABILITIES_MESG_LISTENER_HPP
#include "fit_mesg_capabilities_mesg.hpp"
namespace fit
{
class MesgCapabilitiesMesgListener
{
public:
virtual ~MesgCapabilitiesMesgListener() {}
virtual void OnMesg(MesgCapabilitiesMesg& mesg) = 0;
};
} // namespace fit
#endif // !defined(FIT_MESG_CAPABILITIES_MESG_LISTENER_HPP)
| [
"briceguard-git@yahoo.com"
] | briceguard-git@yahoo.com |
6707ca0bcc933fbbbb69e59ed40280223bb5b351 | 5cad8d9664c8316cce7bc57128ca4b378a93998a | /CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/javax/naming/InsufficientResourcesException.h | d3fc6603c03e029870f59c3b4e95042a442f1b70 | [
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"GPL-3.0-only",
"curl",
"Zlib",
"LicenseRef-scancode-warranty-disclaimer",
"OpenSSL",
"GPL-1.0-or-later",
"MIT",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"BSD-3-... | permissive | huaweicloud/huaweicloud-sdk-c-obs | 0c60d61e16de5c0d8d3c0abc9446b5269e7462d4 | fcd0bf67f209cc96cf73197e9c0df143b1d097c4 | refs/heads/master | 2023-09-05T11:42:28.709499 | 2023-08-05T08:52:56 | 2023-08-05T08:52:56 | 163,231,391 | 41 | 21 | Apache-2.0 | 2023-06-28T07:18:06 | 2018-12-27T01:15:05 | C | UTF-8 | C++ | false | false | 741 | h |
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __javax_naming_InsufficientResourcesException__
#define __javax_naming_InsufficientResourcesException__
#pragma interface
#include <javax/naming/NamingException.h>
extern "Java"
{
namespace javax
{
namespace naming
{
class InsufficientResourcesException;
}
}
}
class javax::naming::InsufficientResourcesException : public ::javax::naming::NamingException
{
public:
InsufficientResourcesException();
InsufficientResourcesException(::java::lang::String *);
private:
static const jlong serialVersionUID = 6227672693037844532LL;
public:
static ::java::lang::Class class$;
};
#endif // __javax_naming_InsufficientResourcesException__
| [
"xiangshijian1@huawei.com"
] | xiangshijian1@huawei.com |
d8683d6572111d112b800f9b7c26163dc90a179f | 4f5b2819d01c5494b7ec50a35985088e811d452a | /moc_fenetreajout.cpp | 96e1331f44c13733db6070a2a0c1669c13193d4c | [] | no_license | Renaudeau82/Code-maker | c0d11f63c70092c082240e858160989d7c9e38e1 | f29439ed605ef29c2384011024cd5caf02c81e5c | refs/heads/master | 2020-09-21T21:17:51.065190 | 2016-09-14T15:04:28 | 2016-09-14T15:04:28 | 66,939,759 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,358 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'fenetreajout.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.2.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "fenetreajout.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'fenetreajout.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.2.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_FenetreAjout_t {
QByteArrayData data[4];
char stringdata[36];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
offsetof(qt_meta_stringdata_FenetreAjout_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData) \
)
static const qt_meta_stringdata_FenetreAjout_t qt_meta_stringdata_FenetreAjout = {
{
QT_MOC_LITERAL(0, 0, 12),
QT_MOC_LITERAL(1, 13, 12),
QT_MOC_LITERAL(2, 26, 0),
QT_MOC_LITERAL(3, 27, 7)
},
"FenetreAjout\0cliquAjouter\0\0cliquer\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_FenetreAjout[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 3, 24, 2, 0x06,
// slots: name, argc, parameters, tag, flags
3, 0, 31, 2, 0x08,
// signals: parameters
QMetaType::Void, QMetaType::QString, QMetaType::QString, QMetaType::QString, 2, 2, 2,
// slots: parameters
QMetaType::Void,
0 // eod
};
void FenetreAjout::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
FenetreAjout *_t = static_cast<FenetreAjout *>(_o);
switch (_id) {
case 0: _t->cliquAjouter((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2])),(*reinterpret_cast< QString(*)>(_a[3]))); break;
case 1: _t->cliquer(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (FenetreAjout::*_t)(QString , QString , QString );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&FenetreAjout::cliquAjouter)) {
*result = 0;
}
}
}
}
const QMetaObject FenetreAjout::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_FenetreAjout.data,
qt_meta_data_FenetreAjout, qt_static_metacall, 0, 0}
};
const QMetaObject *FenetreAjout::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *FenetreAjout::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_FenetreAjout.stringdata))
return static_cast<void*>(const_cast< FenetreAjout*>(this));
return QDialog::qt_metacast(_clname);
}
int FenetreAjout::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 2)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 2;
}
return _id;
}
// SIGNAL 0
void FenetreAjout::cliquAjouter(QString _t1, QString _t2, QString _t3)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
QT_END_MOC_NAMESPACE
| [
"noreply@github.com"
] | noreply@github.com |
a8d3fa5b20e1398bc61841ed07cba275a88f71b7 | a56302f627d99a8fc78d6ed125e691caa13c1249 | /FIT2097_AAA2/Source/FIT2097_AAA2/HealthPickup.cpp | ff8aa3a9e65855d43c0132260e134eeb4ea3e49b | [] | no_license | xuhaojun0522/FIT2097_AAA2 | 9a936561ed33fefbd82c8c29a87827dee3d37b8d | 5191ea8f499865b20b2b945da653e8737b976585 | refs/heads/master | 2020-04-01T20:07:02.459772 | 2018-10-20T08:57:31 | 2018-10-20T08:57:31 | 153,589,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 744 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "HealthPickup.h"
#include "FIT2097_AAA2Character.h"
// Sets default values
AHealthPickup::AHealthPickup()
{
bReplicates = true;
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
OnActorBeginOverlap.AddDynamic(this, &AHealthPickup::OnOverlap);
}
void AHealthPickup::OnOverlap(AActor* MyOverlappedActor, AActor* OtherActor)
{
if (OtherActor != nullptr && OtherActor != this)
{
class AFIT2097_AAA2Character* MyCharacter = Cast<AFIT2097_AAA2Character>(OtherActor);
if (MyCharacter && MyCharacter->getHealth() < 1.0f)
{
MyCharacter->UpdateHealth(30.0f);
Destroy();
}
}
} | [
"hxu137@student.monash.edu"
] | hxu137@student.monash.edu |
6ebf481b877042257988caf4055667260426b1a1 | 7e288ad3bcaca2e00e04113ebd251331b5ea300c | /starviewer/src/core/frameofreferencesynccriterion.h | 8be7ceb06a673f73d9af98261083d1786e85b156 | [] | no_license | idvr/starviewer | b7fb2eb38e8cce6f6cd9b4b10371a071565ae4fc | 94bf98803e4face8f81ff68447cf52a686571ad7 | refs/heads/master | 2020-12-02T17:46:13.018426 | 2014-12-02T11:29:38 | 2014-12-02T11:31:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 465 | h | #ifndef UDG_FRAMEOFREFERENCESYNCCRITERION_H
#define UDG_FRAMEOFREFERENCESYNCCRITERION_H
#include "synccriterion.h"
namespace udg {
class QViewer;
/**
Implements the SyncCriterion for Frame Of References.
*/
class FrameOfReferenceSyncCriterion : public SyncCriterion
{
public:
FrameOfReferenceSyncCriterion();
protected:
bool criterionIsMet(QViewer *viewer1, QViewer *viewer2);
};
} // namespace udg
#endif // UDG_FRAMEOFREFERENCESYNCCRITERION_H
| [
"rogerbramon@gmail.com"
] | rogerbramon@gmail.com |
1a0471250669897bee44b7058426f05bd4be7c81 | c08a26d662bd1df1b2beaa36a36d0e9fecc1ebac | /classicui_plat/extended_notifiers_api/inc/AknSmallIndicator.h | 4d2e4a05ff052d1b66675c41134a833db13e834e | [] | no_license | SymbianSource/oss.FCL.sf.mw.classicui | 9c2e2c31023256126bb2e502e49225d5c58017fe | dcea899751dfa099dcca7a5508cf32eab64afa7a | refs/heads/master | 2021-01-11T02:38:59.198728 | 2010-10-08T14:24:02 | 2010-10-08T14:24:02 | 70,943,916 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,823 | h | /*
* Copyright (c) 2002-2007 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#ifndef C_AKNSMALLINDICATOR_H
#define C_AKNSMALLINDICATOR_H
#include <AknNotify.h>
NONSHARABLE_CLASS(CAknSmallIndicator) : public CAknNotifyBase
{
public:
/**
* Two-phased constructor.
*
* @param aIndicatorUid UID of the status indicator.
* @return Pointer to a new @c CAknSmallIndicator instance.
*/
IMPORT_C static CAknSmallIndicator* NewL( TUid aIndicatorUid );
/**
* Two-phased constructor. Leaves the created instance
* on the cleanup stack.
*
* @param aIndicatorUid UID of the status indicator.
* @return Pointer to a new @c CAknSmallIndicator instance.
*/
IMPORT_C static CAknSmallIndicator* NewLC( TUid aIndicatorUid );
/**
* Destructor.
*/
IMPORT_C ~CAknSmallIndicator();
/**
* Sets the state of the status indicator.
*
* @param aState The state to be set to the indicator.
* @see MAknIndicator::TAknIndicatorState
*/
IMPORT_C void SetIndicatorStateL( const TInt aState );
/**
* Handles stylus tap event on the indicator.
*/
IMPORT_C void HandleIndicatorTapL();
private:
CAknSmallIndicator();
void ConstructL( TUid aIndicatorUid );
private:
IMPORT_C void CAknNotifyBase_Reserved();
private:
TUid iIndicatorUid;
};
#endif // C_AKNSMALLINDICATOR_H
| [
"kirill.dremov@nokia.com"
] | kirill.dremov@nokia.com |
f5427c3919be3c04352d0e97bd89aa7e687352d1 | 1cbaa88247a3555986965f8f1d2f522a9995fe4f | /1.2/ArmnnDriverImpl.hpp | eeb491b65b255456c795082e581c56468363865c | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | MitchellTesla/android-nn-driver | 1e33bd5c96b68a2c3cef7af7460d9e7bbe0b1faa | 0fdc70c630296666820da031e19278ecc7e3ddda | refs/heads/main | 2023-04-19T12:19:07.941529 | 2021-05-02T15:11:43 | 2021-05-02T15:11:43 | 363,674,471 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,333 | hpp | //
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once
#include <HalInterfaces.h>
#include "../DriverOptions.hpp"
#include <armnn/ArmNN.hpp>
#ifdef ARMNN_ANDROID_R
using namespace android::nn::hal;
#endif
#ifdef ARMNN_ANDROID_S
using namespace android::hardware;
#endif
namespace V1_0 = ::android::hardware::neuralnetworks::V1_0;
namespace V1_2 = ::android::hardware::neuralnetworks::V1_2;
namespace armnn_driver
{
namespace hal_1_2
{
class ArmnnDriverImpl
{
public:
static Return<V1_0::ErrorStatus> prepareArmnnModel_1_2(const armnn::IRuntimePtr& runtime,
const armnn::IGpuAccTunedParametersPtr& clTunedParameters,
const DriverOptions& options,
const V1_2::Model& model,
const android::sp<V1_2::IPreparedModelCallback>& cb,
bool float32ToFloat16 = false);
static Return<void> getCapabilities_1_2(const armnn::IRuntimePtr& runtime,
V1_2::IDevice::getCapabilities_1_2_cb cb);
};
} // namespace hal_1_2
} // namespace armnn_driver | [
"noreply@github.com"
] | noreply@github.com |
fa1d30c22371a9e6c78549cc77313a5d79e62dc3 | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/ThirdParty/CEF3/cef_binary_3.3071.1611.g4a19305_macosx64/libcef_dll/cpptoc/render_handler_cpptoc.h | 3c62d30f5191b7c866e493349328355fb7a81907 | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 1,222 | h | // Copyright (c) 2017 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
#ifndef CEF_LIBCEF_DLL_CPPTOC_RENDER_HANDLER_CPPTOC_H_
#define CEF_LIBCEF_DLL_CPPTOC_RENDER_HANDLER_CPPTOC_H_
#pragma once
#if !defined(WRAPPING_CEF_SHARED)
#error This file can be included wrapper-side only
#endif
#include "include/cef_render_handler.h"
#include "include/capi/cef_render_handler_capi.h"
#include "libcef_dll/cpptoc/cpptoc_ref_counted.h"
// Wrap a C++ class with a C structure.
// This class may be instantiated and accessed wrapper-side only.
class CefRenderHandlerCppToC
: public CefCppToCRefCounted<CefRenderHandlerCppToC, CefRenderHandler,
cef_render_handler_t> {
public:
CefRenderHandlerCppToC();
};
#endif // CEF_LIBCEF_DLL_CPPTOC_RENDER_HANDLER_CPPTOC_H_
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
df95285e2afe7819db2c924b99002b10290d7a2f | 68da9bbda7418d0f8ddb205dc8581040ce997baa | /UnionFind.hpp | 8d7ccfeb0810a7d60301a8166821d4bf4a9a4454 | [] | no_license | larissayiyi/six-degrees-of-kevin-bacon | c1840e9e02b28627596ca7e1eb9141f4855f25f8 | 6b20aee1daab9ef07aa68c3ba886aaa35b668b10 | refs/heads/master | 2020-04-17T03:22:48.616300 | 2019-01-17T07:33:43 | 2019-01-17T07:33:43 | 166,180,151 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,776 | hpp | /***
* Name: Aaron Liu, Larissa Johnson
* Date: Nov 28 2016
* Filename: UnionFind.hpp
* Description: Contains methods for a disjoint set data structure, which
* primarily functions as an up-tree.
* Assigment Number: 4
* Sources of help:
***/
#ifndef UNIONFIND_HPP
#define UNIONFIND_HPP
#include <unordered_map>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <fstream>
#include "ActorNode.h"
#include "Movie.h"
using namespace std;
class UnionFind
{
public:
unordered_map<string, Movie *> movieList;
unordered_map<string, vector<ActorNode *>> forest;
UnionFind(void);
bool loadFromFile(const char* in_filename);
ActorNode * find(ActorNode * actor);
bool unionActor(ActorNode * actor1, ActorNode * actor2);
~UnionFind();
private:
};
/* Funtion name: UnionFind
* Description: constructor for the unionfind object
* Parameters: none
* Return value: none
*/
UnionFind::UnionFind(void){}
bool UnionFind::loadFromFile(const char * in_filename)
{
// Initialize the file stream
ifstream infile(in_filename);
bool have_header = false;
// keep reading lines until the end of file is reached
while (infile) {
string s;
// get the next line
if (!getline( infile, s )) break;
if (!have_header) {
// skip the header
have_header = true;
continue;
}
istringstream ss( s );
vector <string> record;
while (ss) {
string next;
// get the next string before hitting a tab character and put it
// in 'next'
if (!getline( ss, next, '\t' )) break;
record.push_back( next );
}
if (record.size() != 3) {
// we should have exactly 3 columns
continue;
}
string actor_name(record[0]);
string movie_title(record[1]);
int movie_year = stoi(record[2]);
// pairing the name of the movie with the year it's made
//pair <string, int> pairMovie(movie_title, movie_year);
//Pair used to hold information about the actor
ActorNode * workingActor;
unordered_map<string, vector<ActorNode *>> :: iterator findActor =
forest.find(actor_name);
//Create new actor node if no node for actor exists yet
if((findActor == forest.end()) || forest.empty())
{
//Create new actor object
ActorNode * newActor = new ActorNode(actor_name);
vector<ActorNode *> forestEntry;
forestEntry.push_back(newActor);
//Create pair with actorname as key to insert to hashmap
pair <string, vector<ActorNode *>>
actorInfo(actor_name, forestEntry);
//Insert to hashmap
forest.insert(actorInfo);
workingActor = newActor;
}
else
{
workingActor = findActor->second[0];
}
string originalTitle = movie_title;
//Find movie in list, if it exists
unordered_map<string, Movie *> :: iterator findMovie =
movieList.find(movie_title.append(record[2]));
//If it doesn't create
if((findMovie == movieList.end()) || movieList.empty())
{
//create move if it doesn't exist yet
Movie * newMovie = new Movie(originalTitle, movie_year);
//Insert the actor into the movie
newMovie->cast.push_back(workingActor);
//Insert new movie into list, with year appended for key
pair<string, Movie *> movieInfo(movie_title, newMovie);
movieList.insert(movieInfo);
}
else
{
//Add actor to new cast if it exists already
findMovie->second->cast.push_back(workingActor);
}
}
if (!infile.eof()) {
cerr << "Failed to read " << in_filename << "!\n";
return false;
}
infile.close();
return true;
}
/* Funtion name: unionActor
* Description: union two actors from two disjointed sets
* Parameters:
* ActorNode * actor1 - first actor to union
* ActorNode * actor2 - second actor to union
* Return value: true if union is successful false otherwise
*/
bool UnionFind::unionActor(ActorNode * actor1, ActorNode * actor2)
{
ActorNode * temp1 = find(actor1);
ActorNode * temp2 = find(actor2);
// if they have the same sentinel theres no need for union
if(temp1 == temp2)
{
return true;
}
// iterators to find the two sets with the sentinels
unordered_map<string, vector<ActorNode *>>::iterator set1 =
forest.find(temp1->name);
unordered_map<string, vector<ActorNode *>>::iterator set2 =
forest.find(temp2->name);
// if the sets are not in the file
if(set1 == forest.end() || set2 == forest.end())
{
return false;
}
// the larger set becomes the sentinel
if(set1->second.size() > set2->second.size())
{
set2->second[0]->prev = set1->second[0];
// add nodes of set2 to the set1's vector
for(int i = 0; i < set2->second.size(); i++)
{
set1->second.push_back(set2->second[i]);
}
}
// when set2 is the bigger set do the opposite
else
{
set1->second[0]->prev = set2->second[0];
for(int i = 0; i < set1->second.size(); i++)
{
set2->second.push_back(set1->second[i]);
}
}
return true;
}
/* Funtion name: find
* Description: find the sentinel of the actor and optimize nodes along the
* paths
* Parameters: ActorNode * actor - actor we would like to find the sentinel of
* Return value: sentinel of the actor
*/
ActorNode * UnionFind::find(ActorNode * actor)
{
// list of actors on the path for optimization purposes
vector<ActorNode *> traversedNodes;
// when actor is the sentinel
if(!actor->prev)
{
return actor;
}
// keep going to the top of the set
while(actor->prev)
{
// add node to traversedNodes to optimize the paths
traversedNodes.push_back(actor);
actor = actor->prev;
}
// for all the nodes on the path
for(int i = 0; i < traversedNodes.size(); i++)
{
// make prev the sentinel of the set
traversedNodes[i]->prev = actor;
}
return actor;
}
/* Funtion name: ~UnionFind
* Description: destructor of the unionfind object
* Parameters: none
* Return value: none
*/
UnionFind::~UnionFind()
{
// iterator for the forest
unordered_map<string, vector<ActorNode *>>::iterator ra;
// iterator for the movieList
unordered_map<string, Movie *>::iterator rm;
for(ra = forest.begin(); ra != forest.end(); ra++)
{
// delete the sentinels of each set, since we never deleted
delete ra->second[0];
}
forest.clear();
for(rm = movieList.begin(); rm != movieList.end(); rm++)
{
// delete all the movie pointers
delete rm->second;
}
}
#endif
| [
"noreply@github.com"
] | noreply@github.com |
b14153f73561d7920ddec9948897dca56f936b9b | 2ce94aa05d8740a57f1dc4557e4da16ddaaabf7f | /src/main.cpp | c60648bd1fd9304a49c3d4b2d0c13659615483e3 | [] | no_license | renneSampaio/basicPixelEditor | 98b740f965b9ecfca623c3682083dbdfe9f1524f | d58d985d70591ed568cde2cbf2a23f68a30aae82 | refs/heads/master | 2020-03-27T09:24:51.176928 | 2018-08-27T18:39:55 | 2018-08-27T18:39:55 | 146,339,095 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,925 | cpp | #include <iostream>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include "Bitmap.hpp"
#include "Tool.hpp"
#include "PenTool.hpp"
#include "LineTool.hpp"
#include "RectTool.hpp"
#include "CircleTool.hpp"
#include "PolyTool.hpp"
#include "FillTool.hpp"
Bitmap image(32,32);
Tool* currentTool;
const int PIXEL_SIZE = 10;
Pixel mainColor = 0x000000FF;
Pixel secondaryColor = 0xFFFFFFFF;
void draw();
void keyboardInput(unsigned char key, int x, int y);
void mouseInput(int button, int state, int x, int y);
void mouseMotionInput(int x, int y);
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutInitWindowSize(image.getWidth() * PIXEL_SIZE, image.getHeight() * PIXEL_SIZE);
glutCreateWindow("Image Editor");
glewInit();
glutDisplayFunc(draw);
glutKeyboardFunc(keyboardInput);
glutMouseFunc(mouseInput);
glutMotionFunc(mouseMotionInput);
image.clear(0xFFFFFFFF);
currentTool = new PolyTool(image, mainColor, secondaryColor);
glClearColor(0,0,0,1);
glutMainLoop();
}
void draw()
{
glClear(GL_COLOR_BUFFER_BIT);
image.draw();
glutSwapBuffers();
glutPostRedisplay();
}
void changeTool(Tool* newTool) {
delete currentTool;
currentTool = newTool;
}
void keyboardInput(unsigned char key, int x, int y)
{
x /= PIXEL_SIZE;
y /= PIXEL_SIZE;
switch(key)
{
case 'c':
case 'C':
image.clear(0xFFFFFFFF);
break;
case 'p':
changeTool(new PenTool(image, mainColor, secondaryColor));
break;
case 'l':
changeTool(new LineTool(image, mainColor, secondaryColor));
break;
case 's':
changeTool(new CircleTool(image, mainColor, secondaryColor));
break;
case 'y':
changeTool(new PolyTool(image, mainColor, secondaryColor));
break;
case 'r':
changeTool(new RectTool(image, mainColor, secondaryColor));
break;
case 'f':
changeTool(new FillTool(image, mainColor, secondaryColor));
break;
case 'h':
std::cout << "Instructions:\n";
std::cout << "-> 'c' - Clear image\n";
std::cout << "-> 'p' - Pen Tool\n";
std::cout << " Left Click to set pixel with main color\n";
std::cout << " Right Click to set pixel with secondary color\n";
std::cout << "-> 'l' - Line Tool\n";
std::cout << " Left Click to set start position\n";
std::cout << " Left Click again to set end position and draw line\n";
std::cout << " Right Click again to finish drawing lines\n";
std::cout << "-> 'r' - Rect Tool\n";
std::cout << " Left Click to set first position\n";
std::cout << " Left Click again to set second position and draw circle\n";
std::cout << "-> 'y' - Poly Tool\n";
std::cout << " Left Click to add positions to polygon\n";
std::cout << " Right Click to draw polygon (Only draws if there are more than 2 positions set)\n";
std::cout << "-> 's' - Circle Tool\n";
std::cout << " Left Click to set center\n";
std::cout << " Left Click again to set radius and draw circle\n";
std::cout << "-> 'f' - Fill Tool\n";
std::cout << " Left Click to fill area\n";
break;
default:
currentTool->getKeyboardInput(key, x, y);
}
}
void mouseInput(int button, int state, int x, int y)
{
x /= PIXEL_SIZE;
y /= PIXEL_SIZE;
currentTool->getMouseInput(button, state, x, y);
}
void mouseMotionInput(int x, int y)
{
x /= PIXEL_SIZE;
y /= PIXEL_SIZE;
currentTool->getMouseMotionInput(x,y);
}
| [
"rennesampaio97@gmail.com"
] | rennesampaio97@gmail.com |
b91743d34cf7e0b2393633eedb69131915d2cd35 | b09f567815d297a169126d5235cfb1d8945e1faa | /TorneoArgentino/Dfelicidad.cc | 69a76368da0e74b2058c264d58717aaeb99fe726 | [] | no_license | alsuga/Maratones | c913c858e317047a3c4b2944627c814fc2084bd2 | 7271bda427a6ebddf0599d4f6b333d0ab81ecb71 | refs/heads/master | 2021-01-17T15:31:11.039085 | 2016-09-05T20:39:00 | 2016-09-05T20:39:00 | 8,393,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 990 | cc | #include <bits/stdc++.h>
using namespace std;
bool visit[1001];
typedef map<int, set<int> > gf;
gf grafo;
int dfs(int i, int R, int E) {
visit[i] = true;
stack<int> st;
st.push(i);
int tmp;
int nodos = 0, aristas = 0;
while(!st.empty()) {
nodos++;
tmp = st.top(); st.pop();
aristas += grafo[tmp].size();
for(set<int>::iterator it = grafo[tmp].begin(); it != grafo[tmp].end(); ++it) {
if(!visit[*it]) {
st.push(*it);
visit[*it] = true;
}
}
}
aristas >>= 1;
tmp = ((nodos - 1) * nodos ) / 2;
tmp -= aristas;
return min(tmp * R, nodos * E);
}
int main() {
int N, M, R, E;
cin >> N >> M >> R >> E;
for(int i = 0; i < N; i++)
visit[i] = false;
int x,y;
for(int i = 0; i < M; i++) {
cin >> x >> y;
x--;
y--;
grafo[x].insert(y);
grafo[y].insert(x);
}
int acum = 0;
for(int i = 0; i < N; i++) {
if(!visit[i])
acum += dfs(i, R, E);
}
cout << acum << endl;
return 0;
}
| [
"alejandro@sirius.utp.edu.co"
] | alejandro@sirius.utp.edu.co |
07bb8ab8f48852371516454eb5a4152edab8a711 | 60c1ece8ba473b0a4060f94a4d61404ea1d63e3b | /devel51f/electromagnetic/src/G4EmLivermoreLEPTSPhysics.cc | 6d4864fc2a081b0ecf54ab45c62dcfeb5a42fdf2 | [] | no_license | antoniomzrl/gitrepo3 | 80b2e868393e8e7872ce1276dbcdc6522edac82b | 9a181a4330ce5d287c0dae7e5a305c8ea22dd747 | refs/heads/master | 2021-06-17T06:05:49.261667 | 2021-04-04T12:29:35 | 2021-04-04T12:29:35 | 82,538,975 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,627 | cc | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// $Id: G4EmLivermoreLEPTSPhysics.cc 80150 2014-04-03 09:40:55Z gcosmo $
#include "G4EmLivermoreLEPTSPhysics.hh"
#include "G4ParticleDefinition.hh"
#include "G4SystemOfUnits.hh"
// *** Processes and models
// gamma
#include "G4PhotoElectricEffect.hh"
#include "G4LivermorePhotoElectricModel.hh"
#include "G4ComptonScattering.hh"
#include "G4LivermoreComptonModel.hh"
#include "G4GammaConversion.hh"
#include "G4LivermoreGammaConversionModel.hh"
#include "G4RayleighScattering.hh"
#include "G4LivermoreRayleighModel.hh"
// e+-
#include "G4eMultipleScattering.hh"
#include "G4UniversalFluctuation.hh"
#include "G4eIonisation.hh"
#include "G4LivermoreIonisationModel.hh"
#include "G4eBremsstrahlung.hh"
#include "G4LivermoreBremsstrahlungModel.hh"
#include "G4Generator2BS.hh"
// e+
#include "G4eplusAnnihilation.hh"
// mu+-
#include "G4MuMultipleScattering.hh"
#include "G4MuIonisation.hh"
#include "G4MuBremsstrahlung.hh"
#include "G4MuPairProduction.hh"
#include "G4MuBremsstrahlungModel.hh"
#include "G4MuPairProductionModel.hh"
#include "G4hBremsstrahlungModel.hh"
#include "G4hPairProductionModel.hh"
// hadrons
#include "G4hMultipleScattering.hh"
#include "G4MscStepLimitType.hh"
#include "G4hBremsstrahlung.hh"
#include "G4hPairProduction.hh"
#include "G4hIonisation.hh"
#include "G4ionIonisation.hh"
#include "G4alphaIonisation.hh"
#include "G4IonParametrisedLossModel.hh"
#include "G4NuclearStopping.hh"
// msc models
#include "G4UrbanMscModel.hh"
#include "G4WentzelVIModel.hh"
#include "G4GoudsmitSaundersonMscModel.hh"
#include "G4CoulombScattering.hh"
#include "G4eCoulombScatteringModel.hh"
// interfaces
#include "G4LossTableManager.hh"
#include "G4EmProcessOptions.hh"
#include "G4UAtomicDeexcitation.hh"
// particles
#include "G4Gamma.hh"
#include "G4Electron.hh"
#include "G4Positron.hh"
#include "G4MuonPlus.hh"
#include "G4MuonMinus.hh"
#include "G4PionPlus.hh"
#include "G4PionMinus.hh"
#include "G4KaonPlus.hh"
#include "G4KaonMinus.hh"
#include "G4Proton.hh"
#include "G4AntiProton.hh"
#include "G4Deuteron.hh"
#include "G4Triton.hh"
#include "G4He3.hh"
#include "G4Alpha.hh"
#include "G4GenericIon.hh"
//
#include "G4PhysicsListHelper.hh"
#include "G4BuilderType.hh"
// factory
#include "G4PhysicsConstructorFactory.hh"
#include "G4ProcessManager.hh"
//
G4_DECLARE_PHYSCONSTR_FACTORY(G4EmLivermoreLEPTSPhysics);
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
G4EmLivermoreLEPTSPhysics::G4EmLivermoreLEPTSPhysics(G4double highELimit, G4int ver)
: G4VPhysicsConstructor("G4EmLivermoreLEPTSPhysics"), verbose(ver)
{
theLEPTSHighEnergyLimit = highELimit;
G4LossTableManager::Instance();
SetPhysicsType(bElectromagnetic);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
G4EmLivermoreLEPTSPhysics::G4EmLivermoreLEPTSPhysics(G4int ver, const G4String&)
: G4VPhysicsConstructor("G4EmLivermoreLEPTSPhysics"), verbose(ver)
{
G4LossTableManager::Instance();
SetPhysicsType(bElectromagnetic);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
G4EmLivermoreLEPTSPhysics::~G4EmLivermoreLEPTSPhysics()
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void G4EmLivermoreLEPTSPhysics::ConstructParticle()
{
// gamma
G4Gamma::Gamma();
// leptons
G4Electron::Electron();
G4Positron::Positron();
G4MuonPlus::MuonPlus();
G4MuonMinus::MuonMinus();
// mesons
G4PionPlus::PionPlusDefinition();
G4PionMinus::PionMinusDefinition();
G4KaonPlus::KaonPlusDefinition();
G4KaonMinus::KaonMinusDefinition();
// baryons
G4Proton::Proton();
G4AntiProton::AntiProton();
// ions
G4Deuteron::Deuteron();
G4Triton::Triton();
G4He3::He3();
G4Alpha::Alpha();
G4GenericIon::GenericIonDefinition();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void G4EmLivermoreLEPTSPhysics::ConstructProcess()
{
if(verbose > 1) {
G4cout << "### " << GetPhysicsName() << " Construct Processes " << G4endl;
}
G4PhysicsListHelper* ph = G4PhysicsListHelper::GetPhysicsListHelper();
// muon & hadron bremsstrahlung and pair production
G4MuBremsstrahlung* mub = new G4MuBremsstrahlung();
G4MuPairProduction* mup = new G4MuPairProduction();
G4hBremsstrahlung* pib = new G4hBremsstrahlung();
G4hPairProduction* pip = new G4hPairProduction();
G4hBremsstrahlung* kb = new G4hBremsstrahlung();
G4hPairProduction* kp = new G4hPairProduction();
G4hBremsstrahlung* pb = new G4hBremsstrahlung();
G4hPairProduction* pp = new G4hPairProduction();
// muon & hadron multiple scattering
G4MuMultipleScattering* mumsc = new G4MuMultipleScattering();
mumsc->AddEmModel(0, new G4WentzelVIModel());
G4hMultipleScattering* pimsc = new G4hMultipleScattering();
//pimsc->AddEmModel(0, new G4WentzelVIModel());
G4hMultipleScattering* kmsc = new G4hMultipleScattering();
//kmsc->AddEmModel(0, new G4WentzelVIModel());
G4hMultipleScattering* pmsc = new G4hMultipleScattering();
//pmsc->AddEmModel(0, new G4WentzelVIModel());
G4hMultipleScattering* hmsc = new G4hMultipleScattering("ionmsc");
// high energy limit for e+- scattering models
G4double highEnergyLimit = 100*MeV;
// nuclear stopping
G4NuclearStopping* ionnuc = new G4NuclearStopping();
G4NuclearStopping* pnuc = new G4NuclearStopping();
// Add Livermore EM Processes
aParticleIterator->reset();
while( (*aParticleIterator)() ){
G4ParticleDefinition* particle = aParticleIterator->value();
G4String particleName = particle->GetParticleName();
G4ProcessManager* pmanager = particle->GetProcessManager();
if (particleName == "gamma") {
// photoelectric effect - Livermore model only
G4PhotoElectricEffect* thePhotoElectricEffect = new G4PhotoElectricEffect();
thePhotoElectricEffect->SetEmModel(new G4LivermorePhotoElectricModel(), 1);
ph->RegisterProcess(thePhotoElectricEffect, particle);
// Compton scattering - Livermore model only
G4ComptonScattering* theComptonScattering = new G4ComptonScattering();
theComptonScattering->SetEmModel(new G4LivermoreComptonModel(),1);
ph->RegisterProcess(theComptonScattering, particle);
// gamma conversion - Livermore model below 80 GeV
G4GammaConversion* theGammaConversion = new G4GammaConversion();
theGammaConversion->SetEmModel(new G4LivermoreGammaConversionModel(),1);
ph->RegisterProcess(theGammaConversion, particle);
// default Rayleigh scattering is Livermore
G4RayleighScattering* theRayleigh = new G4RayleighScattering();
ph->RegisterProcess(theRayleigh, particle);
} else if (particleName == "e-") {
continue; // multiple scattering
G4eMultipleScattering* msc = new G4eMultipleScattering;
msc->SetStepLimitType(fUseDistanceToBoundary);
G4UrbanMscModel* msc1 = new G4UrbanMscModel();
G4WentzelVIModel* msc2 = new G4WentzelVIModel();
msc1->SetHighEnergyLimit(highEnergyLimit);
msc2->SetLowEnergyLimit(highEnergyLimit);
msc->SetRangeFactor(0.01);
msc->AddEmModel(0, msc1);
msc->AddEmModel(0, msc2);
msc1->SetLowEnergyLimit(theLEPTSHighEnergyLimit);
msc2->SetLowEnergyLimit(theLEPTSHighEnergyLimit);
G4eCoulombScatteringModel* ssm = new G4eCoulombScatteringModel();
G4CoulombScattering* ss = new G4CoulombScattering();
ss->SetEmModel(ssm, 1);
ss->SetMinKinEnergy(highEnergyLimit);
ssm->SetLowEnergyLimit(highEnergyLimit);
ssm->SetActivationLowEnergyLimit(highEnergyLimit);
ssm->SetLowEnergyLimit(theLEPTSHighEnergyLimit);
// Ionisation - Livermore should be used only for low energies
G4eIonisation* eIoni = new G4eIonisation();
eIoni->SetLowestEnergyLimit(10*keV);
G4LivermoreIonisationModel* theIoniLivermore = new
G4LivermoreIonisationModel();
// theIoniLivermore->SetHighEnergyLimit(0.4*MeV);
theIoniLivermore->SetLowEnergyLimit(0.01); //xtheLEPTSHighEnergyLimit);
// eIoni->SetEmModel(theIoniLivermore,0);
theIoniLivermore->SetActivationLowEnergyLimit(0.01);
eIoni->AddEmModel(0, theIoniLivermore, new G4UniversalFluctuation() );
eIoni->SetStepFunction(0.2, 100*um); //
G4cout << theIoniLivermore << " LOW " << theIoniLivermore->LowEnergyLimit() << G4endl;//GDEB
// Bremsstrahlung
G4eBremsstrahlung* eBrem = new G4eBremsstrahlung();
G4VEmModel* theBremLivermore = new G4LivermoreBremsstrahlungModel();
theBremLivermore->SetHighEnergyLimit(1*GeV);
theBremLivermore->SetAngularDistribution(new G4Generator2BS());
theBremLivermore->SetLowEnergyLimit(theLEPTSHighEnergyLimit);
eBrem->SetEmModel(theBremLivermore,1);
// register processes
pmanager->AddProcess(msc, -1, 1, 1);
pmanager->AddProcess(eIoni, -1, 2, 2);
pmanager->AddProcess(eBrem, -1,-3, 3);
pmanager->AddProcess(ss, -1,-4, 4);
} else if (particleName == "e+") {
continue;
// multiple scattering
G4eMultipleScattering* msc = new G4eMultipleScattering;
msc->SetStepLimitType(fUseDistanceToBoundary);
G4UrbanMscModel* msc1 = new G4UrbanMscModel();
G4WentzelVIModel* msc2 = new G4WentzelVIModel();
msc1->SetHighEnergyLimit(highEnergyLimit);
msc2->SetLowEnergyLimit(highEnergyLimit);
msc->SetRangeFactor(0.01);
msc->AddEmModel(0, msc1);
msc->AddEmModel(0, msc2);
msc1->SetHighEnergyLimit(theLEPTSHighEnergyLimit);
msc2->SetHighEnergyLimit(theLEPTSHighEnergyLimit);
G4eCoulombScatteringModel* ssm = new G4eCoulombScatteringModel();
G4CoulombScattering* ss = new G4CoulombScattering();
ss->SetEmModel(ssm, 1);
ss->SetMinKinEnergy(highEnergyLimit);
ssm->SetLowEnergyLimit(highEnergyLimit);
ssm->SetActivationLowEnergyLimit(highEnergyLimit);
ssm->SetHighEnergyLimit(theLEPTSHighEnergyLimit);
// ionisation
G4eIonisation* eIoni = new G4eIonisation();
eIoni->SetStepFunction(0.2, 100*um);
// register processes
ph->RegisterProcess(msc, particle);
ph->RegisterProcess(eIoni, particle);
ph->RegisterProcess(new G4eBremsstrahlung(), particle);
ph->RegisterProcess(new G4eplusAnnihilation(), particle);
ph->RegisterProcess(ss, particle);
} else if (particleName == "mu+" ||
particleName == "mu-" ) {
G4MuIonisation* muIoni = new G4MuIonisation();
muIoni->SetStepFunction(0.2, 50*um);
ph->RegisterProcess(mumsc, particle);
ph->RegisterProcess(muIoni, particle);
ph->RegisterProcess(mub, particle);
ph->RegisterProcess(mup, particle);
ph->RegisterProcess(new G4CoulombScattering(), particle);
} else if (particleName == "alpha" ||
particleName == "He3" ) {
G4hMultipleScattering* msc = new G4hMultipleScattering();
G4ionIonisation* ionIoni = new G4ionIonisation();
ionIoni->SetStepFunction(0.1, 10*um);
ph->RegisterProcess(msc, particle);
ph->RegisterProcess(ionIoni, particle);
ph->RegisterProcess(ionnuc, particle);
} else if (particleName == "GenericIon") {
G4ionIonisation* ionIoni = new G4ionIonisation();
ionIoni->SetEmModel(new G4IonParametrisedLossModel());
ionIoni->SetStepFunction(0.1, 1*um);
ph->RegisterProcess(hmsc, particle);
ph->RegisterProcess(ionIoni, particle);
ph->RegisterProcess(ionnuc, particle);
} else if (particleName == "pi+" ||
particleName == "pi-" ) {
//G4hMultipleScattering* pimsc = new G4hMultipleScattering();
G4hIonisation* hIoni = new G4hIonisation();
hIoni->SetStepFunction(0.2, 50*um);
ph->RegisterProcess(pimsc, particle);
ph->RegisterProcess(hIoni, particle);
ph->RegisterProcess(pib, particle);
ph->RegisterProcess(pip, particle);
} else if (particleName == "kaon+" ||
particleName == "kaon-" ) {
//G4hMultipleScattering* kmsc = new G4hMultipleScattering();
G4hIonisation* hIoni = new G4hIonisation();
hIoni->SetStepFunction(0.2, 50*um);
ph->RegisterProcess(kmsc, particle);
ph->RegisterProcess(hIoni, particle);
ph->RegisterProcess(kb, particle);
ph->RegisterProcess(kp, particle);
} else if (particleName == "proton" ||
particleName == "anti_proton") {
//G4hMultipleScattering* pmsc = new G4hMultipleScattering();
G4hIonisation* hIoni = new G4hIonisation();
hIoni->SetStepFunction(0.2, 50*um);
ph->RegisterProcess(pmsc, particle);
ph->RegisterProcess(hIoni, particle);
ph->RegisterProcess(pb, particle);
ph->RegisterProcess(pp, particle);
ph->RegisterProcess(pnuc, particle);
} else if (particleName == "B+" ||
particleName == "B-" ||
particleName == "D+" ||
particleName == "D-" ||
particleName == "Ds+" ||
particleName == "Ds-" ||
particleName == "anti_He3" ||
particleName == "anti_alpha" ||
particleName == "anti_deuteron" ||
particleName == "anti_lambda_c+" ||
particleName == "anti_omega-" ||
particleName == "anti_sigma_c+" ||
particleName == "anti_sigma_c++" ||
particleName == "anti_sigma+" ||
particleName == "anti_sigma-" ||
particleName == "anti_triton" ||
particleName == "anti_xi_c+" ||
particleName == "anti_xi-" ||
particleName == "deuteron" ||
particleName == "lambda_c+" ||
particleName == "omega-" ||
particleName == "sigma_c+" ||
particleName == "sigma_c++" ||
particleName == "sigma+" ||
particleName == "sigma-" ||
particleName == "tau+" ||
particleName == "tau-" ||
particleName == "triton" ||
particleName == "xi_c+" ||
particleName == "xi-" ) {
ph->RegisterProcess(hmsc, particle);
ph->RegisterProcess(new G4hIonisation(), particle);
ph->RegisterProcess(pnuc, particle);
}
}
// Em options
//
G4EmProcessOptions opt;
opt.SetVerbose(verbose);
// Multiple Coulomb scattering
//
opt.SetPolarAngleLimit(CLHEP::pi);
// Physics tables
//
opt.SetMinEnergy(100*eV);
opt.SetMaxEnergy(10*TeV);
opt.SetDEDXBinning(220);
opt.SetLambdaBinning(220);
// Nuclear stopping
pnuc->SetMaxKinEnergy(MeV);
// Ionization
//
//opt.SetSubCutoff(true);
// Deexcitation
//
G4VAtomDeexcitation* de = new G4UAtomicDeexcitation();
G4LossTableManager::Instance()->SetAtomDeexcitation(de);
de->SetFluo(true);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| [
"antonio.mzrl@gmail.com"
] | antonio.mzrl@gmail.com |
b66f56a0561096a5d0d8c428e8b0ee39538cef5b | f8a2e00c2bae4cc8d7f95a7e4f7ce1f4048c7dec | /Source/Parsers/Company/CompanyLinksParser.h | 5481bc03219a968fe3f43e76dbc7129a14b3ef72 | [
"MIT"
] | permissive | AzuxDario/Marsy | 756f81b98d26f6335c04203fbd9084c6ece2547a | d7fb746250566377cd18a9651d6b74c2bef6c342 | refs/heads/master | 2022-12-12T17:22:10.343672 | 2020-09-16T12:57:28 | 2020-09-16T12:57:28 | 274,488,096 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | h | #ifndef MARSY_COMPANY_COMPANYLINKSPARSER_H
#define MARSY_COMPANY_COMPANYLINKSPARSER_H
#include <string>
#include <vector>
#include <optional>
#include "../../Libraries/JSON/json.hpp"
#include "../Parser.h"
#include "../../Models/Company/CompanyLinksModel.h"
#include "../../Const/Company/CompanyLinksConst.h"
using json = nlohmann::json;
namespace Marsy
{
class CompanyLinksParser : public Parser, private CompanyLinksConst
{
public:
CompanyLinksParser();
CompanyLinksModel parseLinks(const json &input);
};
}
#endif | [
"pawel_mibor95@tlen.pl"
] | pawel_mibor95@tlen.pl |
f3480ce0c70abfd2330cc5ad4819a95a28f1c458 | 0ab4ae4862ace02f164b513238fab79f00267824 | /src/lexer.cpp | 70851d8da71e23dde6b27f5a794c6fc6ace18b1f | [
"LicenseRef-scancode-public-domain",
"Unlicense"
] | permissive | patrykstefanski/am-lang | f41f7829585389907f8bcd028ea33de95c0a9f82 | 15297a851665e6403d25618fb1d00ec48e51141e | refs/heads/master | 2021-01-20T18:07:49.641159 | 2016-06-29T16:47:41 | 2016-06-29T16:47:41 | 61,527,821 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,961 | cpp | #include "lexer.hpp"
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <experimental/string_view>
#include "cxx_extensions.hpp"
Lexer::Lexer(const char* source)
: next_symbol_id_(NUM_TOKENS + 1), current_line_number_(1),
current_(source + 1), last_(*source) {
// Insert keywords.
symbols_.emplace("else", ELSE);
symbols_.emplace("fn", FN);
symbols_.emplace("if", IF);
symbols_.emplace("in", IN);
symbols_.emplace("let", LET);
symbols_.emplace("out", OUT);
symbols_.emplace("return", RETURN);
symbols_.emplace("while", WHILE);
}
void Lexer::consume_token() {
int if_single;
int if_double;
for (;;) {
if (std::isalpha(last_) || last_ == '_') {
const char* lexeme = current_ - 1;
do {
last_ = *current_++;
} while (std::isalnum(last_) || last_ == '_');
const std::experimental::string_view symbol_name(lexeme,
current_ - lexeme - 1);
std::size_t symbol_id = find_or_insert_symbol(symbol_name);
if (symbol_id < NUM_TOKENS) {
token_ = symbol_id;
return;
}
token_attribute_.sz = symbol_id;
token_ = IDENTIFIER;
return;
}
if (std::isdigit(last_)) {
char* end;
token_attribute_.i64 = std::strtoll(current_ - 1, &end, 0);
current_ = end;
last_ = *current_++;
token_ = INTEGER_LITERAL;
return;
}
switch (last_) {
// Skip whitespaces.
case '\n':
++current_line_number_;
// fallthrough
case '\t':
case '\v':
case '\f':
case '\r':
case ' ':
last_ = *current_++;
continue;
case '=':
if_single = '=';
if_double = EQ;
goto relational_operators;
case '!':
if_single = '!';
if_double = NE;
goto relational_operators;
case '<':
if_single = '<';
if_double = LE;
goto relational_operators;
case '>':
if_single = '>';
if_double = GE;
goto relational_operators;
default:
token_ = last_;
last_ = *current_++;
return;
}
relational_operators:
last_ = *current_++;
if (last_ == '=') {
last_ = *current_++;
token_ = if_double;
return;
} else {
token_ = if_single;
return;
}
}
UNREACHABLE();
}
void Lexer::check_and_consume_token(int token) {
if (UNLIKELY(token_ != token)) {
std::fprintf(stderr, "Error in line %zu: expected '",
current_line_number());
print_token_name(token, stderr);
std::fputs("', but got '", stderr);
print_token_name(token_, stderr);
std::fputs("'\n", stderr);
std::exit(EXIT_FAILURE);
}
consume_token();
}
std::size_t Lexer::find_or_insert_symbol(
std::experimental::string_view symbol_name) {
auto it = symbols_.find(symbol_name);
if (it != symbols_.end()) {
return it->second;
}
symbols_.emplace(symbol_name, next_symbol_id_);
return next_symbol_id_++;
}
std::size_t Lexer::current_line_number() const {
return current_line_number_;
}
Lexer::TokenAttribute Lexer::token_attribute() const {
return token_attribute_;
}
int Lexer::token() const {
return token_;
}
void Lexer::print_symbol_name(std::size_t symbol_id, std::FILE* file) const {
for (const auto& symbol : symbols_) {
if (symbol.second == symbol_id) {
std::fwrite(symbol.first.data(), 1, symbol.first.size(), file);
return;
}
}
std::fputs("<unknown>", file);
}
void Lexer::print_token_name(int token, std::FILE* file) {
switch (token) {
case ELSE:
std::fputs("else", file);
break;
case EQ:
std::fputs("==", file);
break;
case FN:
std::fputs("fn", file);
break;
case GE:
std::fputs(">=", file);
break;
case IDENTIFIER:
std::fputs("identifier", file);
break;
case IF:
std::fputs("if", file);
break;
case IN:
std::fputs("in", file);
break;
case INTEGER_LITERAL:
std::fputs("integer_literal", file);
break;
case LE:
std::fputs("<=", file);
break;
case LET:
std::fputs("let", file);
break;
case NE:
std::fputs("!=", file);
break;
case OUT:
std::fputs("out", file);
break;
case RETURN:
std::fputs("return", file);
break;
case WHILE:
std::fputs("while", file);
break;
default:
std::fputc(token, file);
break;
}
}
| [
"patryk.stefanski@protonmail.com"
] | patryk.stefanski@protonmail.com |
3568291845cf2352aa140455dcb9bf175c3b64c8 | 66d3de1de3aaaf779df26619ba3488846f7125a8 | /C++/객체 궁금한거.cpp | 5fb1f4c83e41a2443f835fcbe7fdde966a8c3f1b | [] | no_license | donghL-dev/C-and-Cpp | 79e97dd0abf5c023d3969ef840cae0a912d58305 | bea069126eea318bb528f9f9704f729b1397387b | refs/heads/master | 2020-03-09T22:19:51.864767 | 2018-06-16T20:17:45 | 2018-06-16T20:17:45 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,564 | cpp | #include<stdlib.h>
#include<stdio.h>
#define SWAP(x, y, t) ((t)=(x), (x)=(y), (y)=(t))
void bubble_sort(int list[], int n)
{
int i, j, temp; // 변수를 선언 해주고
for(i=n-1; i>0; i--) { // i는 n-1부터 0까지 작아지고
for(j=0; j<i; j++) // j는 0부터 n-1 까지 증가된다.
if(list[j]>list[j+1]) // 여기서 list[j]가 list[j+1]보다 크다면 교체해준다.
// 즉 앞의 숫자가 뒤에숫자보다 크다면 교체해준다.
SWAP(list[j], list[j+1], temp); // j는 temp로 바꿔주고 j+1은 j로 바꿔주고
} // temp는 j+1 로 바꿔주니까 결국 j와 J+1의 자리가 바뀐다.
}
int main()
{
int i, j; // for문을 돌릴 i, j 선언
int *p = NULL; // 포인토 변수 p에 NULL 값 할당
int size = 0; // size 변수 선언 및 초기화
printf("쓰고자 하는 메모리 입력 : ");
scanf("%d", &size); // 쓰고자 하는 메모리의 크기를 입력받고
printf("\n");
p = (int*)malloc(sizeof(int)*size); // 동적 메모리 할당을 한다.
for(i=0; i<size; i++) {
printf("정렬 하고자 하는 값 입력 : ");
scanf("%d", &p[i]);
} // 할당한 메모리로 배열을 만들어 정렬 값을 입력 받는다.
printf("\n");
bubble_sort(p, size); // 버블 정렬 함수를 통해 정렬시킨다.
printf("정렬된 값 : ");
for(i=0; i<size; i++)
printf("%d ", p[i]);
// 정렬된 값을 출력해준다.
free(p); // 동적 메모리 할당을 해제해준다.
}
| [
"odh621@naver.com"
] | odh621@naver.com |
1cbb3f69eab0d7e1884e3b37edf0b28f2d464870 | 0dca3325c194509a48d0c4056909175d6c29f7bc | /outboundbot/include/alibabacloud/outboundbot/model/ListGlobalQuestionsRequest.h | 6fdb013a8eb63c3454e57d04af5ca12124e4e7ee | [
"Apache-2.0"
] | permissive | dingshiyu/aliyun-openapi-cpp-sdk | 3eebd9149c2e6a2b835aba9d746ef9e6bef9ad62 | 4edd799a79f9b94330d5705bb0789105b6d0bb44 | refs/heads/master | 2023-07-31T10:11:20.446221 | 2021-09-26T10:08:42 | 2021-09-26T10:08:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,695 | h | /*
* Copyright 2009-2017 Alibaba Cloud 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.
*/
#ifndef ALIBABACLOUD_OUTBOUNDBOT_MODEL_LISTGLOBALQUESTIONSREQUEST_H_
#define ALIBABACLOUD_OUTBOUNDBOT_MODEL_LISTGLOBALQUESTIONSREQUEST_H_
#include <string>
#include <vector>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <alibabacloud/outboundbot/OutboundBotExport.h>
namespace AlibabaCloud
{
namespace OutboundBot
{
namespace Model
{
class ALIBABACLOUD_OUTBOUNDBOT_EXPORT ListGlobalQuestionsRequest : public RpcServiceRequest
{
public:
ListGlobalQuestionsRequest();
~ListGlobalQuestionsRequest();
int getPageNumber()const;
void setPageNumber(int pageNumber);
std::string getScriptId()const;
void setScriptId(const std::string& scriptId);
std::string getInstanceId()const;
void setInstanceId(const std::string& instanceId);
int getPageSize()const;
void setPageSize(int pageSize);
private:
int pageNumber_;
std::string scriptId_;
std::string instanceId_;
int pageSize_;
};
}
}
}
#endif // !ALIBABACLOUD_OUTBOUNDBOT_MODEL_LISTGLOBALQUESTIONSREQUEST_H_ | [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
cc15ffd8320c4f39ea32a56de788bc0ba3c237f8 | 562bae23042790d1c1dc8ffc4843155465ec14da | /codes/enumtypes.cpp | 6fea9659c8db0b25ef2d92c6f8bf4428f0172cd7 | [] | no_license | JRonca/curso_cpp_basico | 024b9aaa70d455bedea450078f8181da32a5d917 | 2cb8ee77941213a594bbd4eb5bae2a29c982ee75 | refs/heads/main | 2023-07-02T12:56:19.990797 | 2021-07-31T12:54:55 | 2021-07-31T12:54:55 | 391,350,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 395 | cpp | #include <iostream>
enum Cores {
red,
green=50,
blue
};
enum Saidas {
sucesso,
erro_ao_abrir,
erro_de_leitura,
erro_de_permissao
};
int main( int argc, char **argv ){
Cores cores;
Saidas s;
std::cout << "O valor da cor red e: " << red << "\n";
std::cout << "O valor da cor green e: " << green << "\n";
std::cout << "O valor da cor blue e: " << blue << "\n";
return sucesso;
}
| [
"jrfr21112000@gmail.com"
] | jrfr21112000@gmail.com |
8356bb4de86cd69486ff351a1ed9a659c3b288f8 | bc73e04f6efd80f124c65b8c910eddd83105c522 | /Software/Final_UI/Final_UI.ino | 733ae27ab692c9950cfbdc7f1bb824641e787d2f | [] | no_license | jgsantiagojr/Awesome-Controller | 185befa33eeddd43dd84fa9e356fbffcde75ac01 | 431a20e39a3dd3a830dcdd324a0e2a7d98ba3672 | refs/heads/main | 2023-02-06T07:49:15.604856 | 2020-12-18T02:46:38 | 2020-12-18T02:46:38 | 322,411,887 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,938 | ino |
//Libaries needed for LCD Touchscreen
#include <TeensyUserInterface.h>
#include <font_Arial.h>
#include <font_ArialBold.h>
//Libraries needed for Qwiic Relay Board
#include <SparkFun_Qwiic_Relay.h>
#include <Wire.h>
//I2C Address for Qwiic Relay Board
#define RELAY_ADDR 0x6D
int MOS1 = 3;
int MOS2 = 4;
int MOS3 = 5;
int MOS4 = 6;
int hbPWM1 = 24; //Hbridge 1 PWM PIN
int hbDIR1 = 25; //Hbridge 1 Direction PIN
int hbPWM2 = 28; //Hbridge 2 PWM PIN
int hbDIR2 = 29; //Hbridge 2 Direction PIN
//GPIO pins
int pin14 = 14;
int pin15 = 15;
int pin22 = 22;
int pin23 = 23;
TeensyUserInterface ui; // create the user interface object
Qwiic_Relay quadRelay(RELAY_ADDR);// create quadRelay object
// ---------------------------------------------------------------------------------
// Setup the hardware
// ---------------------------------------------------------------------------------
void setup()
{
Serial.begin(115200);
Wire.begin();
Wire.setSDA(18);
Wire.setSCL(19);
if(!quadRelay.begin()){
Serial.println("Check connections to Qwiic Relay");
}
else{
Serial.println("Ready to flip some switches.");
}
pinMode(MOS1, OUTPUT);
pinMode(MOS2, OUTPUT);
pinMode(MOS3, OUTPUT);
pinMode(MOS4, OUTPUT);
pinMode(hbPWM1, OUTPUT);
pinMode(hbDIR1, OUTPUT);
pinMode(hbPWM2, OUTPUT);
pinMode(hbDIR2, OUTPUT);
ui.begin(LCD_ORIENTATION_LANDSCAPE_4PIN_RIGHT, Arial_9_Bold);// setup the LCD orientation, the default font and initialize the user interface
}
extern MENU_ITEM mainMenu[];
extern MENU_ITEM codeMenu[];
extern MENU_ITEM deviceMenu[];
extern MENU_ITEM hBridgeMenu[];
extern MENU_ITEM mosfetMenu[];
extern MENU_ITEM relayMenu[];
//Starting menu
MENU_ITEM mainMenu[] = {
{MENU_ITEM_TYPE_MAIN_MENU_HEADER, "Select Device Type", MENU_COLUMNS_1, mainMenu},
{MENU_ITEM_TYPE_SUB_MENU, "Code Options", NULL, codeMenu},
{MENU_ITEM_TYPE_SUB_MENU, "Individual Device Control", NULL, deviceMenu},
{MENU_ITEM_TYPE_END_OF_MENU, "", NULL, NULL}
};
//the code menu, with the pre-coded options
MENU_ITEM codeMenu[] = {
{MENU_ITEM_TYPE_SUB_MENU_HEADER, "Select Code to run", MENU_COLUMNS_1, mainMenu},
{MENU_ITEM_TYPE_COMMAND, "Sensor Driven Motor", commandSensorDriven, NULL},
{MENU_ITEM_TYPE_END_OF_MENU, "", NULL, NULL}
};
// the device menu, select the device to control
MENU_ITEM deviceMenu[] = {
{MENU_ITEM_TYPE_SUB_MENU_HEADER, "Select Device Type", MENU_COLUMNS_1, mainMenu},
{MENU_ITEM_TYPE_SUB_MENU, "H-Bridges", NULL, hBridgeMenu},
{MENU_ITEM_TYPE_SUB_MENU, "Mosfets", NULL, mosfetMenu},
{MENU_ITEM_TYPE_SUB_MENU, "Relays", NULL, relayMenu},
{MENU_ITEM_TYPE_END_OF_MENU, "", NULL, NULL}
};
//HBridge Selection, go to the individual hbridge controls (PWM and DIRECTION)
MENU_ITEM hBridgeMenu[] = {
{MENU_ITEM_TYPE_SUB_MENU_HEADER, "Select H-Bridge", MENU_COLUMNS_1, deviceMenu},
{MENU_ITEM_TYPE_COMMAND, "H-Bridge 1", commandSetHBridge1, NULL},
{MENU_ITEM_TYPE_COMMAND, "H-Bridge 2", commandSetHBridge2, NULL},
{MENU_ITEM_TYPE_END_OF_MENU, "", NULL, NULL}
};
//MOSFET Selection, go to the individual mosfet controls (PWM)
MENU_ITEM mosfetMenu[] = {
{MENU_ITEM_TYPE_SUB_MENU_HEADER, "Select Mosfet", MENU_COLUMNS_1, deviceMenu},
{MENU_ITEM_TYPE_COMMAND, " MOSFET 1", commandSetMOS1, NULL},
{MENU_ITEM_TYPE_COMMAND, "MOSFET 2", commandSetMOS2, NULL},
{MENU_ITEM_TYPE_COMMAND, "MOSFET 3", commandSetMOS3, NULL},
{MENU_ITEM_TYPE_COMMAND, "MOSFET 4", commandSetMOS4, NULL},
{MENU_ITEM_TYPE_END_OF_MENU, "", NULL, NULL}
};
//RELAY Selection and toggle the different relays individually (ON or OFF)
MENU_ITEM relayMenu[] = {
{MENU_ITEM_TYPE_SUB_MENU_HEADER, "Select Relay", MENU_COLUMNS_1, deviceMenu},
{MENU_ITEM_TYPE_TOGGLE, "1", menuToggleRelay1Callback, NULL},
{MENU_ITEM_TYPE_TOGGLE, "2", menuToggleRelay2Callback, NULL},
{MENU_ITEM_TYPE_TOGGLE, "3", menuToggleRelay3Callback, NULL},
{MENU_ITEM_TYPE_TOGGLE, "4", menuToggleRelay4Callback, NULL},
{MENU_ITEM_TYPE_END_OF_MENU, "", NULL, NULL}
};
//
// display the menu, then execute commands selected by the user
//
void loop()
{
ui.displayAndExecuteMenu(mainMenu);
}
// ---------------------------------------------------------------------------------
// PRE_WRITTEN SCRIPTS
// ---------------------------------------------------------------------------------
void commandSensorDriven(void)
{
ui.drawTitleBar("Driving HBridge1 on Pin14 input");
ui.clearDisplaySpace();
const int numberBoxAndButtonsHeight = 35;
BUTTON backButton = {"Back", ui.displaySpaceCenterX+70, ui.displaySpaceBottomY-25, 120 , numberBoxAndButtonsHeight};
ui.drawButton(backButton);
pinMode(pin14, INPUT);
int input = 0;
while(true){
input = analogRead(pin14);
analogWrite(hbPWM1, input);
digitalWrite(hbDIR1, true);
if (ui.checkForButtonClicked(backButton)){ //BACK TO SUBMENU
return;
}
}
}
// ---------------------------------------------------------------------------------
// H BRIDGE COMMANDS
// ---------------------------------------------------------------------------------
static int hPWM1 = 0;
static boolean hDIR1 = true;
void commandSetHBridge1(void)
{
ui.drawTitleBar("H-Bridge 1: Set PWM and Direction");
ui.clearDisplaySpace();
const int numberBoxWidth = 200;
const int numberBoxAndButtonsHeight = 35;
NUMBER_BOX my_NumberBox;
my_NumberBox.labelText = "Set PWM";
my_NumberBox.value = hPWM1;
my_NumberBox.minimumValue = 0;
my_NumberBox.maximumValue = 255;
my_NumberBox.stepAmount = 2;
my_NumberBox.centerX = ui.displaySpaceCenterX;
my_NumberBox.centerY = ui.displaySpaceCenterY - 60;
my_NumberBox.width = numberBoxWidth;
my_NumberBox.height = numberBoxAndButtonsHeight;
ui.drawNumberBox(my_NumberBox);
SELECTION_BOX directionSelectionBox;
directionSelectionBox.labelText = "Set Direction";
directionSelectionBox.value = hDIR1;
directionSelectionBox.choice0Text = "Backward";
directionSelectionBox.choice1Text = "Forward";
directionSelectionBox.choice2Text = "";
directionSelectionBox.choice3Text = "";
directionSelectionBox.centerX = ui.displaySpaceCenterX;
directionSelectionBox.centerY = ui.displaySpaceCenterY;
directionSelectionBox.width = 250;
directionSelectionBox.height = 33;
ui.drawSelectionBox(directionSelectionBox);
BUTTON highButton = {"MAX PWM", ui.displaySpaceCenterX-70, ui.displaySpaceBottomY - 62, 120, numberBoxAndButtonsHeight};
ui.drawButton(highButton);
BUTTON lowButton = {"MIN PWM", ui.displaySpaceCenterX+70, ui.displaySpaceBottomY - 62, 120, numberBoxAndButtonsHeight};
ui.drawButton(lowButton);
BUTTON okButton = {"OK", ui.displaySpaceCenterX-70, ui.displaySpaceBottomY-25, 120 , numberBoxAndButtonsHeight};
ui.drawButton(okButton);
BUTTON backButton = {"Back", ui.displaySpaceCenterX+70, ui.displaySpaceBottomY-25, 120 , numberBoxAndButtonsHeight};
ui.drawButton(backButton);
while(true)
{
ui.getTouchEvents();
ui.checkForNumberBoxTouched(my_NumberBox);
ui.checkForSelectionBoxTouched(directionSelectionBox);
if (ui.checkForButtonClicked(highButton)){ //MAX PWM SIGNAL
my_NumberBox.value = 255;
ui.drawNumberBox(my_NumberBox);
}
if (ui.checkForButtonClicked(lowButton)){ //MIN PWM SIGNAL
my_NumberBox.value = 0;
ui.drawNumberBox(my_NumberBox);
}
if (ui.checkForButtonClicked(okButton)) //SET SIGNAL
{
hPWM1 = my_NumberBox.value;
hDIR1 = directionSelectionBox.value;
analogWrite(hbPWM1, hPWM1);
digitalWrite(hbDIR1, hDIR1);
}
if (ui.checkForButtonClicked(backButton)) //BACK TO SUBMENU
return;
}
}
static int hPWM2 = 0;
static boolean hDIR2 = true;
void commandSetHBridge2(void)
{
ui.drawTitleBar("H-Bridge 2: Set PWM and Direction");
ui.clearDisplaySpace();
const int numberBoxWidth = 200;
const int numberBoxAndButtonsHeight = 35;
NUMBER_BOX my_NumberBox;
my_NumberBox.labelText = "Set PWM";
my_NumberBox.value = hPWM2;
my_NumberBox.minimumValue = 0;
my_NumberBox.maximumValue = 255;
my_NumberBox.stepAmount = 2;
my_NumberBox.centerX = ui.displaySpaceCenterX;
my_NumberBox.centerY = ui.displaySpaceCenterY - 60;
my_NumberBox.width = numberBoxWidth;
my_NumberBox.height = numberBoxAndButtonsHeight;
ui.drawNumberBox(my_NumberBox);
SELECTION_BOX directionSelectionBox;
directionSelectionBox.labelText = "Set Direction";
directionSelectionBox.value = hDIR2;
directionSelectionBox.choice0Text = "Backward";
directionSelectionBox.choice1Text = "Forward";
directionSelectionBox.choice2Text = "";
directionSelectionBox.choice3Text = "";
directionSelectionBox.centerX = ui.displaySpaceCenterX;
directionSelectionBox.centerY = ui.displaySpaceCenterY;
directionSelectionBox.width = 250;
directionSelectionBox.height = 33;
ui.drawSelectionBox(directionSelectionBox);
BUTTON highButton = {"MAX PWM", ui.displaySpaceCenterX-70, ui.displaySpaceBottomY - 62, 120, numberBoxAndButtonsHeight};
ui.drawButton(highButton);
BUTTON lowButton = {"MIN PWM", ui.displaySpaceCenterX+70, ui.displaySpaceBottomY - 62, 120, numberBoxAndButtonsHeight};
ui.drawButton(lowButton);
BUTTON okButton = {"OK", ui.displaySpaceCenterX-70, ui.displaySpaceBottomY-25, 120 , numberBoxAndButtonsHeight};
ui.drawButton(okButton);
BUTTON backButton = {"Back", ui.displaySpaceCenterX+70, ui.displaySpaceBottomY-25, 120 , numberBoxAndButtonsHeight};
ui.drawButton(backButton);
while(true)
{
ui.getTouchEvents();
ui.checkForNumberBoxTouched(my_NumberBox);
ui.checkForSelectionBoxTouched(directionSelectionBox);
if (ui.checkForButtonClicked(highButton)){ //MAX PWM SIGNAL
my_NumberBox.value = 255;
ui.drawNumberBox(my_NumberBox);
}
if (ui.checkForButtonClicked(lowButton)){ //MIN PWM SIGNAL
my_NumberBox.value = 0;
ui.drawNumberBox(my_NumberBox);
}
if (ui.checkForButtonClicked(okButton)) //SET SIGNAL
{
hPWM2 = my_NumberBox.value;
hDIR2 = directionSelectionBox.value;
analogWrite(hbPWM2, hPWM2);
digitalWrite(hbDIR2, hDIR2);
}
if (ui.checkForButtonClicked(backButton)) //BACK TO SUBMENU
return;
}
}
// ---------------------------------------------------------------------------------
// MOSFET COMMANDS
// ---------------------------------------------------------------------------------
static int PWM1 = 0;
void commandSetMOS1(void)
{
ui.drawTitleBar("MOSFET 1: Set PWM");
ui.clearDisplaySpace();
const int numberBoxWidth = 200;
const int numberBoxAndButtonsHeight = 35;
NUMBER_BOX my_NumberBox;
my_NumberBox.labelText = "Set PWM";
my_NumberBox.value = PWM1;
my_NumberBox.minimumValue = 0;
my_NumberBox.maximumValue = 255;
my_NumberBox.stepAmount = 2;
my_NumberBox.centerX = ui.displaySpaceCenterX;
my_NumberBox.centerY = ui.displaySpaceCenterY - 20;
my_NumberBox.width = numberBoxWidth;
my_NumberBox.height = numberBoxAndButtonsHeight;
ui.drawNumberBox(my_NumberBox);
BUTTON highButton = {"MAX", ui.displaySpaceCenterX-70, ui.displaySpaceBottomY - 70, 120, numberBoxAndButtonsHeight};
ui.drawButton(highButton);
BUTTON lowButton = {"MIN", ui.displaySpaceCenterX+70, ui.displaySpaceBottomY - 70, 120, numberBoxAndButtonsHeight};
ui.drawButton(lowButton);
BUTTON okButton = {"OK", ui.displaySpaceCenterX-70, ui.displaySpaceBottomY-35, 120 , numberBoxAndButtonsHeight};
ui.drawButton(okButton);
BUTTON backButton = {"Back", ui.displaySpaceCenterX+70, ui.displaySpaceBottomY-35, 120 , numberBoxAndButtonsHeight};
ui.drawButton(backButton);
while(true)
{
ui.getTouchEvents();
ui.checkForNumberBoxTouched(my_NumberBox);
if (ui.checkForButtonClicked(highButton)){ //MAX PWM SIGNAL
my_NumberBox.value = 255;
ui.drawNumberBox(my_NumberBox);
}
if (ui.checkForButtonClicked(lowButton)){ //MIN PWM SIGNAL
my_NumberBox.value = 0;
ui.drawNumberBox(my_NumberBox);
}
if (ui.checkForButtonClicked(okButton)) //SET SIGNAL
{
PWM1 = my_NumberBox.value;
analogWrite(MOS1, PWM1);
}
if (ui.checkForButtonClicked(backButton)) //BACK TO SUBMENU
return;
}
}
static int PWM2 = 0;
void commandSetMOS2(void){
ui.drawTitleBar("MOSFET 2: Set PWM");
ui.clearDisplaySpace();
const int numberBoxWidth = 200;
const int numberBoxAndButtonsHeight = 35;
NUMBER_BOX my_NumberBox;
my_NumberBox.labelText = "Set PWM";
my_NumberBox.value = PWM2;
my_NumberBox.minimumValue = 0;
my_NumberBox.maximumValue = 255;
my_NumberBox.stepAmount = 2;
my_NumberBox.centerX = ui.displaySpaceCenterX;
my_NumberBox.centerY = ui.displaySpaceCenterY - 20;
my_NumberBox.width = numberBoxWidth;
my_NumberBox.height = numberBoxAndButtonsHeight;
ui.drawNumberBox(my_NumberBox);
BUTTON highButton = {"MAX", ui.displaySpaceCenterX-70, ui.displaySpaceBottomY - 70, 120, numberBoxAndButtonsHeight};
ui.drawButton(highButton);
BUTTON lowButton = {"MIN", ui.displaySpaceCenterX+70, ui.displaySpaceBottomY - 70, 120, numberBoxAndButtonsHeight};
ui.drawButton(lowButton);
BUTTON okButton = {"OK", ui.displaySpaceCenterX-70, ui.displaySpaceBottomY-35, 120 , numberBoxAndButtonsHeight};
ui.drawButton(okButton);
BUTTON backButton = {"Back", ui.displaySpaceCenterX+70, ui.displaySpaceBottomY-35, 120 , numberBoxAndButtonsHeight};
ui.drawButton(backButton);
while(true)
{
ui.getTouchEvents();
ui.checkForNumberBoxTouched(my_NumberBox);
if (ui.checkForButtonClicked(highButton)){ //MAX PWM SIGNAL
my_NumberBox.value = 255;
ui.drawNumberBox(my_NumberBox);
}
if (ui.checkForButtonClicked(lowButton)){//MIN PWM SIGNAL
my_NumberBox.value = 0;
ui.drawNumberBox(my_NumberBox);
}
if (ui.checkForButtonClicked(okButton)){//SET PWM SIGNAL
PWM2 = my_NumberBox.value;
analogWrite(MOS2, PWM2);
}
if (ui.checkForButtonClicked(backButton)){ //BACK TO SUBMENU
return;
}
}
}
static int PWM3 = 0;
void commandSetMOS3(void)
{
ui.drawTitleBar("MOSFET 3: Set PWM");
ui.clearDisplaySpace();
const int numberBoxWidth = 200;
const int numberBoxAndButtonsHeight = 35;
NUMBER_BOX my_NumberBox;
my_NumberBox.labelText = "Set PWM";
my_NumberBox.value = PWM3;
my_NumberBox.minimumValue = 0;
my_NumberBox.maximumValue = 255;
my_NumberBox.stepAmount = 2;
my_NumberBox.centerX = ui.displaySpaceCenterX;
my_NumberBox.centerY = ui.displaySpaceCenterY - 20;
my_NumberBox.width = numberBoxWidth;
my_NumberBox.height = numberBoxAndButtonsHeight;
ui.drawNumberBox(my_NumberBox);
BUTTON highButton = {"MAX", ui.displaySpaceCenterX-70, ui.displaySpaceBottomY - 70, 120, numberBoxAndButtonsHeight};
ui.drawButton(highButton);
BUTTON lowButton = {"MIN", ui.displaySpaceCenterX+70, ui.displaySpaceBottomY - 70, 120, numberBoxAndButtonsHeight};
ui.drawButton(lowButton);
BUTTON okButton = {"OK", ui.displaySpaceCenterX-70, ui.displaySpaceBottomY-35, 120 , numberBoxAndButtonsHeight};
ui.drawButton(okButton);
BUTTON backButton = {"Back", ui.displaySpaceCenterX+70, ui.displaySpaceBottomY-35, 120 , numberBoxAndButtonsHeight};
ui.drawButton(backButton);
while(true)
{
ui.getTouchEvents();
ui.checkForNumberBoxTouched(my_NumberBox);
if (ui.checkForButtonClicked(highButton)){ //PWM SIGNAL MAX
my_NumberBox.value = 255;
ui.drawNumberBox(my_NumberBox);
}
if (ui.checkForButtonClicked(lowButton)){//PWM SIGNAL MIN
my_NumberBox.value = 0;
ui.drawNumberBox(my_NumberBox);
}
if (ui.checkForButtonClicked(okButton)){//SET SIGNAL
PWM3 = my_NumberBox.value;
analogWrite(MOS3, PWM3);
}
if (ui.checkForButtonClicked(backButton)){//BACK TO SUBMENU
return;
}
}
}
static int PWM4 = 0;
void commandSetMOS4(void)
{
ui.drawTitleBar("MOSFET 4: Set PWM");
ui.clearDisplaySpace();
const int numberBoxWidth = 200;
const int numberBoxAndButtonsHeight = 35;
NUMBER_BOX my_NumberBox;
my_NumberBox.labelText = "Set PWM";
my_NumberBox.value = PWM4;
my_NumberBox.minimumValue = 0;
my_NumberBox.maximumValue = 255;
my_NumberBox.stepAmount = 2;
my_NumberBox.centerX = ui.displaySpaceCenterX;
my_NumberBox.centerY = ui.displaySpaceCenterY - 20;
my_NumberBox.width = numberBoxWidth;
my_NumberBox.height = numberBoxAndButtonsHeight;
ui.drawNumberBox(my_NumberBox);
BUTTON highButton = {"MAX", ui.displaySpaceCenterX-70, ui.displaySpaceBottomY - 70, 120, numberBoxAndButtonsHeight};
ui.drawButton(highButton);
BUTTON lowButton = {"MIN", ui.displaySpaceCenterX+70, ui.displaySpaceBottomY - 70, 120, numberBoxAndButtonsHeight};
ui.drawButton(lowButton);
BUTTON okButton = {"OK", ui.displaySpaceCenterX-70, ui.displaySpaceBottomY-35, 120 , numberBoxAndButtonsHeight};
ui.drawButton(okButton);
BUTTON backButton = {"Back", ui.displaySpaceCenterX+70, ui.displaySpaceBottomY-35, 120 , numberBoxAndButtonsHeight};
ui.drawButton(backButton);
while(true)
{
ui.getTouchEvents();
ui.checkForNumberBoxTouched(my_NumberBox);
if (ui.checkForButtonClicked(highButton)){//PWM SIGNAL MAX
my_NumberBox.value = 255;
ui.drawNumberBox(my_NumberBox);
}
if (ui.checkForButtonClicked(lowButton)){//PWM SIGNAL MIN
my_NumberBox.value = 0;
ui.drawNumberBox(my_NumberBox);
}
if (ui.checkForButtonClicked(okButton)){//SET PWM SIGNAL
PWM4 = my_NumberBox.value;
analogWrite(MOS4, PWM4);
}
if (ui.checkForButtonClicked(backButton)){//BACK TO SUBMENU
return;
}
}
}
// ---------------------------------------------------------------------------------
// RELAY TOGGLE
// ---------------------------------------------------------------------------------
static byte relayState1 = false;
void menuToggleRelay1Callback(void){
if (ui.toggleSelectNextStateFlg){
relayState1 = !relayState1;
quadRelay.toggleRelay(1);
}
if(relayState1){
ui.toggleText = "On";
} else{
ui.toggleText = "Off";
}
}
static byte relayState2 = false;
void menuToggleRelay2Callback(void){
if (ui.toggleSelectNextStateFlg){
relayState2 = !relayState2;
quadRelay.toggleRelay(2);
}
if(relayState2){
ui.toggleText = "On";
} else{
ui.toggleText = "Off";
}
}
static byte relayState3 = false;
void menuToggleRelay3Callback(void){
if (ui.toggleSelectNextStateFlg){
relayState3 = !relayState3;
quadRelay.toggleRelay(3);
}
if(relayState3){
ui.toggleText = "On";
} else{
ui.toggleText = "Off";
}
}
static byte relayState4 = false;
void menuToggleRelay4Callback(void){
if (ui.toggleSelectNextStateFlg){
relayState4 = !relayState4;
quadRelay.toggleRelay(4);
}
if(relayState4){
ui.toggleText = "On";
} else{
ui.toggleText = "Off";
}
}
| [
"noreply@github.com"
] | noreply@github.com |
1562ef1e17c2ae67330882752e01c6d245d409bf | d2f0a9a335c38134e1d669227f6e4c05e9f0c06a | /SD semester projects mostly/Labyrinth/String.cpp | 45e14174b3fe2273ac18a2a8315391c9d63f60d0 | [] | no_license | Anton94/OOP-Cplusplus | 37e9cb9ab9a383b893f36a56fe69862c61a16607 | 7fe21e8cf103bcbb43591f17b5cb095f3ffb6f8f | refs/heads/master | 2021-01-10T21:45:50.652354 | 2017-02-01T15:06:04 | 2017-02-01T15:06:04 | 25,372,476 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,286 | cpp | #include <iostream>
#include "String.h"
#include "Utility.h"
/*
If there is no enough memory throws exeption...
A little fucked up , initial string is empty one always. Unless its given a start capacity size.
*/
std::ostream& operator<<(std::ostream& out, const String& string)
{
if (string.string != NULL)
out << string.string;
return out;
}
String::String()
{
setDefaultValues();
}
/// Makes a string with the capacity->given size.
String::String(int capacitySize)
{
initialResize(capacitySize);
}
/// Makes new string with bigger capacity, given one.
void String::initialResize(int newCapacity)
{
if (newCapacity <= 0)
throw "Invalid size for the initial string! (needs to be bigger than zero)";
string = new char[newCapacity];
size = 1;
capacity = newCapacity;
*string = '\0';
}
String::String(const char* other)
{
copyFrom(other);
}
String::String(const String& other)
{
copyFrom(other);
}
String& String::operator=(const char* other)
{
delete[] string;
copyFrom(other);
return *this;
}
String& String::operator=(const String& other)
{
if (this != &other)
{
delete[] string;
copyFrom(other);
}
return *this;
}
// Adds other char string to the end of existing one.
String& String::operator+=(const char* other)
{
addFrom(getLength() + strLength(other) + 1, other); // + '\0'
return *this;
}
// Adds other String to the end of existing one.
String& String::operator+=(const String& other)
{
addFrom(getLength() + other.size, other.string);
return *this;
}
// Adds other char to the end of existing string.
String& String::operator+=(char ch)
{
if (full())
resize(capacity * 2);
string[size - 1] = ch;
string[size++] = '\0';
return *this;
}
// Check of the strings have the same symbols.
bool String::operator==(const String& other) const
{
if (size != other.size)
return false;
const char * left = string;
const char * right = other.string;
while (*left == *right++ && *left++ != '\0')
{
}
return *--left == '\0';
}
bool String::operator!=(const String& other) const
{
return !(*this == other);
}
// Returns a copy of the char element at the 'index' possition or throws exeption of the index is outside of the bounds of the array.
char String::operator[](int index) const
{
if (index < 0 || index >= (int)size)
throw "Invalid index of the string!";
return string[index];
}
// Returns a pointer to the buffer in the memory.
char* String::getString()
{
return string;
}
// Returns a const pointer to the buffer in the memory.
const char* String::getString() const
{
return string;
}
// Returns the length of the string
size_t String::getLength() const
{
return size - 1;
}
bool String::isEmpty() const
{
return size <= 1;
}
// Deletes the allocated memory.
String::~String()
{
delete[] string;
}
// Sets the string to empty one.
void String::setDefaultValues()
{
copyFrom(""); // Empty string.
}
bool String::full() const
{
return size == capacity;
}
// Creates new char array for the data with the given capacity and copies the symbols there.
void String::resize(size_t newCapacity)
{
char * temp = new char[capacity = newCapacity];
strCopy(temp, string);
delete[] string;
string = temp;
}
// Creates a string from char* string.. if the pointer is null , creates a valid (empty) string.
// The capacity will be exacly the size of the needed string, maybe the string wont be changed in the feature, and it will be perfect world!
void String::copyFrom(const char * other)
{
if (!other)
{
setDefaultValues();
}
else
{
capacity = size = strLength(other) + 1; // + '\0'
string = new char[capacity];
strCopy(string, other);
}
}
// Creates a copy of the given other string.
void String::copyFrom(const String& other)
{
size = other.size;
capacity = other.capacity;
string = new char[other.capacity];
strCopy(string, other.string);
}
// Adds othe char string to the end of the existing one. If the buffer of existing has not enough space- creates new buffer with enough space.
void String::addFrom(size_t newSize, const char* other)
{
if (newSize > capacity)
resize((capacity * 2 > newSize) ? capacity * 2 : newSize); // resize the buffer with the bigger of: twice capacity and the newSize
strCopy(string + getLength(), other);
size = newSize;
} | [
"antonvdudov@gmail.com"
] | antonvdudov@gmail.com |
d3dcfd8c50e209c3bbb0c643e05b685206897c02 | b850bbc30df235514ad0fef631cd0487c335c8b5 | /62圆圈中最后剩下的数字/源.cpp | 181af6ddb3dbfcf30f9e785de925a8d746b1c124 | [] | no_license | jackie-han/Coding-Interview | e87850c9b0b4ceb0bc61cdd08dd50a9da88b4fef | 37d5f9efc139bf464f5fa2777e4f453559730470 | refs/heads/master | 2020-06-12T11:43:05.169633 | 2019-06-28T14:43:24 | 2019-06-28T14:43:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 589 | cpp | #include<list>
using namespace std;
int LastRemaining(unsigned int n, unsigned int m)
{
if (n < 1 || m < 1)
return -1;
unsigned int i = 0;
list<int> numbers;
for (i = 0; i < n; i++)
numbers.push_back(i);
list<int>::iterator current = numbers.begin();
while (numbers.size() > 1)
{
for (int i = 1; i < m; i++)
{
current++;
if (current == numbers.end())
current = numbers.begin();
}
list<int>::iterator next = ++current;
if (next == numbers.end())
next = numbers.begin();
--current;
numbers.erase(current);
current = next;
}
return *current;
} | [
"249853856@qq.com"
] | 249853856@qq.com |
5df73f780844dd705e6164ee3d50e7fc76ec6ab2 | 6f90344a98963551a5c059c4ef9e660acbb63b0e | /classes/Base.hpp | 8df8f8d0cb283aed4fcd195de99504b701fdb9cd | [
"MIT"
] | permissive | return0jz/framework2d | f5b07be5324c3e6fac22a76aedf00068a93b6ce2 | 606b40224316450fff7b567f8d81ce72e2be0714 | refs/heads/master | 2023-07-07T23:07:57.168198 | 2021-08-02T07:36:08 | 2021-08-02T07:36:08 | 385,952,714 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 102 | hpp | #pragma once
namespace jzj { // For generics
struct Base {
Base() {}
virtual ~Base() {}
};
}
| [
"jasperjzhou@gmail.com"
] | jasperjzhou@gmail.com |
b9b546eb66057df236ae00de30c021a21ac51894 | aef14403ea0c30afb6612d4698273c860297cb7e | /src/utils/json/format.cpp | 9c8f7438123f3fccb2a0160a03bcefc12e048195 | [
"BSD-2-Clause"
] | permissive | RAttab/reflect | ba3b939ac6d323e7f31531f0dff6d791abf3a64d | 9a4f0cd1f63f2afa314297d4f07ef5837bdb9f8d | refs/heads/master | 2023-04-06T04:04:14.935469 | 2023-03-26T18:39:10 | 2023-03-26T18:39:10 | 17,706,186 | 47 | 13 | null | null | null | null | UTF-8 | C++ | false | false | 3,815 | cpp | /* format.cpp -*- C++ -*-
Rémi Attab (remi.attab@gmail.com), 14 Apr 2015
FreeBSD-style copyright and disclaimer apply
*/
namespace reflect {
namespace json {
/******************************************************************************/
/* FORMATTER */
/******************************************************************************/
void formatNull(Writer& writer)
{
static const std::string sNull = "null";
writer.push(sNull);
}
void formatBool(Writer& writer, bool value)
{
static const std::string sTrue = "true";
static const std::string sFalse = "false";
if (value) writer.push(sTrue);
else writer.push(sFalse);
}
namespace {
template<typename T>
void format(Writer& writer, const char* format, T value)
{
auto& buffer = writer.buffer();
size_t n = snprintf(buffer.data(), buffer.size(), format, value);
if (n == buffer.size()) {
writer.error("buffer too small to format value");
return;
}
writer.push(buffer.data(), n);
}
} // namespace anonymous
void formatInt(Writer& writer, int64_t value)
{
format(writer, "%ld", value);
}
void formatFloat(Writer& writer, double value)
{
format(writer, "%1.12g", value);
}
size_t escapeUnicode(Writer& writer, const std::string& value, size_t i)
{
size_t bytes = clz(~value[i]);
if (bytes > 4 || bytes < 2) writer.error("invalid UTF-8 header");
if (i + bytes > value.size()) writer.error("invalid UTF-8 encoding");
size_t leftover = 8 - (bytes + 1);
uint32_t code = value[i] & ((1 << leftover) - 1);
i++;
for (size_t j = 0; writer && j < (bytes - 1); ++j, ++i) {
if ((value[i] & 0xC0) != 0x80) writer.error("invalid UTF-8 encoding");
code = (code << 6) | (value[i] & 0x3F);
}
format(writer, "\\u%04x", code);
return i - 1;
}
size_t readUnicode(Writer& writer, const std::string& value, size_t i)
{
size_t bytes = clz(~value[i]);
if (bytes > 4 || bytes < 2) writer.error("invalid UTF-8 header");
if (i + bytes > value.size()) writer.error("invalid UTF-8 encoding");
size_t leftover = 8 - (bytes + 1);
uint32_t code = value[i] & ((1 << leftover) - 1);
writer.push(value[i]);
i++;
for (size_t j = 0; writer && j < (bytes - 1); ++j, ++i) {
if ((value[i] & 0xC0) != 0x80) writer.error("invalid UTF-8 encoding");
code = (code << 6) | (value[i] & 0x3F);
writer.push(value[i]);
}
switch (bytes) {
case 4: if (code <= 0xFFFF) writer.error("invalid UTF-8 encoding"); break;
case 3: if (code <= 0x7FF) writer.error("invalid UTF-8 encoding"); break;
case 2: if (code <= 0x7F) writer.error("invalid UTF-8 encoding"); break;
}
return i - 1;
}
void formatString(Writer& writer, const std::string& value)
{
writer.push('"');
for (size_t i = 0; i < value.size(); ++i) {
char c = value[i];
if (c & 0x80) {
if (writer.escapeUnicode()) {
i = escapeUnicode(writer, value, i);
continue;
}
else if (writer.validateUnicode()) {
i = readUnicode(writer, value, i);
continue;
}
}
switch (c) {
case '"': writer.push("\\\"", 2); break;
case '/': writer.push("\\/", 2); break;
case '\\': writer.push("\\\\", 2); break;
case '\b': writer.push("\\b", 2); break;
case '\f': writer.push("\\f", 2); break;
case '\n': writer.push("\\n", 2); break;
case '\r': writer.push("\\r", 2); break;
case '\t': writer.push("\\t", 2); break;
default: writer.push(c);
}
}
writer.push('"');
}
} // namespace json
} // namespace reflect
| [
"remi.attab@gmail.com"
] | remi.attab@gmail.com |
d1f8de974ca79b1971ff479c62e71713426c8c2f | f556301fd9bdba0e463bb6f08bd83db0fd258a8d | /extensions/basic/statistics/weighted_moving_average.h | 11d0f7e8c160b8ba7bdb35318a51e3a6853fa06c | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | blockspacer/chromium_base_conan | ce7c0825b6a62c2c1272ccab5e31f15d316aa9ac | 726d2a446eb926f694e04ab166c0bbfdb40850f2 | refs/heads/master | 2022-09-14T17:13:27.992790 | 2022-08-24T11:04:58 | 2022-08-24T11:04:58 | 225,695,691 | 18 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,778 | h | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <stdint.h>
#include <deque>
#include "base/macros.h"
#include "basic/statistics/weighted_mean.h"
namespace basic {
// Calculates the weighted moving average of recent points. The points
// do not need to be evenly distributed on the X axis, but the X coordinate
// is assumed to be generally increasing.
//
// Whenever a new sample is added using AddSample(), old samples whose
// x coordinates are farther than |max_x_range_| from the new sample's
// x coordinate will be removed from the average. Note that |max_x_range_|
// must be non-negative.
class WeightedMovingAverage {
public:
explicit WeightedMovingAverage(int64_t max_x_range);
~WeightedMovingAverage();
int64_t max_x_range() const { return max_x_range_; }
// Returns the current number of samples that are in the weighted average.
size_t num_samples() const { return samples_.size(); }
// Adds an (x, y) sample with the provided weight to the average.
// |weight| should be non-negative.
void AddSample(int64_t x, int64_t y, double weight);
// Gets the current average and standard error.
// Returns |true| if the average exists, |false| otherwise. If the average
// does not exist, |average| and |error| are not modified.
bool Average(int64_t* average, double* error) const;
// Clears all current samples from the moving average.
void Clear();
private:
struct Sample {
int64_t x;
int64_t y;
double weight;
};
const int64_t max_x_range_;
std::deque<Sample> samples_;
WeightedMean mean_;
DISALLOW_COPY_AND_ASSIGN(WeightedMovingAverage);
};
} // namespace basic
| [
"user@email.ru"
] | user@email.ru |
b17531c8efb41b4e33d966daa065d1b407f547c3 | 362fb7256f18e22c9852e055709a3df71021cb63 | /testcrack/testcrack.h | 2757e8ae2396f769382db8e9370459189d0c9ffa | [] | no_license | l1007482035/vs2008TestPrj | 29d5735db7b92c714953d7f3ecc5d39714b73b12 | 41392ed176a83149f3cc7144389df2e952785faa | refs/heads/master | 2021-07-05T07:58:14.010559 | 2021-05-04T05:40:25 | 2021-05-04T05:40:25 | 234,276,322 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 476 | h |
// testcrack.h : PROJECT_NAME 应用程序的主头文件
//
#pragma once
#ifndef __AFXWIN_H__
#error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
#endif
#include "resource.h" // 主符号
// CtestcrackApp:
// 有关此类的实现,请参阅 testcrack.cpp
//
class CtestcrackApp : public CWinAppEx
{
public:
CtestcrackApp();
// 重写
public:
virtual BOOL InitInstance();
// 实现
DECLARE_MESSAGE_MAP()
};
extern CtestcrackApp theApp; | [
"1007482035@qq.com"
] | 1007482035@qq.com |
ed040bb1516426a90948778c8e6da45b06a9c700 | 58d959b2402841c811df1823eadc2a5e43c9c64d | /Original_Source Code/RL Software/MLTestProject/_svn/text-base/MLMaze.cpp.svn-base | 3f6cadf4b8424c67396cffeda767494886775bee | [] | no_license | mskim1997/OriginalProject | 8308ad55b807ebdab4c94bbb01ef639c8bd6bc9c | d3aad773d776e28bc2d3b7adabec1e49abdccff1 | refs/heads/master | 2021-01-18T14:18:48.919514 | 2015-07-14T21:57:05 | 2015-07-14T21:57:05 | 39,101,646 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,395 | /////////////////////////////////////////////////////////
//Maze.cpp
//Defines the Maze class.
//
//Manuel Madera
//10/10/09
/////////////////////////////////////////////////////////
#include "MLMaze.h"
#include "Framework\Packages.h"
#include "Framework\PackagerFactory.h"
#include <sstream>
#include "Framework\EventDistributor.h"
#include "Framework\Debug.h"
#ifdef PrintMemoryLeak
#ifdef WIN32
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#endif
#endif
#define MAX_LOOP 3
#define TIME_OUT 0.5 //seconds
#ifdef WIN32
#include <windows.h>
#define sleep(x) Sleep(x*1000)
#endif
using namespace Framework::Factories;
using namespace Framework::Packages;
using namespace Framework::Eventing;
using namespace std;
namespace MLTest
{
IMaze *MLMaze::instance = 0;
MLMaze::MLMaze() : isInitialized(false), maze(NULL), msgDist(NULL), eventDist(NULL), agentDonePublisher(NULL), agentPhysicalPathDonePublisher(NULL)
{
sem_init(&binSem, 0, 1);
sem_init(&canMoveReplySem, 0, 0);
PackagerFactory *packageFactory = PackagerFactory::Instance();
if (packageFactory != NULL)
{
packageFactory->RegisterPackage(PackageType::MAZE_LIMIT, MazeLimitPackage::CreatePackage);
packageFactory->RegisterPackage(PackageType::MAZE_CAN_MOVE, MazeCanMovePackage::CreatePackage);
packageFactory->RegisterPackage(PackageType::MAZE_CAN_MOVE_REPLY, MazeCanMoveReplyPackage::CreatePackage);
packageFactory->RegisterPackage(PackageType::GET_OBJ_ON, GetObjectOnPackage::CreatePackage);
packageFactory->RegisterPackage(PackageType::AGENT_DONE_EVENT, AgentDoneEventPackage::CreatePackage);
packageFactory->RegisterPackage(PackageType::PHYSICAL_PATH_DONE_EVENT, PhysicalPathDoneEventPackage::CreatePackage);
}
}
void MLMaze::Init(Framework::Maze *maze, Framework::Messaging::IMessageDistributor *msgDist, Framework::Eventing::IEventDistributor *eventDistributor, unsigned nodeID)
{
if (!this->isInitialized)
{
this->eventDist = eventDistributor;
this->msgDist = msgDist;
this->maze = maze;
this->isInitialized = true;
if (this->msgDist != NULL)
{
this->msgDist->RegisterCallback(PackageType::MAZE_LIMIT, this, MLMaze::MazeLimitCallback);
this->msgDist->RegisterCallback(PackageType::MAZE_CAN_MOVE, this, MLMaze::CanMoveCallback);
this->msgDist->RegisterCallback(PackageType::MAZE_CAN_MOVE_REPLY, this, MLMaze::CanMoveReplyCallback);
this->msgDist->RegisterCallback(PackageType::GET_OBJ_ON, this, MLMaze::GetObjectOnCallback);
this->msgDist->SendPackage(new MazeLimitPackage(nodeID, 0));
}
this->nodeId = nodeID;
}
}
void MLMaze::Shutdown()
{
delete instance;
instance = NULL;
}
/*static*/ IMaze *MLMaze::Instance()
{
if (instance == 0)
{
instance = new MLMaze();
}
return instance;
}
MLMaze::~MLMaze()
{
//sem_wait(&this->binSem);
sem_destroy(&this->binSem);
sem_destroy(&this->canMoveReplySem);
map<unsigned, Framework::Position<int> *>::iterator iter;
for (iter = this->agentPos.begin(); iter != this->agentPos.end(); iter++)
{
delete iter->second;
iter->second = NULL;
}
map<char, Framework::Position<int> *>::iterator charIter;
for (charIter = this->transferAgentStart.begin(); charIter != this->transferAgentStart.end(); charIter++)
{
delete charIter->second;
charIter->second = NULL;
}
delete this->agentDonePublisher;
this->agentDonePublisher = NULL;
delete this->agentPhysicalPathDonePublisher;
this->agentPhysicalPathDonePublisher = NULL;
delete this->maze;
this->maze = NULL;
if (this->msgDist != NULL)
{
this->msgDist->UnregisterCallback(PackageType::MAZE_LIMIT);
this->msgDist->UnregisterCallback(PackageType::MAZE_CAN_MOVE);
this->msgDist->UnregisterCallback(PackageType::MAZE_CAN_MOVE_REPLY);
this->msgDist->UnregisterCallback(PackageType::GET_OBJ_ON);
}
}
bool MLMaze::IsAvailable(Framework::Position<int> pos)
{
bool isAvailable = false;
isAvailable = IsPositionWithinLocalLimits(pos);
if (isAvailable)
{
if (this->maze != NULL)
{
isAvailable = (this->maze->GetMaze()[pos.GetYCoor()][pos.GetXCoor()] != 'B');
}
}
if (isAvailable)
{
map<unsigned, Framework::Position<int> *>::iterator iter;
for (iter = this->agentPos.begin(); iter != this->agentPos.end(); iter++)
{
if (iter->second != NULL)
{
if ((iter->second->GetXCoor() == pos.GetXCoor())&&
(iter->second->GetYCoor() == pos.GetYCoor()))
{
isAvailable = false;
break;
}
}
}
}
return isAvailable;
}
char MLMaze::GetObjectOn(Framework::Position<int> pos)
{
char object = 'O';
if (IsPositionWithinLocalLimits(pos))
{
if (this->maze != NULL)
{
object = this->maze->GetMaze()[pos.GetYCoor()][pos.GetXCoor()];
}
}
else if (IsPositionWithinGlobalLimits(pos))
{
bool isFound = false;
GetObjectOnReply *storedReply = NULL;
sem_wait(&this->binSem);
list<GetObjectOnReply *>::iterator iter;
for (iter = getObjectOnReplyList.begin(); iter != getObjectOnReplyList.end(); iter++)
{
if (*iter != NULL)
{
storedReply = *iter;
if (storedReply->queryType == GetObjectOnPackage::GET_OBJECT)
{
if ((storedReply->pos.GetXCoor() == pos.GetXCoor())&&
(storedReply->pos.GetYCoor() == pos.GetYCoor()))
{
object = storedReply->object;
isFound = true;
break;
}
}
}
}
sem_post(&this->binSem);
if (!isFound)
{
if (this->msgDist != NULL)
{
this->msgDist->SendPackage(new GetObjectOnPackage(this->nodeId, 0, GetObjectOnPackage::GET_OBJECT, pos + this->msgDist->GetOffset()));
}
sleep(TIME_OUT);
sem_wait(&this->binSem);
for (iter = getObjectOnReplyList.begin(); iter != getObjectOnReplyList.end(); iter++)
{
if (*iter != NULL)
{
storedReply = *iter;
if (storedReply->queryType == GetObjectOnPackage::GET_OBJECT)
{
if ((storedReply->pos.GetXCoor() == pos.GetXCoor())&&
(storedReply->pos.GetYCoor() == pos.GetYCoor()))
{
object = storedReply->object;
isFound = true;
break;
}
}
}
}
if ((isFound)&&(storedReply->object != 'B'))
{
delete *iter;
*iter = NULL;
getObjectOnReplyList.erase(iter);
}
sem_post(&this->binSem);
}
}
return object;
}
//Assumes that if the return is true, the agent will move to the specified position
bool MLMaze::CanMove(unsigned agentID, Framework::Position<int> pos)
{
bool canMove = false;
sem_wait(&this->binSem);
if (IsAvailable(pos))
{
canMove = true;
if (this->transferedAgentsPos.find(agentID) != this->transferedAgentsPos.end())
{
canMove = false;
/*Framework::Position<int> *tempPos = this->transferedAgentsPos[agentID];
if ((tempPos->GetXCoor() == pos.GetXCoor())&&
(tempPos->GetYCoor() == pos.GetYCoor()))
{
canMove = false;
}*/
}
if (canMove)
{
if (this->agentPos.find(agentID) == this->agentPos.end())
{
this->agentPos[agentID] = new Framework::Position<int>(pos);
}
else
{
if (this->agentPos[agentID] != NULL)
{
this->agentPos[agentID]->SetXCoor(pos.GetXCoor());
this->agentPos[agentID]->SetYCoor(pos.GetYCoor());
}
}
}
}
sem_post(&this->binSem);
return canMove;
}
bool MLMaze::CanMoveToGlobal(unsigned agentID, Framework::Position<int> movingFomPos, Framework::Position<int> movingToPos, unsigned &dest, char &newStartLoc)
{
bool canMove = false;
if (this->msgDist != NULL)
{
this->msgDist->SendPackage(new MazeCanMovePackage(this->nodeId, 0, movingToPos + this->msgDist->GetOffset(), agentID));
}
//sem_wait(&this->canMoveReplySem);
//for (int i = 0; i < MAX_LOOP; i++)
//{
sleep(TIME_OUT);
sem_wait(&this->binSem);
if (this->canMoveReplyMap.find(agentID) != this->canMoveReplyMap.end())
{
canMove = this->canMoveReplyMap[agentID].canMove;
dest = this->canMoveReplyMap[agentID].node;
newStartLoc = this->canMoveReplyMap[agentID].startLoc;
if (canMove)
{
Framework::Position<int> *temp = this->agentPos[agentID];
this->agentPos.erase(agentID);
delete temp;
temp = NULL;
//Add to the transfered agents pos list, in case the transfered agent tries to
//come back to this position.
if (this->transferedAgentsPos.find(agentID) == this->transferedAgentsPos.end())
{
this->transferedAgentsPos[agentID] = new Framework::Position<int>(movingFomPos);
}
else
{
if (this->transferedAgentsPos[agentID] != NULL)
{
this->transferedAgentsPos[agentID]->SetXCoor(movingFomPos.GetXCoor());
this->transferedAgentsPos[agentID]->SetYCoor(movingFomPos.GetYCoor());
}
}
}
//break;
}
sem_post(&this->binSem);
//}
return canMove;
}
Framework::Position<int> MLMaze::GetLimits()
{
Framework::Position<int> limits;
if (this->maze != NULL)
{
limits = Framework::Position<int>(this->maze->GetXSize() - 1, this->maze->GetYSize() - 1);
}
return limits;
}
void MLMaze::NotifyAgentIsDone(unsigned agentId, bool isTransferedAgent, bool hasFoundGoal)
{
sem_wait(&this->binSem);
if (this->agentDonePublisher == NULL)
{
//this->eventDist->RegisterRemoteSubscription(PackageType::AGENT_DONE_EVENT, SubscriptionTypes::AGENT_DONE);
this->agentDonePublisher = new Publisher(this->eventDist, SubscriptionTypes::AGENT_DONE);
}
if (this->agentDonePublisher != NULL)
{
this->agentDonePublisher->Publish(new AgentDoneEventPackage(this->nodeId, 0, agentId, 0, 0, 0, isTransferedAgent, hasFoundGoal));
}
//Remove agent from the map once it has found its goal, and it is done searching
if (this->agentPos.find(agentId) != this->agentPos.end())
{
Framework::Position<int> *temp = this->agentPos[agentId];
this->agentPos.erase(agentId);
delete temp;
temp = NULL;
}
sem_post(&this->binSem);
}
void MLMaze::NotifyPhysicalPathDone(PhysicalPathEventInfo agentInfo)
{
sem_wait(&this->binSem);
if (this->agentPhysicalPathDonePublisher == NULL)
{
this->agentPhysicalPathDonePublisher = new Publisher(this->eventDist, SubscriptionTypes::PHYSICAL_PATH_DONE_EVENT);
}
if (this->agentPhysicalPathDonePublisher != NULL)
{
this->agentPhysicalPathDonePublisher->Publish(new PhysicalPathDoneEventPackage(this->nodeId, 0, agentInfo));
}
//Remove agent from the map once it has found its goal, and it is done searching
if (this->agentPos.find(agentInfo.agentId) != this->agentPos.end())
{
Framework::Position<int> *temp = this->agentPos[agentInfo.agentId];
this->agentPos.erase(agentInfo.agentId);
delete temp;
temp = NULL;
}
if (this->transferedAgentsPos.find(agentInfo.agentId) != this->transferedAgentsPos.end())
{
Framework::Position<int> *temp = this->transferedAgentsPos[agentInfo.agentId];
this->transferedAgentsPos.erase(agentInfo.agentId);
delete temp;
temp = NULL;
}
sem_post(&this->binSem);
}
bool MLMaze::IsPositionWithinLocalLimits(Framework::Position<int> pos)
{
bool isWithinLimits = true;
if (this->maze != NULL)
{
if ((pos.GetXCoor() < 0)||
(pos.GetXCoor() >= this->maze->GetXSize())||
(pos.GetYCoor() < 0)||
(pos.GetYCoor() >= this->maze->GetYSize()))
{
isWithinLimits = false;
}
}
return isWithinLimits;
}
bool MLMaze::IsPositionWithinGlobalLimits(Framework::Position<int> pos)
{
bool isWithinLimits = true;
if (this->msgDist != NULL)
{
Framework::Position<int> tempPos = pos + this->msgDist->GetOffset();
if ((tempPos.GetXCoor() < 0)||
(tempPos.GetXCoor() >= this->limit.GetXCoor())||
(tempPos.GetYCoor() < 0)||
(tempPos.GetYCoor() >= this->limit.GetYCoor()))
{
isWithinLimits = false;
}
}
return isWithinLimits;
}
Framework::Position<int> MLMaze::GetPosition(char object)
{
bool found = false;
Framework::Position<int> objPos;
if (this->maze != NULL)
{
char **maze = this->maze->GetMaze();
unsigned ySize = this->maze->GetYSize();
unsigned xSize = this->maze->GetXSize();
//Check the maze
for (unsigned i = 0; i < ySize; i++)
{
for (unsigned j = 0; j < xSize; j++)
{
if (maze[i][j] == object)
{
objPos.SetXCoor(j);
objPos.SetYCoor(i);
found = true;
break;
}
}
}
}
//Check to see if it was a transfered agent
if (!found)
{
sem_wait(&this->binSem);
if (this->transferAgentStart.find(object) != this->transferAgentStart.end())
{
objPos = *this->transferAgentStart[object];
found = true;
}
sem_post(&this->binSem);
}
//As a last resort, ask the main node.
if (!found)
{
bool isFound = false;
GetObjectOnReply *storedReply = NULL;
sem_wait(&this->binSem);
list<GetObjectOnReply *>::iterator iter;
for (iter = getObjectOnReplyList.begin(); iter != getObjectOnReplyList.end(); iter++)
{
if (*iter != NULL)
{
storedReply = *iter;
if (storedReply->queryType == GetObjectOnPackage::GET_POSITION)
{
if (storedReply->object == object)
{
objPos = storedReply->pos;
isFound = true;
break;
}
}
}
}
sem_post(&this->binSem);
if (!isFound)
{
if (this->msgDist != NULL)
{
this->msgDist->SendPackage(new GetObjectOnPackage(this->nodeId, 0, GetObjectOnPackage::GET_POSITION, object));
}
sleep(TIME_OUT);
sem_wait(&this->binSem);
for (iter = getObjectOnReplyList.begin(); iter != getObjectOnReplyList.end(); iter++)
{
if (*iter != NULL)
{
storedReply = *iter;
if (storedReply->queryType == GetObjectOnPackage::GET_POSITION)
{
if (storedReply->object == object)
{
objPos = storedReply->pos;
isFound = true;
break;
}
}
}
}
if (isFound)
{
delete *iter;
*iter = NULL;
getObjectOnReplyList.erase(iter);
}
sem_post(&this->binSem);
}
}
return objPos;
}
/*static*/ void MLMaze::MazeLimitCallback(void *ownerObject, Framework::Packages::IPackage *package)
{
MLMaze *pThis = static_cast<MLMaze *>(ownerObject);
if (pThis != NULL)
{
MazeLimitPackage *limitPackage = dynamic_cast<MazeLimitPackage *>(package);
sem_wait(&pThis->binSem);
if (limitPackage != NULL)
{
pThis->limit = limitPackage->GetLimit();
}
sem_post(&pThis->binSem);
}
delete package;
package = NULL;
}
/*static*/ void MLMaze::CanMoveCallback(void *ownerObject, Framework::Packages::IPackage *package)
{
MLMaze *pThis = static_cast<MLMaze *>(ownerObject);
if (pThis != NULL)
{
MazeCanMovePackage *canMovePackage = dynamic_cast<MazeCanMovePackage *>(package);
if (canMovePackage != NULL)
{
Framework::Position<int> tempPos = canMovePackage->GetPos() - pThis->msgDist->GetOffset();
if (pThis->IsPositionWithinLocalLimits(tempPos))
{
bool canMove = pThis->CanMove(canMovePackage->GetAgentId(), tempPos);
unsigned id = canMovePackage->GetAgentId();
string agentID;
stringstream out;
out << id;
agentID = out.str();
out.str("");
out.flush();
char start[5];
strcpy(start, agentID.c_str());
sem_wait(&pThis->binSem);
if (canMove)
{
pThis->transferAgentStart[start[0]] = new Framework::Position<int>(tempPos);
}
sem_post(&pThis->binSem);
if (pThis->msgDist != NULL)
{
pThis->msgDist->SendPackage(new MazeCanMoveReplyPackage(pThis->nodeId, canMovePackage->GetSource(), canMove, id, start[0]));
}
}
}
}
delete package;
package = NULL;
}
/*static*/ void MLMaze::GetObjectOnCallback(void *ownerObject, Framework::Packages::IPackage *package)
{
MLMaze *pThis = static_cast<MLMaze *>(ownerObject);
if (pThis != NULL)
{
GetObjectOnPackage *objectOnPackage = dynamic_cast<GetObjectOnPackage *>(package);
GetObjectOnReply *reply = new GetObjectOnReply();
if ((objectOnPackage != NULL)&&(reply != NULL))
{
reply->object = objectOnPackage->GetObj();
if (objectOnPackage->GetQueryType() == GetObjectOnPackage::GET_POSITION)
{
if (pThis->msgDist != NULL)
{
reply->pos = objectOnPackage->GetPosition() - pThis->msgDist->GetOffset();
}
}
else
{
reply->pos = objectOnPackage->GetPosition();
}
reply->queryType = objectOnPackage->GetQueryType();
sem_wait(&pThis->binSem);
pThis->getObjectOnReplyList.push_back(reply);
sem_post(&pThis->binSem);
}
delete reply;
reply = NULL;
}
delete package;
package = NULL;
}
/*static*/ void MLMaze::CanMoveReplyCallback(void *ownerObject, Framework::Packages::IPackage *package)
{
MLMaze *pThis = static_cast<MLMaze *>(ownerObject);
if (pThis != NULL)
{
MazeCanMoveReplyPackage *canMoveReplyPackage = dynamic_cast<MazeCanMoveReplyPackage *>(package);
if (canMoveReplyPackage != NULL)
{
MoveReply reply;
reply.canMove = canMoveReplyPackage->GetCanMove();
reply.node = canMoveReplyPackage->GetSource();
reply.startLoc = canMoveReplyPackage->GetStartLoc();
pThis->canMoveReplyMap[canMoveReplyPackage->GetAgentId()] = reply;
}
}
delete package;
package = NULL;
//sem_post(&pThis->canMoveReplySem);
}
} | [
"rk97688@hotmail.com"
] | rk97688@hotmail.com | |
a86ba4c6aa73be0c4436a14a7beb817920089738 | 41eff3e9ed1b5743c18a977feeba9639f5e73736 | /Projects/Project2_HangmanV2/main.cpp | 2b0efd6d94d9caf963f12a51015b203f8f20a637 | [] | no_license | Kcarrillo/CarrilloKevin_48102 | ecb8db6828359d2229e090226e2502f2de5b50fd | 628cadc0bb36c228fba47fb6d30918c6cb917de2 | refs/heads/master | 2020-07-14T00:22:58.275393 | 2016-12-13T20:28:18 | 2016-12-13T20:28:18 | 68,247,215 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,453 | cpp | /*
File: main
Author: Kevin Carrillo
Created on October 17th, 8:30 AM
Purpose: Menu with Functions
*/
//System Libraries
#include <iostream> //Input/Output objects
#include <string> //Strings
#include <iomanip> //Formating
#include <fstream> //File I/O
using namespace std; //Name-space used in the System Library
//User Libraries
//Global Constants
//Function prototypes
void gmeinfo();
void gmeruls();
void playgme();
void hghscre();
void PvP();
void PvC();
//Execution Begins Here!
int main() {
//Declaration of Variables
int menuItm; //Choice from menu
//New Version
cout<<"WELCOME to the NEW Version of Hangman!"<<endl;
//Loop until users exits
do{
//Prompt for problem for user input
cout<<"1. Type 1 for More Information"<<endl;
cout<<"2. Type 2 for the Rules"<<endl;
cout<<"3. Type 3 to Play against computer"<<endl;
cout<<"4. Type 4 to Play against another player"<<endl;
cout<<"5. Type 5 for High scores"<<endl;
cin>>menuItm;
//Go to the Problem
switch(menuItm){
case 1:gmeinfo();break;
case 2:gmeruls();break;
case 3:PvC();break;
case 4:PvP();break;
case 5:hghscre();
}//End the Switch/Case
}while(menuItm>0&&menuItm<=5);//Ends the Do-While Loop
//Exit Program
return 0;
}
void gmeinfo(){
cout<<" More Info: "<<endl;
cout<<" New Features: "<<endl;
cout<<"Now includes Computer Opponent, randomly selected pre-implemented words. \n";
cout<<"Now keeps a high score and track of player score. \n";
cout<<" Old info: "<<endl;
cout<<"Technically 2 players are required to play the game. \n";
cout<<"I thought it would be more fun to have an actual person choose the word which creates more difficulty. \n";
cout<<"Yes, I could have made a menu to allow the user to choose a difficulty and a have it randomize a list of words. \n";
cout<<"But, Hey now you can play with a friend or your spouse ;) \n";
cout<<"Enjoy. \n";
}
void gmeruls(){
cout<<setw(38)<<endl;
cout<<"!The Rules!"<<endl;
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
cout<<" 1.) A person will input a word or phrase ."<<endl;
cout<<" 2.)The actual person has to guess the word or phrase."<<endl;
cout<<" 3.)You are given 6 tries no matter the word size."<<endl;
cout<<" 4.)If guess is correct no tries are used."<<endl;
cout<<" 5.)After all tries, Player loses."<<endl;
cout<<" 6.)GAME IS CASE SENSITIVE."<<endl;
cout<<" 7.)New Mode: A word is selected randomly by computer."<<endl;
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
}
void PvP(){
cout<<"!!Let The Games Begin!!"<<endl;
//Declare Variables
string word;
int wrong=0,score;
char x=' ';
char o='O';
char l='|';
char a='\\';
char b='/';
char d='_';
char c='-';
ifstream in;
ofstream out;
//Input Values
cout << "Enter the word for the other player to guess" << endl;
cin.ignore();
getline(cin, word);
//Process Word
string copy = word;
string undrScr;
for(int i=0; i!=word.length(); i++){
if(word.at(i) == ' '){
undrScr += " ";
}
else{
undrScr += "_";
}
}
//Display Board
cout<<x<<x<<x<<x<<x<<x<<x<<x<<endl;
cout<<x<<x<<x<<c<<c<<c<<l<<x<<endl;
cout<<x<<x<<x<<l<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<d<<x<<endl;
//Process Guesses
for(int i=0; i!=50; ++i){
cout << endl;
}
string guess;
while(1){
if(wrong == 6){
cout << "You Lose! The word was: " << word << endl;
cout<<x<<x<<x<<x<<x<<x<<x<<x<<endl;
cout<<x<<x<<x<<c<<c<<c<<l<<x<<endl;
cout<<x<<x<<x<<l<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<o<<x<<x<<l<<x<<endl;
cout<<x<<x<<b<<l<<a<<x<<l<<x<<endl;
cout<<x<<x<<b<<x<<a<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<d<<x<<endl;
break;
}
else if (wrong==5){
cout<<x<<x<<x<<x<<x<<x<<x<<x<<endl;
cout<<x<<x<<x<<c<<c<<c<<l<<x<<endl;
cout<<x<<x<<x<<l<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<o<<x<<x<<l<<x<<endl;
cout<<x<<x<<b<<l<<a<<x<<l<<x<<endl;
cout<<x<<x<<b<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<d<<x<<endl;
}
else if (wrong==4){
cout<<x<<x<<x<<x<<x<<x<<x<<x<<endl;
cout<<x<<x<<x<<c<<c<<c<<l<<x<<endl;
cout<<x<<x<<x<<l<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<o<<x<<x<<l<<x<<endl;
cout<<x<<x<<b<<l<<a<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<d<<x<<endl;
}
else if(wrong==3){
cout<<x<<x<<x<<x<<x<<x<<x<<x<<endl;
cout<<x<<x<<x<<c<<c<<c<<l<<x<<endl;
cout<<x<<x<<x<<l<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<o<<x<<x<<l<<x<<endl;
cout<<x<<x<<b<<l<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<d<<x<<endl;
}
else if(wrong==2){
cout<<x<<x<<x<<x<<x<<x<<x<<x<<endl;
cout<<x<<x<<x<<c<<c<<c<<l<<x<<endl;
cout<<x<<x<<x<<l<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<o<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<l<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<d<<x<<endl;
}
else if(wrong==1){
cout<<x<<x<<x<<x<<x<<x<<x<<x<<endl;
cout<<x<<x<<x<<c<<c<<c<<l<<x<<endl;
cout<<x<<x<<x<<l<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<o<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<l<<x<<endl;
cout<<x<<x<<x<<x<<x<<x<<d<<x<<endl;
}
cout << undrScr << endl;
cout << "There are " << word.length() << " letters " << endl;
cout << "You have " << 6 - wrong << " more tries left" << endl;
if(undrScr == word){
cout << "CONGRATS, You win!" << endl;
break;
}
cout << "Guess a letter or a word" << endl;
getline(cin, guess);
if(guess.length() > 1){
if(guess == word){
cout << "You are correct, YOU WIN!" << endl;
break;
} else{
cout << "wrong word " << endl;
wrong++;
}
} else if(copy.find(guess) != -1){
while(copy.find(guess) != -1){
undrScr.replace(copy.find(guess), 1, guess);
copy.replace(copy.find(guess), 1, "_");
}
} else{
cout << "That's wrong" << endl;
wrong++;
}
cout << endl;
}
in.open("HighScores.dat");
score=((10-wrong)*3);
in>>score;
in.close();
in.clear();
}
void PvC(){
}
void hghscre(){
//Declaration of Variables
int score;
ifstream in;
ofstream out;
string name, name1, buffer=" ";
short score1;
//Open High Score File
in.open("HighScores.dat");
in>>name1>>score1>>score; //Pull in the name and the score from the file
//Close and clear
in.close();
in.clear();
if (score > score1){ //If the user beat the previous score
//Display both players score and the one stored
cout<<endl;
cout<<"You beat the pervious high-score"<<endl;
cout<<"The pervious score was:" << endl;
cout<<score1<<" Points"<<endl;
cout<<"Your score is:"<<endl;
cout<<score<<" Points"<<endl;
//Open the file
out.open("HighScores.dat");
//Change the name and high score
cout<<"Input your first name:";
cin >> name;
out<<name<<buffer<<score;
//Display the player's score.
cout<<endl<<endl<<endl<< "Final score :"<<endl;
cout<<setprecision(2)<<showpoint<<fixed<<endl;
cout<<name<<" "<<static_cast<float>(score)<<" Points"<<endl;
//Close and clear the file
out.close();
out.clear();
}
else if(score==score1){
cout<<"Tied with previous score "<<endl;
//User enters name and their score is displayed
cout<<"Input your first name:";
cin >> name;
cout<<setprecision(2)<<showpoint<<fixed<<endl;
cout<<name1<<" "<<static_cast<float>(score)<<endl;
}
else{//Else
//User enters name and their score is displayed
cout << "You didn't beat the pervious high-score"<<endl;
cout<<"Input your first name:";
cin >> name;
cout<<setprecision(2)<<showpoint<<fixed<<endl;
cout<<name1<<" "<<static_cast<float>(score)<<endl;
}
} | [
"kcarrillo12@student.rcc.edu"
] | kcarrillo12@student.rcc.edu |
b82b10227ba50c6a8a9b4c589616d2a760f925da | c254c37b30fba0c41b3157dd5581e03035df43c1 | /C++ Solutions/Caribbean Online Judge/Ad-Hoc/1312 - R2.cpp | 2b9dec79fe2dac02ba643e7fd034f263853adbe4 | [] | no_license | AntonioSanchez115/Competitive-Programming | 12c8031bbb0c82d99b4615d414f5eb727ac5a113 | 49dac0119337a45fe8cbeae50d7d8563140a3119 | refs/heads/master | 2022-02-14T10:51:19.125143 | 2022-01-26T07:59:34 | 2022-01-26T07:59:34 | 186,081,160 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 147 | cpp | #include<stdio.h>
int main()
{
int R1;//11
int S;//15
scanf("%d%d",&R1,&S);
int R2=(S*2)-R1;
printf("%d", R2);
return 0;
}
| [
"sanchezantonio.115@gmail.com"
] | sanchezantonio.115@gmail.com |
d25d330e69cbde5d4093bb0e17534f4311200c4d | 40f64ca70e69d19d6cd4d485efc75c72b89fe336 | /第七章 排序/heapsort.cpp | 101388d7f25ec2ea7bb19891068cd71be7909e96 | [] | no_license | MingHuan-L/Data-Strucntures | 0c8b7d9185f0395aaa5eac72842be9cbd54b3485 | 9e560c255d474ca0a396e73622a06117d1eb2367 | refs/heads/master | 2023-06-18T20:29:41.958846 | 2021-07-13T09:22:42 | 2021-07-13T09:22:42 | 241,047,261 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,189 | cpp | #include <iostream>
#include <time.h>
#include <stdio.h>
int radomnum(int A[])
{
A[0] = 0;
int range = 100;
const int maxsize = 100;
srand((int)time(0));
for (int i = 1; i <=maxsize; i++)
{
A[i] = rand() % range;
}
return 0;
}
void display(int A[], int n)
{
for (int i = 0; i <= n; i++)
std::cout <<"A["<<i<<"] is "<< A[i] << " ";
std::cout << std::endl;
}
void headadjust(int A[], int k, int len) //调整当前双亲结点
{
A[0] = A[k]; //A【0】记录当前的双亲结点
for (int i = 2 * k; i <= len; i *= 2) //A【i】为A【k}的左孩子
{
if (i < len && A[i] < A[i + 1]) //右孩子大于左孩子
i++; //则指向右孩子
if (A[0] >= A[i]) //如果双亲结点大于孩子结点,不用交换
break;
else
{ //双亲结点小于孩子结点
A[k] = A[i]; //交换结点的值
k = i; //k指向当前的孩子结点,循环不断向下调整
}
}
A[k] = A[0]; //被筛选结点的值放入最终位置
}
void Buildmaxheap(int A[], int len)
{
for (int i = len / 2; i > 0; i--) //最后一个双亲结点的编号为i/2取下界,第一个双亲结点为1.
{ //对所有具有双亲结点含义的编号从大到小(i/2~1)做出调整
headadjust(A, i, len);
}
}
void heapsort(int A[], int len)
{
Buildmaxheap(A, len); //建立大根堆。已调整完i/2~1的双亲结点。建立了初始的大根堆
std::cout<<"current heaptop elem:"<<A[1]<<" ";
for (int i = len; i > 1; i--)
{
int temp = A[i];
A[i] = A[1];
std::cout << A[1] << " "; //不断输出堆顶
A[1] = temp; //堆底元素放到堆顶,破坏堆的结构。
headadjust(A, 1, i - 1); //重新建堆,长度为1~i-1;
}
}
int main()
{
int A[101];
radomnum(A);
std::cout << "A:" << std::endl;
display(A, 100);
std::cout << "heapsort A" << std::endl;
heapsort(A, 100);
system("pause");
return 0;
} | [
"394431799@qq.com"
] | 394431799@qq.com |
cfde5bdb80a969c0d870a975bfd721d225abb2c2 | 634120df190b6262fccf699ac02538360fd9012d | /Develop/Server/GameServerOck/main/GDBTaskItemDecstackAmt.h | 74a0a55268db7b952786fc129fc2aefa254cd6e9 | [] | no_license | ktj007/Raiderz_Public | c906830cca5c644be384e68da205ee8abeb31369 | a71421614ef5711740d154c961cbb3ba2a03f266 | refs/heads/master | 2021-06-08T03:37:10.065320 | 2016-11-28T07:50:57 | 2016-11-28T07:50:57 | 74,959,309 | 6 | 4 | null | 2016-11-28T09:53:49 | 2016-11-28T09:53:49 | null | UTF-8 | C++ | false | false | 611 | h | #ifndef _GDBTASK_ITEM_DEC_STACK_AMT_H
#define _GDBTASK_ITEM_DEC_STACK_AMT_H
#include "GDBTaskItemStackAmt.h"
#include "GDBTaskItemData.h"
#include "MMemPool.h"
class GDBTaskItemDecStackAmt : public GDBTaskItemStackAmt, public MMemPool<GDBTaskItemDecStackAmt>
{
public :
GDBTaskItemDecStackAmt(const MUID& uidPlayer);
~GDBTaskItemDecStackAmt() {}
enum
{
ITEM_DEC_STACK_AMT = 0,
};
bool Input(GDBT_ITEM_DEC_STACK_AMT_DATA& data);
void OnExecute(mdb::MDatabase& rfDB) override;
mdb::MDB_THRTASK_RESULT _OnCompleted() override;
protected :
GDBT_ITEM_DEC_STACK_AMT_DATA m_Data;
};
#endif | [
"espause0703@gmail.com"
] | espause0703@gmail.com |
8ec7ffb4a300e96417f5d8b15c39241994833559 | c23b42b301b365f6c074dd71fdb6cd63a7944a54 | /contest/Daejeon/2015/f2.cpp | 4f4d19f8bbe2a702899ed564c789bee6b0e44679 | [] | no_license | NTUwanderer/PECaveros | 6c3b8a44b43f6b72a182f83ff0eb908c2e944841 | 8d068ea05ee96f54ee92dffa7426d3619b21c0bd | refs/heads/master | 2020-03-27T22:15:49.847016 | 2019-01-04T14:20:25 | 2019-01-04T14:20:25 | 147,217,616 | 1 | 0 | null | 2018-09-03T14:40:49 | 2018-09-03T14:40:49 | null | UTF-8 | C++ | false | false | 5,110 | cpp | #include <bits/stdc++.h>
using namespace std;
#define N 101010
#define MXN 101010
#define PB push_back
#define FZ(X) memset(X,0,sizeof X)
struct Scc{
int n, nScc, vst[MXN], bln[MXN];
vector<int> E[MXN], rE[MXN], vec;
void init(int _n){
n = _n;
for (int i=0; i<=n; i++){
E[i].clear();
rE[i].clear();
}
}
void add_edge(int u, int v){
E[u].PB(v);
rE[v].PB(u);
}
void DFS(int u){
vst[u]=1;
for (auto v : E[u])
if (!vst[v]) DFS(v);
vec.PB(u);
}
void rDFS(int u){
vst[u] = 1;
bln[u] = nScc;
for (auto v : rE[u])
if (!vst[v]) rDFS(v);
}
void solve(){
nScc = 0;
vec.clear();
FZ(vst);
for (int i=0; i<=n; i++)
if (!vst[i]) DFS(i);
reverse(vec.begin(),vec.end());
FZ(vst);
for (auto v : vec){
if (!vst[v]){
rDFS(v);
nScc++;
}
}
}
} scc;
int n , m;
vector< int > v[ N ] , ov[ N ];
set< pair<int,int> > S;
void init(){
scanf( "%d%d" , &n , &m );
for( int i = 0 ; i <= n ; i ++ ){
v[ i ].clear();
ov[ i ].clear();
}
S.clear();
scc.init( n );
for( int i = 0 ; i < m ; i ++ ){
int ui , vi; scanf( "%d%d" , &ui , &vi );
ov[ ui ].push_back( vi );
v[ ui ].push_back( vi );
v[ vi ].push_back( ui );
scc.add_edge( ui , vi );
S.insert( { ui , vi } );
}
for( int i = 1 ; i <= n ; i ++ ){
ov[ 0 ].push_back( i );
v[ 0 ].push_back( i );
v[ i ].push_back( 0 );
}
scc.solve();
}
bool got;
int clr[ N ] , id[ N ] , cand;
vector< int > oo[ N ];
int sssk[ N ];
vector< int > candv;
void go( int now , int tclr , int ndep ){
sssk[ ndep ] = now;
clr[ now ] = tclr;
for( int x : v[ now ] )
if( scc.bln[ now ] == scc.bln[ x ] ){
if( clr[ x ] ){
if( clr[ x ] == clr[ now ] ){
cand = 1;
for( int i = ndep ; sssk[ i ] != x ; i -- )
candv.push_back( sssk[ i ] );
candv.push_back( x );
return;
}
}else{
go( x , 3 - tclr , ndep + 1 );
if( candv.size() ) return;
}
}
}
int stk[ N ] , vst[ N ] , dep[ N ];
//void gogo( int now , int tdep ){
//stk[ tdep ] = now;
//dep[ now ] = tdep;
//vst[ now ] = 1;
//for( int x : v[ now ] ){
//if( vst[ x ] ){
//if( ( dep[ now ] - dep[ x ] ) % 2 == 0 ){
//for( int i = dep[ x ] ; i <= dep[ now ] ; i ++ )
//candv.push_back( i );
//return;
//}
//continue;
//}
//gogo( x , tdep + 1 );
//if( candv.size() ) return;
//}
//}
vector< int > ans;
int ssk[ N ];
bool f , bye , gggt[ N ];
void gogogogo( int now , int tar , int tdep ){
ssk[ tdep ] = now;
gggt[ now ] = true;
if( now == tar ){
if( tdep % 2 == 0 ){
puts( "1" );
printf( "%d\n" , tdep + 1 );
for( int i = 0 ; i <= tdep ; i ++ )
printf( "%d\n" , ssk[ i ] );
f = bye = true;
return;
}else{
for( int i = 1 ; i < tdep ; i ++ )
ans.push_back( ssk[ i ] );
f = true;
return;
}
}
for( int u : ov[ now ] ){
if( gggt[ u ] || scc.bln[ now ] != scc.bln[ u ] )
continue;
gogogogo( u , tar , tdep + 1 );
if( f || bye ) return;
}
}
void fixup( int ss , int tt ){
if( S.count( { ss , tt } ) ) return;
f = false;
gogogogo( ss , tt , 0 );
}
int pre[ N ];
bool bb[ N ];
void shrink(){
for( size_t i = 0 ; i < ans.size() ; i ++ ){
pre[ ans[ i ] ] = -1;
bb[ i ] = false;
}
for( size_t i = 0 ; i < ans.size() ; i ++ )
if( pre[ ans[ i ] ] != -1 ){
int dlt = i - pre[ ans[ i ] ];
if( dlt % 2 ){
vector< int > tans;
for( size_t j = pre[ ans[ i ] ] ; j < i ; j ++ )
tans.push_back( ans[ j ] );
ans = tans;
return;
}else{
for( size_t j = pre[ ans[ i ] ] ; j < i ; j ++ ){
pre[ ans[ j ] ] = -1;
bb[ j ] = true;
}
pre[ ans[ i ] ] = i;
}
}else
pre[ ans[ i ] ] = i;
size_t ksz = 0;
for( size_t i = 0 ; i < ans.size() ; i ++ )
if( !bb[ i ] )
ans[ ksz ++ ] = ans[ i ];
ans.resize( ksz );
}
void go( int id ){
if( oo[ id ].empty() ) return;
int rt = oo[ id ][ 0 ];
candv.clear();
cand = -1;
go( rt , 1 , 0 );
if( candv.empty() ) return;
for( int x : oo[ id ] ){
vst[ x ] = 0;
gggt[ x ] = false;
}
bye = false;
ans.clear();
for( size_t i = 0 ; i < candv.size() ; i ++ ){
ans.push_back( candv[ i ] );
for( int x : oo[ id ] )
gggt[ x ] = false;
fixup( candv[ i ] , candv[ ( i + 1 ) % candv.size() ] );
if( bye ){
got = true;
return;
}
}
got = true;
shrink();
puts( "1" );
printf( "%d\n" , (int)ans.size() );
for( auto i : ans )
printf( "%d\n" , i );
}
void solve(){
for( int i = 1 ; i <= n ; i ++ ){
id[ i ] = scc.bln[ i ];
oo[ scc.bln[ i ] ].push_back( i );
clr[ i ] = 0;
}
got = false;
for( int i = 0 ; i < scc.nScc && !got ; i ++ )
go( i );
if( !got ) puts( "-1" );
for( int i = 0 ; i <= n ; i ++ )
oo[ i ].clear();
}
int main(){
int _; scanf( "%d" , &_ ); while( _ -- ){
init();
solve();
}
}
| [
"c.c.hsu01@gmail.com"
] | c.c.hsu01@gmail.com |
99f9f306feae2cb37a528bccc38fa1a56ad50a36 | 738293cecc7af7719c1465bdd3f9f6a37aeeb41c | /Week6/rob_2.cpp | b8c3a4619c0643aef73b1e1906009e4609cfa84c | [] | no_license | liwenhao8123/algorithm020 | 58d0dfd757633a81bf12aee343b2255a74472105 | 58954912eb40be3b9df7b090c0d02804cd8f11aa | refs/heads/main | 2023-03-08T11:56:30.286275 | 2021-01-31T15:17:36 | 2021-01-31T15:17:36 | 314,124,354 | 0 | 0 | null | 2020-11-19T03:19:44 | 2020-11-19T03:19:43 | null | UTF-8 | C++ | false | false | 1,664 | cpp | /*
你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。
给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。
示例 1:
输入:[1,2,3,1]
输出:4
解释:偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
偷窃到的最高金额 = 1 + 3 = 4 。
示例 2:
输入:[2,7,9,3,1]
输出:12
解释:偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
偷窃到的最高金额 = 2 + 9 + 1 = 12 。
*/
//方法二: 时间复杂度O(n) 空间复杂度O(n)
//利用一维数组DP[0..n], 定义出DP方程:
//dp[i] = max(dp[i-1] + 0, nums[i]+dp[i-2])
//对于第 i 个房子,取第i-1个房子+0,与nums[i]+第i-2个房子 的较大值
//当然也可以nums[i]+第i-3个房子或nums[i]+第i-4个房子
//仔细思考下在计算dp[i-2]时,它的值一定是大于i-3和i-4的,所以可以忽略
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.empty())
return 0;
int n = nums.size();
if (n == 1)
return nums[0];
vector<int> dp(n, 0);
dp[0] = max(0, nums[0]);
dp[1] = max(dp[0], nums[1]);
for (int i = 2; i < n; i++){
dp[i] = max(dp[i-1], nums[i] + dp[i-2]);
}
return dp[n-1];
}
}; | [
"lwh8123@foxmail.com"
] | lwh8123@foxmail.com |
e5ff92eead0c9a4a894eeef2cd82dda04f54b4f6 | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/windows/feime/kor/ime2k/imm32/fmode.h | c8c9def972518a7c359eaf8a353e1563ce0c8561 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 742 | h | //
// FMODE.H
//
#if !defined (__FMODE_H__INCLUDED_)
#define __FMODE_H__INCLUDED_
#include "cicbtn.h"
#include "toolbar.h"
class FMode : public CCicButton
{
public:
FMode(CToolBar *ptb);
~FMode() {}
STDMETHODIMP GetIcon(HICON *phIcon);
HRESULT OnLButtonUp(const POINT pt, const RECT* prcArea);
// HRESULT OnRButtonUp(const POINT pt, const RECT* prcArea);
STDMETHODIMP InitMenu(ITfMenu *pMenu);
STDMETHODIMP OnMenuSelect(UINT wID);
STDMETHODIMP_(ULONG) Release(void);
private:
DWORD GetCMode() { return m_pTb->GetConversionMode(); }
DWORD SetCMode(DWORD dwConvMode) { return m_pTb->SetConversionMode(dwConvMode); }
CToolBar *m_pTb;
};
#endif // __FMODE_H__INCLUDED_
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
47022e1603f41bed66286c670249c70b5078a5c9 | ca7b94c3fc51f8db66ab41b32ee0b7a9ebd9c1ab | /wallet/universal_lib/include/CommonLib/String/Convert.h | 9a20059c3c5f9ad6f8a19cbd5239e132363036ca | [] | no_license | blockspacer/TronWallet | 9235b933b67de92cd06ca917382de8c69f53ce5a | ffc60e550d1aff5f0f6f1153e0fcde212d37bdc6 | refs/heads/master | 2021-09-15T15:17:47.632925 | 2018-06-05T14:28:16 | 2018-06-05T14:28:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,585 | h | // Author: chenjianjun
#pragma once
#include <util.h>
#include "../../Universal.h"
struct CodePage
{
CodePage() : dwCodePage(CP_UTF8) {}
CodePage(DWORD c, int) : dwCodePage(c) {}
~CodePage() {}
bool operator == (const CodePage &cp) const
{
return dwCodePage == cp.dwCodePage;
}
bool operator != (const CodePage &cp) const
{
return dwCodePage != cp.dwCodePage;
}
DWORD dwCodePage;
};
const int g_iAcp_DONOT_USE_THIS = CP_ACP;
const int g_iUtf8_DONOT_USE_THIS = CP_UTF8;
const int g_iUtf7_DONOT_USE_THIS = CP_UTF7;
#undef CP_ACP
#undef CP_OEMCP
#undef CP_MACCP
#undef CP_THREAD_ACP
#undef CP_SYMBOL
#undef CP_UTF7
#undef CP_UTF8
#define CP_Utf8 CodePage(g_iUtf8_DONOT_USE_THIS, 0)
#define CP_Utf7 CodePage(g_iUtf7_DONOT_USE_THIS, 0)
#define CP_Ansi CodePage(g_iAcp_DONOT_USE_THIS, 0)
#define CP_GBK CodePage(936, 0)
UNIVERSAL_LIB_API std::wstring AToW(__in LPCSTR lpszSrc, __in int iSrcLen = -1, __in CodePage codePage = CP_Utf8);
UNIVERSAL_LIB_API std::wstring AToW(__in const std::string& str, __in CodePage codePage = CP_Utf8);
UNIVERSAL_LIB_API std::wstring AToW(__in const se::stringbuf& sb, __in CodePage codePage = CP_Utf8);
LPCWSTR AToW(__in LPCSTR lpszSrc, __out LPWSTR lpszDest, __in const int iDestLen, __in CodePage codePage = CP_Utf8);
LPCWSTR AToW(__in LPCSTR lpszSrc, __in const int iSrcLen, __out LPWSTR lpszDest, __in const int iDestLen, __in CodePage codePage = CP_Utf8);
LPCWSTR AToW(__in LPCSTR lpszSrc, __out std::wstring& strDest, __in CodePage codePage = CP_Utf8);
UNIVERSAL_LIB_API LPCWSTR AToW(__in LPCSTR lpszSrc, __in const int iSrcLen, __out std::wstring& strDest, __in CodePage codePage = CP_Utf8);
UNIVERSAL_LIB_API std::string WToA(__in LPCWSTR lpszSrc, __in const int iSrcLen = -1, __in CodePage codePage = CP_Utf8);
UNIVERSAL_LIB_API std::string WToA(__in const std::wstring& str, __in CodePage codePage = CP_Utf8);
UNIVERSAL_LIB_API std::string WToA(__in const se::wstringbuf& sb, __in CodePage codePage = CP_Utf8);
UNIVERSAL_LIB_API LPCSTR WToA(__in LPCWSTR lpszSrc, __out LPSTR lpszDest, __in const int iDestLen, __in CodePage codePage = CP_Utf8);
UNIVERSAL_LIB_API LPCSTR WToA(__in LPCWSTR lpszSrc, __in const int iSrcLen, __out LPSTR lpszDest, __in const int iDestLen,
__in CodePage codePage = CP_Utf8);
UNIVERSAL_LIB_API LPCSTR WToA(__in LPCWSTR lpszSrc, __out std::string& strDest, __in CodePage codePage = CP_Utf8);
UNIVERSAL_LIB_API LPCSTR WToA(__in LPCWSTR lpszSrc, __in const int iSrcLen, __out std::string& strDest, __in CodePage codePage = CP_Utf8);
| [
"abce@live.cn"
] | abce@live.cn |
e76e7e8559fe55a5cde700102bb5e47196063952 | 5142fa57a2561d2c53ee4159a6dc742f918875e2 | /자료구조/SearchGraph.h | 8d48086e7c17c81046ee08c045f7a7ab399b4b67 | [] | no_license | skarltjr/prac-cpp | b408ee0bdcb51c780a5eed10e7dd00bcae0a291b | 6b327516bfadfb5b289dec09775ce67663840a81 | refs/heads/master | 2022-11-17T18:20:17.939932 | 2020-07-13T09:18:57 | 2020-07-13T09:18:57 | 279,254,178 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 11,018 | h | #pragma once
#include<iostream>
#include<string>
#include<fstream>
#include<sstream>
#include"CircularQueue.h"
#define MAX_VTXS 256
class Node//각 노드마다 연결리스트가 있으니 연결리스트 클래스를 만들어준다
{
protected:
int id;
Node* link;
public:
Node(int i, Node* l = nullptr)
:id(i), link(l) {}
~Node()
{
if (link != nullptr)
{
delete link;
}
}
int getId()
{
return id;
}
Node* getLink() { return link; }
void setLink(Node* l) { link = l; }//다음 노드 연결
};
class AdjListGraph
{
protected:
int size; //전체 그래프의 사이즈
std::string vertices[MAX_VTXS]; //각 vertex의 이름
Node* adj[MAX_VTXS];
public:
AdjListGraph(void) :size(0) { }
~AdjListGraph(void) { reset(); }
std::string getVertex(int i) { return vertices[i]; }//i번 째 vertex를 가져오는
bool isEmpty() { return size == 0; }
bool isFull() { return size >= MAX_VTXS; }
void reset()
{
for (int i = 0; i < size; i++)
{
if (adj != nullptr) { delete adj[i]; }
}
size = 0;
}
void insertVertex(std::string name)
{
if (!isFull())
{
vertices[size] = name;
adj[size++] = nullptr;
}
else { std::cout << "최대 정점수 이상을 입력할 수 없다"; }
}
void insertEdge(int u, int v)
{
//adj[u] = new Node(v, adj[u]);
//★★ 이미 adj[u]에 B->A가 들어있다고 해보자 그럼 new Node해서 만들어주면
//새로만들어진 Node의 link에 B->A가 담겨져있다 즉
//새로만든 노드이름이 C라면 이걸 새로만들었으니 c의 링크부분에 b-a가 있다.
//이제 adj[u]=c-b-a가된다.
//만약 Adj Matrix와같은 순서로 만들고 싶으면
if (adj[u] == nullptr) {
adj[u] = new Node(v, adj[u]);//id가 v이고 링크가 adj[u]인 노드데이터를 adj[u]에 대입.
}
else {
Node* p = adj[u];
while (p->getLink() != nullptr) {//이 p라는 노드 끝까지 탐색 예를들어 지금 B->A->null까지 있으면 A까지 탐색
p = p->getLink();//다음껄로 넘어가고
}
p->setLink(new Node(v, nullptr));//맨 뒤에 새노드추가해준다.B->A->C->NULL 굳이이럴필욘없다.
}
}
void display()
{
std::cout << size << "\n";
for (int i = 0; i < size; i++)
{
std::cout << getVertex(i) << " ";//구ㅡ럼 행ㅁ마다 A B C D이렇게 나오고
for (Node* v = adj[i]; v != nullptr; v = v->getLink())//adj[0]은 첫번째 노드부터 순회 그다음 adj[1]....
{
std::cout << getVertex(v->getId()) << " ";//v가 nullptr일때까지니까 a-b-c처럼 되어있으면
}std::cout << "\n"; //a나오고b그다음 안 비어있으니 c까지 해준다음 그 다음
} //adj[1]로 넘어가는것
}
void load(std::string filename)
{
std::ifstream ifs(filename);//파일불러오고
std::string line;
std::getline(ifs, line);
std::stringstream ls(line);//공백 단위로 끊어서 값을 받게된다
int n;
ls >> n;//첫줄에 사이즈 던져주니까 사이즈 얻고
for (int i = 0; i < n; i++)
{
std::getline(ifs, line);
std::string str;
int val;
std::stringstream ls(line);//공백단위니까 처음에 A 0 1 0 1 이라면 ls에 A들어가고
ls >> str;//A를 str에 옮기고
insertVertex(str);//이렇게 노드 A 그다음 루프에서 B..가 생겨난다.
for (int j = 0; j < n; j++)
{
ls >> val;
if (val != 0)
{
insertEdge(i, j);
}
}
}ifs.close();
}
};
class AdjMatGraph
{
protected:
int size; //전체 그래프의 사이즈
std::string vertices[MAX_VTXS]; //각 vertex의 이름
int adj[MAX_VTXS][MAX_VTXS];//인접행렬
public:
AdjMatGraph() { reset(); }
~AdjMatGraph() {}
std::string getVertex(int i) { return vertices[i]; }//i번 째 vertex를 가져오는
int getEdge(int i, int j) { return adj[i][j]; }//i와j사이에 edge가 있는지 있으면 1 없으면 0
void setEdge(int i, int j, int val) { adj[i][j] = val; }//이 val은 가중치가 있는 그래프에서 사용
bool isEmpty() { return size == 0; }
bool isFull() { return size >= MAX_VTXS; }
void reset()
{
size = 0;
for (int i = 0; i < MAX_VTXS; i++)
{
for (int j = 0; j < MAX_VTXS; j++)
{
setEdge(i, j, 0);
}
}
}
void insertVertex(std::string name)
{
if (!isFull()) { vertices[size++] = name; }//예를들어 3번에 넣고싶다하면
//index가 0부터시작이니까 vertices[2] 0,1,2 에들어간다 그러니까 size++로 맞춰주는것
else { std::cout << "최대 정점수 이상을 입력할 수 없다"; }
}
void insertEdge(int u, int v)
{
setEdge(u, v, 1);//1인 이유는 가중치가없으니 다 동일한 1로맞춘다.
setEdge(v, u, 1);//가중치가 없으니 대칭행렬
}
void display()
{
std::cout << size << "\n";
for (int i = 0; i < size; i++)
{
std::cout << getVertex(i) << " ";
for (int j = 0; j < size; j++)
{
std::cout << getEdge(i, j) << " ";
}std::cout << "\n";
}
}
void load(std::string filename)
{
std::ifstream ifs(filename);//파일을 입력받고
std::string line;
std::getline(ifs, line);//line에 파일에있는 문자열을 한 줄씩 받아오게하고.
std::stringstream ls(line);//A0101을 한 줄로 즉 스트링을 공백단위로 끊어서
int n;
ls >> n; //첫 줄에 std::cout << size << "\n";니까 size인 4만 적혀있을거니까 이 첫줄4가 n에 들어가고
for (int i = 0; i < n; i++)//전체그래프의 사이즈 행렬로 나타내면 맨위에 ABCD니까 size가 4줄 이라 생각 . 행이 4
{
std::getline(ifs, line);// 맨 위4 다음 한 줄을 받기위해 다시 2번째 줄부터 getline
std::string str;
int val;
std::stringstream ls(line);//공백단위로 끊으니까 A 0 1 0 1 일때
ls >> str;//이건 A B C D처럼 vertex이름 공백단위로 맨 앞에꺼 밭고 처음엔 A
insertVertex(str);
for (int j = 0; j < n; j++)
{
ls >> val;//그 다음 열 따라 0 1 0 1
if (val != 0)
{
insertEdge(i, j);
}
}//다시 행 바뀌면 이번엔 B
}ifs.close();
}
void store(std::string filename)//display랑 똑같다
{
std::ofstream ofs(filename);
ofs << size << "\n";
for (int i = 0; i < MAX_VTXS; i++)
{
ofs << getVertex(i) << " ";
for (int j = 0; j < MAX_VTXS; j++)
{
ofs << getEdge(i, j) << " ";
}ofs << "\n";
}ofs.close();
}
};
class SrchAMGraph :public AdjMatGraph
{
protected:
bool visited[MAX_VTXS];
public:
void resetVisited()
{
for (int i = 0; i < size; i++)
{
visited[i] = false;
}
}
bool isLinked(int u, int v) { return getEdge(u, v) != 0; }
void DFS(int v)//시작점 v or 자기자신 v
{
visited[v] = true;
std::cout << getVertex(v) << " ";
for (int w = 0; w < size; w++)
{
if (isLinked(v, w) && visited[w] == false)///시작점v와 다른 한 정점 w가 연결되어있고 아직 w를 방문하지않았으면
{
DFS(w);
}
}
}
void BFS(int v)
{
visited[v] = true;
std::cout << getVertex(v) << " ";
CircularQueue que;
que.enqueue(v);
while (!que.isEmpty())
{
int v = que.dequeue();//선입선출을 생각해봐라
for (int w = 0; w < size; w++)
{
if (isLinked(v, w) && visited[w] == false)//시작점v와 다른 한 정점 w가 연결되어있고 아직 w를 방문하지않았으면
{
visited[w] = true;
std::cout << getVertex(w) << " ";
que.enqueue(w);
}
}
}
}
};
class SrchALGraph :public AdjListGraph
{
protected:
bool visited[MAX_VTXS];
public:
void resetVisited()
{
for (int i = 0; i < size; i++)
{
visited[i] = false;
}
}
bool isLinked(int u, int v)
{
for (Node* p = adj[u]; p != nullptr; p = p->getLink())//시작점p
{
if (p->getId() == v) { return true; }
}
return false;
}
void DFS(int v)//시작점 v or 자기자신 v
{
visited[v] = true;
std::cout << getVertex(v) << " ";
for (Node* p = adj[v]; p != nullptr; p = p->getLink())
{
if (visited[p->getId()] == false)
{
DFS(p->getId());
}
}
}
void BFS(int v)
{
visited[v] = true;
std::cout << getVertex(v) << " ";
CircularQueue que;
que.enqueue(v);
while (!que.isEmpty())
{
int v = que.dequeue();
for (Node* w = adj[v]; w != nullptr; w = w->getLink())
{
int id = w->getId();
if (visited[id] == false)//시작점v와 다른 한 정점 w가 연결되어있고 아직 w를 방문하지않았으면
{
visited[id] = true;
std::cout << getVertex(id) << " ";
que.enqueue(id);
}
}
}
}
};
class ConnectedComponentGraph : public SrchAMGraph
{
protected:
int label[MAX_VTXS];
public:
void labelDFS(int v, int color)
{
visited[v] = true;
label[v] = color;//연결성분끼리 구분짓기 위해
std::cout << getVertex(v) << " ";
for (int w = 0; w < size; w++)
{
if (isLinked(v, w) && visited[w] == false)
{
labelDFS(w, color);
}
}
}
void findConnectedComponent()
{
int count = 0;
for (int i = 0; i < size; i++)
{
if (visited[i] == false)//같은 연결성분끼리는 같은 크기의 count를 갖을 것
{
labelDFS(i, ++count);
}
}
std::cout << "\n연결 성분의 수는 : " << count << "\n";
for (int i = 0; i < size; i++)
{
std::cout << getVertex(i) << ":" << label[i] << " ";
}
std::cout << "\n";
}
};
/*
위상정렬이란 방향이 있는 그래프에 대해 정점들의 선행 순서를 위배하지 않으면서 모든 정점을 나열하는 것
*/
class ToposortGraph :public AdjListGraph//방향성이 존재한다
{
public:
ToposortGraph() {}
~ToposortGraph() {}
void insertDirEdge(int u, int v)//u에서시작해서 v에 도착하는 간선을 만든다
{
adj[u] = new Node(v, adj[u]);
}
void TopoSort()
{
CircularQueue q;
int* inDeg = new int[size];//모든 정점의 in-degree(진입 차수)를 담는 변수
for (int i = 0; i < size; i++)
{
inDeg[i] = 0;
}
for (int i = 0; i < size; i++)
{
Node* node = adj[i];
while (node != nullptr)
{
inDeg[node->getId()]++;//★
node = node->getLink();//다음 노드로 넘어가기
}
}
for (int i = 0; i < size; i++)
{
if (inDeg[i] == 0) { q.enqueue(i); }
}
while (q.isEmpty() == false)
{
int w = q.dequeue();
std::cout << getVertex(w) << " ";
Node* node = adj[w];
while (node != nullptr)
{
int u = node->getId();
inDeg[u]--;//★위 별표와 비교해보면 위는 큐에 데이터넣는거고 이건 빼오는거고
if (inDeg[u] == 0)
{
q.enqueue(u);
}
node = node->getLink();//다음 노드로 넘어가기
}
}
std::cout << "\n";
delete[] inDeg;//★★
}
};/*
int main()
{
ToposortGraph g;
for (int i = 0; i < 6; i++)
{
g.insertVertex(std::string(1, 'A' + i));//'A'+1 아스키코드로 바꾸서 다시 'B' 처럼
}
g.insertDirEdge(0, 2);
g.insertDirEdge(0, 3);
g.insertDirEdge(1, 3);
g.insertDirEdge(1, 4);
g.insertDirEdge(2, 3);
g.insertDirEdge(2, 5);
g.insertDirEdge(3, 5);
g.insertDirEdge(4, 5);
std::cout << " 위상정렬 수행:";
g.TopoSort();
return 0;
}*/ | [
"62214428+skarltjr@users.noreply.github.com"
] | 62214428+skarltjr@users.noreply.github.com |
a3962bb7f37c950ae8009d526b3a258cb2ce86db | b3518cceb94927fa3a5d15cd9a2e887defe0cdb7 | /src/applications/appl_utility.h | c8705edf659b7ee751af73b56be47290c717d37b | [] | no_license | koichiHik/blog_bundle_adjust | b3921fd5b546c0ccc161d02407b0270d9826c79d | 8c05aabfba141ee82f14681bb26e6594cae63e03 | refs/heads/main | 2023-05-12T08:59:56.700168 | 2021-05-21T10:50:20 | 2021-05-21T10:50:20 | 363,568,665 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,151 | h |
// STL
#include <vector>
// Boost
#include <boost/filesystem.hpp>
// Eigen
#include <Eigen/Dense>
#include <Eigen/Geometry>
// Google
#include <gflags/gflags.h>
#include <glog/logging.h>
// Original
#include <common_def.h>
#include <error_metric.h>
#include <file_utility.h>
#include <optimizations.h>
namespace optimization {
struct SfmData {
std::vector<Camera> extrinsic_cams;
std::map<size_t, size_t> extrinsic_intrinsic_map;
std::vector<Eigen::Matrix3d> intrinsic_cams;
std::vector<Eigen::Vector3d> points3d;
std::vector<Track> tracks;
};
inline void AddRandomNoiseToTrack(const std::vector<Track>& tracks, double mean,
double stddev,
std::vector<Track>& noised_tracks) {
std::default_random_engine engine(0);
std::normal_distribution<> dist(mean, stddev);
noised_tracks = tracks;
for (size_t idx = 0; idx < noised_tracks.size(); idx++) {
Track& noised_track = noised_tracks[idx];
for (Track::iterator itr = noised_track.begin(); itr != noised_track.end();
itr++) {
itr->second(0) += dist(engine);
itr->second(1) += dist(engine);
}
}
}
inline void AddRandomNoiseToPoints3d(
const std::vector<Eigen::Vector3d>& points3d, double mean, double stddev,
std::vector<Eigen::Vector3d>& noised_points3d) {
std::default_random_engine engine(0);
std::normal_distribution<> dist(mean, stddev);
noised_points3d = points3d;
for (size_t idx = 0; idx < noised_points3d.size(); idx++) {
noised_points3d[idx](0) += dist(engine);
noised_points3d[idx](1) += dist(engine);
noised_points3d[idx](2) += dist(engine);
}
}
inline void AddRandomNoiseToExtrinsic(const std::vector<Camera>& extrinsics,
double mean_trans, double stddev_trans,
double mean_angles, double stddev_angles,
std::vector<Camera>& noised_extrinsics) {
std::default_random_engine engine(0);
std::normal_distribution<> dists(mean_trans, stddev_trans);
std::normal_distribution<> angles(mean_angles, stddev_angles);
for (const Camera& extrinsic : extrinsics) {
Eigen::Matrix3d R_noised;
Eigen::Vector3d T_noised;
Eigen::Vector3d euler = extrinsic.block<3, 3>(0, 0).eulerAngles(0, 1, 2);
R_noised =
Eigen::AngleAxisd(euler(0) + angles(engine), Eigen::Vector3d::UnitX()) *
Eigen::AngleAxisd(euler(1) + angles(engine), Eigen::Vector3d::UnitY()) *
Eigen::AngleAxisd(euler(2) + angles(engine), Eigen::Vector3d::UnitZ());
T_noised(0) = extrinsic.block<3, 1>(0, 3)(0) + dists(engine);
T_noised(1) = extrinsic.block<3, 1>(0, 3)(1) + dists(engine);
T_noised(2) = extrinsic.block<3, 1>(0, 3)(2) + dists(engine);
Camera noised_cam;
noised_cam.block<3, 3>(0, 0) = R_noised;
noised_cam.block<3, 1>(0, 3) = T_noised;
noised_extrinsics.push_back(noised_cam);
}
}
inline void AddRandomNoiseToIntrinsic(
const std::vector<Eigen::Matrix3d>& intrinsics, double mean_fx,
double stddev_fx, double mean_fy, double stddev_fy, double mean_cx,
double stddev_cx, double mean_cy, double stddev_cy, double mean_skew,
double stddev_skew, std::vector<Eigen::Matrix3d>& noised_intrinsics) {
std::default_random_engine engine(0);
std::normal_distribution<> dist_fx(mean_fx, stddev_fx);
std::normal_distribution<> dist_fy(mean_fy, stddev_fy);
std::normal_distribution<> dist_cx(mean_cx, stddev_cx);
std::normal_distribution<> dist_cy(mean_cy, stddev_cy);
std::normal_distribution<> dist_skew(mean_skew, stddev_skew);
for (const Eigen::Matrix3d& K : intrinsics) {
Eigen::Matrix3d K_ = K;
K_(0, 0) += dist_fx(engine);
K_(1, 1) += dist_fy(engine);
K_(0, 2) += dist_cx(engine);
K_(1, 2) += dist_cy(engine);
K_(0, 1) += dist_skew(engine);
noised_intrinsics.push_back(K_);
}
}
inline void LoadData(const std::string& extrinsic_filepath,
const std::string& intrinsic_filepath,
const std::string& image_location_filepath,
const std::string& points_location_filepath,
SfmData& org_data) {
// X. Load extrinsics.
utility::LoadCameraExtrinsicMatrix(extrinsic_filepath,
org_data.extrinsic_cams);
// X. Load intrinsics
utility::LoadCameraIntrinsicMatrix(intrinsic_filepath,
org_data.extrinsic_intrinsic_map,
org_data.intrinsic_cams);
// X. Load tracks.
utility::LoadTracks(image_location_filepath, org_data.extrinsic_cams.size(),
org_data.tracks);
// X. Load points 3d.
utility::LoadPoints3D(points_location_filepath, org_data.points3d);
// X. Create reprojection error of original and noised.
LOG(INFO) << "Reprojection Error (Original Data) : "
<< optimization::ComputeReprojectionError(
org_data.tracks, org_data.intrinsic_cams,
org_data.extrinsic_intrinsic_map, org_data.extrinsic_cams,
org_data.points3d);
}
inline void SaveData(const std::string& result_directory,
const std::string& file_prefix, const SfmData& data) {
boost::filesystem::path dir_path(result_directory);
std::map<size_t, std::vector<size_t>> cam_indices_map;
for (size_t idx = 0; idx < data.extrinsic_cams.size(); idx++) {
const Camera& cam = data.extrinsic_cams[idx];
utility::WriteCameraExtrinsicMatrix(
dir_path.append(file_prefix + "_camera_extrinsics.txt")
.generic_string(),
cam.block<3, 3>(0, 0), cam.block<3, 1>(0, 3), false);
cam_indices_map[data.extrinsic_intrinsic_map.at(idx)].push_back(idx);
}
for (size_t idx = 0; idx < data.intrinsic_cams.size(); idx++) {
utility::WriteCameraIntrinsicMatrix(
dir_path.append(file_prefix + "_camera_intrinsics.txt")
.generic_string(),
cam_indices_map[idx], data.intrinsic_cams[idx], false);
}
std::vector<std::vector<Eigen::Vector2d>> image_points;
for (const Track& track : data.tracks) {
std::vector<Eigen::Vector2d> points;
for (Track::const_iterator citr = track.cbegin(); citr != track.cend();
citr++) {
points.push_back(citr->second);
}
image_points.push_back(points);
}
utility::WritePoints2D(
dir_path.append(file_prefix + "_image_points2d.txt").generic_string(),
image_points);
utility::WritePoints3D(
dir_path.append(file_prefix + "_refined_points3d.txt").generic_string(),
data.points3d);
}
inline void AddNoise(const SfmData& org_data, SfmData& noised_data) {
// X. Load extrinsics.
optimization::AddRandomNoiseToExtrinsic(
org_data.extrinsic_cams, 0.0, 0.1, 0.0, 0.05, noised_data.extrinsic_cams);
// optimization::AddRandomNoiseToExtrinsic(org_data.extrinsic_cams, 0.0, 0.0,
// 0.0, 0.0,
// noised_data.extrinsic_cams);
// X. Load intrinsics
/*
optimization::AddRandomNoiseToIntrinsic(org_data.intrinsic_cams, 0.0, 5.0,
0.0, 5.0, 0.0, 5.0, 0.0, 5.0, 0.0, 0.0, noised_data.intrinsic_cams);
*/
optimization::AddRandomNoiseToIntrinsic(org_data.intrinsic_cams, 0.0, 5.0,
0.0, 5.0, 0.0, 5.0, 0.0, 5.0, 0.0,
0.0, noised_data.intrinsic_cams);
noised_data.extrinsic_intrinsic_map = org_data.extrinsic_intrinsic_map;
// X. Load tracks.
AddRandomNoiseToTrack(org_data.tracks, 0.0, 0.0, noised_data.tracks);
// X. Load points 3d.
AddRandomNoiseToPoints3d(org_data.points3d, 0.0, 0.1, noised_data.points3d);
// AddRandomNoiseToPoints3d(org_data.points3d, 0.0, 0.0,
// noised_data.points3d);
// X. Create reprojection error of original and noised.
LOG(INFO) << "Reprojection Error (Noised Data) : "
<< optimization::ComputeReprojectionError(
noised_data.tracks, noised_data.intrinsic_cams,
noised_data.extrinsic_intrinsic_map,
noised_data.extrinsic_cams, noised_data.points3d);
}
inline void NormalizeParameters(SfmData& data, double& image_coord_scale,
double& euclid_coord_scale) {
// X. Scaling for pixel unit.
{
double max_internal_p = 0;
for (const Eigen::Matrix3d& K : data.intrinsic_cams) {
max_internal_p = std::max(max_internal_p, K(0, 0));
max_internal_p = std::max(max_internal_p, K(1, 1));
max_internal_p = std::max(max_internal_p, K(0, 2));
max_internal_p = std::max(max_internal_p, K(1, 2));
}
image_coord_scale = 1.0 / max_internal_p;
}
{
for (Eigen::Matrix3d& K : data.intrinsic_cams) {
K(0, 0) = K(0, 0) * image_coord_scale;
K(1, 1) = K(1, 1) * image_coord_scale;
K(0, 2) = K(0, 2) * image_coord_scale;
K(1, 2) = K(1, 2) * image_coord_scale;
}
for (Track& track : data.tracks) {
for (Track::iterator itr = track.begin(); itr != track.end(); itr++) {
itr->second(0) = itr->second(0) * image_coord_scale;
itr->second(1) = itr->second(1) * image_coord_scale;
}
}
}
// X. Scaling for euclid coordinate.
{
double max_coord = 0;
for (const Eigen::Vector3d& p : data.points3d) {
max_coord = std::max(std::abs(p(0)), max_coord);
max_coord = std::max(std::abs(p(1)), max_coord);
max_coord = std::max(std::abs(p(2)), max_coord);
}
for (const Camera cam : data.extrinsic_cams) {
max_coord = std::max(std::abs(cam(0, 3)), max_coord);
max_coord = std::max(std::abs(cam(1, 3)), max_coord);
max_coord = std::max(std::abs(cam(2, 3)), max_coord);
}
euclid_coord_scale = 1.0 / max_coord;
for (Eigen::Vector3d& p : data.points3d) {
p(0) = p(0) * euclid_coord_scale;
p(1) = p(1) * euclid_coord_scale;
p(2) = p(2) * euclid_coord_scale;
}
for (Camera& cam : data.extrinsic_cams) {
cam(0, 3) = cam(0, 3) * euclid_coord_scale;
cam(1, 3) = cam(1, 3) * euclid_coord_scale;
cam(2, 3) = cam(2, 3) * euclid_coord_scale;
}
}
}
inline void RenormalizeParameters(double image_scale, double euclid_scale,
SfmData& data) {
{
for (Eigen::Matrix3d& K : data.intrinsic_cams) {
K(0, 0) = K(0, 0) / image_scale;
K(1, 1) = K(1, 1) / image_scale;
K(0, 2) = K(0, 2) / image_scale;
K(1, 2) = K(1, 2) / image_scale;
}
for (Track& track : data.tracks) {
for (Track::iterator itr = track.begin(); itr != track.end(); itr++) {
itr->second(0) = itr->second(0) / image_scale;
itr->second(1) = itr->second(1) / image_scale;
}
}
}
for (Eigen::Vector3d& p : data.points3d) {
p(0) = p(0) / euclid_scale;
p(1) = p(1) / euclid_scale;
p(2) = p(2) / euclid_scale;
}
for (Camera& cam : data.extrinsic_cams) {
cam(0, 3) = cam(0, 3) / euclid_scale;
cam(1, 3) = cam(1, 3) / euclid_scale;
cam(2, 3) = cam(2, 3) / euclid_scale;
}
}
} // namespace optimization | [
"rkoichi2001@gmail.com"
] | rkoichi2001@gmail.com |
ab3cca22aafd1921d6013638d6cdc45038bdb333 | 648faac19a60118ff1021be69ed4ce08d95356cf | /EVA1/bead3/JPSMA3/amobadataaccess.cpp | bb55f4d2b0b4e4c2fbfc8c52723ef18db899895a | [] | no_license | BenJoey/felev4 | 29324954dd2691be1b27b96a86741edd791a65db | 389240edf4a81f532f9a2a09ef68c658e3cb4d42 | refs/heads/master | 2020-03-08T19:35:35.623191 | 2018-06-23T10:28:29 | 2018-06-23T10:28:29 | 128,358,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,411 | cpp | #include "amobadataaccess.h"
#include <QDateTime>
#include <QFileInfo>
#include <QFile>
#include <QTextStream>
QVector<QString> amobadataaccess::saveGameList() const
{
QVector<QString> result(5);
for (int i = 0; i < 5; i++)
{
if (QFile::exists("game" + QString::number(i) + ".sav"))
{
QFileInfo info("game"+ QString::number(i) + ".sav");
result[i] = "[" + QString::number(i + 1) + "] " + info.lastModified().toString("yyyy.MM.dd HH:mm:ss");
}
}
return result;
}
bool amobadataaccess::loadGame(int gameIndex, QVector<int> &saveGameData)
{
QFile file("game" + QString::number(gameIndex) + ".sav");
if (!file.open(QFile::ReadOnly))return false;
QTextStream stream(&file);
saveGameData.push_back(stream.readLine().toInt());
saveGameData.push_back(stream.readLine().toInt());
int meret = saveGameData[0]*saveGameData[1]+3;
for (int i = 2; i < meret; i++)
saveGameData.push_back(stream.readLine().toInt());
file.close();
return true;
}
bool amobadataaccess::saveGame(int gameIndex, const QVector<int> &saveGameData)
{
QFile file("game" + QString::number(gameIndex) + ".sav");
if (!file.open(QFile::WriteOnly))return false;
QTextStream stream(&file);
for (int i = 0; i < saveGameData.size(); i++)
stream << saveGameData[i] << endl;
file.close();
return true;
}
| [
"32818693+BenJoey@users.noreply.github.com"
] | 32818693+BenJoey@users.noreply.github.com |
e34ecf47a340300c05a47c3048d016e1d7be65f2 | 2114c5e7a2d3ce4e2cb30bbec65a2e7e11134140 | /lib/csgo/offsets.h | b6dec6b07f49055c4fa0951870ecb611912adac7 | [] | no_license | kurisufriend/clarketech | 3172a9cebe937d930bf6ab09ed67ee33d232d27c | efe73710c29f7760107dc5912819ea21f48e114a | refs/heads/master | 2023-06-30T09:41:52.261668 | 2021-08-09T02:14:31 | 2021-08-09T02:14:31 | 394,119,474 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,226 | h | #pragma once
#pragma once
#include <cstddef>
// 2021-06-02 00:51:49.386962600 UTC
namespace hazedumper {
namespace netvars {
constexpr ::std::ptrdiff_t cs_gamerules_data = 0x0;
constexpr ::std::ptrdiff_t m_ArmorValue = 0xB37C;
constexpr ::std::ptrdiff_t m_Collision = 0x320;
constexpr ::std::ptrdiff_t m_CollisionGroup = 0x474;
constexpr ::std::ptrdiff_t m_Local = 0x2FBC;
constexpr ::std::ptrdiff_t m_MoveType = 0x25C;
constexpr ::std::ptrdiff_t m_OriginalOwnerXuidHigh = 0x31C4;
constexpr ::std::ptrdiff_t m_OriginalOwnerXuidLow = 0x31C0;
constexpr ::std::ptrdiff_t m_SurvivalGameRuleDecisionTypes = 0x1328;
constexpr ::std::ptrdiff_t m_SurvivalRules = 0xD00;
constexpr ::std::ptrdiff_t m_aimPunchAngle = 0x302C;
constexpr ::std::ptrdiff_t m_aimPunchAngleVel = 0x3038;
constexpr ::std::ptrdiff_t m_angEyeAnglesX = 0xB380;
constexpr ::std::ptrdiff_t m_angEyeAnglesY = 0xB384;
constexpr ::std::ptrdiff_t m_bBombPlanted = 0x9A5;
constexpr ::std::ptrdiff_t m_bFreezePeriod = 0x20;
constexpr ::std::ptrdiff_t m_bGunGameImmunity = 0x3944;
constexpr ::std::ptrdiff_t m_bHasDefuser = 0xB38C;
constexpr ::std::ptrdiff_t m_bHasHelmet = 0xB370;
constexpr ::std::ptrdiff_t m_bInReload = 0x32A5;
constexpr ::std::ptrdiff_t m_bIsDefusing = 0x3930;
constexpr ::std::ptrdiff_t m_bIsQueuedMatchmaking = 0x74;
constexpr ::std::ptrdiff_t m_bIsScoped = 0x3928;
constexpr ::std::ptrdiff_t m_bIsValveDS = 0x7C;
constexpr ::std::ptrdiff_t m_bSpotted = 0x93D;
constexpr ::std::ptrdiff_t m_bSpottedByMask = 0x980;
constexpr ::std::ptrdiff_t m_bStartedArming = 0x33F0;
constexpr ::std::ptrdiff_t m_bUseCustomAutoExposureMax = 0x9D9;
constexpr ::std::ptrdiff_t m_bUseCustomAutoExposureMin = 0x9D8;
constexpr ::std::ptrdiff_t m_bUseCustomBloomScale = 0x9DA;
constexpr ::std::ptrdiff_t m_clrRender = 0x70;
constexpr ::std::ptrdiff_t m_dwBoneMatrix = 0x26A8;
constexpr ::std::ptrdiff_t m_fAccuracyPenalty = 0x3330;
constexpr ::std::ptrdiff_t m_fFlags = 0x104;
constexpr ::std::ptrdiff_t m_flC4Blow = 0x2990;
constexpr ::std::ptrdiff_t m_flCustomAutoExposureMax = 0x9E0;
constexpr ::std::ptrdiff_t m_flCustomAutoExposureMin = 0x9DC;
constexpr ::std::ptrdiff_t m_flCustomBloomScale = 0x9E4;
constexpr ::std::ptrdiff_t m_flDefuseCountDown = 0x29AC;
constexpr ::std::ptrdiff_t m_flDefuseLength = 0x29A8;
constexpr ::std::ptrdiff_t m_flFallbackWear = 0x31D0;
constexpr ::std::ptrdiff_t m_flFlashDuration = 0xA420;
constexpr ::std::ptrdiff_t m_flFlashMaxAlpha = 0xA41C;
constexpr ::std::ptrdiff_t m_flLastBoneSetupTime = 0x2924;
constexpr ::std::ptrdiff_t m_flLowerBodyYawTarget = 0x3A90;
constexpr ::std::ptrdiff_t m_flNextAttack = 0x2D70;
constexpr ::std::ptrdiff_t m_flNextPrimaryAttack = 0x3238;
constexpr ::std::ptrdiff_t m_flSimulationTime = 0x268;
constexpr ::std::ptrdiff_t m_flTimerLength = 0x2994;
constexpr ::std::ptrdiff_t m_hActiveWeapon = 0x2EF8;
constexpr ::std::ptrdiff_t m_hMyWeapons = 0x2DF8;
constexpr ::std::ptrdiff_t m_hObserverTarget = 0x338C;
constexpr ::std::ptrdiff_t m_hOwner = 0x29CC;
constexpr ::std::ptrdiff_t m_hOwnerEntity = 0x14C;
constexpr ::std::ptrdiff_t m_iAccountID = 0x2FC8;
constexpr ::std::ptrdiff_t m_iClip1 = 0x3264;
constexpr ::std::ptrdiff_t m_iCompetitiveRanking = 0x1A84;
constexpr ::std::ptrdiff_t m_iCompetitiveWins = 0x1B88;
constexpr ::std::ptrdiff_t m_iCrosshairId = 0xB3E8;
constexpr ::std::ptrdiff_t m_iEntityQuality = 0x2FAC;
constexpr ::std::ptrdiff_t m_iFOV = 0x31E4;
constexpr ::std::ptrdiff_t m_iFOVStart = 0x31E8;
constexpr ::std::ptrdiff_t m_iGlowIndex = 0xA438;
constexpr ::std::ptrdiff_t m_iHealth = 0x100;
constexpr ::std::ptrdiff_t m_iItemDefinitionIndex = 0x2FAA;
constexpr ::std::ptrdiff_t m_iItemIDHigh = 0x2FC0;
constexpr ::std::ptrdiff_t m_iMostRecentModelBoneCounter = 0x2690;
constexpr ::std::ptrdiff_t m_iObserverMode = 0x3378;
constexpr ::std::ptrdiff_t m_iShotsFired = 0xA390;
constexpr ::std::ptrdiff_t m_iState = 0x3258;
constexpr ::std::ptrdiff_t m_iTeamNum = 0xF4;
constexpr ::std::ptrdiff_t m_lifeState = 0x25F;
constexpr ::std::ptrdiff_t m_nFallbackPaintKit = 0x31C8;
constexpr ::std::ptrdiff_t m_nFallbackSeed = 0x31CC;
constexpr ::std::ptrdiff_t m_nFallbackStatTrak = 0x31D4;
constexpr ::std::ptrdiff_t m_nForceBone = 0x268C;
constexpr ::std::ptrdiff_t m_nTickBase = 0x3430;
constexpr ::std::ptrdiff_t m_rgflCoordinateFrame = 0x444;
constexpr ::std::ptrdiff_t m_szCustomName = 0x303C;
constexpr ::std::ptrdiff_t m_szLastPlaceName = 0x35B4;
constexpr ::std::ptrdiff_t m_thirdPersonViewAngles = 0x31D8;
constexpr ::std::ptrdiff_t m_vecOrigin = 0x138;
constexpr ::std::ptrdiff_t m_vecVelocity = 0x114;
constexpr ::std::ptrdiff_t m_vecViewOffset = 0x108;
constexpr ::std::ptrdiff_t m_viewPunchAngle = 0x3020;
} // namespace netvars
namespace signatures {
constexpr ::std::ptrdiff_t anim_overlays = 0x2980;
constexpr ::std::ptrdiff_t clientstate_choked_commands = 0x4D30;
constexpr ::std::ptrdiff_t clientstate_delta_ticks = 0x174;
constexpr ::std::ptrdiff_t clientstate_last_outgoing_command = 0x4D2C;
constexpr ::std::ptrdiff_t clientstate_net_channel = 0x9C;
constexpr ::std::ptrdiff_t convar_name_hash_table = 0x2F0F8;
constexpr ::std::ptrdiff_t dwClientState = 0x588FE4;
constexpr ::std::ptrdiff_t dwClientState_GetLocalPlayer = 0x180;
constexpr ::std::ptrdiff_t dwClientState_IsHLTV = 0x4D48;
constexpr ::std::ptrdiff_t dwClientState_Map = 0x28C;
constexpr ::std::ptrdiff_t dwClientState_MapDirectory = 0x188;
constexpr ::std::ptrdiff_t dwClientState_MaxPlayer = 0x388;
constexpr ::std::ptrdiff_t dwClientState_PlayerInfo = 0x52C0;
constexpr ::std::ptrdiff_t dwClientState_State = 0x108;
constexpr ::std::ptrdiff_t dwClientState_ViewAngles = 0x4D90;
constexpr ::std::ptrdiff_t dwEntityList = 0x4DA20DC;
constexpr ::std::ptrdiff_t dwForceAttack = 0x31D2628;
constexpr ::std::ptrdiff_t dwForceAttack2 = 0x31D2634;
constexpr ::std::ptrdiff_t dwForceBackward = 0x31D267C;
constexpr ::std::ptrdiff_t dwForceForward = 0x31D2658;
constexpr ::std::ptrdiff_t dwForceJump = 0x524BECC;
constexpr ::std::ptrdiff_t dwForceLeft = 0x31D2670;
constexpr ::std::ptrdiff_t dwForceRight = 0x31D2694;
constexpr ::std::ptrdiff_t dwGameDir = 0x627780;
constexpr ::std::ptrdiff_t dwGameRulesProxy = 0x52BF1BC;
constexpr ::std::ptrdiff_t dwGetAllClasses = 0xDB0F6C;
constexpr ::std::ptrdiff_t dwGlobalVars = 0x588CE8;
constexpr ::std::ptrdiff_t dwGlowObjectManager = 0x52EA570;
constexpr ::std::ptrdiff_t dwInput = 0x51F36A0;
constexpr ::std::ptrdiff_t dwInterfaceLinkList = 0x944D14;
constexpr ::std::ptrdiff_t dwLocalPlayer = 0xD892CC;
constexpr ::std::ptrdiff_t dwMouseEnable = 0xD8EE18;
constexpr ::std::ptrdiff_t dwMouseEnablePtr = 0xD8EDE8;
constexpr ::std::ptrdiff_t dwPlayerResource = 0x31D0990;
constexpr ::std::ptrdiff_t dwRadarBase = 0x51D6E54;
constexpr ::std::ptrdiff_t dwSensitivity = 0xD8ECB4;
constexpr ::std::ptrdiff_t dwSensitivityPtr = 0xD8EC88;
constexpr ::std::ptrdiff_t dwSetClanTag = 0x8A1B0;
constexpr ::std::ptrdiff_t dwViewMatrix = 0x4D939F4;
constexpr ::std::ptrdiff_t dwWeaponTable = 0x51F4160;
constexpr ::std::ptrdiff_t dwWeaponTableIndex = 0x325C;
constexpr ::std::ptrdiff_t dwYawPtr = 0xD8EA78;
constexpr ::std::ptrdiff_t dwZoomSensitivityRatioPtr = 0xD93D18;
constexpr ::std::ptrdiff_t dwbSendPackets = 0xD76DA;
constexpr ::std::ptrdiff_t dwppDirect3DDevice9 = 0xA7050;
constexpr ::std::ptrdiff_t find_hud_element = 0x2DDDF980;
constexpr ::std::ptrdiff_t force_update_spectator_glow = 0x3AFD6A;
constexpr ::std::ptrdiff_t interface_engine_cvar = 0x3E9EC;
constexpr ::std::ptrdiff_t is_c4_owner = 0x3BC9C0;
constexpr ::std::ptrdiff_t m_bDormant = 0xED;
constexpr ::std::ptrdiff_t m_flSpawnTime = 0xA370;
constexpr ::std::ptrdiff_t m_pStudioHdr = 0x294C;
constexpr ::std::ptrdiff_t m_pitchClassPtr = 0x51D70F0;
constexpr ::std::ptrdiff_t m_yawClassPtr = 0xD8EA78;
constexpr ::std::ptrdiff_t model_ambient_min = 0x58C05C;
constexpr ::std::ptrdiff_t set_abs_angles = 0x1E0B80;
constexpr ::std::ptrdiff_t set_abs_origin = 0x1E09C0;
} // namespace signatures
} // namespace hazedumper
| [
"buffer@sidekek.ml"
] | buffer@sidekek.ml |
a4a1837feb45fc3a9ebbb2c6b61da7cc5924830c | 38c833575af2f7731379fe145ba9ca82c4232e73 | /Volume1(PCK)/aoj0141_SpiralPattern.cpp | f7c8d50e40b0b52e5bbd8ea0afb7fdc12df1c8d0 | [] | no_license | xuelei7/AOJ | b962fad9e814274b4c24ae1e891b37cae5c143f2 | 81f565ab8b3967a5db838e09f70154bb7a8af507 | refs/heads/main | 2023-08-26T08:39:46.392711 | 2021-11-10T14:27:04 | 2021-11-10T14:27:04 | 426,647,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,409 | cpp | // ぐるぐる模様
// 「ぐるぐる模様」を表示するプログラムを作成することにしました。「ぐるぐる模様」は以下のようなものとします。
// 1 辺の長さが n の場合、n 行 n 列の文字列として表示する。
// 左下隅を基点とし,時計回りに回転する渦状の模様とする。
// 線のある部分は #(半角シャープ)、空白部分は " "(半角空白)で表現する。
// 線と線の間は空白を置く。
// 整数 n を入力とし,1 辺の長さが n の「ぐるぐる模様」を出力するプログラムを作成してください。
// Input
// 入力は以下の形式で与えられます。
// d
// n1
// n2
// :
// nd
// 1行目にデータセットの数 d (d ≤ 20)、続く d 行に i 個目のぐるぐる模様の辺の長さ ni (1 ≤ ni ≤ 100) がそれぞれ1行に与えられます。
// Output
// データセットごとに、ぐるぐる模様を出力してください。データセットの間に1行の空行を入れてください。
#include <bits/stdc++.h>
using namespace std;
int dh[4] = {-1,0,1,0};
int dw[4] = {0,1,0,-1};
bool a[110][110];
void draw (int h, int w, int d) {
if (d == 1) {
a[h][w] = 1;
} else if (d == 2) {
a[h][w] = 1;
a[h-1][w] = 1;
a[h-1][w+1] = 1;
} else if (d == 3) {
for (int i = 0; i < 3; i++) {
a[h-i][w] = 1;
a[h-2][w+i] = 1;
a[h-i][w+2] = 1;
}
} else {
for (int i = 0; i < d; i++) {
a[h-i][w] = 1;
a[h-d+1][w+i] = 1;
a[h-i][w+d-1] = 1;
a[h][w+i] = 1;
}
a[h][w+1] = 0;
if (d != 4) {
a[h-1][w+2] = 1;
}
}
}
void solve(){
int n;
cin >> n;
for (int i = 0; i < n; i++) memset(a[i],0,sizeof(a[i]));
int h = n-1, w = 0, d = n;
while (d > 0) {
draw(h,w,d);
h -= 2;
w += 2;
d -= 4;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << (a[i][j]?'#':' ');
}
cout << endl;
}
}
int main() {
int n;
cin >> n;
bool bg = 1;
while (n--) {
if (!bg) cout << endl;
bg = 0;
solve();
}
return 0;
} | [
"yuxuelei52@hotmail.com"
] | yuxuelei52@hotmail.com |
06421f04ac835acc061e6d4171b9cf43bc40e9e6 | 5840c895988f9dd3edcbc3942fdc86f4ce6a4856 | /examples/LedController/Method.h | 4b450ec4c80d3bb239d1150facf946f5ac6c991b | [
"LicenseRef-scancode-other-permissive"
] | permissive | mateoconfeugo/Functor | 85cbe656dd4447800af3ee0bbd0dc4d83c7f0730 | 361029135af78a646465b4ebfdc029455cfc7ea0 | refs/heads/master | 2021-07-06T07:10:53.721347 | 2017-10-02T19:46:34 | 2017-10-02T19:46:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 444 | h | // ----------------------------------------------------------------------------
// Method.h
//
//
// Authors:
// Peter Polidoro polidorop@janelia.hhmi.org
// ----------------------------------------------------------------------------
#ifndef _METHOD_H_
#define _METHOD_H_
#include <Functor.h>
class Method
{
public:
Method();
void attachCallback(const Functor0 & callback);
void callback();
protected:
Functor0 callback_;
};
#endif
| [
"peterpolidoro@gmail.com"
] | peterpolidoro@gmail.com |
d1bd3359bb1ce9fd0618affe1d92d419f39f4344 | 2281cb9754250b212752fb7014eee2aeea250299 | /Codes/Main/NAANU_V7A/NAANU_V7A_current_A_IIT/algorithm.ino | f6e56ac5cad78366835081b913e0a7b5aed829b2 | [] | no_license | riderman10000/Micromouse | f051dc50b6cbb18905adede152618608d95e1b28 | 28cc2ed23521edf4d634f35c5982894b52f017e9 | refs/heads/master | 2022-06-28T01:32:57.132879 | 2020-05-12T15:07:55 | 2020-05-12T15:07:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,978 | ino | #pragma once
#include "Node.h"
Node node[16][16];
int X = 0, Y = 0;
Node testNode;
void printNode() {
Serial.println(testNode.nodeDetails());
}
void printPotential() {
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
Serial.print("Nodes : "); Serial.print(" X "); Serial.print(i); Serial.print(" ,Y : "); Serial.print(j); Serial.print(" :: "); Serial.println(node[i][j].value);
}
}
}
void updateDirection() {
myDirection = OppositeOf(myDirection);
}
void printDirection() {
Serial.println(myDirection);
}
void updatePosition() {
myDirection = (Direction)LeftOf(myDirection);
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
}
void printPosition() {
Serial.println(X);
Serial.println(Y);
}
void potential() {
uint8_t i, j;
for (i = 0; i < sizeX; i++) {
for (j = 0; j < sizeY; j++) {
node[i][j].value = 0;
}
}
for (j = 0; j < sizeY / 2; j++) {
for (i = 0; i < sizeX / 2; i++) {
node[i][j].value = 14 - i - j; //1st quadrat
}
}
for (j = 0; j < sizeY / 2; j++) {
for (i = sizeX / 2; i < sizeX; i++) {
node[i][j].value = i - j - 1; //2nd quadrant
}
}
for (j = sizeY / 2; j < sizeY; j++) {
for (i = 0; i < sizeX / 2; i++) {
node[i][j].value = j - i - 1; //4th quadrant
}
}
for (j = sizeY / 2; j < sizeY; j++) {
for (i = sizeX / 2; i < sizeX; i++) {
node[i][j].value = i + j - 16; //3rd quadrant
}
}
}
void wetRun()
{
Direction tmpLeft = (Direction)LeftOf(myDirection);
Direction tmpRight = (Direction)RightOf(myDirection);
if (!wallLeft() && (node[abs(X + RelativeX(tmpLeft))][abs(Y + RelativeY(tmpLeft))].map == 11))
{
turnLeft();
myDirection = tmpLeft;
Serial.println("Turn Left");
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
}
else if (!wallFront() && (node[abs(X + RelativeX(myDirection))][abs(Y + RelativeY(myDirection))].map == 44))
{
moveForward();
Serial.println("Moving Forward");
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
}
else if (!wallRight() && (node[abs(X + RelativeX(tmpRight))][abs(Y + RelativeY(tmpRight))].map == 22))
{
turnRight();
Serial.println("Turn Right");
myDirection = tmpRight;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
}
}
void returnNow()
{
Direction tmpLeft = (Direction)LeftOf(myDirection);
Direction tmpRight = (Direction)RightOf(myDirection);
if (!wallLeft() && (node[abs(X + RelativeX(tmpLeft))][abs(Y + RelativeY(tmpLeft))].map == 1))
{
// node[X][Y].map = 11;
// shortPath[path] = 'R';
eepromWrite(_RIGHT);
path++;
turnLeft();
myDirection = tmpLeft;
// Seria/l.println("Turn Left");
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
}
else if (!wallFront() && (node[abs(X + RelativeX(myDirection))][abs(Y + RelativeY(myDirection))].map == 1))
{
// node[X][Y].map = 44;
// shortPath[path] = 'F';
eepromWrite(_FORWARD);
path++;
moveForward();
// Serial.pr/intln("Moving Forward");
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
}
else if (!wallRight() && (node[abs(X + RelativeX(tmpRight))][abs(Y + RelativeY(tmpRight))].map == 1))
{
// node[X][Y].map = 22;
// shortPath[path] = 'L';
// eeprom.writeByte('L');
eepromWrite(_LEFT);
path++;
turnRight();
Serial.println("Turn Right");
myDirection = tmpRight;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
}
}
void TremauxAlgorithm() {
if ((abs(X) == 7 && abs(Y) == 7) || (abs(X) == 8 && abs(Y) == 8))
{
BUZZER_ON;
delay(200);
BUZZER_OFF;
delay(200);
BUZZER_ON;
delay(200);
BUZZER_OFF;
delay(200);
BUZZER_ON;
delay(200);
BUZZER_OFF;
myDirection = OppositeOf(myDirection);
turnRight();
turnRight();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
moveForward();
while (true)
{
returnNow();
if (abs(X) == 0 && abs(Y) == 0)
{
// eeprom.writeB/yte('Z');
FLASH_Unlock();
// FLASH_ProgramHalfWord(flagAddress, 555);/
FLASH_ProgramHalfWord(flagAddress, _END);
FLASH_Lock();
FLASH_Unlock();
FLASH_ProgramHalfWord(pathAddress, path);
FLASH_Lock();
break;
}
}
myDirection = OppositeOf(myDirection);
turnRight();
turnRight();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
moveForward();
// while (true) {
// wetRun();
// if (X >= 7 && X <= 8 && Y >= 7 && Y <= 8)
// {
// Serial.print("MAZE SOLVED");
// break;
// }
// }
while (1);
return;
}
//center
// if (node[7][7].map && node[7][8].map && node[8][7].map && node[8][8].map > 0)
// {
// Serial.print("EXPLORED");
//
// }
if (node[abs(X)][abs(Y)].nodeDetails() == 10) {
Direction tmp = (Direction)myDirection;
Direction tmpLeft = (Direction)LeftOf(myDirection);
Direction tmpRight = (Direction)RightOf(myDirection);
tmpRight = (Direction)RightOf(myDirection);
myDirection = tmp;
Serial.println("Dead End found");
node[abs(X)][abs(Y)].map = 2;
// myDirection = OppositeOf(myDirection);
myDirection = (Direction)RightOf(myDirection);
turnRight();
myDirection = (Direction)RightOf(myDirection);
turnRight();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
moveForward();
}
else if (node[abs(X)][abs(Y)].nodeDetails() == 3) {
Direction tmp = (Direction)myDirection;
Direction tmpLeft = (Direction)LeftOf(myDirection);
Direction tmpRight = (Direction)RightOf(myDirection);
tmpRight = (Direction)RightOf(myDirection);
myDirection = tmp;
Serial.println("PATH 3");
if ((2 * node[abs(X + RelativeX(tmpLeft))][abs(Y + RelativeY(tmpLeft))].value - (node[abs(X + RelativeX(myDirection))][abs(Y + RelativeY(myDirection))].value + node[abs(X + RelativeX(tmpRight))][abs(Y + RelativeY(tmpRight))].value)) < 0) {
Serial.println("turned Left");
node[abs(X)][abs(Y)].map = 1 ;
myDirection = tmpLeft;
turnLeft();
if (!wallFront()) moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
}
else if ((2 * node[abs(X + RelativeX(myDirection))][abs(Y + RelativeY(myDirection))].value - (node[abs(X + RelativeX(tmpRight))][abs(Y + RelativeY(tmpRight))].value + node[abs(X + RelativeX(tmpLeft))][abs(Y + RelativeY(tmpLeft))].value)) < 0) {
node[abs(X)][abs(Y)].map = 1 ;
if (!wallFront()) moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
}
else if ((2 * node[abs(X + RelativeX(tmpRight))][abs(Y + RelativeY(tmpRight))].value - (node[abs(X + RelativeX(myDirection))][abs(Y + RelativeY(myDirection))].value + node[abs(X + RelativeX(tmpLeft))][abs(Y + RelativeY(tmpLeft))].value)) < 0) {
Serial.println("turned Right");
node[abs(X)][abs(Y)].map = 1 ;
myDirection = tmpRight;
turnRight();
if (!wallFront()) moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
}
}
else if (node[abs(X)][abs(Y)].nodeDetails() == 2) {
Serial.println("PATH 2");
Direction tmp = (Direction)myDirection;
Direction tmpLeft = (Direction)LeftOf(myDirection);
Direction tmpRight = (Direction)RightOf(myDirection);
tmpRight = (Direction)RightOf(myDirection);
myDirection = tmp;
if (!wallLeft() && !wallRight())
{
//checking the weight of left and right
if (node[abs(X + RelativeX(tmpLeft))][abs(Y + RelativeY(tmpLeft))].value <= node[abs(X + RelativeX(tmpRight))][abs(Y + RelativeY(tmpRight))].value)
{
if (node[abs(X + RelativeX(tmpLeft))][abs(Y + RelativeY(tmpLeft))].map < 1 )
{
node[abs(X)][abs(Y)].map = 1;
turnLeft();
myDirection = tmpLeft;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
else
{
node[abs(X)][abs(Y)].map = 1;
turnRight();
myDirection = tmpRight;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
}
else
{
if (node[abs(X + RelativeX(tmpRight))][abs(Y + RelativeY(tmpRight))].map < 1 )
{
node[abs(X)][abs(Y)].map = 1;
turnRight();
myDirection = tmpRight;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
else
{
node[abs(X)][abs(Y)].map = 1;
turnLeft();
myDirection = tmpLeft;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
}
}
//for front and left
if (!wallFront() && !wallLeft())
{
if (node[abs(X + RelativeX(tmpLeft))][abs(Y + RelativeY(tmpLeft))].value <= node[abs(X + RelativeX(myDirection))][abs(Y + RelativeY(myDirection))].value)
{
if (node[abs(X + RelativeX(tmpLeft))][abs(Y + RelativeY(tmpLeft))].map < 1 )
{
node[abs(X)][abs(Y)].map = 1;
turnLeft();
myDirection = tmpLeft;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
else
{
node[abs(X)][abs(Y)].map = 1;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
}
else
{
if (node[abs(X + RelativeX(myDirection))][abs(Y + RelativeY(myDirection))].map < 1 )
{
node[abs(X)][abs(Y)].map = 1;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
else
{
node[abs(X)][abs(Y)].map = 1;
turnLeft();
myDirection = tmpLeft;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
}
}
//for front and right
if (!wallFront() && !wallRight())
{
if (node[abs(X + RelativeX(tmpRight))][abs(Y + RelativeY(tmpRight))].value <= node[abs(X + RelativeX(myDirection))][abs(Y + RelativeY(myDirection))].value)
{
if (node[abs(X + RelativeX(tmpRight))][abs(Y + RelativeY(tmpRight))].map < 1 )
{
node[abs(X)][abs(Y)].map = 1;
turnRight();
myDirection = tmpRight;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
else
{
node[abs(X)][abs(Y)].map = 1;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
}
else
{
if (node[abs(X + RelativeX(myDirection))][abs(Y + RelativeY(myDirection))].map < 1 )
{
node[abs(X)][abs(Y)].map = 1;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
else
{
node[abs(X)][abs(Y)].map = 1;
turnRight();
myDirection = tmpRight;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
}
}
}//end of node.details == 2
else //(node[X][Y].nodeDetails() == 1)
{
Direction tmp = (Direction)myDirection;
Direction tmpLeft = (Direction)LeftOf(myDirection);
Direction tmpRight = (Direction)RightOf(myDirection);
tmpRight = (Direction)RightOf(myDirection);
myDirection = tmp;
Serial.println("PATH 1");
if (!wallLeft() && node[abs(X + RelativeX(tmpLeft))][abs(Y + RelativeY(tmpLeft))].map < 2) {
node[abs(X)][abs(Y)].map += 1;
turnLeft();
myDirection = tmpLeft;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
else if (!wallRight() && node[abs(X + RelativeX(tmpRight))][abs(Y + RelativeY(tmpRight))].map < 2) {
node[abs(X)][abs(Y)].map += 1;
turnRight();
myDirection = tmpRight;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
else if (!wallFront() && node[abs(X + RelativeX(myDirection))][abs(Y + RelativeX(myDirection))].map < 2) {
Serial.println("moving Forward");
node[abs(X)][abs(Y)].map += 1 ;
moveForward();
X += RelativeX(myDirection);
Y += RelativeY(myDirection);
return;
}
}
}
| [
"rabin47nepal@gmail.com"
] | rabin47nepal@gmail.com |
b76a2af1725fbf1b03353cce16ec549bd562b92e | d3893a2ee04e4752cecbc873b369a8fa7113b70d | /third_party/skia_m63/src/sksl/SkSLHCodeGenerator.cpp | a4a5c9a6ace22f7f547aa492aa52c08a2b8cf4c8 | [
"MIT",
"BSD-3-Clause"
] | permissive | kniefliu/WindowsSamples | e849137467acdfe5351e8fdd31945c37203be3c5 | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | refs/heads/master | 2021-01-09T10:25:49.744308 | 2020-08-12T12:37:05 | 2020-08-12T12:37:05 | 242,264,984 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,319 | cpp | /*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkSLHCodeGenerator.h"
#include "SkSLUtil.h"
#include "ir/SkSLFunctionDeclaration.h"
#include "ir/SkSLFunctionDefinition.h"
#include "ir/SkSLSection.h"
#include "ir/SkSLVarDeclarations.h"
namespace SkSL {
HCodeGenerator::HCodeGenerator(const Context* context, const Program* program,
ErrorReporter* errors, String name, OutputStream* out)
: INHERITED(program, errors, out)
, fContext(*context)
, fName(std::move(name))
, fFullName(String::printf("Gr%s", fName.c_str()))
, fSectionAndParameterHelper(*program, *errors) {}
String HCodeGenerator::ParameterType(const Context& context, const Type& type) {
if (type == *context.fFloat_Type || type == *context.fHalf_Type) {
return "float";
} else if (type == *context.fFloat2_Type || type == *context.fHalf2_Type) {
return "SkPoint";
} else if (type == *context.fInt4_Type || type == *context.fShort4_Type) {
return "SkIRect";
} else if (type == *context.fFloat4_Type || type == *context.fHalf4_Type) {
return "SkRect";
} else if (type == *context.fFloat4x4_Type || type == *context.fHalf4x4_Type) {
return "SkMatrix44";
} else if (type.kind() == Type::kSampler_Kind) {
return "sk_sp<GrTextureProxy>";
} else if (type == *context.fColorSpaceXform_Type) {
return "sk_sp<GrColorSpaceXform>";
} else if (type == *context.fFragmentProcessor_Type) {
return "std::unique_ptr<GrFragmentProcessor>";
}
return type.name();
}
String HCodeGenerator::FieldType(const Context& context, const Type& type) {
if (type.kind() == Type::kSampler_Kind) {
return "TextureSampler";
} else if (type == *context.fFragmentProcessor_Type) {
// we don't store fragment processors in fields, they get registered via
// registerChildProcessor instead
ASSERT(false);
return "<error>";
}
return ParameterType(context, type);
}
void HCodeGenerator::writef(const char* s, va_list va) {
static constexpr int BUFFER_SIZE = 1024;
va_list copy;
va_copy(copy, va);
char buffer[BUFFER_SIZE];
int length = vsnprintf(buffer, BUFFER_SIZE, s, va);
if (length < BUFFER_SIZE) {
fOut->write(buffer, length);
} else {
std::unique_ptr<char[]> heap(new char[length + 1]);
vsprintf(heap.get(), s, copy);
fOut->write(heap.get(), length);
}
}
void HCodeGenerator::writef(const char* s, ...) {
va_list va;
va_start(va, s);
this->writef(s, va);
va_end(va);
}
bool HCodeGenerator::writeSection(const char* name, const char* prefix) {
const Section* s = fSectionAndParameterHelper.getSection(name);
if (s) {
this->writef("%s%s", prefix, s->fText.c_str());
return true;
}
return false;
}
void HCodeGenerator::writeExtraConstructorParams(const char* separator) {
// super-simple parse, just assume the last token before a comma is the name of a parameter
// (which is true as long as there are no multi-parameter template types involved). Will replace
// this with something more robust if the need arises.
const Section* section = fSectionAndParameterHelper.getSection(CONSTRUCTOR_PARAMS_SECTION);
if (section) {
const char* s = section->fText.c_str();
#define BUFFER_SIZE 64
char lastIdentifier[BUFFER_SIZE];
int lastIdentifierLength = 0;
bool foundBreak = false;
while (*s) {
char c = *s;
++s;
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
c == '_') {
if (foundBreak) {
lastIdentifierLength = 0;
foundBreak = false;
}
ASSERT(lastIdentifierLength < BUFFER_SIZE);
lastIdentifier[lastIdentifierLength] = c;
++lastIdentifierLength;
} else {
foundBreak = true;
if (c == ',') {
ASSERT(lastIdentifierLength < BUFFER_SIZE);
lastIdentifier[lastIdentifierLength] = 0;
this->writef("%s%s", separator, lastIdentifier);
separator = ", ";
} else if (c != ' ' && c != '\t' && c != '\n' && c != '\r') {
lastIdentifierLength = 0;
}
}
}
if (lastIdentifierLength) {
ASSERT(lastIdentifierLength < BUFFER_SIZE);
lastIdentifier[lastIdentifierLength] = 0;
this->writef("%s%s", separator, lastIdentifier);
}
}
}
void HCodeGenerator::writeMake() {
const char* separator;
if (!this->writeSection(MAKE_SECTION)) {
this->writef(" static std::unique_ptr<GrFragmentProcessor> Make(");
separator = "";
for (const auto& param : fSectionAndParameterHelper.getParameters()) {
this->writef("%s%s %s", separator, ParameterType(fContext, param->fType).c_str(),
String(param->fName).c_str());
separator = ", ";
}
this->writeSection(CONSTRUCTOR_PARAMS_SECTION, separator);
this->writef(") {\n"
" return std::unique_ptr<GrFragmentProcessor>(new %s(",
fFullName.c_str());
separator = "";
for (const auto& param : fSectionAndParameterHelper.getParameters()) {
if (param->fType == *fContext.fFragmentProcessor_Type) {
this->writef("%s%s->clone()", separator, String(param->fName).c_str());
} else {
this->writef("%s%s", separator, String(param->fName).c_str());
}
separator = ", ";
}
this->writeExtraConstructorParams(separator);
this->writef("));\n"
" }\n");
}
}
void HCodeGenerator::failOnSection(const char* section, const char* msg) {
std::vector<const Section*> s = fSectionAndParameterHelper.getSections(section);
if (s.size()) {
fErrors.error(s[0]->fOffset, String("@") + section + " " + msg);
}
}
void HCodeGenerator::writeConstructor() {
if (this->writeSection(CONSTRUCTOR_SECTION)) {
const char* msg = "may not be present when constructor is overridden";
this->failOnSection(CONSTRUCTOR_CODE_SECTION, msg);
this->failOnSection(CONSTRUCTOR_PARAMS_SECTION, msg);
this->failOnSection(COORD_TRANSFORM_SECTION, msg);
this->failOnSection(INITIALIZERS_SECTION, msg);
this->failOnSection(OPTIMIZATION_FLAGS_SECTION, msg);
}
this->writef(" %s(", fFullName.c_str());
const char* separator = "";
for (const auto& param : fSectionAndParameterHelper.getParameters()) {
this->writef("%s%s %s", separator, ParameterType(fContext, param->fType).c_str(),
String(param->fName).c_str());
separator = ", ";
}
this->writeSection(CONSTRUCTOR_PARAMS_SECTION, separator);
this->writef(")\n"
" : INHERITED(k%s_ClassID", fFullName.c_str());
if (!this->writeSection(OPTIMIZATION_FLAGS_SECTION, ", (OptimizationFlags) ")) {
this->writef(", kNone_OptimizationFlags");
}
this->writef(")");
this->writeSection(INITIALIZERS_SECTION, "\n , ");
for (const auto& param : fSectionAndParameterHelper.getParameters()) {
String nameString(param->fName);
const char* name = nameString.c_str();
if (param->fType.kind() == Type::kSampler_Kind) {
this->writef("\n , %s(std::move(%s)", FieldName(name).c_str(), name);
for (const Section* s : fSectionAndParameterHelper.getSections(
SAMPLER_PARAMS_SECTION)) {
if (s->fArgument == name) {
this->writef(", %s", s->fText.c_str());
}
}
this->writef(")");
} else if (param->fType == *fContext.fFragmentProcessor_Type) {
// do nothing
} else {
this->writef("\n , %s(%s)", FieldName(name).c_str(), name);
}
}
for (const Section* s : fSectionAndParameterHelper.getSections(COORD_TRANSFORM_SECTION)) {
String field = FieldName(s->fArgument.c_str());
this->writef("\n , %sCoordTransform(%s, %s.proxy())", field.c_str(), s->fText.c_str(),
field.c_str());
}
this->writef(" {\n");
this->writeSection(CONSTRUCTOR_CODE_SECTION);
for (const auto& param : fSectionAndParameterHelper.getParameters()) {
if (param->fType.kind() == Type::kSampler_Kind) {
this->writef(" this->addTextureSampler(&%s);\n",
FieldName(String(param->fName).c_str()).c_str());
} else if (param->fType == *fContext.fFragmentProcessor_Type) {
this->writef(" this->registerChildProcessor(std::move(%s));",
String(param->fName).c_str());
}
}
for (const Section* s : fSectionAndParameterHelper.getSections(COORD_TRANSFORM_SECTION)) {
String field = FieldName(s->fArgument.c_str());
this->writef(" this->addCoordTransform(&%sCoordTransform);\n", field.c_str());
}
this->writef(" }\n");
}
void HCodeGenerator::writeFields() {
this->writeSection(FIELDS_SECTION);
for (const auto& param : fSectionAndParameterHelper.getParameters()) {
if (param->fType == *fContext.fFragmentProcessor_Type) {
continue;
}
this->writef(" %s %s;\n", FieldType(fContext, param->fType).c_str(),
FieldName(String(param->fName).c_str()).c_str());
}
for (const Section* s : fSectionAndParameterHelper.getSections(COORD_TRANSFORM_SECTION)) {
this->writef(" GrCoordTransform %sCoordTransform;\n",
FieldName(s->fArgument.c_str()).c_str());
}
}
bool HCodeGenerator::generateCode() {
this->writef(kFragmentProcessorHeader, fFullName.c_str());
this->writef("#ifndef %s_DEFINED\n"
"#define %s_DEFINED\n",
fFullName.c_str(),
fFullName.c_str());
this->writef("#include \"SkTypes.h\"\n"
"#if SK_SUPPORT_GPU\n");
this->writeSection(HEADER_SECTION);
this->writef("#include \"GrFragmentProcessor.h\"\n"
"#include \"GrCoordTransform.h\"\n"
"#include \"GrColorSpaceXform.h\"\n");
this->writef("class %s : public GrFragmentProcessor {\n"
"public:\n",
fFullName.c_str());
this->writeSection(CLASS_SECTION);
for (const auto& param : fSectionAndParameterHelper.getParameters()) {
if (param->fType.kind() == Type::kSampler_Kind ||
param->fType.kind() == Type::kOther_Kind) {
continue;
}
String nameString(param->fName);
const char* name = nameString.c_str();
this->writef(" %s %s() const { return %s; }\n",
FieldType(fContext, param->fType).c_str(), name, FieldName(name).c_str());
}
this->writeMake();
this->writef(" %s(const %s& src);\n"
" std::unique_ptr<GrFragmentProcessor> clone() const override;\n"
" const char* name() const override { return \"%s\"; }\n"
"private:\n",
fFullName.c_str(), fFullName.c_str(), fName.c_str());
this->writeConstructor();
this->writef(" GrGLSLFragmentProcessor* onCreateGLSLInstance() const override;\n"
" void onGetGLSLProcessorKey(const GrShaderCaps&,"
"GrProcessorKeyBuilder*) const override;\n"
" bool onIsEqual(const GrFragmentProcessor&) const override;\n"
" GR_DECLARE_FRAGMENT_PROCESSOR_TEST\n");
this->writeFields();
this->writef(" typedef GrFragmentProcessor INHERITED;\n"
"};\n");
this->writeSection(HEADER_END_SECTION);
this->writef("#endif\n"
"#endif\n");
return 0 == fErrors.errorCount();
}
} // namespace
| [
"liuxiufeng@qiyi.com"
] | liuxiufeng@qiyi.com |
33deecf7ef73d6e70b8845f2236dda47749bd71a | 6a67e360dc122b6c2f6e454d2e297ec3e6414f20 | /car/car.ino | 677ba60933ee2c57f6b052c1dcd6de2637711b05 | [] | no_license | strangecamelcaselogin/arduino-nrf-rc | 9e76e9221bc89350b2e364e3aa9c6a884176335f | 7af8e383f40f4aa1507a84decffe62cbc6066f0e | refs/heads/master | 2020-03-15T16:27:29.762017 | 2019-04-06T18:41:42 | 2019-04-06T18:41:42 | 132,234,973 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,259 | ino | #include "nRF24L01.h"
#include "RF24.h"
#include <ServoTimer2.h>
#define BAUDRATE 115200
// Radio Commands
#define CMD_NONE 1
#define CMD_ACTIVE 2
// Engine mode control params
#define FREE 0
#define FORWARD 1
#define BACKWARD 2
#define BRAKE 3
// NRF24 pins
#define NRF_CE 3
#define NRF_CS 10
// NRF24 settings
#define NRF_ADDR 0
#define NRF_CHAN 0x60
#define NRF_PAYLOAD_SIZE 32
// L298 or MX1508 driver pins
#define ENG_PWM_PIN -1 // -1 is MX1508 driver
#define FWD_PIN 9
#define BCWD_PIN 6
// Steering servo pin
#define STEERING_SERVO_PIN 5
// Steerings params
#define ZERO 1390
#define RIGTH ZERO - 320
#define LEFT ZERO + 300
// Engine PWM controls
#define PWM_LOW_LIMIT 50 // low limit of PWM
#define PWM_LIMIT 255 // limit for PWM of engine (0-255)
RF24 radio(NRF_CE, NRF_CS);
uint8_t address[][6] = {"1Node","2Node","3Node","4Node","5Node","6Node"};
uint8_t pipeNo;
struct payload_t {
uint8_t command;
uint16_t stick1_x;
uint16_t stick1_y;
bool stick1_p;
uint16_t stick2_x;
uint16_t stick2_y;
bool stick2_p;
uint8_t delay_ms;
} p;
long int recieve_package_time = millis(); // last command recieved time
ServoTimer2 steering_servo; // create servo object to control stearing
/*
* Set steering servo position.
* timing - between LEFT and RIGTH
*/
void set_steering(uint16_t timing) {
static uint16_t p_timing = 0;
if (abs(timing - p_timing) > 0) {
steering_servo.write(timing); // sets the servo position according to the scaled value
}
p_timing = timing;
}
void set_engine(uint8_t eng_direction, uint8_t eng_pwm) {
if (ENG_PWM_PIN == -1) {
set_MX1508_engine(eng_direction, eng_pwm);
} else {
set_L298_engine(eng_direction, eng_pwm);
}
}
/*
* Set engine state for L298. Control both direction and PWM.
* In case FREE and BRAKE direction commands pwm value ignores;
*
* Direction - one of FREE | FORWARD | BACKWARD | BRAKE
*
* FREE - disconnect engine from circuit
* BRAKE - short engine terminals
*/
void set_L298_engine(uint8_t eng_direction, uint8_t eng_pwm) {
switch (eng_direction) {
case FREE:
// set both INs to same (low or high) AND enable to low;
digitalWrite(FWD_PIN, LOW);
digitalWrite(BCWD_PIN, LOW);
eng_pwm = 0;
break;
case FORWARD:
digitalWrite(FWD_PIN, HIGH);
digitalWrite(BCWD_PIN, LOW);
break;
case BACKWARD:
digitalWrite(BCWD_PIN, HIGH);
digitalWrite(FWD_PIN, LOW);
break;
case BRAKE:
// set both INs to same (low or high) AND enable to 1;
digitalWrite(BCWD_PIN, LOW);
digitalWrite(FWD_PIN, LOW);
eng_pwm = 255;
break;
}
analogWrite(ENG_PWM_PIN, eng_pwm); // send PWM signal to engine
};
void set_MX1508_engine(uint8_t eng_direction, uint8_t eng_pwm) {
switch (eng_direction) {
case FREE:
digitalWrite(FWD_PIN, LOW);
digitalWrite(BCWD_PIN, LOW);
break;
case FORWARD:
analogWrite(FWD_PIN, eng_pwm);
digitalWrite(BCWD_PIN, LOW);
break;
case BACKWARD:
digitalWrite(FWD_PIN, LOW);
analogWrite(BCWD_PIN, eng_pwm);
break;
case BRAKE:
digitalWrite(FWD_PIN, HIGH);
digitalWrite(BCWD_PIN, HIGH);
break;
}
}
void debug(uint8_t eng_direction, uint8_t eng_pwm, uint16_t steering_servo_value) {
char t[100];
snprintf(t, 100, "car. eng_direction: %i, eng_pwm: %i, steering: %i",
eng_direction, eng_pwm, steering_servo_value);
Serial.println(t);
}
/*
* Simple greeting to determine car status.
*/
void hello() {
set_steering(ZERO);
analogWrite(FWD_PIN, 20);
delay(400);
// set_steering(LEFT);
analogWrite(FWD_PIN, 0);
analogWrite(BCWD_PIN, 20);
delay(400);
// set_steering(RIGTH);
analogWrite(BCWD_PIN, 0);
analogWrite(FWD_PIN, 20);
delay(400);
// set_steering(ZERO);
analogWrite(FWD_PIN, 0);
};
void setup() {
// pins setup
if (ENG_PWM_PIN != -1) pinMode(ENG_PWM_PIN, OUTPUT);
pinMode(FWD_PIN, OUTPUT);
pinMode(BCWD_PIN, OUTPUT);
pinMode(STEERING_SERVO_PIN, OUTPUT);
Serial.begin(BAUDRATE);
radio.begin();
steering_servo.attach(STEERING_SERVO_PIN);
hello();
while (!Serial) {}
// radio setup
radio.setAutoAck(1);
radio.setRetries(0, 15); // delay, count of retry
radio.setPayloadSize(NRF_PAYLOAD_SIZE); // package size
radio.openReadingPipe(1, address[NRF_ADDR]); // address
radio.setChannel(NRF_CHAN); // chanel
radio.setPALevel(RF24_PA_MAX); // RF24_PA_MIN | RF24_PA_LOW | RF24_PA_HIGH | RF24_PA_MAX
radio.setDataRate(RF24_1MBPS); // RF24_2MBPS | RF24_1MBPS, | RF24_250KBPS
radio.powerUp();
radio.startListening(); // listen
Serial.println("Setup end");
}
void loop() {
while (radio.available(&pipeNo)) {
recieve_package_time = millis();
radio.read(&p, sizeof(payload_t));
if (p.command == 0) {
Serial.println("received junk package");
continue;
}
Serial.println("received ok package");
// steering
uint16_t steering_servo_value = map(p.stick2_x, 0, 1023, LEFT, RIGTH); // map 0 - 1023 to servo timing
set_steering(steering_servo_value);
switch (p.command) {
case CMD_NONE:
set_engine(FREE, 0);
break;
case CMD_ACTIVE:
int8_t eng_direction = FREE;
uint8_t eng_pwm = 0;
if (p.stick1_p) {
eng_direction = BRAKE;
} else {
if (p.stick1_y > 512) {
eng_direction = FORWARD;
eng_pwm = map(p.stick1_y, 512, 1023, PWM_LOW_LIMIT, PWM_LIMIT);
}
else if (p.stick1_y < 512) {
eng_direction = BACKWARD;
eng_pwm = map(p.stick1_y, 512, 0, PWM_LOW_LIMIT, PWM_LIMIT);
}
}
debug(eng_direction, eng_pwm, steering_servo_value);
set_engine(eng_direction, eng_pwm);
break;
}
}
// in case of lose connection
if ((millis() - recieve_package_time) > p.delay_ms * 5) {
Serial.println("Reset state");
set_engine(BRAKE, 0); // brake by engine
// set_steering(ZERO); // set steering to center point
delay(p.delay_ms); // wait some time...
}
}
| [
"strangecamelcaselogin@gmail.com"
] | strangecamelcaselogin@gmail.com |
94e5a40e7b8b8660bde02065084c4e9a0d83918f | c3d9f339e725af8c98ac4d891273a3d5581ba0ee | /acelaso.ino/SI1143_pulse_PSO2/SI1143_pulse_PSO2.ino | 15d611724a7a0bfb6e6d7b2d3a307334c22b660b | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | mdmckni2/Acelaso_project | 6a8e987a0c90178893a17d2380d993fc3ef3b174 | ba0d654badf8597e093865dd08d893f12d08cc4a | refs/heads/master | 2020-05-07T22:53:12.967713 | 2015-08-02T19:29:16 | 2015-08-02T19:29:16 | 33,674,625 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,462 | ino | /* SI114_pulse_PSO2.ino
* A version of SI114_Pulse_Demo.ino with PSO2 sensing added
* demo code for the Modern Device SI1143-based pulse sensor
* http://moderndevice.com/product/pulse-heartbeat-sensor-pulse-sensor-1x/
* Paul Badger 2013 with plenty of coding help from Jean-Claude Wippler
* Hardware setup - please read the chart below and set the appropriate options
* See the #defines for various printing options
* This is experimental software (and pre-beta) at that, it is not suitable
* for any particular purpose. No life-critical devices should
* be based on this software.
* Code in the public domain but credit for the software is nice :)
*/
#include <SI114.h>
const int portForSI114 = 4; // change to the JeeNode port number used
/*
For Arduino users just use the following pins for various port settings
Or use port 0 for traditional SDA (A4) and SCL (A5)
Connect pins with 10k resistors in series
JeeNode users just set the appropriate port
JeeNode Port SCL ('duino pin) SDA ('duino pin)
0 18 (A5) 19 (A4)
1 4 14 (A0)
2 5 15 (A1)
3 6 16 (A2)
4 7 17 (A3)
*/
const int SAMPLES_TO_AVERAGE = 5; // samples for smoothing 1 to 10 seem useful 5 is default
// increase for smoother waveform (with less resolution - slower!)
//#define SEND_TOTAL_TO_PROCESSING // Use this option exclusive of other options
// for sending data to HeartbeatGraph in Processing
// #define POWERLINE_SAMPLING // samples on an integral of a power line period [eg 1/60 sec]
// #define AMBIENT_LIGHT_SAMPLING // also samples ambient slight (slightly slower)
// #define PRINT_LED_VALS // print LED raw values
#define GET_PULSE_READING // prints HB, signal size, PSO2 ratio
int binOut; // 1 or 0 depending on state of heartbeat
int BPM;
unsigned long red; // read value from visible red LED
unsigned long IR1; // read value from infrared LED1
unsigned long IR2; // read value from infrared LED2
unsigned long IR_total; // IR LED reads added together
PortI2C myBus (portForSI114);
PulsePlug pulse (myBus);
void setup () {
Serial.begin(57600);
Serial.println("\n Pulse_demo ");
if (pulse.isPresent()) {
Serial.print("SI114x Pulse Sensor found on Port ");
Serial.println(portForSI114);
}
else {
Serial.print("No SI114x found on Port ");
Serial.println(portForSI114);
}
Serial.begin(57600);
digitalWrite(3, HIGH);
initPulseSensor();
}
void loop() {
readPulseSensor();
delay(1000);
}
// simple smoothing function for heartbeat detection and processing
float smooth(float data, float filterVal, float smoothedVal) {
if (filterVal > 1) { // check to make sure param's are within range
filterVal = .99;
}
else if (filterVal <= 0.0) {
filterVal = 0.01;
}
smoothedVal = (data * (1.0 - filterVal)) + (smoothedVal * filterVal);
return smoothedVal;
}
void initPulseSensor() {
pulse.setReg(PulsePlug::HW_KEY, 0x17);
// pulse.setReg(PulsePlug::COMMAND, PulsePlug::RESET_Cmd);
Serial.print("PART: ");
Serial.print(pulse.getReg(PulsePlug::PART_ID));
Serial.print(" REV: ");
Serial.println(pulse.getReg(PulsePlug::REV_ID));
Serial.print(" SEQ: ");
Serial.println(pulse.getReg(PulsePlug::SEQ_ID));
pulse.setReg(PulsePlug::INT_CFG, 0x03); // turn on interrupts
pulse.setReg(PulsePlug::IRQ_ENABLE, 0x10); // turn on interrupt on PS3
pulse.setReg(PulsePlug::IRQ_MODE2, 0x01); // interrupt on ps3 measurement
pulse.setReg(PulsePlug::MEAS_RATE, 0x84); // see datasheet
pulse.setReg(PulsePlug::ALS_RATE, 0x08); // see datasheet
pulse.setReg(PulsePlug::PS_RATE, 0x08); // see datasheet
// Current setting for LEDs pulsed while taking readings
// PS_LED21 Setting for LEDs 1 & 2. LED 2 is high nibble
// each LED has 16 possible (0-F in hex) possible settings
// see the SI114x datasheet.
// These settings should really be autimated with feedback from output
// On my todo list but your patch is appreciated :)
// support at moderndevice dot com.
pulse.setReg(PulsePlug::PS_LED21, 0x39); // LED current for 2 (IR1 - high nibble) & LEDs 1 (red - low nibble)
pulse.setReg(PulsePlug::PS_LED3, 0x02); // LED current for LED 3 (IR2)
//debug info for the led currents
Serial.print( "PS_LED21 = ");
Serial.println(pulse.getReg(PulsePlug::PS_LED21), BIN);
Serial.print("CHLIST = ");
Serial.println(pulse.readParam(0x01), BIN);
pulse.writeParam(PulsePlug::PARAM_CH_LIST, 0x77); // all measurements on
// increasing PARAM_PS_ADC_GAIN will increase the LED on time and ADC window
// you will see increase in brightness of visible LED's, ADC output, & noise
// datasheet warns not to go beyond 4 because chip or LEDs may be damaged
pulse.writeParam(PulsePlug::PARAM_PS_ADC_GAIN, 0x00);
// You can select which LEDs are energized for each reading.
// The settings below (in the comments)
// turn on only the LED that "normally" would be read
// ie LED1 is pulsed and read first, then LED2 & LED3.
pulse.writeParam(PulsePlug::PARAM_PSLED12_SELECT, 0x21); // 21 select LEDs 2 & 1 (red) only
pulse.writeParam(PulsePlug::PARAM_PSLED3_SELECT, 0x04); // 4 = LED 3 only
// Sensors for reading the three LEDs
// 0x03: Large IR Photodiode
// 0x02: Visible Photodiode - cannot be read with LEDs on - just for ambient measurement
// 0x00: Small IR Photodiode
pulse.writeParam(PulsePlug::PARAM_PS1_ADCMUX, 0x03); // PS1 photodiode select
pulse.writeParam(PulsePlug::PARAM_PS2_ADCMUX, 0x03); // PS2 photodiode select
pulse.writeParam(PulsePlug::PARAM_PS3_ADCMUX, 0x03); // PS3 photodiode select
pulse.writeParam(PulsePlug::PARAM_PS_ADC_COUNTER, B01110000); // B01110000 is default
pulse.setReg(PulsePlug::COMMAND, PulsePlug::PSALS_AUTO_Cmd); // starts an autonomous read loop
Serial.println(pulse.getReg(PulsePlug::CHIP_STAT), HEX);
Serial.print("end init");
}
void readPulseSensor() {
static int foundNewFinger, red_signalSize, red_smoothValley;
static long red_valley, red_Peak, red_smoothRedPeak, red_smoothRedValley,
red_HFoutput, red_smoothPeak; // for PSO2 calc
static int IR_valley = 0, IR_peak = 0, IR_smoothPeak, IR_smoothValley, binOut, lastBinOut, BPM;
static unsigned long lastTotal, lastMillis, IRtotal, valleyTime = millis(), lastValleyTime = millis(), peakTime = millis(), lastPeakTime = millis(), lastBeat, beat;
static float IR_baseline, red_baseline, IR_HFoutput, IR_HFoutput2, shiftedOutput, LFoutput, hysterisis;
unsigned long total = 0, start;
int i = 0;
int IR_signalSize;
red = 0;
IR1 = 0;
IR2 = 0;
total = 0;
start = millis();
#ifdef POWERLINE_SAMPLING
while (millis() - start < 16) { // 60 hz - or use 33 for two cycles
// 50 hz in Europe use 20, or 40
Serial.print("sample");
#else
while (i < SAMPLES_TO_AVERAGE) {
#endif
#ifdef AMBIENT_LIGHT_SAMPLING
pulse.fetchData();
#else
pulse.fetchLedData();
#endif
red += pulse.ps1;
IR1 += pulse.ps2;
IR2 += pulse.ps3;
i++;
}
red = red / i; // get averages
IR1 = IR1 / i;
IR2 = IR2 / i;
total = IR1 + IR2 + red; // red excluded
IRtotal = IR1 + IR2;
#ifdef AMBIENT_LIGHT_SAMPLING
Serial.print(pulse.resp, HEX); // resp
Serial.print("\t");
Serial.print(pulse.als_vis); // ambient visible
Serial.print("\t");
Serial.print(pulse.als_ir); // ambient IR
Serial.print("\t");
#endif
#ifdef PRINT_LED_VALS
Serial.print(red);
Serial.print("\t");
Serial.print(IR1);
Serial.print("\t");
Serial.print(IR2);
Serial.print("\t");
Serial.println((long)total);
#endif
#ifdef SEND_TOTAL_TO_PROCESSING
Serial.println(total);
#endif
#ifdef GET_PULSE_READING
// except this one for Processing heartbeat monitor
// comment out all the bottom print lines
if (lastTotal < 20000L && total > 20000L) foundNewFinger = 1; // found new finger!
lastTotal = total;
// if found a new finger prime filters first 20 times through the loop
if (++foundNewFinger > 25) foundNewFinger = 25; // prevent rollover
if ( foundNewFinger < 20) {
IR_baseline = total - 200; // take a guess at the baseline to prime smooth filter
Serial.println("found new finger");
}
else if (total > 20000L) { // main running function
// baseline is the moving average of the signal - the middle of the waveform
// the idea here is to keep track of a high frequency signal, HFoutput and a
// low frequency signal, LFoutput
// The LF signal is shifted downward slightly downward (heartbeats are negative peaks)
// The high freq signal has some hysterisis added.
// When the HF signal crosses the shifted LF signal (on a downward slope),
// we have found a heartbeat.
IR_baseline = smooth(IRtotal, 0.99, IR_baseline); //
IR_HFoutput = smooth((IRtotal - IR_baseline), 0.2, IR_HFoutput); // recycling output - filter to slow down response
red_baseline = smooth(red, 0.99, red_baseline);
red_HFoutput = smooth((red - red_HFoutput), 0.2, red_HFoutput);
// beat detection is performed only on the IR channel so
// fewer red variables are needed
IR_HFoutput2 = IR_HFoutput + hysterisis;
LFoutput = smooth((IRtotal - IR_baseline), 0.95, LFoutput);
// heartbeat signal is inverted - we are looking for negative peaks
shiftedOutput = LFoutput - (IR_signalSize * .05);
if (IR_HFoutput > IR_peak) IR_peak = IR_HFoutput;
if (red_HFoutput > red_Peak) red_Peak = red_HFoutput;
// default reset - only if reset fails to occur for 1800 ms
if (millis() - lastPeakTime > 1800) { // reset peak detector slower than lowest human HB
IR_smoothPeak = smooth((float)IR_peak, 0.6, (float)IR_smoothPeak); // smooth peaks
IR_peak = 0;
red_smoothPeak = smooth((float)red_Peak, 0.6, (float)red_smoothPeak); // smooth peaks
red_Peak = 0;
lastPeakTime = millis();
}
if (IR_HFoutput < IR_valley) IR_valley = IR_HFoutput;
if (red_HFoutput < red_valley) red_valley = red_HFoutput;
/* if (IR_valley < -1500){
IR_valley = -1500; // ditto above
Serial.println("-1500");
}
if (red_valley < -1500) red_valley = -1500; // ditto above */
if (millis() - lastValleyTime > 1800) { // insure reset slower than lowest human HB
IR_smoothValley = smooth((float)IR_valley, 0.6, (float)IR_smoothValley); // smooth valleys
IR_valley = 0;
lastValleyTime = millis();
}
// IR_signalSize = IR_smoothPeak - IR_smoothValley; // this the size of the smoothed HF heartbeat signal
hysterisis = constrain((IR_signalSize / 15), 35, 120) ; // you might want to divide by smaller number
// if you start getting "double bumps"
// Serial.print(" T ");
// Serial.print(IR_signalSize);
if (IR_HFoutput2 < shiftedOutput) {
// found a beat - pulses are valleys
lastBinOut = binOut;
binOut = 1;
// Serial.println("\t1");
hysterisis = -hysterisis;
IR_smoothValley = smooth((float)IR_valley, 0.99, (float)IR_smoothValley); // smooth valleys
IR_signalSize = IR_smoothPeak - IR_smoothValley;
IR_valley = 0x7FFF;
red_smoothValley = smooth((float)red_valley, 0.99, (float)red_smoothValley); // smooth valleys
red_signalSize = red_smoothPeak - red_smoothValley;
red_valley = 0x7FFF;
lastValleyTime = millis();
}
else {
// Serial.println("\t0");
lastBinOut = binOut;
binOut = 0;
IR_smoothPeak = smooth((float)IR_peak, 0.99, (float)IR_smoothPeak); // smooth peaks
IR_peak = 0;
red_smoothPeak = smooth((float)red_Peak, 0.99, (float)red_smoothPeak); // smooth peaks
red_Peak = 0;
lastPeakTime = millis();
}
if (lastBinOut == 1 && binOut == 0) {
Serial.println(binOut);
}
if (lastBinOut == 0 && binOut == 1) {
lastBeat = beat;
beat = millis();
BPM = 60000 / (beat - lastBeat);
Serial.print(binOut);
Serial.print("\t BPM ");
Serial.print(BPM);
Serial.print("\t IR ");
Serial.print(IR_signalSize);
Serial.print("\t PSO2 ");
Serial.println(((float)red_baseline / (float)(IR_baseline / 2)), 3);
}
}
#endif
}
| [
"jrhowel2@ncsu.edu"
] | jrhowel2@ncsu.edu |
083a3ce256e58815738a99ab49e88b2d409220f6 | 6467bb08e02e7bb47a59ad7d512926d70da3c5f5 | /trunk/themis/common/BasePrefsView.cpp | bdc66d1053080b6b3cb2b1e6114ebe53fb3d7801 | [] | no_license | svn2github/Themis | 1ed26434317a30c61e751eb9800ea96077b6c73c | 20be549491930fe86246ff748c55139201ead7a8 | refs/heads/master | 2020-12-25T15:28:53.785606 | 2018-03-12T21:55:53 | 2018-03-12T21:55:53 | 61,454,928 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,034 | cpp | /*
Copyright (c) 2010 Mark Hellegers. All Rights Reserved.
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.
Original Author: Mark Hellegers (mark@firedisk.net)
Project Start Date: October 18, 2000
Class Start Date: October 31, 2010
*/
/* BasePrefsView implementation
See BasePrefsView.hpp for more information
*/
// Standard C headers
#include <stdio.h>
// BeOS headers
#include <interface/Window.h>
#include <interface/Box.h>
#include <interface/PopUpMenu.h>
#include <interface/MenuItem.h>
#include <interface/MenuField.h>
#include <storage/Directory.h>
#include <storage/Entry.h>
#include <storage/Path.h>
// Themis headers
#include "BasePrefsView.hpp"
#include "commondefs.h"
#include "PrefsDefs.h"
BasePrefsView :: BasePrefsView(BRect aFrame,
const char* aName)
: BView(aFrame,
aName,
B_FOLLOW_ALL,
0) {
mMainBox = new BBox(
Bounds(),
"MainBox",
B_FOLLOW_ALL);
mMainBox->SetLabel(Name());
AddChild(mMainBox);
SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
}
| [
"mark_hellegers@ecaf47ba-bb13-0410-a3b6-899b003a5108"
] | mark_hellegers@ecaf47ba-bb13-0410-a3b6-899b003a5108 |
63da2698596bb44886c055c75bf198ff2d14d907 | e71d40ad4e76272fca4494c6bcc818050d221090 | /Blink/Source/modules/webdatabase/SQLResultSet.cpp | ec517a25aa380d50f5967d3019990d2bc8969393 | [] | no_license | yuanyan/know-your-chrome | e038e49c160bdf46b28241427e99bf2816fac022 | 18cace725261122f6903c98bfdcbfa0b370138c3 | refs/heads/master | 2022-12-29T18:31:42.046729 | 2013-12-18T11:45:13 | 2013-12-18T11:45:13 | 9,907,874 | 7 | 7 | null | 2022-12-18T00:00:55 | 2013-05-07T08:55:26 | C++ | UTF-8 | C++ | false | false | 2,568 | cpp | /*
* Copyright (C) 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "modules/webdatabase/SQLResultSet.h"
#include "core/dom/ExceptionCode.h"
namespace WebCore {
static unsigned const MaxErrorCode = 2;
SQLResultSet::SQLResultSet()
: m_rows(SQLResultSetRowList::create())
, m_insertId(0)
, m_insertIdSet(false)
, m_rowsAffected(0)
{
}
int64_t SQLResultSet::insertId(ExceptionCode& e) const
{
// 4.11.4 - Return the id of the last row inserted as a result of the query
// If the query didn't result in any rows being added, raise an INVALID_ACCESS_ERR exception
if (m_insertIdSet)
return m_insertId;
e = INVALID_ACCESS_ERR;
return -1;
}
int SQLResultSet::rowsAffected() const
{
return m_rowsAffected;
}
SQLResultSetRowList* SQLResultSet::rows() const
{
return m_rows.get();
}
void SQLResultSet::setInsertId(int64_t id)
{
ASSERT(!m_insertIdSet);
m_insertId = id;
m_insertIdSet = true;
}
void SQLResultSet::setRowsAffected(int count)
{
m_rowsAffected = count;
}
}
| [
"yuanyan.cao@gmail.com"
] | yuanyan.cao@gmail.com |
ef746297af9bd0ebc501faedd26388f65b179c1c | 4eeea285cfbc6b60f573804182000a0fc819fee3 | /include/webcachesim/caches/gd_variants.h | 625afbc71b2c7276f55d88c69cd6dbd748bcf01a | [
"BSD-2-Clause"
] | permissive | sunnyszy/lrb | 13385277247bc8cc9af3308045a5dd976d05ef5f | 9e8b4423383c01c4528deb447f152f0437a37c3a | refs/heads/master | 2023-01-23T13:22:54.610943 | 2023-01-20T15:11:42 | 2023-01-20T15:11:42 | 242,271,426 | 74 | 28 | BSD-2-Clause | 2021-09-21T14:51:08 | 2020-02-22T03:12:53 | C++ | UTF-8 | C++ | false | false | 6,895 | h | #ifndef GD_VARIANTS_H
#define GD_VARIANTS_H
#include <unordered_map>
#include "utils.h"
#include <map>
#include <queue>
#include "cache.h"
typedef std::multimap<long double, uint64_t> ValueMapType;
typedef ValueMapType::iterator ValueMapIteratorType;
typedef std::unordered_map<uint64_t, ValueMapIteratorType> GdCacheMapType;
typedef std::unordered_map<uint64_t, uint64_t> CacheStatsMapType;
#ifdef EVICTION_LOGGING
#include "mongocxx/client.hpp"
#endif
using namespace std;
using namespace webcachesim;
/*
GD: greedy dual eviction (base class)
[implementation via heap: O(log n) time for each cache miss]
*/
class GreedyDualBase : public Cache
{
protected:
// the GD current value
long double _currentL = 0;
// ordered multi map of GD values, access object id + size
ValueMapType _valueMap;
// find objects via unordered_map
GdCacheMapType _cacheMap;
unordered_map<uint64_t , uint64_t > _sizemap;
#ifdef EVICTION_LOGGING
uint32_t current_t;
unordered_map<uint64_t, uint32_t> future_timestamps;
vector<uint8_t> eviction_qualities;
vector<uint16_t> eviction_logic_timestamps;
uint64_t byte_million_req;
string task_id;
string dburi;
#endif
virtual long double ageValue(const SimpleRequest& req);
virtual void hit(const SimpleRequest& req);
bool has(const uint64_t& id) {return _cacheMap.find(id) != _cacheMap.end();}
public:
GreedyDualBase()
: Cache(),
_currentL(0)
{
}
virtual ~GreedyDualBase()
{
}
bool lookup(const SimpleRequest &req) override;
void admit(const SimpleRequest &req) override;
// void evict(SimpleRequest &req);
//
virtual void evict();
};
static Factory<GreedyDualBase> factoryGD("GD");
//
///*
// Greedy Dual Size policy
//*/
//class GDSCache : public GreedyDualBase
//{
//protected:
// virtual long double ageValue(const SimpleRequest* req);
//
//public:
// GDSCache()
// : GreedyDualBase()
// {
// }
// virtual ~GDSCache()
// {
// }
//};
//
//static Factory<GDSCache> factoryGDS("GDS");
/*
Greedy Dual Size Frequency policy
*/
class GDSFCache : public GreedyDualBase
{
protected:
CacheStatsMapType _reqsMap;
virtual long double ageValue(const SimpleRequest& req);
public:
GDSFCache()
: GreedyDualBase()
{
}
virtual ~GDSFCache()
{
}
virtual bool lookup(const SimpleRequest &req);
};
static Factory<GDSFCache> factoryGDSF("GDSF");
/*
LRU-K policy
*/
typedef std::unordered_map<uint64_t , std::queue<uint64_t>> lrukMapType;
class LRUKCache : public GreedyDualBase
{
protected:
lrukMapType _refsMap;
unsigned int _tk;
uint64_t _curTime;
long double ageValue(const SimpleRequest &req) override;
public:
LRUKCache();
void init_with_params(const map<string, string> ¶ms) override {
//set params
for (auto& it: params) {
if (it.first == "k") {
_tk = stoul(it.second);
#ifdef EVICTION_LOGGING
} else if (it.first == "byte_million_req") {
byte_million_req = stoull(it.second);
} else if (it.first == "task_id") {
task_id = it.second;
} else if (it.first == "dburi") {
dburi = it.second;
#endif
} else {
cerr << "unrecognized parameter: " << it.first << endl;
}
}
}
#ifdef EVICTION_LOGGING
void update_stat(bsoncxx::v_noabi::builder::basic::document &doc) override {
//Log to GridFs because the value is too big to store in mongodb
try {
mongocxx::client client = mongocxx::client{mongocxx::uri(dburi)};
mongocxx::database db = client["webcachesim"];
auto bucket = db.gridfs_bucket();
auto uploader = bucket.open_upload_stream(task_id + ".evictions");
for (auto &b: eviction_qualities)
uploader.write((uint8_t *) (&b), sizeof(uint8_t));
uploader.close();
uploader = bucket.open_upload_stream(task_id + ".eviction_timestamps");
for (auto &b: eviction_logic_timestamps)
uploader.write((uint8_t *) (&b), sizeof(uint16_t));
uploader.close();
} catch (const std::exception &xcp) {
cerr << "error: db connection failed: " << xcp.what() << std::endl;
abort();
}
}
#endif
bool lookup(const SimpleRequest &req) override;
// void evict(SimpleRequest &req) ;
void evict() override;
};
static Factory<LRUKCache> factoryLRUK("LRUK");
/*
LFUDA
*/
class LFUDACache : public GreedyDualBase
{
protected:
CacheStatsMapType _reqsMap;
virtual long double ageValue(const SimpleRequest& req);
public:
LFUDACache()
: GreedyDualBase()
{
}
virtual ~LFUDACache()
{
}
#ifdef EVICTION_LOGGING
void init_with_params(const map<string, string> ¶ms) override {
//set params
for (auto &it: params) {
if (it.first == "byte_million_req") {
byte_million_req = stoull(it.second);
} else if (it.first == "task_id") {
task_id = it.second;
} else if (it.first == "dburi") {
dburi = it.second;
} else {
cerr << "unrecognized parameter: " << it.first << endl;
}
}
}
#endif
#ifdef EVICTION_LOGGING
void update_stat(bsoncxx::builder::basic::document &doc) override {
//Log to GridFs because the value is too big to store in mongodb
try {
mongocxx::client client = mongocxx::client{mongocxx::uri(dburi)};
mongocxx::database db = client["webcachesim"];
auto bucket = db.gridfs_bucket();
auto uploader = bucket.open_upload_stream(task_id + ".evictions");
for (auto &b: eviction_qualities)
uploader.write((uint8_t *) (&b), sizeof(uint8_t));
uploader.close();
uploader = bucket.open_upload_stream(task_id + ".eviction_timestamps");
for (auto &b: eviction_logic_timestamps)
uploader.write((uint8_t *) (&b), sizeof(uint16_t));
uploader.close();
} catch (const std::exception &xcp) {
cerr << "error: db connection failed: " << xcp.what() << std::endl;
abort();
}
}
#endif
virtual bool lookup(const SimpleRequest &req);
};
static Factory<LFUDACache> factoryLFUDA("LFUDA");
/*
LFU
*/
class LFUCache : public GreedyDualBase
{
protected:
CacheStatsMapType _reqsMap;
virtual long double ageValue(const SimpleRequest& req);
public:
LFUCache()
: GreedyDualBase()
{
}
virtual ~LFUCache()
{
}
virtual bool lookup(const SimpleRequest &req);
};
static Factory<LFUCache> factoryLFU("LFU");
#endif /* GD_VARIANTS_H */
| [
"sunnyszy@gmail.com"
] | sunnyszy@gmail.com |
87aaec32ca4bf76266c401f82443d86fe388de0a | 1073f60829eb29bb4ba4f8436046936eb7344212 | /MPI-2-C++/contrib/test_suite/bsend.cc | 7918012eb07f0082a6224444413cbe992217a9cd | [
"LicenseRef-scancode-notre-dame",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | matthiasdiener/mpich | c6f369b5e1cd45ab51e8ee2d7b7319f049e6897f | 8c5903e77ee847b4f22cde6f9313ad5f46e68d64 | refs/heads/master | 2021-05-12T04:32:41.235171 | 2018-01-11T23:22:17 | 2018-01-11T23:22:17 | 117,158,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,692 | cc | // Copyright 1997-2000, University of Notre Dame.
// Authors: Jeremy G. Siek, Jeffery M. Squyres, Michael P. McNally, and
// Andrew Lumsdaine
//
// This file is part of the Notre Dame C++ bindings for MPI.
//
// You should have received a copy of the License Agreement for the Notre
// Dame C++ bindings for MPI along with the software; see the file
// LICENSE. If not, contact Office of Research, University of Notre
// Dame, Notre Dame, IN 46556.
//
// Permission to modify the code and to distribute modified code is
// granted, provided the text of this NOTICE is retained, a notice that
// the code was modified is included with the above COPYRIGHT NOTICE and
// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE
// file is distributed with the modified code.
//
// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.
// By way of example, but not limitation, Licensor MAKES NO
// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY
// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS
// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS
// OR OTHER RIGHTS.
//
// Additional copyrights may follow.
/****************************************************************************
MESSAGE PASSING INTERFACE TEST CASE SUITE
Copyright IBM Corp. 1995
IBM Corp. hereby grants a non-exclusive license to use, copy, modify, and
distribute this software for any purpose and without fee provided that the
above copyright notice and the following paragraphs appear in all copies.
IBM Corp. makes no representation that the test cases comprising this
suite are correct or are an accurate representation of any standard.
In no event shall IBM be liable to any party for direct, indirect, special
incidental, or consequential damage arising out of the use of this software
even if IBM Corp. has been advised of the possibility of such damage.
IBM CORP. SPECIFICALLY DISCLAIMS ANY WARRANTIES INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS AND IBM
CORP. HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
ENHANCEMENTS, OR MODIFICATIONS.
****************************************************************************
These test cases reflect an interpretation of the MPI Standard. They are
are, in most cases, unit tests of specific MPI behaviors. If a user of any
test case from this set believes that the MPI Standard requires behavior
different than that implied by the test case we would appreciate feedback.
Comments may be sent to:
Richard Treumann
treumann@kgn.ibm.com
****************************************************************************
*/
#include "mpi2c++_test.h"
void
bsend()
{
#if _MPIPP_USEEXCEPTIONS_
char msg[150];
int class1;
int data[100000];
int i;
int size;
void* oldbuf;
MPI::Status status;
#endif
char* buf1;
Testing("Bsend");
if (flags[SKIP_IBM21014])
Done("Skipped (IBM 2.1.0.14)");
else if (flags[SKIP_IBM21015])
Done("Skipped (IBM 2.1.0.15)");
else if (flags[SKIP_IBM21016])
Done("Skipped (IBM 2.1.0.16)");
else if (flags[SKIP_IBM21017])
Done("Skipped (IBM 2.1.0.17)");
else {
buf1 = new char[sizeof(int) * 1000 + MPI::BSEND_OVERHEAD];
#if _MPIPP_USEEXCEPTIONS_
MPI::COMM_WORLD.Set_errhandler(MPI::ERRORS_THROW_EXCEPTIONS);
if((my_rank % 2) == 0) {
for(i = 0; i < 100000; i++)
data[i] = 1;
class1 = MPI::SUCCESS;
MPI::Attach_buffer(buf1, sizeof(int) * 1000 + MPI::BSEND_OVERHEAD);
try {
MPI::COMM_WORLD.Bsend(data, 1000, MPI::INT, my_rank + 1, 1);
}
catch(MPI::Exception e) {
class1 = e.Get_error_class();
}
if(class1 != MPI::SUCCESS) {
sprintf(msg, "NODE %d - 1) Error in 1st bsend: %d", my_rank, class1);
Fail(msg);
}
size = MPI::Detach_buffer(oldbuf);
if(size != sizeof(int) * 1000 + MPI::BSEND_OVERHEAD) {
sprintf(msg, "NODE %d - 2) ERROR in Detach_buffer, incorrect size returned.", my_rank);
Fail(msg);
}
} else if((my_rank % 2) == 1) {
for(i = 0; i < 100000; i++)
data[i] = 2;
MPI::COMM_WORLD.Recv(data, 1000, MPI::INT, my_rank - 1, 1, status);
for(i = 0; i < 1000; i++)
if(data[i] != 1) {
sprintf(msg, "NODE %d - 6) ERROR, incorrect data value received, task 1, recv 1",
my_rank);
Fail(msg);
}
}
MPI::COMM_WORLD.Set_errhandler(MPI::ERRORS_RETURN);
Pass(); // Bsend
#else
Done("Compiler does not have exceptions");
#endif
delete[] buf1;
}
}
| [
"mdiener@illinois.edu"
] | mdiener@illinois.edu |
04a488699f699237f0005e34d5a56e6217c79308 | 5827e701daa0220b58c53cb4eeafbb67d07b3ff8 | /Final Project/Game Engine/Controller.cpp | 790218a4f6d32f26a422830fc53133db05babcea | [] | no_license | zextrix/SpaceShip-Shooter | 8c236667309b0b86e5dfdcaaf354d83ba105eb7e | ff7477a6b65ce791022a907ad14e91703dba654b | refs/heads/master | 2020-04-19T09:35:50.674914 | 2019-01-29T08:48:17 | 2019-01-29T08:48:17 | 168,115,716 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,847 | cpp | /*------------------------------------------------------------------
Copyright (C) 2018 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the prior
written consent of DigiPen Institute of Technology is prohibited.
File Name: Controller
Purpose:
To implement a controller to control the movements of the player gameobject
Language: C++
Platform:
Compiler:- Visual Studio 2017 - Visual C++ 14.1
Hardware Requirements:- Display monitor, keyboard.
Operating System:- Microsoft Windows 8.1+
Project:
Student Login:- pratyush.gawai
Class:- MSCS Fall2018
Assignment :- MileStone4
Author: Pratyush Gawai
Student login: pratyush.gawai
Student ID: 60001818
Creation date: 11/25/2018
---------------------------------------------------------*/
#include "Controller.h"
#include "InputManager.h"
#include "GameObject.h"
#include "Transform.h"
#include "SDL_scancode.h"
#include "Body.h"
#include "CollisionManager.h"
#include "EventManager.h"
#include "PhysicsManager.h"
#include "Sprite.h"
#include "RenderManager.h"
#include "ObjectFactory.h"
#include "GameObjectManager.h"
extern InputManager *gpIM;
extern EventManager *gpEM;
extern RenderManager *gpREM;
extern ObjectFactory *gpOF;
Controller::Controller() : Component(CONTROLLER)
{
}
Controller::~Controller()
{
}
void Controller::Update()
{
tribtime += 0.016f;
spdtime += 0.016f;
if (nullptr != mpOwner && nullptr != gpIM)
{
Body *pBody = static_cast<Body *> (mpOwner->getComponent(BODY));
Transform *pTr = static_cast<Transform *> (mpOwner->getComponent(TRANSFORM));
Sprite *psp = static_cast<Sprite *> (mpOwner->getComponent(SPRITE));
if (nullptr != pTr)
{
if (gpIM->IsTriggered(SDL_SCANCODE_W) && pBody->mVelY == 0)
{
pBody->mTotalForceY += 1500.0f;
}
if (gpIM->IsPressed(SDL_SCANCODE_A))
pBody->mTotalForceX -= speed;
else if (gpIM->IsPressed(SDL_SCANCODE_D))
pBody->mTotalForceX += speed;
if (gpIM->IsTriggered(SDL_SCANCODE_SPACE))
{
if (gpREM->debug)
gpREM->debug = false;
else
gpREM->debug = true;
}
if (mg == true)
{
if (gpIM->IsTriggered(SDL_SCANCODE_K))
{
if (trib == false && tribtime < 3.0f)
{
GameObject * bullet1 = gpOF->CreateRunTimeObject("Bullet.txt");
if (bullet1 != nullptr)
{
Transform * bPtr1 = static_cast<Transform *> (bullet1->getComponent(TRANSFORM));
Body *bPbody1 = static_cast<Body *> (bullet1->getComponent(BODY));
bPtr1->mxPos = pTr->mxPos + 20.0f; bPtr1->myPos = pTr->myPos + 35.0f;
bPtr1->mxScale = 25.0f; bPtr1->myScale = 25.0f;
bPbody1->mPosX = pTr->mxPos + 20.0f; bPbody1->mPosY = pTr->myPos + 35.0f;
bPbody1->mVelY += 200.0;
}
GameObject * bullet2 = gpOF->CreateRunTimeObject("Bullet.txt");
if (bullet2 != nullptr)
{
Transform * bPtr2 = static_cast<Transform *> (bullet2->getComponent(TRANSFORM));
Body *bPbody2 = static_cast<Body *> (bullet2->getComponent(BODY));
bPtr2->mxPos = pTr->mxPos - 20.0f; bPtr2->myPos = pTr->myPos + 35.0f;
bPtr2->mxScale = 25.0f; bPtr2->myScale = 25.0f;
bPbody2->mPosX = pTr->mxPos - 20.0f; bPbody2->mPosY = pTr->myPos + 35.0f;
bPbody2->mVelY += 200.0;
}
}
if (trib == true)
{
GameObject * bullet1 = gpOF->CreateRunTimeObject("Bullet.txt");
if (bullet1 != nullptr)
{
Transform * bPtr1 = static_cast<Transform *> (bullet1->getComponent(TRANSFORM));
Body *bPbody1 = static_cast<Body *> (bullet1->getComponent(BODY));
bPtr1->mxPos = pTr->mxPos; bPtr1->myPos = pTr->myPos + 35.0f;
bPtr1->mxScale = 25.0f; bPtr1->myScale = 25.0f;
bPbody1->mPosX = pTr->mxPos; bPbody1->mPosY = pTr->myPos + 35.0f;
bPbody1->mVelY += 200.0;
}
}
}
}
if (mg == false)
{
if (gpIM->IsPressed(SDL_SCANCODE_K))
{
GameObject * bullet1 = gpOF->CreateRunTimeObject("Bullet.txt");
if (bullet1 != nullptr)
{
Transform * bPtr1 = static_cast<Transform *> (bullet1->getComponent(TRANSFORM));
Body *bPbody1 = static_cast<Body *> (bullet1->getComponent(BODY));
bPtr1->mxPos = pTr->mxPos + 20.0f; bPtr1->myPos = pTr->myPos + 35.0f;
bPtr1->mxScale = 25.0f; bPtr1->myScale = 25.0f;
bPbody1->mPosX = pTr->mxPos + 20.0f; bPbody1->mPosY = pTr->myPos + 35.0f;
bPbody1->mVelY += 200.0;
}
}
}
}
if (tribtime > 3.0f)
trib = true;
if (spdtime > 1.8f)
{
mg = true;
}
}
}
void Controller::HandleEvent(Event * pEvent)
{
if (SPEED_UP == pEvent->mType)
{
spdtime = 0.0f;
mg = false;
}
if (TRI_BUL == pEvent->mType)
{
tribtime = 0.0f;
trib = false;
}
}
Component * Controller::ReturnThis()
{
return new Controller(*this);
}
| [
"pratyush.gawai@digipen.edu"
] | pratyush.gawai@digipen.edu |
8c8d5cea7d4bb62e72e6f9956af1e78b7a929627 | 2cdedf3648e7e6d03010c6ba4ce3625d1b25aec4 | /NDS/mapping/game_play/GameMapProcessor.cpp | 029104c8ad1cd62a06b27c534fa353612d841beb | [] | no_license | rara1818/games | 7361377396d35b2e9a21b149c0d18abba1614185 | a228a78cdbe20e08dc13f3a155e250b75151caa8 | refs/heads/master | 2021-01-18T01:17:17.368236 | 2015-04-05T00:18:13 | 2015-04-05T00:18:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,380 | cpp | /*
* GameMapProcessor.cpp
*
* Created on: 07/09/2013
* Author: vitor
*/
#include "GameMapProcessor.h"
#include <assert.h>
#include <string.h>
#include <assert.h>
/* References */
#include "nds/arm9/video.h"
#include "nds/arm9/console.h"
#include "nds/arm9/input.h"
#include "nds/arm9/background.h"
/* Game related includes */
#include "util.h"
/* Definitions */
#define TILE_LEN_BYTES 2
#define TILES_TO_CP 32
#define TILE_SIZE 32
#define MAP_H_SIZE 184
#define VERTICAL_OFFSET 32
#define NO_VERTICAL_OFFSET 0
#define ANIMATED_LAYER_COOLDOWN 10 //! How much time between changing the displayed layers.
/*************************************************************************************************/
/* Public Functions Declaration */
/*************************************************************************************************/
GameMapProcessor::GameMapProcessor(void):
m_LoadedMap(0),
m_AnimatedLayer_cooldown(ANIMATED_LAYER_COOLDOWN)
{
this->clean_resources();
}
/*************************************************************************************************/
void GameMapProcessor::clean_resources(void)
{
memset(&m_LoadedMap_bounds_8px, 0, sizeof(m_LoadedMap_bounds_8px));
memset(&m_LoadedMap_offset_8px, 0, sizeof(m_LoadedMap_offset_8px));
}
/*************************************************************************************************/
void GameMapProcessor::load_Map(GameMap *map)
{
size_t i;
/*if ((x_offset_32px < SPRITE_SCREEN_CENTER_X_TILES) || (y_offset_32px < SPRITE_SCREEN_CENTER_Y_TILES) ||
(x_offset_32px > (map->m_SizeTile_32px.w - SPRITE_SCREEN_CENTER_X_TILES)) ||
(y_offset_32px > (map->m_SizeTile_32px.h - SPRITE_SCREEN_CENTER_Y_TILES))) {
debug("Invalid character starting point.");
assert(0);
return;
}*/
for (i = 0; i < map->m_LayersCount; ++i) {
/* Initialize the layers of the background. */
map->m_Background[i].id = bgInit(
map->m_Background[i].layer,
map->m_Background[i].type,
map->m_Background[i].size,
map->m_Background[i].dataBase,
map->m_Background[i].tileBase);
/* Set layers priority. */
bgSetPriority(map->m_Background[i].id, map->m_Background[i].prio);
debug("Loaded %d - id %d; prio %d", i, map->m_Background[i].id, map->m_Background[i].prio);
}
/* Set map palette. */
dmaCopy(map->m_Tiles, bgGetGfxPtr(map->m_Background[0].id), map->m_TilesLen);
dmaCopy(map->m_Palette, BG_PALETTE, map->m_PaletteLen);
m_LoadedMap = map;
/* Find map data loading bounds.
*
* Map origin = 0,0 8px;
* Map max is the size of the map in tiles of 8px minus a screen of 128x128px
*
*/
m_LoadedMap_bounds_8px.w = m_LoadedMap->m_SizeTile_8px.w - PIXEL_TO_TILE_8PX(SCREEN_WIDTH);
m_LoadedMap_bounds_8px.h = m_LoadedMap->m_SizeTile_8px.h - PIXEL_TO_TILE_8PX(SCREEN_HEIGHT);
/* Starting offset must be given with the move map function. */
m_LoadedMap_offset_8px.x = 0;//TILE_32PX_TO_8PX(x_offset_32px);
m_LoadedMap_offset_8px.x = 0;//TILE_32PX_TO_8PX(y_offset_32px);
this->draw_LoadedMap();
/* Draw the loaded map at the given position. */
//this->move_map_32px((x_offset_32px - SPRITE_SCREEN_CENTER_X_TILES),
// (y_offset_32px - SPRITE_SCREEN_CENTER_Y_TILES));
}
/*************************************************************************************************/
int GameMapProcessor::move_map_8px(const int x, const int y)
{
/* Right now, can move to only one direction per frame. */
en_direction load_data = DIRECT_NONE;
/* Find which direction. */
if (x < 0) {
load_data = DIRECT_LEFT;
}
else if (y < 0) {
load_data = DIRECT_UP;
}
else if (x > 0) {
load_data = DIRECT_RIGHT;
}
else if (y > 0) {
load_data = DIRECT_DOWN;
}
/* x = 0; y = 0 */
else {
return 0;
}
//debug("Direction: %d", load_data);
if (load_MapData_8px(load_data) != 0) {
/* Map limits reached. */
//debug("Invalid bounds");
return -1;
}
draw_LoadedMap();
return 0;
}
/*************************************************************************************************/
int GameMapProcessor::load_MapData_8px(en_direction direction)
{
switch(direction) {
case DIRECT_LEFT:
if ((m_LoadedMap_offset_8px.x - 1) < 0) {
/* There is no more tiles to the left. */
//debug("data_offset.pos.x: %d", m_LoadedMap_data_offset.pos.x);
return -1;
}
m_LoadedMap_offset_8px.x -= 1;
break;
case DIRECT_UP:
if ((m_LoadedMap_offset_8px.y - 1) < 0) {
/* There is no more tiles to the top. */
//debug("data_offset.pos.y: %d", m_LoadedMap_data_offset.pos.y);
return -1;
}
m_LoadedMap_offset_8px.y -= 1;
break;
case DIRECT_RIGHT:
if ((m_LoadedMap_offset_8px.x + 1) > m_LoadedMap_bounds_8px.w) {
/* There is no more tiles to the right. */
//debug("data_offset.pos.x: %d", m_LoadedMap_data_offset.pos.x);
return -1;
}
m_LoadedMap_offset_8px.x += 1;
break;
case DIRECT_DOWN:
// higher or equal??
if ((m_LoadedMap_offset_8px.y + 1) > m_LoadedMap_bounds_8px.h) {
/* There is no more tiles to the bottom. */
//debug("data_offset.pos.y: %d", m_LoadedMap_data_offset.pos.y);
return -1;
}
m_LoadedMap_offset_8px.y += 1;
break;
default:
/* Unhandled direction. */
return -1;
break;
}
return 0;
}
/*************************************************************************************************/
void GameMapProcessor::move_map_32px(const int x, const int y)
{
for (int i = 0; i < x; ++i) {
for (int j = 0; j < TILE_8PX_IN_TILE_32PX; ++j) {
this->move_map_8px(1, 0);
}
}
for (int i = 0; i < y; ++i) {
for (int j = 0; j < TILE_8PX_IN_TILE_32PX; ++j) {
this->move_map_8px(0, 1);
}
}
}
/*************************************************************************************************/
int GameMapProcessor::check_static_collision_px(const int x, const int y)
{
const unsigned short x_index_32px = PIXEL_TO_TILE_32PX(x);
const unsigned short y_index_32px = PIXEL_TO_TILE_32PX(y);
const unsigned int coll_index = find_index (y_index_32px, x_index_32px, m_LoadedMap->m_SizeTile_32px.w);
for (unsigned int layer = 0; layer < m_LoadedMap->m_LayersCount; ++layer) {
//debug("Move to %d,%d; is %s", x, y, (m_LoadedMap->m_CollisionMap[0][coll_index])? "blocked":"free");
if (m_LoadedMap->m_CollisionMap[layer][coll_index] != 0) {
return 1;
}
}
return 0;
}
/*************************************************************************************************/
/* x,y x1,y
* +-----+
* | |
* | |
* +-----+
* x,y1 x1,y1
*/
bool GameMapProcessor::check_static_collision(st_rect& rect_elem)
{
const unsigned int x = rect_elem.pos.x;
const unsigned int y = rect_elem.pos.y;
const unsigned int x1 = rect_elem.pos.x + rect_elem.w;
const unsigned int y1 = rect_elem.pos.y + rect_elem.h;
if (this->check_static_collision_px(x, y)) {
return true;
}
else if (this->check_static_collision_px(x1, y)) {
return true;
}
else if (this->check_static_collision_px(x, y1)) {
return true;
}
else if (this->check_static_collision_px(x1, y1)) {
return true;
}
return false;
}
/*************************************************************************************************/
void GameMapProcessor::update(void)
{
this->draw_LoadedMap();
}
/*************************************************************************************************/
/* Private Functions Declaration */
/*************************************************************************************************/
void GameMapProcessor::draw_LoadedMap(void)
{
// What layer to show: layer 3 (false) or layer 4 (true).
static bool draw_animated = false;
// static bool switch_layer = false;
unsigned int i;
u16* screen_mem = NULL;
this->update_animated_layer_cooldown();
for (i = 0; i < m_LoadedMap->m_LayersCount; ++i) {
// After drawing base layer and objects layer, draw animated layers.
if (i > 1) {
if (i > 2) {
/* Only support one animated layer (so far). */
break;
}
if (get_animated_layer_cooldown() <= 0) {
/* Reset cooldown. */
set_animated_layer_cooldown(ANIMATED_LAYER_COOLDOWN);
/* Switch display. */
draw_animated = (draw_animated)? false : true;
}
if (draw_animated == false) {
bgHide(m_LoadedMap->m_Background[i].id);
break;
}
else {
bgShow(m_LoadedMap->m_Background[i].id);
}
}
screen_mem = (u16*)bgGetMapPtr(m_LoadedMap->m_Background[i].id);
draw_LayerQuarter(FIRST_QUARTER, m_LoadedMap->m_Background[i].data, screen_mem);
// TODO: support more sizes.
if (m_LoadedMap->m_Background[i].size != BgSize_T_512x512) {
continue;
}
draw_LayerQuarter(SECOND_QUARTER, m_LoadedMap->m_Background[i].data, screen_mem);
draw_LayerQuarter(THIRD_QUARTER, m_LoadedMap->m_Background[i].data, screen_mem);
draw_LayerQuarter(FOURTH_QUARTER, m_LoadedMap->m_Background[i].data, screen_mem);
}
}
/*************************************************************************************************/
void GameMapProcessor::draw_LayerQuarter(
const en_screen_quarter screen_quarter,
const unsigned short *origin,
u16 *dest)
{
const unsigned int map_width = m_LoadedMap->m_SizeTile_8px.w;
const unsigned int mem_to_copy = TILES_TO_CP*TILE_LEN_BYTES;
const unsigned int map_data_offset = m_LoadedMap_offset_8px.x +
m_LoadedMap_offset_8px.y*m_LoadedMap->m_SizeTile_8px.w;
int origin_offset = 0;
int dest_offset = 0;
int origin_quarter_offset = 0;
int dest_quarter_offset = 0;
int origin_vertical_offset = 0;
int dest_vertical_offset = 0;
switch (screen_quarter) {
case FIRST_QUARTER:
break;
case SECOND_QUARTER:
// TODO: Find out why these values.
origin_quarter_offset = 32;
dest_quarter_offset = 128*8; // offset to the left size of the screen (128*8 tiles).
break;
case FOURTH_QUARTER:
origin_quarter_offset = 32;
dest_quarter_offset = 128*8;
case THIRD_QUARTER:
origin_vertical_offset = VERTICAL_OFFSET;
dest_vertical_offset = VERTICAL_OFFSET*VERTICAL_OFFSET*TILE_LEN_BYTES;
break;
default:
debug("Invalid quarter received.");
break;
}
for(int iy = 0; iy < 32; iy++) {
origin_offset = ((origin_vertical_offset + iy) * map_width) + origin_quarter_offset + map_data_offset;
dest_offset = (iy * TILES_TO_CP) + dest_quarter_offset + dest_vertical_offset;
dmaCopy(origin + origin_offset, dest + dest_offset, mem_to_copy);
}
}
| [
"vitor.rozsa@hotmail.com"
] | vitor.rozsa@hotmail.com |
832f951db95c208e65bcd866b41455d829f127e0 | 930a3dcf5fe78c782e30ed9cbeea2c29a814f886 | /X8servo.cpp | 95004dcf46fa314c04cff3c9b6dfe67794375402 | [] | no_license | rasheeddo/mbed-X8servo | 66bf3a80235b8edd29e041e1c66c619c2a3c1e26 | 74f3cc2d43f290e0dbab0e7f2b197411a6e3f8aa | refs/heads/master | 2020-10-01T17:55:02.883690 | 2019-12-30T04:51:27 | 2019-12-30T04:51:27 | 227,592,209 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,532 | cpp | #include "mbed.h"
#include "X8servo.hpp"
#include "rtos.h"
CAN can1(PB_8,PB_9); // RD then TD (PD_0,PD_1)
Serial pc(USBTX, USBRX,115200);
X8servo::X8servo(){
can1.frequency(1000000);
}
void X8servo::Int16ToByteData(unsigned int Data, unsigned char StoreByte[2]){
StoreByte[0] = (Data & 0xFF00) >> 8;
StoreByte[1] = (Data & 0x00FF);
}
void X8servo::Int32ToByteData(unsigned int Data, unsigned char StoreByte[4]){
StoreByte[0] = (Data & 0xFF000000) >> 24;
StoreByte[1] = (Data & 0x00FF0000) >> 16;
StoreByte[2] = (Data & 0x0000FF00) >> 8;
StoreByte[3] = (Data & 0x000000FF);
}
uint16_t X8servo::ByteDataToInt16(unsigned char ByteData[2]){
uint16_t IntData;
IntData = (ByteData[0] & 0xFF) | ((ByteData[1] & 0xFF) << 8);
return IntData;
}
int64_t X8servo::ByteDataToInt64(unsigned char ByteData[8]){
int64_t IntData;
IntData = (ByteData[1] & 0xFF) | ((ByteData[2] & 0xFF) << 8) | ((ByteData[3] & 0xFF) << 16) | ((ByteData[4] & 0xFF) << 24) | ((ByteData[5] & 0xFF) << 32) | ((ByteData[6] & 0xFF) << 40) | ((ByteData[7] & 0xFF) << 48) ;
return IntData;
}
long X8servo::map(long x, long in_min, long in_max, long out_min, long out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
void X8servo::CANErrorCheck(){
// If there is an error of tx or rx caused by overflow ( still don't know where there is overflow...)
// the servo will move for a while then stop forever even we keep sending command
if (can1.rderror() || can1.tderror()){
pc.printf("rderror: %d\n", can1.rderror());
pc.printf("tderror: %d\n", can1.tderror());
//can1.reset();
}
}
void X8servo::canWrite(unsigned int _ID, char data[8]){
int i;
// create a CANMessage object
CANMessage sendMsg = CANMessage(_ID, data, 8, CANData, CANStandard);
// keep sending it until there is nothing to send
do{
i = can1.write(sendMsg);
}
while(!i);
//wait_us(100);
}
void X8servo::readReplyFlush(unsigned int _ID){
pc.printf("readReplyFlush\n");
CANMessage replyMsg;
while (can1.read(replyMsg)){
/*
pc.printf("ID: %d\n", (replyMsg.id-320));
pc.printf("data[0]: %X\n", replyMsg.data[0]);
pc.printf("data[1]: %X\n", replyMsg.data[1]);
pc.printf("data[2]: %X\n", replyMsg.data[2]);
pc.printf("data[3]: %X\n", replyMsg.data[3]);
pc.printf("data[4]: %X\n", replyMsg.data[4]);
pc.printf("data[5]: %X\n", replyMsg.data[5]);
pc.printf("data[6]: %X\n", replyMsg.data[6]);
pc.printf("data[7]: %X\n", replyMsg.data[7]);
*/
}
}
bool X8servo::readReply(unsigned int _ID, unsigned char output[8]){
pc.printf("readReply\n");
CANMessage replyMsg;
bool readOK = false;
while (can1.read(replyMsg)){
/*
pc.printf("ID: %d\n", (replyMsg.id-320));
pc.printf("data[0]: %X\n", replyMsg.data[0]);
pc.printf("data[1]: %X\n", replyMsg.data[1]);
pc.printf("data[2]: %X\n", replyMsg.data[2]);
pc.printf("data[3]: %X\n", replyMsg.data[3]);
pc.printf("data[4]: %X\n", replyMsg.data[4]);
pc.printf("data[5]: %X\n", replyMsg.data[5]);
pc.printf("data[6]: %X\n", replyMsg.data[6]);
pc.printf("data[7]: %X\n", replyMsg.data[7]);
*/
output[0] = replyMsg.data[0];
output[1] = replyMsg.data[1];
output[2] = replyMsg.data[2];
output[3] = replyMsg.data[3];
output[4] = replyMsg.data[4];
output[5] = replyMsg.data[5];
output[6] = replyMsg.data[6];
output[7] = replyMsg.data[7];
readOK = true;
}
return readOK;
}
int64_t X8servo::ReadMultiturn(unsigned int _ID){
uint64_t startTime = rtos::Kernel::get_ms_count();
pc.printf("ReadMultiturn\n");
unsigned char reply[8];
int64_t output;
char CommandByte[8] = {0x92, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
canWrite(_ID, CommandByte);
if(readReply(_ID, reply)){
output = ByteDataToInt64(reply);
output = (output/(100*gearRatio)); // 0.01 deg/LSB
}
else{
output = NULL;
pc.printf("unable to read output\n");
}
pc.printf("output: %lld\n", output);
CANErrorCheck();
uint64_t stopTime = rtos::Kernel::get_ms_count();
uint64_t period_ms = stopTime - startTime;
pc.printf("Time Used %f ms\n", (float)period_ms);
return output;
}
void X8servo::ReadMotorStatusError(unsigned int _ID){
pc.printf("ReadMultiturn\n");
unsigned char reply[8];
unsigned char voltByte[2];
unsigned char tempByte;
float output_volt;
uint8_t output_temp;
char CommandByte[8] = {0x9A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
canWrite(_ID, CommandByte);
if (readReply(_ID, reply)){
tempByte = reply[1];
voltByte[0] = reply[3];
voltByte[1] = reply[4];
output_volt = ByteDataToInt16(voltByte)*0.1;
output_temp = (int)tempByte;
pc.printf("voltage: %f\n", output_volt);
pc.printf("temperature: %d\n", output_temp);
}
CANErrorCheck();
if ((int)reply[7] > 0){
switch ((int)reply[7]){
case 1 :
pc.printf("Low voltage protection error\n");
break;
case 8 :
pc.printf("Over temperature protection error\n");
break;
case 9 :
pc.printf("Low voltage and Over temp error\n");
break;
}
}
}
void X8servo::ReadEncoderData(unsigned int _ID){
pc.printf("ReadEncoderData\n");
unsigned char reply[8];
unsigned char EncoderPosByte[2];
unsigned char EncoderOriByte[2];
unsigned char EncoderOffByte[2];
char CommandByte[8] = {0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
canWrite(_ID, CommandByte);
if (readReply(_ID, reply)){
EncoderPosByte[0] = reply[2];
EncoderPosByte[1] = reply[3];
EncoderOriByte[0] = reply[4];
EncoderOriByte[1] = reply[5];
EncoderOffByte[0] = reply[6];
EncoderOffByte[1] = reply[7];
EncoderPosition[_ID-320-1] = ByteDataToInt16(EncoderPosByte);
EncoderOriginal[_ID-320-1] = ByteDataToInt16(EncoderOriByte);
EncoderOffset[_ID-320-1] = ByteDataToInt16(EncoderOffByte);
}
CANErrorCheck();
}
void X8servo::WriteEncoderOffset(unsigned int _ID, uint16_t offset){
pc.printf("WriteEncoderOffset\n");
unsigned char offsetByte[2];
Int16ToByteData(offset, offsetByte);
char CommandByte[8] = {0x91, 0x00, 0x00, 0x00, 0x00, 0x00, offsetByte[1], offsetByte[0]};
canWrite(_ID, CommandByte);
readReplyFlush(_ID);
CANErrorCheck();
}
void X8servo::MotorOff(unsigned int _ID){
pc.printf("MotorOff\n");
char CommandByte[8] = {0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
canWrite(_ID, CommandByte);
readReplyFlush(_ID);
CANErrorCheck();
}
void X8servo::MotorStop(unsigned int _ID){
pc.printf("MotorStop\n");
char CommandByte[8] = {0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
canWrite(_ID, CommandByte);
readReplyFlush(_ID);
CANErrorCheck();
}
void X8servo::MotorRun(unsigned int _ID){
pc.printf("MotorRun\n");
char CommandByte[8] = {0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
canWrite(_ID, CommandByte);
readReplyFlush(_ID);
CANErrorCheck();
}
void X8servo::SpeedControl(unsigned int _ID, float DPS){
pc.printf("SpeedControl\n");
pc.printf("DPS %f\n", DPS);
float SpeedLSB = DPS*100*gearRatio;
unsigned char SpeedByte[4];
char CommandSpeedByte[8];
Int32ToByteData((int)SpeedLSB, SpeedByte);
CommandSpeedByte[0] = 0xA2;
CommandSpeedByte[1] = 0x00;
CommandSpeedByte[2] = 0x00;
CommandSpeedByte[3] = 0x00;
CommandSpeedByte[4] = SpeedByte[3];
CommandSpeedByte[5] = SpeedByte[2];
CommandSpeedByte[6] = SpeedByte[1];
CommandSpeedByte[7] = SpeedByte[0];
canWrite(_ID, CommandSpeedByte);
// the servo will reply everytime we send command to it
// readReplyFlush seem like to eliminate the tderror and rderror after sending command
readReplyFlush(_ID);
CANErrorCheck();
}
void X8servo::PositionControl1(unsigned int _ID, float Deg){
float DegLSB = Deg*100*gearRatio;
unsigned char PositionByte[4];
char CommandPosition1Byte[8];
Int32ToByteData((int)DegLSB, PositionByte);
CommandPosition1Byte[0] = 0xA3;
CommandPosition1Byte[1] = 0x00;
CommandPosition1Byte[2] = 0x00;
CommandPosition1Byte[3] = 0x00;
CommandPosition1Byte[4] = PositionByte[3];
CommandPosition1Byte[5] = PositionByte[2];
CommandPosition1Byte[6] = PositionByte[1];
CommandPosition1Byte[7] = PositionByte[0];
canWrite(_ID, CommandPosition1Byte);
// the servo will reply everytime we send command to it
// readReplyFlush seem like to eliminate the tderror and rderror after sending command
readReplyFlush(_ID);
CANErrorCheck();
}
void X8servo::PositionControl2(unsigned int _ID, float Deg, float DPS){
//uint64_t startTime = rtos::Kernel::get_ms_count();
pc.printf("PositionControl2\n");
pc.printf("Target Output Deg %f and DPS %f\n", Deg, DPS);
float DegLSB = Deg*100*gearRatio;
float SpeedLSB = DPS*gearRatio;
unsigned char PositionByte[4];
unsigned char SpeedByte[2];
Int32ToByteData((int)DegLSB, PositionByte);
Int16ToByteData((int)SpeedLSB, SpeedByte); // This two conversion functions takes 5ms most of the time
char CommandPosition2Byte[8];
CommandPosition2Byte[0] = 0xA4;
CommandPosition2Byte[1] = 0x00;
CommandPosition2Byte[2] = SpeedByte[1];
CommandPosition2Byte[3] = SpeedByte[0];
CommandPosition2Byte[4] = PositionByte[3];
CommandPosition2Byte[5] = PositionByte[2];
CommandPosition2Byte[6] = PositionByte[1];
CommandPosition2Byte[7] = PositionByte[0];
// until here use 5ms
canWrite(_ID, CommandPosition2Byte); // write and read function is super fast totally just 2ms
// until here still 5ms
// the servo will reply everytime we send command to it
// readReplyFlush seem like to eliminate the tderror and rderror after sending command
readReplyFlush(_ID); // if there is printf it will take 15ms if no printf it's 7ms
CANErrorCheck(); //
//uint64_t stopTime = rtos::Kernel::get_ms_count();
//uint64_t period_ms = stopTime - startTime;
//pc.printf("Time Used %f ms\n", (float)period_ms);
}
void X8servo::PositionControl3(unsigned int _ID, float Deg, unsigned char Direction){
// This mode 3 still doesn't work I don't know what happend...
pc.printf("PositionControl3\n");
pc.printf("Target Output Deg %f and Turn %X\n", Deg, Direction);
float DegLSB = Deg*100*gearRatio;
unsigned char PositionByte[2];
Int16ToByteData((int)DegLSB, PositionByte);
char CommandPosition3Byte[8];
CommandPosition3Byte[0] = 0xA5;
CommandPosition3Byte[1] = Direction;
CommandPosition3Byte[2] = 0x00;
CommandPosition3Byte[3] = 0x00;
CommandPosition3Byte[4] = PositionByte[1];
CommandPosition3Byte[5] = PositionByte[0];
CommandPosition3Byte[6] = 0x00;
CommandPosition3Byte[7] = 0x00;
canWrite(_ID, CommandPosition3Byte);
// the servo will reply everytime we send command to it
// readReplyFlush seem like to eliminate the tderror and rderror after sending command
readReplyFlush(_ID);
CANErrorCheck();
}
void X8servo::PositionControl4(unsigned int _ID, float Deg, float DPS, unsigned char Direction){
pc.printf("PositionControl4\n");
pc.printf("Target Output Deg %f and DPS %f and Direction %d\n", Deg, DPS, Direction);
float DegLSB = Deg*100*gearRatio;
float SpeedLSB = DPS*gearRatio;;
unsigned char PositionByte[2];
unsigned char SpeedByte[2];
Int16ToByteData((int)DegLSB, PositionByte);
Int16ToByteData((int)SpeedLSB, SpeedByte);
char CommandPosition4Byte[8];
CommandPosition4Byte[0] = 0xA6;
CommandPosition4Byte[1] = Direction;
CommandPosition4Byte[2] = SpeedByte[1];
CommandPosition4Byte[3] = SpeedByte[0];
CommandPosition4Byte[4] = PositionByte[1];
CommandPosition4Byte[5] = PositionByte[0];
CommandPosition4Byte[6] = 0x00;
CommandPosition4Byte[7] = 0x00;
canWrite(_ID, CommandPosition4Byte);
// the servo will reply everytime we send command to it
// readReplyFlush seem like to eliminate the tderror and rderror after sending command
readReplyFlush(_ID);
CANErrorCheck();
}
| [
"rasheedo.kit@gmail.com"
] | rasheedo.kit@gmail.com |
a1dee8a2d1b07340e6a4f2e475dd6afae16bcb4d | 3bcc62d2db138b6087072e0978b5e8ca71a0d13f | /PiratesEngine/src/Platform/OpenGl/OpenGLContext.cpp | d04185e89e6dd9b0c9e442d2f6e2d69cefd76945 | [
"MIT"
] | permissive | michaelzaki-12/PiratesEngine | 4ec7bd6ecec2d0e473f82c52c6fd0d68cc7566f0 | 69e875eb2d21350c499245316351552bc217cbcb | refs/heads/main | 2023-06-16T05:07:47.907954 | 2021-07-12T23:38:10 | 2021-07-12T23:38:10 | 385,247,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 719 | cpp | #include "PEPCH.h"
#include "OpenGLContext.h"
#include <GLFW/glfw3.h>
#include "glad/glad.h"
namespace Pirates
{
OpenGLContext::OpenGLContext(GLFWwindow* windowhandle) : m_WindowHandle(windowhandle)
{
PR_CORE_ASSERT(m_WindowHandle, "WindowHandle is not assert");
}
void OpenGLContext::Init()
{
PR_PROFILE_FUNCTION();
glfwMakeContextCurrent(m_WindowHandle);
int status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
PR_CORE_ASSERT(status, "Failed to initize glad";)
PR_CORE_INFO(glGetString(GL_VENDOR));
PR_CORE_INFO(glGetString(GL_RENDERER));
PR_CORE_INFO(glGetString(GL_VERSION));
}
void OpenGLContext::SwapBuffers()
{
PR_PROFILE_FUNCTION();
glfwSwapBuffers(m_WindowHandle);
}
} | [
"miki44512@gmail.com"
] | miki44512@gmail.com |
6a3167e96fabd88d7f40b6f9164a0def79c9efe2 | f54f058d973efd641cd65b84715b27eec2a6cba7 | /DemoDirectX/FrameWork/GameObjects/Enemies/Guard_1st/Guard1Data.h | 6e385adb38afb45accdb322d3a441841bbf77b49 | [] | no_license | nganle97/Aladdin | bd9cb355e23b2fb9add8442bd5758b9a5912fa73 | 1c64eb701525dd751820c586acd0e6eaeb8f7278 | refs/heads/master | 2020-09-05T17:05:50.553274 | 2019-11-07T06:16:11 | 2019-11-07T06:16:11 | 220,164,396 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 178 | h | #pragma once
//pre define
class Guard1State;
class Guard1;
class Guard1Data
{
public:
Guard1Data();
~Guard1Data();
Guard1 *guard1;
Guard1State *state;
protected:
};
| [
"lephutrongngan@gmail.com"
] | lephutrongngan@gmail.com |
94134a0747fd0b485b845e251c9a3a8878c11907 | 1570b52233e06aa7a3efc5a0260ab7ad69889157 | /DaedalicTestAutomationPlugin/Source/DaedalicTestAutomationPlugin/Public/DaeDelayFramesAction.h | 8a1ca5ee6789864f48c9745fa66cedcaa948e9ca | [
"MIT"
] | permissive | risooonho/ue4-test-automation | b17881d43e10be9412c3837c330b8465c7638e38 | 854689824cbb002facbc143e82d2b7124255c11e | refs/heads/master | 2022-11-06T21:00:38.157682 | 2020-05-19T11:35:27 | 2020-05-19T11:35:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 584 | h | #pragma once
#include <CoreMinimal.h>
#include <LatentActions.h>
/** Triggers the output link after the specified number of frames. */
class DAEDALICTESTAUTOMATIONPLUGIN_API FDaeDelayFramesAction : public FPendingLatentAction
{
public:
int32 FramesRemaining;
FName ExecutionFunction;
int32 OutputLink;
FWeakObjectPtr CallbackTarget;
FDaeDelayFramesAction(const FLatentActionInfo& LatentInfo, int32 NumFrames);
virtual void UpdateOperation(FLatentResponse& Response) override;
#if WITH_EDITOR
virtual FString GetDescription() const override;
#endif
};
| [
"dev@npruehs.de"
] | dev@npruehs.de |
02f3e7dc91cf34a227dc2eff7fe7790716896787 | e83017bd962c2264718b7878458c2b1b5e6c0a06 | /NMSELauncher/main.cpp | 75a2e1f03e136490ed9d5a23633f068361c14c32 | [] | no_license | Raided/NMSExtender | d170282a7a707bd70df2711b7694426220a25f01 | 303b92cc5422eba6e0779240a18c7acf3ea866fb | refs/heads/master | 2020-12-11T04:19:58.674336 | 2016-08-20T11:36:27 | 2016-08-20T11:36:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,108 | cpp | #include "NMSE_Libs\Hooking.h"
#include "NMSE_Libs\Steam.h"
#include "NMSE_Libs\VersionControl.h"
// Have to give large credit to the F4SE/SKSE/OBSE etc.. crew. This first pre-alpha is VERY LARGELY based off their SE's.
#define DEBUG 0
//275850 -- game id
int main(int argc, char* argv) {
const char* dllName = "NMSE Core.dll";
std::string prgmName = "NMS.exe";
std::string curPath = RunTimePath();
std::cout << "Using runtime: " << curPath << "\n";
bool steam;
if (SteamVersion(curPath)){
steam = true;
std::cout << "Using Steam Version\n";
if (!CheckSteam()) {
std::cout << "Steam not open... Launching\n";
LaunchSteam();
}
}
else{
steam = false;
std::cout << "Using GOG Version\n";
}
std::cout << "Starting NMS\n";
std::string exe = curPath + "\\" + prgmName;
//ValidateVersion(exe); -- waiting for VC implementation on HG's side :\
if (steam){
const char* nmsId = "275850";
SetEnvironmentVariable("SteamGameId", nmsId);
SetEnvironmentVariable("SteamAppID", nmsId);
}
STARTUPINFO startup = { 0 };
PROCESS_INFORMATION nmsProc = { 0 };
if (!CreateProcess(exe.c_str(), NULL, NULL, NULL, false,
CREATE_SUSPENDED, NULL, NULL, &startup, &nmsProc)) {
std::cout << "Failed to start NMS: " << GetLastError() << std::endl;
std::cout << "If 740 please try running as Admin\n";
}
#if DEBUG
std::cout << "HOOK BASE: " << std::hex << GetModuleHandle(NULL) << std::endl;
MessageBox(0, "APP SUSPENDED, HOOK AND PRESS OK", "CUSTOM NMSE", MB_OK | MB_ICONWARNING);
#endif
//inject the dll via the steam dll
std::string NMSEsteam = curPath + "\\NMSE_steam.dll";
bool isInjected = InjectDLLThread(&nmsProc, NMSEsteam.c_str(), true, false);
if (isInjected) {
std::cout << "Loader injected...\n";
}
else {
std::cout << "Loader Injection Failed\n";
}
if (!ResumeThread(nmsProc.hThread)) {
std::cout << "Thread resume failed.\n";
}
std::cout << "\nProgram Injected Everything Succesfully!\n";
std::cout << "Please wait for this to close before worrying :)\n";
CloseHandle(nmsProc.hProcess);
CloseHandle(nmsProc.hThread);
Sleep(10000);
return 0;
}
| [
"graetgandalf@aol.com"
] | graetgandalf@aol.com |
515c54eb358cd20bc8337665396c4e763ed98845 | d814c03e642ef1f081285f0d2e94f1e213dfc7c2 | /partners_api/partners_api_tests/viator_tests.cpp | ffd1fb53931402c1c346bfaa7aa8e9a752720223 | [
"Apache-2.0"
] | permissive | hatimmakki/omim | b39ad2737d9c8f32f0ed4c8ee9ce2193ca51ae7c | 60bcecc07be59bf1920c1164a15a3f4da51c0a42 | refs/heads/master | 2021-01-21T23:09:17.950900 | 2017-06-22T16:39:03 | 2017-06-22T16:45:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,353 | cpp | #include "testing/testing.hpp"
#include "partners_api/viator_api.hpp"
#include <algorithm>
#include <random>
#include <sstream>
#include <vector>
#include "3party/jansson/myjansson.hpp"
namespace
{
UNIT_TEST(Viator_GetTopProducts)
{
string result;
viator::RawApi::GetTopProducts("684", "USD", 5, result);
TEST(!result.empty(), ());
my::Json root(result.c_str());
bool success;
FromJSONObjectOptionalField(root.get(), "success", success, false);
TEST(success, ());
}
UNIT_TEST(Viator_GetTop5Products)
{
viator::Api api;
std::string const kSofia = "5630";
std::string resultId;
std::vector<viator::Product> resultProducts;
api.GetTop5Products(kSofia, "",
[&resultId, &resultProducts](std::string const & destId,
std::vector<viator::Product> const & products) {
resultId = destId;
resultProducts = products;
testing::StopEventLoop();
});
testing::RunEventLoop();
TEST_EQUAL(resultId, kSofia, ());
TEST(!resultProducts.empty(), ());
}
UNIT_TEST(Viator_SortProducts)
{
std::vector<viator::Product> products =
{
{"1", 10.0, 10, "", 10.0, "", "", "", ""},
{"2", 9.0, 100, "", 200.0, "", "", "", ""},
{"3", 9.0, 100, "", 100.0, "", "", "", ""},
{"4", 9.0, 10, "", 200.0, "", "", "", ""},
{"5", 9.0, 9, "", 300.0, "", "", "", ""},
{"6", 8.0, 200, "", 400.0, "", "", "", ""},
{"7", 7.0, 20, "", 200.0, "", "", "", ""},
{"8", 7.0, 20, "", 1.0, "", "", "", ""},
{"9", 7.0, 0, "", 300.0, "", "", "", ""},
{"10", 7.0, 0, "", 1.0, "", "", "", ""}
};
for (size_t i = 0; i < 1000; ++i)
{
std::shuffle(products.begin(), products.end(), std::minstd_rand(std::minstd_rand::default_seed));
viator::SortProducts(products);
TEST_EQUAL(products[0].m_title, "1", ());
TEST_EQUAL(products[1].m_title, "2", ());
TEST_EQUAL(products[2].m_title, "3", ());
TEST_EQUAL(products[3].m_title, "4", ());
TEST_EQUAL(products[4].m_title, "5", ());
TEST_EQUAL(products[5].m_title, "6", ());
TEST_EQUAL(products[6].m_title, "7", ());
TEST_EQUAL(products[7].m_title, "8", ());
TEST_EQUAL(products[8].m_title, "9", ());
TEST_EQUAL(products[9].m_title, "10", ());
}
}
} // namespace
| [
"milcars@mapswithme.com"
] | milcars@mapswithme.com |
b92aeef92e27c1d154a328759931558352965149 | f732cf220b6976aafb8bde460174bfa41f68267b | /Base/base_version.cpp | dc5cdb69be313f23bba8a6bd28a81356efec7d65 | [] | no_license | WorkerBeesTeam/Helpz | 5195ddd780053efcca28d348c0e01604628a5a7b | 4f916bb8836d5c4472e5c4f389d80048ddd9b5e0 | refs/heads/master | 2021-10-15T13:26:40.350238 | 2020-08-17T17:38:36 | 2020-08-17T17:38:36 | 147,148,813 | 0 | 0 | null | 2019-11-21T05:27:34 | 2018-09-03T03:51:13 | C++ | UTF-8 | C++ | false | false | 307 | cpp | #include "base_version.h"
#define STR(x) #x
namespace Helpz {
namespace Base {
quint8 ver_major() { return VER_MJ; }
quint8 ver_minor() { return VER_MN; }
int ver_build() { return VER_B; }
QString ver_str() { return STR(VER_MJ) "." STR(VER_MN) "." STR(VER_B); }
} // namespace Base
} // namespace Helpz
| [
"kirill@zimnikov.ru"
] | kirill@zimnikov.ru |
47d00529fa21831ffd2963541fc77da8acc04054 | 37b9c5651016dd0afd7009542dfd21f7f7abd5ef | /loan.cc | 2afaec1c3729d9d7210230a7429641921b96f205 | [] | no_license | tbchhetri/cppProjects | 9b824a83a455f16c5caaef0bf2dbc65a5d295f89 | f2b534c39dfd4666b8ddba21057dd9123e822b57 | refs/heads/master | 2023-04-03T12:03:32.437333 | 2021-04-13T01:05:59 | 2021-04-13T01:05:59 | 357,378,035 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 773 | cc | #include <iostream>
#include <cmath>
#include <iomanip> // Used for sigfig
using namespace std;
int main () {
// step 0: variables
int
n; //number of payments
double
r, //interest rate
apr, //annual interest rate
pv, //principal rate
pmt; //payment per period
// step 1: inpput values for pv, r and n
cout << "Enter amount of loan (dollars): ";
cin >> pv;
cout << "Enter the annual interest rate (3.75% = 0.0375): ";
cin >> apr;
cout << "Enter number of payments (months): ";
cin >> n;
// step 1.5: convert apt to mpr
r = apr/12;
// step 2: calculate
pmt = r * pv / (1.0 - pow(1.0+r,-n));
//step 3: output payment amount
cout << fixed << setprecision(2);
cout << "Payment is $" <<pmt<< endl;
// all done!
return 0;
}
| [
"saagarchhetri02@gmail.com"
] | saagarchhetri02@gmail.com |
cb3b80c0a62b0466645c97a9ed2527cc43943436 | 58a0ba5ee99ec7a0bba36748ba96a557eb798023 | /Olympiad Solutions/URI/2461.cpp | 5fb46133303b4905b7701f365df18179240fd8bf | [
"MIT"
] | permissive | adityanjr/code-DS-ALGO | 5bdd503fb5f70d459c8e9b8e58690f9da159dd53 | 1c104c33d2f56fe671d586b702528a559925f875 | refs/heads/master | 2022-10-22T21:22:09.640237 | 2022-10-18T15:38:46 | 2022-10-18T15:38:46 | 217,567,198 | 40 | 54 | MIT | 2022-10-18T15:38:47 | 2019-10-25T15:50:28 | C++ | UTF-8 | C++ | false | false | 748 | cpp | // Ivan Carvalho
// Solution to https://www.urionlinejudge.com.br/judge/problems/view/2461
#include <cstdio>
#include <set>
using namespace std;
int main(){
set<int> conjuntoa,conjuntob;
set<int>::iterator it;
int a,b;
scanf("%d %d",&a,&b);
for(int i=0;i<a;i++){
int davez;
scanf("%d",&davez);
conjuntoa.insert(davez);
}
for(int i=0;i<b;i++){
int davez;
scanf("%d",&davez);
if (conjuntoa.count(davez)){
conjuntob.insert(davez);
continue;
}
bool verdade = true;
for(it = conjuntob.begin();it!=conjuntob.end();it++){
if (conjuntob.count(davez - *it)){
conjuntob.insert(davez);
verdade = false;
break;
}
}
if (verdade) {
printf("%d\n",davez);
return 0;
}
}
printf("sim\n");
return 0;
}
| [
"samant04aditya@gmail.com"
] | samant04aditya@gmail.com |
2f37329f723a673b135a1eb2f690b96166c5ad18 | 35df86a47ae92bf748c7fc1d6bb6ee21de8d11e9 | /hw5/hw5q5.h | 641ae222e723d568cf2c662138de52c429a51361 | [] | no_license | dhdan97/csc-21200 | 920319a0dc0e166273b7445caf359a10cd7dfd92 | d2de266f7012bfa2b57f0429662a3167cb251dbf | refs/heads/master | 2020-04-19T13:42:19.958139 | 2019-08-20T18:57:37 | 2019-08-20T18:57:37 | 168,224,110 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,115 | h | #ifndef __HEAP_H__
#define __HEAP_H__
// Previous two lines are the start of the marco guard
// CSc 21200 - Spring 2019
// Homework 5 header file
// Try not to change this file
#include <iostream>
#include <cstdlib>
#include <cassert>
#include <climits>
#include <cmath>
using namespace std;
template <class Item>
class Heap
{
public:
const size_t DEF_CAP = 30;
// CONSTRUCTOR
Heap();
size_t getCount() {return count;}
// MODIFICATION MEMBER FUNCTIONS
void insert(const Item& entry) {
data[count] = INT_MIN;
count++;
increaseKey(count-1, entry);
}
void increaseKey(size_t i, const Item& entry);
Item removeMax();
void maxHeapify(const size_t& i);
void buildMaxHeap();
Item* heapsort();
Item minimum();
Item maximum();
private:
Item* data;
size_t count;
size_t capacity;
size_t parent(const size_t i) {return floor((i-1)/2);}
size_t left (const size_t i) {return 2*i+1;}
size_t right (const size_t i) {return 2*i+2;}
};
template <class Item>
void swap(Item& x, Item& y) {
Item temp = x;
x = y;
y = temp;
}
#endif | [
"dhdan97@gmail.com"
] | dhdan97@gmail.com |
d56621133fe5e34bc24db4b5a810c5e675ca3fa6 | 087c5da0807c2757cb1e677ce73d6d51c22dd96d | /Tools/graphchi-cpp-master/src/engine/graphchi_engine.hpp | 682e35a1cb943996b09a08530d023c0101601af5 | [
"Apache-2.0"
] | permissive | prateekmehta/SocialLDA | 606449c083a3b4a3dbadad106179a092e61bc8e2 | c8c0c00479992078d07826f6efd432f2930e5fd1 | refs/heads/master | 2020-05-19T15:37:26.003793 | 2014-04-17T21:47:30 | 2014-04-17T21:47:30 | 18,464,333 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 48,809 | hpp | /**
* @file
* @author Aapo Kyrola <akyrola@cs.cmu.edu>
* @version 1.0
*
* @section LICENSE
*
* Copyright [2012] [Aapo Kyrola, Guy Blelloch, Carlos Guestrin / Carnegie Mellon University]
*
* 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.
*
* @section DESCRIPTION
*
* The basic GraphChi engine.
*/
#ifndef DEF_GRAPHCHI_GRAPHCHI_ENGINE
#define DEF_GRAPHCHI_GRAPHCHI_ENGINE
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdio>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <omp.h>
#include <vector>
#include <sys/time.h>
#include "api/chifilenames.hpp"
#include "api/graph_objects.hpp"
#include "api/graphchi_context.hpp"
#include "api/graphchi_program.hpp"
#include "engine/auxdata/degree_data.hpp"
#include "engine/auxdata/vertex_data.hpp"
#include "engine/bitset_scheduler.hpp"
#include "io/stripedio.hpp"
#include "logger/logger.hpp"
#include "metrics/metrics.hpp"
#include "shards/memoryshard.hpp"
#include "shards/slidingshard.hpp"
#include "util/pthread_tools.hpp"
#include "output/output.hpp"
namespace graphchi {
template <typename VertexDataType, typename EdgeDataType,
typename svertex_t = graphchi_vertex<VertexDataType, EdgeDataType> >
class graphchi_engine {
public:
typedef sliding_shard<VertexDataType, EdgeDataType, svertex_t> slidingshard_t;
typedef memory_shard<VertexDataType, EdgeDataType, svertex_t> memshard_t;
protected:
std::string base_filename;
int nshards;
/* IO manager */
stripedio * iomgr;
/* Shards */
std::vector<slidingshard_t *> sliding_shards;
memshard_t * memoryshard;
std::vector<std::pair<vid_t, vid_t> > intervals;
/* Auxilliary data handlers */
degree_data * degree_handler;
vertex_data_store<VertexDataType> * vertex_data_handler;
/* Computational context */
graphchi_context chicontext;
/* Scheduler */
bitset_scheduler * scheduler;
/* Configuration */
bool modifies_outedges;
bool modifies_inedges;
bool disable_outedges;
bool only_adjacency;
bool use_selective_scheduling;
bool enable_deterministic_parallelism;
bool store_inedges;
bool disable_vertexdata_storage;
bool randomization;
bool initialize_edges_before_run;
size_t blocksize;
int membudget_mb;
int load_threads;
int exec_threads;
/* State */
vid_t sub_interval_st;
vid_t sub_interval_en;
int iter;
int niters;
int exec_interval;
size_t nupdates;
size_t nedges;
size_t work; // work is the number of edges processed
unsigned int maxwindow;
mutex modification_lock;
bool reset_vertexdata;
bool save_edgesfiles_after_inmemmode;
/* Outputs */
std::vector<ioutput<VertexDataType, EdgeDataType> *> outputs;
/* Metrics */
metrics &m;
void print_config() {
logstream(LOG_INFO) << "Engine configuration: " << std::endl;
logstream(LOG_INFO) << " exec_threads = " << exec_threads << std::endl;
logstream(LOG_INFO) << " load_threads = " << load_threads << std::endl;
logstream(LOG_INFO) << " membudget_mb = " << membudget_mb << std::endl;
logstream(LOG_INFO) << " blocksize = " << blocksize << std::endl;
logstream(LOG_INFO) << " scheduler = " << use_selective_scheduling << std::endl;
}
public:
/**
* Initialize GraphChi engine
* @param base_filename prefix of the graph files
* @param nshards number of shards
* @param selective_scheduling if true, uses selective scheduling
*/
graphchi_engine(std::string _base_filename, int _nshards, bool _selective_scheduling, metrics &_m) : base_filename(_base_filename), nshards(_nshards), use_selective_scheduling(_selective_scheduling), m(_m) {
/* Initialize IO */
m.start_time("iomgr_init");
iomgr = new stripedio(m);
m.stop_time("iomgr_init");
#ifndef DYNAMICEDATA
logstream(LOG_INFO) << "Initializing graphchi_engine. This engine expects " << sizeof(EdgeDataType)
<< "-byte edge data. " << std::endl;
#else
logstream(LOG_INFO) << "Initializing graphchi_engine with dynamic edge-data. This engine expects " << sizeof(int)
<< "-byte edge data. " << std::endl;
#endif
/* If number of shards is unspecified - discover */
if (nshards < 1) {
nshards = get_option_int("nshards", 0);
if (nshards < 1) {
logstream(LOG_WARNING) << "Number of shards was not specified (command-line argument 'nshards'). Trying to detect. " << std::endl;
nshards = discover_shard_num();
}
}
/* Initialize a plenty of fields */
memoryshard = NULL;
modifies_outedges = true;
modifies_inedges = true;
save_edgesfiles_after_inmemmode = false;
only_adjacency = false;
disable_outedges = false;
reset_vertexdata = false;
initialize_edges_before_run = false;
blocksize = 1024 * 1024;
#ifndef DYNAMICEDATA
while (blocksize % sizeof(EdgeDataType) != 0) blocksize++;
#endif
disable_vertexdata_storage = false;
membudget_mb = get_option_int("membudget_mb", 1024);
nupdates = 0;
iter = 0;
work = 0;
nedges = 0;
scheduler = NULL;
store_inedges = true;
degree_handler = NULL;
vertex_data_handler = NULL;
enable_deterministic_parallelism = true;
load_threads = get_option_int("loadthreads", 2);
exec_threads = get_option_int("execthreads", omp_get_max_threads());
maxwindow = 40000000;
/* Load graph shard interval information */
_load_vertex_intervals();
_m.set("file", _base_filename);
_m.set("engine", "default");
_m.set("nshards", (size_t)nshards);
}
virtual ~graphchi_engine() {
if (degree_handler != NULL) delete degree_handler;
if (vertex_data_handler != NULL) delete vertex_data_handler;
if (memoryshard != NULL) {
delete memoryshard;
memoryshard = NULL;
}
for(int i=0; i < (int)sliding_shards.size(); i++) {
if (sliding_shards[i] != NULL) {
delete sliding_shards[i];
}
sliding_shards[i] = NULL;
}
degree_handler = NULL;
vertex_data_handler = NULL;
delete iomgr;
}
protected:
virtual degree_data * create_degree_handler() {
return new degree_data(base_filename, iomgr);
}
/**
* Try to find suitable shards by trying with different
* shard numbers. Looks up to shard number 2000.
*/
int discover_shard_num() {
#ifndef DYNAMICEDATA
int _nshards = find_shards<EdgeDataType>(base_filename);
#else
int _nshards = find_shards<int>(base_filename);
#endif
if (_nshards == 0) {
logstream(LOG_ERROR) << "Could not find suitable shards - maybe you need to run sharder to create them?" << std::endl;
logstream(LOG_ERROR) << "Was looking with filename [" << base_filename << "]" << std::endl;
logstream(LOG_ERROR) << "You need to create the shards with edge data-type of size " << sizeof(EdgeDataType) << " bytes." << std::endl;
logstream(LOG_ERROR) << "To specify the number of shards, use command-line parameter 'nshards'" << std::endl;
assert(0);
}
return _nshards;
}
virtual void initialize_sliding_shards() {
assert(sliding_shards.size() == 0);
for(int p=0; p < nshards; p++) {
#ifndef DYNAMICEDATA
std::string edata_filename = filename_shard_edata<EdgeDataType>(base_filename, p, nshards);
std::string adj_filename = filename_shard_adj(base_filename, p, nshards);
#else
std::string edata_filename = filename_shard_edata<int>(base_filename, p, nshards);
std::string adj_filename = filename_shard_adj(base_filename, p, nshards);
#endif
sliding_shards.push_back(
new slidingshard_t(iomgr, edata_filename,
adj_filename,
intervals[p].first,
intervals[p].second,
blocksize,
m,
!modifies_outedges,
only_adjacency));
if (!only_adjacency)
nedges += sliding_shards[sliding_shards.size() - 1]->num_edges();
}
}
virtual void initialize_scheduler() {
if (use_selective_scheduling) {
if (scheduler != NULL) delete scheduler;
scheduler = new bitset_scheduler((int) num_vertices());
scheduler->add_task_to_all();
} else {
scheduler = NULL;
}
}
/**
* If the data is only in one shard, we can just
* keep running from memory.
*/
virtual bool is_inmemory_mode() {
return (nshards == 1 && num_vertices() < 2 * maxwindow); // Do not switch to in-memory mode if num of vertices too high. Ugly heuristic.
}
/**
* Extends the window to fill the memory budget, but not over maxvid
*/
virtual vid_t determine_next_window(vid_t iinterval, vid_t fromvid, vid_t maxvid, size_t membudget) {
/* Load degrees */
degree_handler->load(fromvid, maxvid);
/* If is in-memory-mode, memory budget is not considered. */
if (is_inmemory_mode() || svertex_t().computational_edges()) {
return maxvid;
} else {
size_t memreq = 0;
int max_interval = maxvid - fromvid;
for(int i=0; i < max_interval; i++) {
degree deg = degree_handler->get_degree(fromvid + i);
int inc = deg.indegree;
int outc = deg.outdegree * (!disable_outedges);
// Raw data and object cost included
memreq += sizeof(svertex_t) + (sizeof(EdgeDataType) + sizeof(vid_t) + sizeof(graphchi_edge<EdgeDataType>))*(outc + inc);
if (memreq > membudget) {
logstream(LOG_DEBUG) << "Memory budget exceeded with " << memreq << " bytes." << std::endl;
return fromvid + i - 1; // Previous was enough
}
}
return maxvid;
}
}
/**
* Calculates the exact number of edges
* required to load in the subinterval.
*/
size_t num_edges_subinterval(vid_t st, vid_t en) {
size_t num_edges = 0;
int nvertices = en - st + 1;
if (scheduler != NULL) {
for(int i=0; i < nvertices; i++) {
bool is_sched = scheduler->is_scheduled(st + i);
if (is_sched) {
degree d = degree_handler->get_degree(st + i);
num_edges += d.indegree * store_inedges + d.outdegree;
}
}
} else {
for(int i=0; i < nvertices; i++) {
degree d = degree_handler->get_degree(st + i);
num_edges += d.indegree * store_inedges + d.outdegree;
}
}
return num_edges;
}
virtual void load_before_updates(std::vector<svertex_t> &vertices) {
omp_set_num_threads(load_threads);
#pragma omp parallel for schedule(dynamic, 1)
for(int p=-1; p < nshards; p++) {
if (p==(-1)) {
/* Load memory shard - is internally parallelized */
if (!memoryshard->loaded()) {
memoryshard->load();
}
/* Load vertex edges from memory shard */
memoryshard->load_vertices(sub_interval_st, sub_interval_en, vertices, true, !disable_outedges);
/* Load vertices */
if (!disable_vertexdata_storage) {
vertex_data_handler->load(sub_interval_st, sub_interval_en);
}
} else {
/* Load edges from a sliding shard */
if (!disable_outedges) {
if (p != exec_interval) {
if (randomization) {
sliding_shards[p]->set_disable_async_writes(true); // Cannot write async if we use randomization, because async assumes we can write previous vertices edgedata because we won't touch them this iteration
}
sliding_shards[p]->read_next_vertices((int) vertices.size(), sub_interval_st, vertices,
(randomization || scheduler != NULL) && chicontext.iteration == 0);
}
}
}
}
/* Wait for all reads to complete */
iomgr->wait_for_reads();
}
virtual void exec_updates(GraphChiProgram<VertexDataType, EdgeDataType, svertex_t> &userprogram,
std::vector<svertex_t> &vertices) {
metrics_entry me = m.start_time();
size_t nvertices = vertices.size();
if (!enable_deterministic_parallelism) {
for(int i=0; i < (int)nvertices; i++) vertices[i].parallel_safe = true;
}
int sub_interval_len = sub_interval_en - sub_interval_st;
std::vector<vid_t> random_order(randomization ? sub_interval_len + 1 : 0);
if (randomization) {
// Randomize vertex-vector
for(int idx=0; idx <= (int)sub_interval_len; idx++) random_order[idx] = idx;
std::random_shuffle(random_order.begin(), random_order.end());
}
do {
omp_set_num_threads(exec_threads);
#pragma omp parallel sections
{
#pragma omp section
{
#pragma omp parallel for schedule(dynamic)
for(int idx=0; idx <= (int)sub_interval_len; idx++) {
vid_t vid = sub_interval_st + (randomization ? random_order[idx] : idx);
svertex_t & v = vertices[vid - sub_interval_st];
if (exec_threads == 1 || v.parallel_safe) {
if (!disable_vertexdata_storage)
v.dataptr = vertex_data_handler->vertex_data_ptr(vid);
if (v.scheduled)
userprogram.update(v, chicontext);
}
}
}
#pragma omp section
{
if (exec_threads > 1 && enable_deterministic_parallelism) {
int nonsafe_count = 0;
for(int idx=0; idx <= (int)sub_interval_len; idx++) {
vid_t vid = sub_interval_st + (randomization ? random_order[idx] : idx);
svertex_t & v = vertices[vid - sub_interval_st];
if (!v.parallel_safe && v.scheduled) {
if (!disable_vertexdata_storage)
v.dataptr = vertex_data_handler->vertex_data_ptr(vid);
userprogram.update(v, chicontext);
nonsafe_count++;
}
}
m.add("serialized-updates", nonsafe_count);
}
}
}
} while (userprogram.repeat_updates(chicontext));
m.stop_time(me, "execute-updates");
}
/**
Special method for running all iterations with the same vertex-vector.
This is a hacky solution.
FIXME: this does not work well with deterministic parallelism. Needs a
a separate analysis phase to check which vertices can be run in parallel, and
then run it in chunks. Not difficult.
**/
virtual void exec_updates_inmemory_mode(GraphChiProgram<VertexDataType, EdgeDataType, svertex_t> &userprogram,
std::vector<svertex_t> &vertices) {
work = nupdates = 0;
for(iter=0; iter<niters; iter++) {
logstream(LOG_INFO) << "In-memory mode: Iteration " << iter << " starts. (" << chicontext.runtime() << " secs)" << std::endl;
chicontext.iteration = iter;
if (iter > 0) // First one run before -- ugly
userprogram.before_iteration(iter, chicontext);
userprogram.before_exec_interval(0, (int)num_vertices(), chicontext);
if (use_selective_scheduling) {
if (iter > 0 && !scheduler->has_new_tasks) {
logstream(LOG_INFO) << "No new tasks to run!" << std::endl;
niters = iter;
break;
}
scheduler->new_iteration(iter);
bool newtasks = false;
for(int i=0; i < (int)vertices.size(); i++) { // Could, should parallelize
if (iter == 0 || scheduler->is_scheduled(i)) {
vertices[i].scheduled = true;
newtasks = true;
nupdates++;
work += vertices[i].inc + vertices[i].outc;
} else {
vertices[i].scheduled = false;
}
}
if (!newtasks) {
// Finished
niters = iter;
break;
}
scheduler->has_new_tasks = false; // Kind of misleading since scheduler may still have tasks - but no new tasks.
} else {
nupdates += num_vertices();
if (!only_adjacency) {
work += num_edges();
}
}
exec_updates(userprogram, vertices);
load_after_updates(vertices);
userprogram.after_exec_interval(0, (int)num_vertices(), chicontext);
userprogram.after_iteration(iter, chicontext);
if (chicontext.last_iteration > 0 && chicontext.last_iteration <= iter){
logstream(LOG_INFO)<<"Stopping engine since last iteration was set to: " << chicontext.last_iteration << std::endl;
break;
}
}
if (save_edgesfiles_after_inmemmode) {
logstream(LOG_INFO) << "Saving memory shard..." << std::endl;
}
}
virtual void init_vertices(std::vector<svertex_t> &vertices, graphchi_edge<EdgeDataType> * &edata) {
size_t nvertices = vertices.size();
/* Compute number of edges */
size_t num_edges = num_edges_subinterval(sub_interval_st, sub_interval_en);
/* Allocate edge buffer */
edata = (graphchi_edge<EdgeDataType>*) malloc(num_edges * sizeof(graphchi_edge<EdgeDataType>));
/* Assign vertex edge array pointers */
size_t ecounter = 0;
for(int i=0; i < (int)nvertices; i++) {
degree d = degree_handler->get_degree(sub_interval_st + i);
int inc = d.indegree;
int outc = d.outdegree * (!disable_outedges);
vertices[i] = svertex_t(sub_interval_st + i, &edata[ecounter],
&edata[ecounter + inc * store_inedges], inc, outc);
/* Store correct out-degree even if out-edge loading disabled */
if (disable_outedges) {
vertices[i].outc = d.outdegree;
}
if (scheduler != NULL) {
bool is_sched = ( scheduler->is_scheduled(sub_interval_st + i));
if (is_sched) {
vertices[i].scheduled = true;
nupdates++;
ecounter += inc * store_inedges + outc;
}
} else {
nupdates++;
vertices[i].scheduled = true;
ecounter += inc * store_inedges + outc;
}
}
work += ecounter;
assert(ecounter <= num_edges);
}
void save_vertices(std::vector<svertex_t> &vertices) {
if (disable_vertexdata_storage) return;
size_t nvertices = vertices.size();
bool modified_any_vertex = false;
for(int i=0; i < (int)nvertices; i++) {
if (vertices[i].modified) {
modified_any_vertex = true;
break;
}
}
if (modified_any_vertex) {
vertex_data_handler->save();
}
}
virtual void load_after_updates(std::vector<svertex_t> &vertices) {
// Do nothing.
}
virtual void write_delta_log() {
// Write delta log
std::string deltafname = iomgr->multiplexprefix(0) + base_filename + ".deltalog";
FILE * df = fopen(deltafname.c_str(), (chicontext.iteration == 0 ? "w" : "a"));
fprintf(df, "%d,%lu,%lu,%lf\n", chicontext.iteration, nupdates, work, chicontext.get_delta());
fclose(df);
}
public:
virtual std::vector< std::pair<vid_t, vid_t> > get_intervals() {
return intervals;
}
virtual std::pair<vid_t, vid_t> get_interval(int i) {
return intervals[i];
}
/**
* Returns first vertex of i'th interval.
*/
vid_t get_interval_start(int i) {
return get_interval(i).first;
}
/**
* Returns last vertex (inclusive) of i'th interval.
*/
vid_t get_interval_end(int i) {
return get_interval(i).second;
}
virtual size_t num_vertices() {
return 1 + intervals[nshards - 1].second;
}
graphchi_context &get_context() {
return chicontext;
}
virtual int get_nshards() {
return nshards;
}
size_t num_updates() {
return nupdates;
}
/**
* Thread-safe version of num_edges
*/
virtual size_t num_edges_safe() {
return num_edges();
}
virtual size_t num_buffered_edges() {
return 0;
}
/**
* Counts the number of edges from shard sizes.
*/
virtual size_t num_edges() {
if (sliding_shards.size() == 0) {
logstream(LOG_ERROR) << "engine.num_edges() can be called only after engine has been started. To be fixed later. As a workaround, put the engine into a global variable, and query the number afterwards in begin_iteration(), for example." << std::endl;
assert(false);
}
if (only_adjacency) {
// TODO: fix.
logstream(LOG_ERROR) << "Asked number of edges, but engine was run without edge-data." << std::endl;
return 0;
}
return nedges;
}
/**
* Checks whether any vertex is scheduled in the given interval.
* If no scheduler is configured, returns always true.
*/
// TODO: support for a minimum fraction of scheduled vertices
bool is_any_vertex_scheduled(vid_t st, vid_t en) {
if (scheduler == NULL) return true;
for(vid_t v=st; v<=en; v++) {
if (scheduler->is_scheduled(v)) {
return true;
}
}
return false;
}
virtual void initialize_iter() {
// Do nothing
}
virtual void initialize_before_run() {
if (reset_vertexdata && vertex_data_handler != NULL) {
vertex_data_handler->clear(num_vertices());
}
}
virtual memshard_t * create_memshard(vid_t interval_st, vid_t interval_en) {
#ifndef DYNAMICEDATA
return new memshard_t(this->iomgr,
filename_shard_edata<EdgeDataType>(base_filename, exec_interval, nshards),
filename_shard_adj(base_filename, exec_interval, nshards),
interval_st,
interval_en,
blocksize,
m);
#else
return new memshard_t(this->iomgr,
filename_shard_edata<int>(base_filename, exec_interval, nshards),
filename_shard_adj(base_filename, exec_interval, nshards),
interval_st,
interval_en,
blocksize,
m);
#endif
}
/**
* Run GraphChi program, specified as a template
* parameter.
* @param niters number of iterations
*/
void run(GraphChiProgram<VertexDataType, EdgeDataType, svertex_t> &userprogram, int _niters) {
m.start_time("runtime");
if (degree_handler == NULL)
degree_handler = create_degree_handler();
iomgr->set_cache_budget(get_option_long("cachesize_mb", 0) * 1024L * 1024L);
m.set("cachesize_mb", get_option_int("cachesize_mb", 0));
m.set("membudget_mb", get_option_int("membudget_mb", 0));
randomization = get_option_int("randomization", 0) == 1;
if (svertex_t().computational_edges()) {
// Heuristic
set_maxwindow(membudget_mb * 1024 * 1024 / 3 / 100);
logstream(LOG_INFO) << "Set maxwindow:" << maxwindow << std::endl;
}
if (randomization) {
timeval tt;
gettimeofday(&tt, NULL);
uint32_t seed = (uint32_t) get_option_int("seed", (int)tt.tv_usec);
std::cout << "SEED: " << seed << std::endl;
srand(seed);
}
niters = _niters;
logstream(LOG_INFO) << "GraphChi starting" << std::endl;
logstream(LOG_INFO) << "Licensed under the Apache License 2.0" << std::endl;
logstream(LOG_INFO) << "Copyright Aapo Kyrola et al., Carnegie Mellon University (2012)" << std::endl;
if (vertex_data_handler == NULL && !disable_vertexdata_storage)
vertex_data_handler = new vertex_data_store<VertexDataType>(base_filename, num_vertices(), iomgr);
initialize_before_run();
/* Setup */
if (sliding_shards.size() == 0) {
initialize_sliding_shards();
if (initialize_edges_before_run) {
for(int j=0; j<(int)sliding_shards.size(); j++) sliding_shards[j]->initdata();
}
} else {
logstream(LOG_DEBUG) << "Engine being restarted, do not reinitialize." << std::endl;
}
initialize_scheduler();
omp_set_nested(1);
/* Install a 'mock'-scheduler to chicontext if scheduler
is not used. */
chicontext.scheduler = scheduler;
if (scheduler == NULL) {
chicontext.scheduler = new non_scheduler();
}
/* Print configuration */
print_config();
/* Main loop */
for(iter=0; iter < niters; iter++) {
logstream(LOG_INFO) << "Start iteration: " << iter << std::endl;
initialize_iter();
/* Check vertex data file has the right size (number of vertices may change) */
if (!disable_vertexdata_storage)
vertex_data_handler->check_size(num_vertices());
/* Keep the context object updated */
chicontext.filename = base_filename;
chicontext.iteration = iter;
chicontext.num_iterations = niters;
chicontext.nvertices = num_vertices();
if (!only_adjacency) chicontext.nedges = num_edges();
chicontext.execthreads = exec_threads;
chicontext.reset_deltas(exec_threads);
/* Call iteration-begin event handler */
userprogram.before_iteration(iter, chicontext);
/* Check scheduler. If no scheduled tasks, terminate. */
if (use_selective_scheduling) {
if (scheduler != NULL) {
if (!scheduler->has_new_tasks) {
logstream(LOG_INFO) << "No new tasks to run!" << std::endl;
break;
}
scheduler->has_new_tasks = false; // Kind of misleading since scheduler may still have tasks - but no new tasks.
}
}
/* Now clear scheduler bits for the interval */
if (scheduler != NULL)
scheduler->new_iteration(iter);
std::vector<int> intshuffle(nshards);
if (randomization) {
for(int i=0; i<nshards; i++) intshuffle[i] = i;
std::random_shuffle(intshuffle.begin(), intshuffle.end());
}
/* Interval loop */
for(int interval_idx=0; interval_idx < nshards; ++interval_idx) {
exec_interval = interval_idx;
if (randomization && iter > 0) { // NOTE: only randomize shard order after first iteration so we can compute indices
exec_interval = intshuffle[interval_idx];
// Hack to make system work if we jump backwards
// if (interval_idx > 0 && last_exec_interval> exec_interval) {
for(int p=0; p<nshards; p++) {
sliding_shards[p]->flush();
sliding_shards[p]->set_offset(0, 0, 0);
}
// }
}
/* Determine interval limits */
vid_t interval_st = get_interval_start(exec_interval);
vid_t interval_en = get_interval_end(exec_interval);
if (interval_st > interval_en) continue; // Can happen on very very small graphs.
if (!is_inmemory_mode())
userprogram.before_exec_interval(interval_st, interval_en, chicontext);
/* Flush stream shard for the exec interval */
sliding_shards[exec_interval]->flush();
iomgr->wait_for_writes(); // Actually we would need to only wait for writes of given shard. TODO.
/* Initialize memory shard */
if (memoryshard != NULL) delete memoryshard;
memoryshard = create_memshard(interval_st, interval_en);
memoryshard->only_adjacency = only_adjacency;
memoryshard->set_disable_async_writes(randomization);
sub_interval_st = interval_st;
logstream(LOG_INFO) << chicontext.runtime() << "s: Starting: "
<< sub_interval_st << " -- " << interval_en << std::endl;
while (sub_interval_st <= interval_en) {
modification_lock.lock();
/* Determine the sub interval */
sub_interval_en = determine_next_window(exec_interval,
sub_interval_st,
std::min(interval_en, (is_inmemory_mode() ? interval_en : sub_interval_st + maxwindow)),
size_t(membudget_mb) * 1024 * 1024);
assert(sub_interval_en >= sub_interval_st);
logstream(LOG_INFO) << "Iteration " << iter << "/" << (niters - 1) << ", subinterval: " << sub_interval_st << " - " << sub_interval_en << std::endl;
bool any_vertex_scheduled = is_any_vertex_scheduled(sub_interval_st, sub_interval_en);
if (!any_vertex_scheduled) {
logstream(LOG_INFO) << "No vertices scheduled, skip." << std::endl;
sub_interval_st = sub_interval_en + 1;
modification_lock.unlock();
continue;
}
/* Initialize vertices */
int nvertices = sub_interval_en - sub_interval_st + 1;
graphchi_edge<EdgeDataType> * edata = NULL;
std::vector<svertex_t> vertices(nvertices, svertex_t());
logstream(LOG_DEBUG) << "Allocation " << nvertices << " vertices, sizeof:" << sizeof(svertex_t)
<< " total:" << nvertices * sizeof(svertex_t) << std::endl;
init_vertices(vertices, edata);
/* Load data */
load_before_updates(vertices);
modification_lock.unlock();
logstream(LOG_INFO) << "Start updates" << std::endl;
/* Execute updates */
if (!is_inmemory_mode()) {
exec_updates(userprogram, vertices);
/* Load phase after updates (used by the functional engine) */
load_after_updates(vertices);
} else {
exec_updates_inmemory_mode(userprogram, vertices);
}
logstream(LOG_INFO) << "Finished updates" << std::endl;
/* Save vertices */
if (!disable_vertexdata_storage) {
save_vertices(vertices);
}
sub_interval_st = sub_interval_en + 1;
/* Delete edge buffer. TODO: reuse. */
if (edata != NULL) {
delete edata;
edata = NULL;
}
} // while subintervals
if (memoryshard->loaded() && (save_edgesfiles_after_inmemmode || !is_inmemory_mode())) {
memoryshard->commit(modifies_inedges, modifies_outedges & !disable_outedges);
if (!randomization) {
sliding_shards[exec_interval]->set_offset(memoryshard->offset_for_stream_cont(), memoryshard->offset_vid_for_stream_cont(),
memoryshard->edata_ptr_for_stream_cont());
}
delete memoryshard;
memoryshard = NULL;
}
if (!is_inmemory_mode())
userprogram.after_exec_interval(interval_st, interval_en, chicontext);
} // For exec_interval
if (!is_inmemory_mode()) // Run sepately
userprogram.after_iteration(iter, chicontext);
/* Move the sliding shard of the current interval to correct position and flush
writes of all shards for next iteration. */
for(int p=0; p<nshards; p++) {
sliding_shards[p]->flush();
sliding_shards[p]->set_offset(0, 0, 0);
}
iomgr->wait_for_writes();
/* Write progress log */
write_delta_log();
/* Check if user has defined a last iteration */
if (chicontext.last_iteration >= 0) {
niters = chicontext.last_iteration + 1;
logstream(LOG_DEBUG) << "Last iteration is now: " << (niters-1) << std::endl;
}
iteration_finished();
iomgr->first_pass_finished(); // Tell IO-manager that we have passed over the graph (used for optimization)
} // Iterations
m.stop_time("runtime");
m.set("updates", nupdates);
m.set("work", work);
m.set("nvertices", num_vertices());
m.set("execthreads", (size_t)exec_threads);
m.set("loadthreads", (size_t)load_threads);
#ifndef GRAPHCHI_DISABLE_COMPRESSION
m.set("compression", 1);
#else
m.set("compression", 0);
#endif
m.set("scheduler", (size_t)use_selective_scheduling);
m.set("niters", niters);
// Close outputs
for(int i=0; i< (int)outputs.size(); i++) {
outputs[i]->close();
}
outputs.clear();
// Commit vertex data
if (vertex_data_handler != NULL) {
delete vertex_data_handler;
vertex_data_handler = NULL;
}
if (modifies_inedges || modifies_outedges) {
iomgr->commit_cached_blocks();
}
}
virtual void iteration_finished() {
// Do nothing
}
stripedio * get_iomanager() {
return iomgr;
}
virtual void set_modifies_inedges(bool b) {
modifies_inedges = b;
}
virtual void set_modifies_outedges(bool b) {
modifies_outedges = b;
}
virtual void set_only_adjacency(bool b) {
only_adjacency = b;
}
virtual void set_disable_outedges(bool b) {
disable_outedges = b;
}
/**
* Configure the blocksize used when loading shards.
* Default is one megabyte.
* @param blocksize_in_bytes the blocksize in bytes
*/
void set_blocksize(size_t blocksize_in_bytes) {
blocksize = blocksize_in_bytes;
}
/**
* Set the amount of memory available for loading graph
* data. Default is 1000 megabytes.
* @param mbs amount of memory to be used.
*/
void set_membudget_mb(int mbs) {
membudget_mb = mbs;
}
int get_membudget_mb() {
return membudget_mb;
}
void set_load_threads(int lt) {
load_threads = lt;
}
void set_exec_threads(int et) {
exec_threads = et;
}
/**
* Sets whether the engine is run in the deterministic
* mode. Default true.
*/
void set_enable_deterministic_parallelism(bool b) {
#ifdef DYNAMICEDATA
if (!b) {
logstream(LOG_ERROR) << "With dynamic edge data, you cannot disable determinic parallelism." << std::endl;
logstream(LOG_ERROR) << "Otherwise race conditions would corrupt the structure of the data." << std::endl;
assert(b);
return;
}
#endif
enable_deterministic_parallelism = b;
}
public:
void set_disable_vertexdata_storage() {
this->disable_vertexdata_storage = true;
}
void set_enable_vertexdata_storage() {
this->disable_vertexdata_storage = false;
}
void set_maxwindow(unsigned int _maxwindow){
maxwindow = _maxwindow;
};
/* Outputs */
size_t add_output(ioutput<VertexDataType, EdgeDataType> * output) {
outputs.push_back(output);
return (outputs.size() - 1);
}
ioutput<VertexDataType, EdgeDataType> * output(size_t idx) {
if (idx >= outputs.size()) {
logstream(LOG_FATAL) << "Tried to get output with index " << idx << ", but only " << outputs.size() << " outputs were initialized!" << std::endl;
}
assert(idx < outputs.size());
return outputs[idx];
}
protected:
virtual void _load_vertex_intervals() {
load_vertex_intervals(base_filename, nshards, intervals);
}
protected:
mutex httplock;
std::map<std::string, std::string> json_params;
public:
/**
* Replace all shards with zero values in edges.
*/
template<typename ET>
void reinitialize_edge_data(ET zerovalue) {
for(int p=0; p < nshards; p++) {
std::string edatashardname = filename_shard_edata<ET>(base_filename, p, nshards);
std::string dirname = dirname_shard_edata_block(edatashardname, blocksize);
size_t edatasize = get_shard_edata_filesize<ET>(edatashardname);
logstream(LOG_INFO) << "Clearing data: " << edatashardname << " bytes: " << edatasize << std::endl;
int nblocks = (int) ((edatasize / blocksize) + (edatasize % blocksize == 0 ? 0 : 1));
for(int i=0; i < nblocks; i++) {
std::string block_filename = filename_shard_edata_block(edatashardname, i, blocksize);
int len = (int) std::min(edatasize - i * blocksize, blocksize);
int f = open(block_filename.c_str(), O_RDWR | O_CREAT, S_IROTH | S_IWOTH | S_IWUSR | S_IRUSR);
ET * buf = (ET *) malloc(len);
for(int i=0; i < (int) (len / sizeof(ET)); i++) {
buf[i] = zerovalue;
}
write_compressed(f, buf, len);
close(f);
#ifdef DYNAMICEDATA
write_block_uncompressed_size(block_filename, len);
#endif
}
}
}
/**
* If true, the vertex data is initialized before
* the engineis started. Default false.
*/
void set_reset_vertexdata(bool reset) {
reset_vertexdata = reset;
}
/**
* Whether edges should be saved after in-memory mode
*/
virtual void set_save_edgesfiles_after_inmemmode(bool b) {
this->save_edgesfiles_after_inmemmode = b;
}
virtual void set_initialize_edges_before_run(bool b) {
this->initialize_edges_before_run = b;
}
/**
* HTTP admin management
*/
void set_json(std::string key, std::string value) {
httplock.lock();
json_params[key] = value;
httplock.unlock();
}
template <typename T>
void set_json(std::string key, T val) {
std::stringstream ss;
ss << val;
set_json(key, ss.str());
}
std::string get_info_json() {
std::stringstream json;
json << "{";
json << "\"file\" : \"" << base_filename << "\",\n";
json << "\"numOfShards\": " << nshards << ",\n";
json << "\"iteration\": " << chicontext.iteration << ",\n";
json << "\"numIterations\": " << chicontext.num_iterations << ",\n";
json << "\"runTime\": " << chicontext.runtime() << ",\n";
json << "\"updates\": " << nupdates << ",\n";
json << "\"nvertices\": " << chicontext.nvertices << ",\n";
json << "\"interval\":" << exec_interval << ",\n";
json << "\"windowStart\":" << sub_interval_st << ",";
json << "\"windowEnd\": " << sub_interval_en << ",";
json << "\"shards\": [";
for(int p=0; p < (int)nshards; p++) {
if (p>0) json << ",";
json << "{";
json << "\"p\": " << p << ", ";
json << sliding_shards[p]->get_info_json();
json << "}";
}
json << "]";
json << "}";
return json.str();
}
};
};
#endif
| [
"er.prateekmehta@gmail.com"
] | er.prateekmehta@gmail.com |
a954b72129c0ccbb6a32eb3e5c85f0b91f0a9100 | 4c7a4655875b8f73f6c0ee7f0f9c88b21e5b107e | /nall/string/markup/node.hpp | 77822373dcaab28f4f799e381ed1b6d914f4757e | [
"ISC"
] | permissive | juvenal/gcmtools | 9f2b30521c732e1eb483bdfe6674c2a75e9f0af8 | 15f54f5e2ebc042c43258ddcc8435dd83cd80d70 | refs/heads/master | 2020-06-04T23:33:18.563013 | 2014-07-29T22:41:10 | 2014-07-29T22:41:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,117 | hpp | #ifdef NALL_STRING_INTERNAL_HPP
//note: specific markups inherit from Markup::Node
//vector<Node> will slice any data; so derived nodes must not contain data nor virtual functions
//vector<Node*> would incur a large performance penalty and greatly increased complexity
namespace nall {
namespace Markup {
struct Node {
string name;
string data;
bool attribute;
bool exists() const {
return !name.empty();
}
string text() const {
return string{data}.strip();
}
intmax_t integer() const {
return numeral(text());
}
uintmax_t decimal() const {
return numeral(text());
}
void reset() {
children.reset();
}
bool evaluate(const string &query) const {
if(query.empty()) return true;
lstring rules = string{query}.replace(" ", "").split(",");
for(auto &rule : rules) {
enum class Comparator : unsigned { ID, EQ, NE, LT, LE, GT, GE };
auto comparator = Comparator::ID;
if(rule.wildcard("*!=*")) comparator = Comparator::NE;
else if(rule.wildcard("*<=*")) comparator = Comparator::LE;
else if(rule.wildcard("*>=*")) comparator = Comparator::GE;
else if(rule.wildcard ("*=*")) comparator = Comparator::EQ;
else if(rule.wildcard ("*<*")) comparator = Comparator::LT;
else if(rule.wildcard ("*>*")) comparator = Comparator::GT;
if(comparator == Comparator::ID) {
if(find(rule).size()) continue;
return false;
}
lstring side;
switch(comparator) {
case Comparator::EQ: side = rule.split<1> ("="); break;
case Comparator::NE: side = rule.split<1>("!="); break;
case Comparator::LT: side = rule.split<1> ("<"); break;
case Comparator::LE: side = rule.split<1>("<="); break;
case Comparator::GT: side = rule.split<1> (">"); break;
case Comparator::GE: side = rule.split<1>(">="); break;
}
string data = text();
if(side(0).empty() == false) {
auto result = find(side(0));
if(result.size() == 0) return false;
data = result(0).data;
}
switch(comparator) {
case Comparator::EQ: if(data.wildcard(side(1)) == true) continue; break;
case Comparator::NE: if(data.wildcard(side(1)) == false) continue; break;
case Comparator::LT: if(numeral(data) < numeral(side(1))) continue; break;
case Comparator::LE: if(numeral(data) <= numeral(side(1))) continue; break;
case Comparator::GT: if(numeral(data) > numeral(side(1))) continue; break;
case Comparator::GE: if(numeral(data) >= numeral(side(1))) continue; break;
}
return false;
}
return true;
}
vector<Node> find(const string &query) const {
vector<Node> result;
lstring path = query.split("/");
string name = path.take(0), rule;
unsigned lo = 0u, hi = ~0u;
if(name.wildcard("*[*]")) {
lstring side = name.split<1>("[");
name = side(0);
side = side(1).rtrim<1>("]").split<1>("-");
lo = side(0).empty() ? 0u : numeral(side(0));
hi = side(1).empty() ? ~0u : numeral(side(1));
}
if(name.wildcard("*(*)")) {
lstring side = name.split<1>("(");
name = side(0);
rule = side(1).rtrim<1>(")");
}
unsigned position = 0;
for(auto &node : children) {
if(node.name.wildcard(name) == false) continue;
if(node.evaluate(rule) == false) continue;
bool inrange = position >= lo && position <= hi;
position++;
if(inrange == false) continue;
if(path.size() == 0) result.append(node);
else {
auto list = node.find(path.concatenate("/"));
for(auto &item : list) result.append(item);
}
}
return result;
}
Node operator[](const string &query) const {
auto result = find(query);
return result(0);
}
Node* begin() { return children.begin(); }
Node* end() { return children.end(); }
const Node* begin() const { return children.begin(); }
const Node* end() const { return children.end(); }
Node() : attribute(false), level(0) {}
protected:
unsigned level;
vector<Node> children;
};
}
}
#endif
| [
"johnwchadwick@gmail.com"
] | johnwchadwick@gmail.com |
5482e1eb50f9168587475b580cd013d289b550fd | 1ec2a65236d658327324975c74df59c16f6da157 | /doc/code/2-4.cpp | 892a6ee13056cabc79eece0df5cb0f90b343edbd | [] | no_license | realcomputation/DOUBLESTAR | c9eefb21f3a258f0dfd08abed0cecc87c848f459 | db566aa8a3458c787695563949b361a7dc9ddc38 | refs/heads/master | 2022-09-13T15:23:17.900119 | 2020-06-01T06:26:24 | 2020-06-01T06:26:24 | 216,155,259 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,125 | cpp | #include "iRRAM.h"
#include <vector>
#include <string>
#include <qd/qd_real.h>
#include <chrono>
using namespace iRRAM;
using std::string;
using std::vector;
using std::to_string;
using std::chrono::nanoseconds;
using std::chrono::duration_cast;
using std::chrono::high_resolution_clock;
void compute(){
fpu_fix_start(NULL);
// # of iterations
// double, DD, QD: correct by ? (depends on init value)
long nPlus = 1000;
// repetitions of performance tests
long m = 1<<10;
// init values
REAL rInit = 314159;
double dInit = 314159;
dd_real ddInit = 314159;
qd_real qdInit = 314159;
// precision controller(epsilon)
int eps = -20; // 2^(?)
// initial values
REAL r; double d; dd_real dd; qd_real qd;
// correctness check
r = rInit; d = dInit; dd = ddInit; qd = qdInit;
REAL errD, errDD, errQD;
bool isDbroken=false, isDDbroken=false, isQDbroken=false;
for(long i=0;i<nPlus;i++) {
// check error
if(!isDbroken) { if(!bound(r - REAL(d), eps)) {
cout << "correctness failure: double at " + to_string(i) + "\n";
isDbroken = true;
}}
if(!isDDbroken) { if(!bound(r - REAL(dd.to_string()), eps)) {
cout << "correctness failure: DD at " + to_string(i) + "\n";
isDDbroken = true;
}}
if(!isQDbroken) { if(!bound(r - REAL(qd.to_string()), eps)) {
cout << "correctness failure: QD at " + to_string(i) + "\n";
isQDbroken = true;
}}
// do work!
r = sin(r);
d = sin(d);
dd = sin(dd);
qd = sin(qd);
}
cout << "correctness test done.\n";
//- performance test -//
auto beginTime = high_resolution_clock::now();
auto endTime = high_resolution_clock::now();
long elapsed;
// iRRAM
elapsed = 0;
for(int i=0;i<m;i++) {
beginTime = high_resolution_clock::now();
r = rInit;
for(long i=0;i<nPlus;i++) r = sin(r);
endTime = high_resolution_clock::now();
elapsed += duration_cast<nanoseconds>(endTime-beginTime).count();
}
cout << "iRRAM: " << elapsed/m << " ns \n";
// double
if(!isDbroken) {
elapsed = 0;
for(int i=0;i<m;i++) {
beginTime = high_resolution_clock::now();
d = dInit;
for(long i=0;i<nPlus;i++) d = sin(d);
endTime = high_resolution_clock::now();
elapsed += duration_cast<nanoseconds>(endTime-beginTime).count();
}
cout << "double: " << elapsed/m << " ns \n";
}
// double double
if(!isDDbroken) {
elapsed = 0;
for(int i=0;i<m;i++) {
beginTime = high_resolution_clock::now();
dd = ddInit;
for(long i=0;i<nPlus;i++) dd = sin(dd);
endTime = high_resolution_clock::now();
elapsed += duration_cast<nanoseconds>(endTime-beginTime).count();
}
cout << "DD: " << elapsed/m << " ns \n";
}
// quad double
if(!isQDbroken) {
elapsed = 0;
for(int i=0;i<m;i++) {
beginTime = high_resolution_clock::now();
qd = qdInit;
for(long i=0;i<nPlus;i++) qd = sin(qd);
endTime = high_resolution_clock::now();
elapsed += duration_cast<nanoseconds>(endTime-beginTime).count();
}
cout << "QD: " << elapsed/m << " ns \n";
}
}
| [
"40803236+molehair@users.noreply.github.com"
] | 40803236+molehair@users.noreply.github.com |
f9d555d6bf366ef8d9a1b318fed71dc2b41e760f | 656dd58a6662eeedc467e84911d4ccbe102e3c18 | /Sub.cpp | 7e8b00da9e1244cf3fdaa8ebdc332714dde6dfa2 | [] | no_license | vamprier/Factory | 26ca16d339a123ee5af5546a14cdadbe61083378 | 2d26823797d468b7b0e7911e430c0821922ba1e8 | refs/heads/master | 2021-01-10T02:09:15.071140 | 2016-04-11T01:24:56 | 2016-04-11T01:24:56 | 55,932,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 139 | cpp | #include "Sub.h"
Sub::Sub(float a,float b):Operation(a,b)
{
}
Sub::~Sub(void)
{
}
float Sub::GetResult()
{
return numberA-numberB;
}
| [
"zj855810@163.com"
] | zj855810@163.com |
5afcd62a08ae05970e1052c6218948d49af2f9d7 | 05d51e21772b25acda1a9025e358f98706e476f4 | /AtCoder/AtCoder035-AGC-D.cpp | 34449663ba3651c15dcfa1f9d2ae6661ef04494b | [] | no_license | taow-com-prog/problemsolving | f26cc32d957b22543ef72cbe7865d2ca52cfdfee | cfcfd6c8fc57c47d143596c773db54d974eb4487 | refs/heads/master | 2020-06-18T13:01:50.839446 | 2020-01-21T20:16:04 | 2020-01-21T20:16:04 | 196,310,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,411 | cpp | #pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf_int = 1e9 + 100;
const ll inf_ll = 1e18;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef long double dbl;
#define pb push_back
const double pi = 3.1415926535898;
#define dout if(debug) cout
#define fi first
#define se second
#define sp setprecision
#define sz(a) (int(a.size()))
#define all(a) a.begin(),a.end()
bool debug = 0;
const int MAXN = 4100 + 100;
const int LOG = 22;
const int mod = 1e9 + 7;
const int MX = 1e6 + 100;
typedef long long li;
const li MOD = 1000000000949747713ll;
int a[MAXN];
vector<pll> dp[20][20];
void solve() {
int n;
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
for (int i = 1; i <= n - 1; ++i) {
dp[i][i + 1].pb({0, 0});
}
for (int len = 3; len <= n; ++len) {
for (int l = 1; l <= n; ++l) {
for (int r = l + len - 1; r <= n; ++r) {
vector<pll> vals;
for (int mid = l + 1; mid <= r - 1; ++mid) {
for (auto x:dp[l][mid]) {
for (auto y:dp[mid][r]) {
vals.pb({x.fi + x.se + y.fi + a[mid], x.se + y.fi + y.se + a[mid]});
}
}
}
sort(all(vals));
dp[l][r].pb(vals[0]);
ll mx = vals[0].se;
for (int i = 1; i < sz(vals); ++i) {
if (vals[i].se >= mx) {
continue;
} else {
mx = vals[i].se;
dp[l][r].pb(vals[i]);
}
}
}
}
}
ll ans = inf_ll;
for(auto x:dp[1][n]){
ans = min(ans, x.fi + x.se);
}
cout << ans + a[1] + a[n]<<"\n";
}
signed main() {
#ifdef zxc
debug = 1;
freopen("../input.txt", "r", stdin);
// freopen("../output.txt", "w", stdout);
#else
#endif //zxc
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cout.setf(ios::fixed);
cout.precision(20);
int t = 1;
while (t--)
solve();
if (debug)
cerr << endl << "time : " << (1.0 * clock() / CLOCKS_PER_SEC) << endl;
} | [
"xildar98@mail.ru"
] | xildar98@mail.ru |
39bbbdbca13621923ad90876150b0b5950fa5077 | 672f7f03865183660b4f433f7799b4c488768772 | /FantasyFightingGame/Source.cpp | 137eb80985c149a0fe52d52e0610b92154f9d605 | [] | no_license | Austin-Chandler/FantasyFightingGame | 8917e89daeccd7df4ac516e82a5c4da07b83438b | 2d42d846c7635fe50b8e233d0450cd48fbfe94df | refs/heads/master | 2022-04-17T11:43:04.524922 | 2020-04-20T03:27:58 | 2020-04-20T03:27:58 | 254,797,915 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 193 | cpp | // Austin Chandler
// This is my own work
// Fantasy Fighting Game
#include <iostream>
#include "Game.h"
using namespace std;
int main() {
Game SannhetsLegacy;
SannhetsLegacy.playGame();
} | [
"agcmint@gmail.com"
] | agcmint@gmail.com |
b3fce1f9ee4a0d254160b13f4704ffae29d21e7b | 2e5c7683142042f86e0380a3cac0ef5adcb61d3d | /source/ev3way2/unit/sequence/ISequence.cpp | a2d749078b04d9d542c450c9990f6eaf291739eb | [] | no_license | kuromido/ET_RoboCon_2017 | 15d975d54ce60fdbff0a62fbc18b2190200df727 | cd154bec4b448d4242a29aade1e6a659d5c61428 | refs/heads/master | 2019-08-05T01:36:21.784159 | 2017-09-19T13:29:28 | 2017-09-19T13:29:28 | 83,324,557 | 0 | 0 | null | 2017-02-27T15:18:47 | 2017-02-27T15:18:47 | null | UTF-8 | C++ | false | false | 125 | cpp | #include "ISequence.h"
namespace unit
{
ISequence::ISequence()
{
}
ISequence::~ISequence()
{
}
} // namespace unit
| [
"kuromido@users.noreply.github.com"
] | kuromido@users.noreply.github.com |
a92df1831fd40331ea7c6d864209154cac8d0ec5 | c1c7429a531ad8869eeba07d0e7b9e6a2af56d61 | /LineTracking.h | 626963df2f0874a8952962bd31c189a81d6dfc0d | [] | no_license | orcilano/LineSLAM-1 | e4d593fbb7d74640aa43a811ed56eebd9fa6e95f | 4a5d429b14039f1c34cef5d0ce23b3503e0fedec | refs/heads/master | 2021-12-12T13:22:17.663456 | 2016-10-09T01:41:54 | 2016-10-09T01:41:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,314 | h | #ifndef _LINETRACKING_H_
#define _LINETRACKING_H_
#include <opencv2/opencv.hpp>
#include <opencv2/line_descriptor.hpp>
#include "opencv2/core/utility.hpp"
#include <opencv2/imgproc.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/highgui.hpp>
#include <thread>
#include <iostream>
#include "Timer.h"
#include "Drawer.h"
#include "LS.h"
LS *DetectLinesByED(unsigned char *srcImg, int width, int height, int *pNoLines);
namespace LineSLAM
{
class Drawer;
class LineTracking
{
private:
public:
LineTracking(int detectMethod, Drawer *ttFrameDrawer);
//for all methods
int methods;//which methods do we use to detect line.
cv::Mat currentImg;
cv::Mat lastImg;
cv::Mat currentDescrib;
cv::Mat lastDescrib;
int currentLineNum;
int lastLineNum;
//for EDLine method
LS *currentLines;
LS *lastLines;
//for LSD method
std::vector<cv::line_descriptor::KeyLine> lines;
std::vector<cv::line_descriptor::KeyLine> lastlines;
//detect line segements
void detectLSD(const cv::Mat &im);
void detectEDL(const cv::Mat &im);
//matching line segements
void matchingLine();
int Tracking(const cv::Mat &im, const double ×tamp);
protected:
Drawer* tFrameDrawer;
};
}
#endif
| [
"weixinyutongzhi@gmail.com"
] | weixinyutongzhi@gmail.com |
364533ad9765225a982fa7375be62c10cac2afe7 | 1ae40287c5705f341886bbb5cc9e9e9cfba073f7 | /Osmium/SDK/FN_BGA_SuperShielder_Shield_classes.hpp | dd20658c66fec8cc500fe864bd89d2884e8c0b25 | [] | no_license | NeoniteDev/Osmium | 183094adee1e8fdb0d6cbf86be8f98c3e18ce7c0 | aec854e60beca3c6804f18f21b6a0a0549e8fbf6 | refs/heads/master | 2023-07-05T16:40:30.662392 | 2023-06-28T23:17:42 | 2023-06-28T23:17:42 | 340,056,499 | 14 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 3,143 | hpp | #pragma once
// Fortnite (4.5-CL-4159770) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BGA_SuperShielder_Shield.BGA_SuperShielder_Shield_C
// 0x0038 (0x06E0 - 0x06A8)
class ABGA_SuperShielder_Shield_C : public ABuildingGameplayActor
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x06A8(0x0008) (Transient, DuplicateTransient)
class UParticleSystemComponent* P_SuperShielder_ShieldContact; // 0x06B0(0x0008) (BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData)
class UStaticMeshComponent* ShieldMesh; // 0x06B8(0x0008) (BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData)
class USceneComponent* DefaultSceneRoot; // 0x06C0(0x0008) (BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData)
bool ShielderDead; // 0x06C8(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
unsigned char UnknownData00[0x7]; // 0x06C9(0x0007) MISSED OFFSET
class UMaterialInstanceDynamic* Shield_MID; // 0x06D0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
class UMaterialInstanceDynamic* Shield_MID_2; // 0x06D8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BGA_SuperShielder_Shield.BGA_SuperShielder_Shield_C");
return ptr;
}
void UserConstructionScript();
void OnDamagePlayEffects(float* Damage, struct FGameplayTagContainer* DamageTags, struct FVector* Momentum, struct FHitResult* HitInfo, class AFortPawn** InstigatedBy, class AActor** DamageCauser, struct FGameplayEffectContextHandle* EffectContext);
void OnDamageServer(float* Damage, struct FGameplayTagContainer* DamageTags, struct FVector* Momentum, struct FHitResult* HitInfo, class AController** InstigatedBy, class AActor** DamageCauser, struct FGameplayEffectContextHandle* EffectContext);
void OnDeathServer(float* Damage, struct FGameplayTagContainer* DamageTags, struct FVector* Momentum, struct FHitResult* HitInfo, class AController** InstigatedBy, class AActor** DamageCauser, struct FGameplayEffectContextHandle* EffectContext);
void ReceiveBeginPlay();
void SuperShielderDied();
void FadeIn();
void FadeOut();
void ExecuteUbergraph_BGA_SuperShielder_Shield(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"kareemolim@gmail.com"
] | kareemolim@gmail.com |
14aff254154af7d82e136fa36486b2da353fc2f7 | 48a9d509e6cdec0c946f0cf0fcdceb7ef06a5121 | /CloudCompare/libs/qCC_glWindow/ccGuiParameters.h | e90f7b6cf4760877d6e6acf834a57b835a2eb4d9 | [] | no_license | ilcamf/CloudCompare-Qt | 3bc0495019e4d2e4f091a24bb99c55ee70e16ebd | 932df7b8daaa5e0db1ef658ecdc7dd2a26750da3 | refs/heads/master | 2020-03-26T11:09:17.914508 | 2018-08-08T17:59:26 | 2018-08-08T17:59:26 | 144,830,534 | 1 | 0 | null | 2018-08-15T09:01:49 | 2018-08-15T09:01:48 | null | UTF-8 | C++ | false | false | 4,651 | h | //##########################################################################
//# #
//# CLOUDCOMPARE #
//# #
//# This program is free software; you can redistribute it and/or modify #
//# it under the terms of the GNU General Public License as published by #
//# the Free Software Foundation; version 2 or later of the License. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU General Public License for more details. #
//# #
//# COPYRIGHT: EDF R&D / TELECOM ParisTech (ENST-TSI) #
//# #
//##########################################################################
#ifndef GUI_PARAMETERS_HEADER
#define GUI_PARAMETERS_HEADER
//Qt
#include <QString>
//qCC_db
#include <ccColorTypes.h>
/***************************************************
GUI parameters
***************************************************/
//! This class manages some persistent parameters (mostly for display)
/** Values of persistent parameters are stored by the system
(either in the registry or in a separate file depending on the OS).
**/
class ccGui
{
public:
//! GUI parameters
struct ParamStruct
{
//! Light diffuse color (RGBA)
ccColor::Rgbaf lightDiffuseColor;
//! Light ambient color (RGBA)
ccColor::Rgbaf lightAmbientColor;
//! Light specular color (RGBA)
ccColor::Rgbaf lightSpecularColor;
//! Default mesh diffuse color (front)
ccColor::Rgbaf meshFrontDiff;
//! Default mesh diffuse color (back)
ccColor::Rgbaf meshBackDiff;
//! Default mesh specular color
ccColor::Rgbaf meshSpecular;
//! Default text color
ccColor::Rgbub textDefaultCol;
//! Default 3D points color
ccColor::Rgbub pointsDefaultCol;
//! Background color
ccColor::Rgbub backgroundCol;
//! Labels background color
ccColor::Rgbub labelBackgroundCol;
//! Labels marker color
ccColor::Rgbub labelMarkerCol;
//! Bounding-boxes color
ccColor::Rgbub bbDefaultCol;
//! Use background gradient
bool drawBackgroundGradient;
//! Decimate meshes when moved
bool decimateMeshOnMove;
//! Min mesh size for decimation
unsigned minLoDMeshSize;
//! Decimate clouds when moved
bool decimateCloudOnMove;
//! Min cloud size for decimation
unsigned minLoDCloudSize;
//! Display cross in the middle of the screen
bool displayCross;
//! Whether to use VBOs for faster display
bool useVBOs;
//! Label marker size
unsigned labelMarkerSize;
//! Color scale option: show histogram next to color ramp
bool colorScaleShowHistogram;
//! Whether to use shader for color scale display (if available) or not
bool colorScaleUseShader;
//! Whether shader for color scale display is available or not
bool colorScaleShaderSupported;
//! Color scale ramp width (for display)
unsigned colorScaleRampWidth;
//! Default displayed font size
unsigned defaultFontSize;
//! Label font size
unsigned labelFontSize;
//! Displayed numbers precision
unsigned displayedNumPrecision;
//! Labels background opcaity
unsigned labelOpacity;
//! Zoom speed (1.0 by default)
double zoomSpeed;
//! Octree computation (for picking) behaviors
enum ComputeOctreeForPicking { ALWAYS = 0, ASK_USER = 1, NEVER = 2 };
//! Octree computation (for picking) behavior
ComputeOctreeForPicking autoComputeOctree;
//! Default constructor
ParamStruct();
//! Resets parameters to default values
void reset();
//! Loads from persistent DB
void fromPersistentSettings();
//! Saves to persistent DB
void toPersistentSettings() const;
//! Returns whether a given parameter is already defined in persistent settings or not
/** \param paramName the corresponding attribute name
**/
bool isInPersistentSettings(QString paramName) const;
};
//! Returns the stored values of each parameter.
static const ParamStruct& Parameters();
//! Sets GUI parameters
static void Set(const ParamStruct& params);
//! Release unique instance (if any)
static void ReleaseInstance();
protected:
//! Parameters set
ParamStruct params;
};
#endif
| [
"huihut@outlook.com"
] | huihut@outlook.com |
4a261d3d5a37c043dc71f968dd2e70945aa7893a | 6fc8ce3b7435694acfac95ef26cd457869fc3cbb | /codeeval/moderate/suggest-groups.cpp | 64ad3798c04cffcb4e62852bc0fd141359860446 | [] | no_license | ivan-filonov/online-challenges | 4089d6774a603ffcca530f5be3beb77007e5b15f | 3153830fc83730483edfde1bfb894e6dcd1f2fbf | refs/heads/master | 2023-05-11T22:36:54.393386 | 2023-04-27T15:42:01 | 2023-04-30T18:32:15 | 30,825,887 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,238 | cpp | /*
* Common base C++ source for codeeval solutions.
* */
#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <string>
#include <vector>
void test();
void process_file(char*);
int main(int argc, char ** argv) {
if( !1 ) {
test();
} else {
process_file(argv[1]);
}
return 0;
}
void add_line(const std::string &line);
void print_suggestions();
void test() {
add_line("Amira:Isaura,Lizzie,Madalyn,Margarito,Shakira,Un:Driving,Mineral collecting");
add_line("Elliot:Isaura,Madalyn,Margarito,Shakira:Juggling,Mineral collecting");
add_line("Isaura:Amira,Elliot,Lizzie,Margarito,Verla,Wilford:Juggling");
add_line("Lizzie:Amira,Isaura,Verla:Driving,Mineral collecting,Rugby");
add_line("Madalyn:Amira,Elliot,Margarito,Verla:Driving,Mineral collecting,Rugby");
add_line("Margarito:Amira,Elliot,Isaura,Madalyn,Un,Verla:Mineral collecting");
add_line("Shakira:Amira,Elliot,Verla,Wilford:Mineral collecting");
add_line("Un:Amira,Margarito,Wilford:");
add_line("Verla:Isaura,Lizzie,Madalyn,Margarito,Shakira:Driving,Juggling,Mineral collecting");
add_line("Wilford:Isaura,Shakira,Un:Driving");
print_suggestions();
std::cout << "Isaura:Driving,Mineral collecting" "\n";
std::cout << "Lizzie:Juggling" "\n";
std::cout << "Madalyn:Juggling" "\n";
std::cout << "Margarito:Driving,Juggling" "\n";
std::cout << "Shakira:Driving,Juggling" "\n";
std::cout << "Un:Driving,Mineral collecting" "\n";
}
namespace {
template<typename _1, typename _2> using map_t = std::map<_1,_2>;
typedef std::pair<int,int> ref_t;
template<typename _1> using set_t = std::set<_1>;
map_t<int,std::string> user_by_id;
map_t<std::string,int> user_by_name;
map_t<int,std::string> group_by_id;
map_t<std::string,int> group_by_name;
map_t<int, set_t<int>> friends;
map_t<int, set_t<int>> groups;
int user(const std::string& name) {
auto it = user_by_name.find(name);
if(user_by_name.end() != it) {
return it->second;
}
// add user
auto id = user_by_name[name] = user_by_name.size();
user_by_id[id] = name;
// add relations
friends[id];
groups[id];
return id;
}
void make_friends(const int uid1, const int uid2) {
friends[uid1].insert(uid2);
friends[uid2].insert(uid1);
}
int group(const std::string& name) {
auto it = group_by_name.find(name);
if(group_by_name.end() != it) {
return it->second;
}
// add group
auto id = group_by_name[name] = group_by_name.size();
group_by_id[id] = name;
return id;
}
}
void process_file(char* path) {
std::ifstream stream(path);
for(std::string line; std::getline(stream, line); ) {
add_line(line);
}
print_suggestions();
}
void add_line(const std::string &line) {
const auto dname = line.find(':');
const auto name = line.substr(0, dname);
const auto uid = user(name);
const auto dfriends = line.find(':', dname + 1);
for(int i = dname + 1; i < dfriends;) {
int j = line.find(',', i + 1);
if(j > dfriends) {
j = dfriends;
}
const auto fname = line.substr(i, j - i);
const auto uf = user(fname);
i = j + 1;
make_friends(uid, uf);
}
for(int i = dfriends + 1; i < line.length();) {
int j = line.find(',', i + 1);
if(j > line.length()) {
j = line.length();
}
const auto gname = line.substr(i, j - i);
i = j + 1;
groups[uid].insert(group(gname));
}
}
void print_suggestions() {
// for each user:
for(auto it_user = user_by_name.begin(); user_by_name.end() != it_user; ++it_user) {
const auto uid = it_user->second;
const auto uname = it_user->first;
const auto flist = friends[uid];
const auto glist = groups[uid];
// std::cout << "UID " << uid << ", UNAME " << uname << ", flist: " << flist.size() << ", glist: " << glist.size() << "\n";
map_t<int,int> g2c;
for(auto it_f = flist.begin(); flist.end() != it_f; ++it_f) {
auto fglist = groups[*it_f];
for(auto it_fg = fglist.begin(); fglist.end() != it_fg; ++it_fg) {
g2c[*it_fg]++;
}
}
int threshold = (flist.size() + 1 ) / 2 - 1;
std::vector<std::string> sgn;
for(auto it_g = group_by_name.begin(); group_by_name.end() != it_g; ++it_g) {
const auto gid = it_g->second;
const auto gname = it_g->first;
if(glist.count(it_g->second) > 0) {
continue;
}
if(g2c[gid] > threshold) {
sgn.push_back(gname);
}
}
if(sgn.empty()) {
continue;
}
std::cout << uname << ':';
for(int i = 0; i < sgn.size(); ++i) {
if(i) {
std::cout << ',';
}
std::cout << sgn[i];
}
std::cout << "\n";
}
}
| [
"ivan.filonov@gmail.com"
] | ivan.filonov@gmail.com |
0fa6b94f1765ba64ff551ed53d64b70a2557319c | 6e47e4637a3f7245714f241fd74883f79af3afb8 | /Secro/Secro/source/secro/framework/player/PlayerAttributes.h | a1d6058ab36e9d9ab15e8d596e3355ecd73084da | [] | no_license | LagMeester4000/secro | c359d5113236e4967288b5582a76b603f16506d5 | 0896ce8e86af66207a5724fe1af7e09c9538910c | refs/heads/master | 2020-04-19T07:36:43.849720 | 2020-01-24T11:45:18 | 2020-01-24T11:45:18 | 168,052,698 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,929 | h | #pragma once
#include <cereal/cereal.hpp>
#include <secro/framework/math/Curve.h>
namespace secro {
enum class PlaterAttributesVersion {
First,
};
struct PlayerAttributes {
//air
float fallSpeed;
float airAcceleration;
float airDeceleration;
float airMaxSpeed;
float fastfallSpeed;
//airdodge
float airdodgeInvStart, airdodgeInvDuration;
float airdodgeDuration;
float airdodgeSpeed;
float airdodgeLandingLag;
Curve airdodgeSpeedCurve;
//jump
int jumpAmount;
float jumpFullSpeed;
float jumpShortSpeed;
float doubleJumpSpeed;
float jumpSquatDuration;
//airdash
float airDashSpeed;
float airDashInputTimeFrame;
float airDashCooldown;
//dash (not the character dash, but the dash on the ground)
float dashDuration;
float dashInitialSpeed;
Curve dashSpeedCurve;
//ground move
float runAcceleration;
float walkMaxSpeed;
float runMaxSpeed;
float groundDeceleration;
//tech
float techInPlaceInvDuration;
float techInPlaceDuration;
float techRollInvDuration;
float techRollDuration;
float techRollSpeed;
};
}
#pragma region serialization
template<typename T>
void serialize(T& ar, secro::PlayerAttributes& attr, std::uint32_t const version)
{
switch (version)
{
case (std::uint32_t)secro::PlaterAttributesVersion::First:
ar(
CEREAL_NVP(attr.fallSpeed),
CEREAL_NVP(attr.airAcceleration),
CEREAL_NVP(attr.airDeceleration),
CEREAL_NVP(attr.airMaxSpeed),
CEREAL_NVP(attr.fastfallSpeed),
CEREAL_NVP(attr.jumpAmount),
CEREAL_NVP(attr.jumpFullSpeed),
CEREAL_NVP(attr.jumpShortSpeed),
CEREAL_NVP(attr.doubleJumpSpeed),
CEREAL_NVP(attr.jumpSquatDuration),
CEREAL_NVP(attr.dashDuration),
CEREAL_NVP(attr.dashInitialSpeed),
CEREAL_NVP(attr.runAcceleration),
CEREAL_NVP(attr.runMaxSpeed),
CEREAL_NVP(attr.walkMaxSpeed),
CEREAL_NVP(attr.groundDeceleration)
);
break;
}
}
#pragma endregion | [
"lagmeester4000@gmail.com"
] | lagmeester4000@gmail.com |
f6240428860a57250016d7ae9780643de19c8c36 | 47db2b092319ef72c3ae888ec6d60a00b1eb91a0 | /Src/ZipConverter.cpp | 0b41453848c779603760715bfe915ac395e6ef3b | [
"MIT"
] | permissive | Remag/ReversedLibrary | 2b42c4acc216f2f062b8d16726d4f785dcba7d8b | b206f3d1e6feea6aca1f49edf4ee2266005c61d0 | refs/heads/master | 2023-03-11T15:53:07.085315 | 2023-02-27T01:13:52 | 2023-02-27T01:13:52 | 183,803,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,282 | cpp | #include <ZipConverter.h>
#ifndef RELIB_NO_ZLIB
#include <zlib\zlib.h>
#include <ArrayBuffer.h>
#include <Array.h>
#include <Errors.h>
#include <StaticAllocators.h>
namespace Relib {
//////////////////////////////////////////////////////////////////////////
const int minWriteChunk = 64 * 1024;
const int maxWriteChunk = 64 * 1024 * 1024;
const int minZipSize = minWriteChunk;
extern const CError Err_ZlibInitError;
void CZipConverter::ZipData( CArrayView<BYTE> data, CArray<BYTE>& result )
{
const auto resultStartSize = result.Size();
z_stream zStream;
::memset( &zStream, 0, sizeof( zStream ) );
zStream.zalloc = allocationFunction;
zStream.zfree = freeFunction;
const auto initResult = deflateInit( &zStream, Z_DEFAULT_COMPRESSION );
check( initResult == Z_OK, Err_ZlibInitError, initResult );
zStream.avail_in = data.Size();
zStream.next_in = const_cast<BYTE*>( data.Ptr() );
const int writeChunk = Clamp( data.Size() / 4, minWriteChunk, maxWriteChunk );
for( ;; ) {
const int writePos = result.Size();
result.IncreaseSizeNoInitialize( result.Size() + writeChunk );
zStream.avail_out = writeChunk;
zStream.next_out = result.Ptr() + writePos;
const auto deflateResult = deflate( &zStream, Z_FINISH );
assert( deflateResult != Z_STREAM_ERROR );
if( deflateResult == Z_STREAM_END ) {
const auto totalByteCount = zStream.total_out + resultStartSize;
result.DeleteLast( result.Size() - totalByteCount );
break;
}
}
deflateEnd( &zStream );
}
const int minReadChunk = 64 * 1024;
const int maxReadChunk = 64 * 1024 * 1024;
extern const CError Err_ZlibInflateError;
void CZipConverter::UnzipData( CArrayView<BYTE> data, CArray<BYTE>& result )
{
const auto resultStartSize = result.Size();
z_stream zStream;
memset( &zStream, 0, sizeof( zStream ) );
zStream.zalloc = allocationFunction;
zStream.zfree = freeFunction;
const auto initResult = inflateInit( &zStream );
check( initResult == Z_OK, Err_ZlibInitError, initResult );
zStream.avail_in = data.Size();
zStream.next_in = const_cast<BYTE*>( data.Ptr() );
const int readChunk = Clamp( data.Size(), minReadChunk, maxReadChunk );
for( ;; ) {
const int readPos = result.Size();
result.IncreaseSizeNoInitialize( result.Size() + readChunk );
zStream.avail_out = readChunk;
zStream.next_out = result.Ptr() + readPos;
const auto inflateResult = inflate( &zStream, Z_NO_FLUSH );
if( inflateResult == Z_STREAM_END ) {
const auto totalByteCount = zStream.total_out + resultStartSize;
result.DeleteLast( result.Size() - totalByteCount );
break;
}
if( inflateResult == Z_NEED_DICT || inflateResult == Z_DATA_ERROR || inflateResult == Z_MEM_ERROR ) {
inflateEnd( &zStream );
check( false, Err_ZlibInflateError, inflateResult );
}
}
inflateEnd( &zStream );
}
void* CZipConverter::allocationFunction( void*, unsigned itemCount, unsigned itemSize )
{
const auto byteCount = itemSize * itemCount;
return CRuntimeHeap::Allocate( byteCount );
}
void CZipConverter::freeFunction( void*, void* ptr )
{
CRuntimeHeap::Free( ptr );
}
//////////////////////////////////////////////////////////////////////////
} // namespace Relib.
#endif // RELIB_NO_ZLIB | [
"remag91@gmail.com"
] | remag91@gmail.com |
7b7b760daed9743cc415de0b56bddf6b9cf46e49 | 3f3840bf7d0dd4b768b35fccbb30954ac37a8208 | /3_Implementation/src/List.cpp | 7606628be0ae5f96f4ae80bd2782923139bc756c | [] | no_license | git170060024/MiniProject_OOPS | a6f854e5a1e74c0ce301c81708c5bb74adb80339 | d6e97e4c073099ac3829d9e6a0855e1a83322d05 | refs/heads/main | 2023-07-20T11:49:35.658951 | 2021-09-04T10:32:05 | 2021-09-04T10:32:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,790 | cpp |
#include "shoppingcart.h"
#include<iostream>
using std::cout;
using std::endl;
//default constructor dynamically allocates a 4 element Item array
//that can be resized. It is filled with default Items
bool operator==(Item &a, Item &b)
{
if(a.getName() == b.getName())
return true;
else
return false;
}
List::List()
{
//default Item
Item newItems;
listSize = 4;
//dynamic allocation of Item array
itemlist = new Item[listSize];
//all elements filled with the default Item
for (int item = 0; item < listSize; item++)
itemlist[item] = newItems;
}
//destructor properly frees space taken to make dynamically
//allocated array for Items. This is automatically called
//before the program terminates
List::~List()
{
delete[] itemlist;
itemlist = nullptr;
listSize = 0;
}
//if the Item to be added is similar in name to an Item already in the list
//the user can either update it to the new Item or just leave it as is and no
//new Item will be added. Otherwise, a new dynamically allocated array will
//be created that is 1 larger then the array that is already being pointed to.
//The user entered Item will be added to the new array and the oringinal pointer
//will point to the new array while freeing the old array space
void List::addItem(Item item)
{
for (int index = 0; index < listSize; index++)
{
//overloaded == allows two Item names to be compared
if (item == itemlist[index])
{
cout << "That item already exists in the list. Would you like to update "
"it with what you entered? Type 1 for yes, 2 for no." << endl;
//input validation for postitive integer
int confirm = getUnsignedInt();
//if the input is anything other than 1 or 2
while (confirm != 1 && confirm != 2)
{
cout << "Error. Please only enter either 1 or 2." << endl;
confirm = getUnsignedInt();
}
//if the user chose yes, the Item at index is now replaced with
//the new Item the user typed out
if (confirm == 1)
{
itemlist[index] = item;
return;
}
//if the user chose no, the function exits
else
return;
}
}
//dyanmically allocated array that is 1 size larger than the list size
//before this
Item *biggerList = new Item[listSize + 1];
//copy all elements from the old array into the new
//this means there is just 1 more space to fill at the end
for (int item = 0; item < listSize; item++)
biggerList[item] = itemlist[item];
//free the old space and set the original pointer to
//point to the new array
delete[] itemlist;
itemlist = biggerList;
biggerList = nullptr;
//add new Item to the very end of the new array
itemlist[listSize] = item;
//the list size is now 1 larger
listSize += 1;
}
//since there are 4 default Items, if the list size is
//greater than 4, that means there is at least 1 Item
//that is not default, so it can be removed
//an array that is 1 element smaller is created
//this will remove the last Item in the array
void List::removeItem()
{
//if list size is greater than 4, remove can execute
if (listSize > 4)
{
//list size is now 1 less than before
listSize -= 1;
//dynamically allocated array that is 1 less than the last
Item *smallerList = new Item[listSize];
//copies all of the old Items into the new array
for (int item = 0; item < listSize; item++)
smallerList[item] = itemlist[item];
//free the old array and update pointer to new array
delete[] itemlist;
itemlist = smallerList;
smallerList = nullptr;
}
}
//prints the info of all Items. If the last element in the
//list is a default Item, this means all elements are currently
//default items and the user is told the list is empty
void List::print()
{
//accum for grand total price of list
int total = 0;
for (int item = 0; item < listSize; item++)
{
//if the Item has a real name, unlike the default does
if (itemlist[item].getName() != "")
{
cout << "Name: " << itemlist[item].getName() << endl;
cout << "Unit: " << itemlist[item].getUnit() << endl;
cout << "Quantity: " << itemlist[item].getQuantity() << endl;
cout << "Unit Price: $" << itemlist[item].getPrice() << endl;
cout << "Extended Price: $" << itemlist[item].extendedPrice() << endl;
cout << endl;
total += itemlist[item].extendedPrice();
}
}
//last element is a default Item
if (itemlist[listSize - 1].getName() == "")
cout << "The list is empty." << endl;
cout << "The grand total of the list is: $" << total << endl;
}
//this allows the name of two Items to be compared
//this is used in addItem() to check to see if the
//user is trying to add an Item already in the list
| [
"mohammedferoz17@gmail.com"
] | mohammedferoz17@gmail.com |
5fb608ecd4775613b6334fa8043020d0d5f99b8c | 27ebd7f3cf3bd1d483f8a1d27c3575c720f642e5 | /Think_in_C++/code/C21/Compose2.cpp | 5aa8e3b4fbaf826b712955101b7706a4b327f10b | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | walte/resourcerepo | a6ad55e907c72811b7aec82be7bfd5c58edecf5c | b8450232a098077965e76eb7134eca894b0a38c6 | refs/heads/master | 2016-09-06T05:35:18.599888 | 2013-11-22T06:43:35 | 2013-11-22T06:43:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 900 | cpp | //: C21:Compose2.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 1999
// Copyright notice in Copyright.txt
// Using the SGI STL compose2() function
#include "copy_if.h"
#include <algorithm>
#include <vector>
#include <iostream>
#include <functional>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(0));
vector<int> v(100);
generate(v.begin(), v.end(), rand);
transform(v.begin(), v.end(), v.begin(),
bind2nd(divides<int>(), RAND_MAX/100));
vector<int> r;
copy_if(v.begin(), v.end(), back_inserter(r),
compose2(logical_and<bool>(),
bind2nd(greater_equal<int>(), 30),
bind2nd(less_equal<int>(), 40)));
sort(r.begin(), r.end());
copy(r.begin(), r.end(),
ostream_iterator<int>(cout, " "));
cout << endl;
} ///:~
| [
"walther.zhao@gmail.com"
] | walther.zhao@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.