blob_id stringlengths 40 40 | language stringclasses 1 value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34 values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | text stringlengths 13 4.23M | download_success bool 1 class |
|---|---|---|---|---|---|---|---|---|---|---|---|
c6016e2fda7acdb0e563f49667f98a81141b014a | C++ | wenfh2020/c_test | /interview/test_index.cpp | UTF-8 | 395 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <map>
int main() {
int n, k, v;
std::map<int, int> _map;
std::cin >> n;
while (n-- > 0) {
std::cin >> k >> v;
auto it = _map.insert({k, v});
if (!it.second) {
it.first->second += v;
}
}
for (auto it : _map) {
std::cout << it.first << " " << it.second << std::endl;
}
return 0;
} | true |
eb335f0441e234a1a21a656211b21209fd006775 | C++ | yuliy/sport_programming | /codeforces/379/B/main.cpp | UTF-8 | 1,074 | 2.609375 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <vector>
#include <deque>
#include <cstring>
#include <string>
#include <map>
#include <set>
#include <list>
#include <algorithm>
using namespace std;
int main() {
int n;
scanf("%d", &n);
vector<int> a(n);
for (int i = 0; i < n; ++i)
scanf("%d", &a[i]);
int total = accumulate(a.begin(), a.end(), 0);
bool movingRight = true;
for (int pos = 1; total; ) {
if (a[pos-1]) {
--a[pos-1];
printf("P");
--total;
}
if (0 == total)
break;
if (movingRight) {
if (pos == n) {
--pos;
printf("L");
movingRight = false;
} else {
++pos;
printf("R");
}
} else {
if (pos == 1) {
++pos;
printf("R");
movingRight = true;
} else {
--pos;
printf("L");
}
}
}
return 0;
}
| true |
1c67622340e90ca099f0d2c3efbce4f16be4d95c | C++ | dgquintas/my-code-samples | /cpp/compilador/TS/tipoarray.h | UTF-8 | 464 | 2.625 | 3 | [] | no_license | #ifndef TIPOARRAY_H
#define TIPOARRAY_H
#include "tipo.h"
#include <string>
using namespace std;
class TipoArray: public Tipo {
public:
TipoArray(Tipo*, size_t tam);
TipoArray(unsigned int tam);
virtual unsigned int getTam ( );
virtual string getNombre() { return "array";};
Tipo* getTipo ( );
void setTipo (Tipo* tipo);
virtual bool pasoPorReferencia() { return true; };
private:
size_t tam;
Tipo* tipo;
};
#endif
| true |
816b3de962d63d9d4ebd1c2846f0e3b61c1087b7 | C++ | JahooYoung/RISCV-Simulator | /src/elf.hpp | UTF-8 | 4,027 | 2.671875 | 3 | [] | no_license | #ifndef ELF_HPP
#define ELF_HPP
#include <cstdint>
/* Type for a 16-bit quantity. */
typedef uint16_t Elf64_Half;
/* Types for signed and unsigned 32-bit quantities. */
typedef uint32_t Elf64_Word;
typedef int32_t Elf64_Sword;
/* Types for signed and unsigned 64-bit quantities. */
typedef uint64_t Elf64_Xword;
typedef int64_t Elf64_Sxword;
/* Type of addresses. */
typedef uint64_t Elf64_Addr;
/* Type of file offsets. */
typedef uint64_t Elf64_Off;
struct Elf64_Ehdr
{
unsigned char e_ident[16]; /* ELF identification */
Elf64_Half e_type; /* Object file type */
Elf64_Half e_machine; /* Machine type */
Elf64_Word e_version; /* Object file version */
Elf64_Addr e_entry; /* Entry point address */
Elf64_Off e_phoff; /* Program header offset */
Elf64_Off e_shoff; /* Section header offset */
Elf64_Word e_flags; /* Processor-specific flags */
Elf64_Half e_ehsize; /* ELF header size */
Elf64_Half e_phentsize; /* Size of program header entry */
Elf64_Half e_phnum; /* Number of program header entries */
Elf64_Half e_shentsize; /* Size of section header entry */
Elf64_Half e_shnum; /* Number of section header entries */
Elf64_Half e_shstrndx; /* Section name string table index */
};
/* Conglomeration of the identification bytes, for easy testing as a word. */
#define ELFMAG "\177ELF"
#define SELFMAG 4
#define EI_CLASS 4
#define EI_DATA 5
#define EI_VERSION 6
#define EI_OSABI 7
#define EI_ABIVERSION 8
#define EI_PAD 9
#define EI_NIDENT 16
struct Elf64_Shdr
{
Elf64_Word sh_name; /* Section name */
Elf64_Word sh_type; /* Section type */
Elf64_Xword sh_flags; /* Section attributes */
Elf64_Addr sh_addr; /* Virtual address in memory */
Elf64_Off sh_offset; /* Offset in file */
Elf64_Xword sh_size; /* Size of section */
Elf64_Word sh_link; /* Link to other section */
Elf64_Word sh_info; /* Miscellaneous information */
Elf64_Xword sh_addralign; /* Address alignment boundary */
Elf64_Xword sh_entsize; /* Size of entries, if section has table */
};
/* Legal values for sh_type (section type). */
#define SHT_NULL 0 /* Section header table entry unused */
#define SHT_PROGBITS 1 /* Program data */
#define SHT_SYMTAB 2 /* Symbol table */
#define SHT_STRTAB 3 /* String table */
/* Special section indices. */
#define SHN_UNDEF 0
#define SHN_LOPROC 0xFF00
#define SHN_HIPROC 0xFF1F
#define SHN_LOOS 0xFF20
#define SHN_HIOS 0xFF3F
#define SHN_ABS 0xFFF1
#define SHN_COMMON 0xFFF2
struct Elf64_Sym
{
Elf64_Word st_name; /* Symbol name */
unsigned char st_info; /* Type and Binding attributes */
unsigned char st_other; /* Reserved */
Elf64_Half st_shndx; /* Section table index */
Elf64_Addr st_value; /* Symbol value */
Elf64_Xword st_size; /* Size of object (e.g., common) */
};
/* How to extract and insert information held in the st_info field. */
#define ELF32_ST_BIND(val) (((unsigned char) (val)) >> 4)
#define ELF32_ST_TYPE(val) ((val) & 0xf)
#define ELF32_ST_INFO(bind, type) (((bind) << 4) + ((type) & 0xf))
/* Both Elf32_Sym and Elf64_Sym use the same one-byte st_info field. */
#define ELF64_ST_BIND(val) ELF32_ST_BIND (val)
#define ELF64_ST_TYPE(val) ELF32_ST_TYPE (val)
#define ELF64_ST_INFO(bind, type) ELF32_ST_INFO ((bind), (type))
struct Elf64_Phdr
{
Elf64_Word p_type; /* Type of segment */
Elf64_Word p_flags; /* Segment attributes */
Elf64_Off p_offset; /* Offset in file */
Elf64_Addr p_vaddr; /* Virtual address in memory */
Elf64_Addr p_paddr; /* Reserved */
Elf64_Xword p_filesz; /* Size of segment in file */
Elf64_Xword p_memsz; /* Size of segment in memory */
Elf64_Xword p_align; /* Alignment of segment */
};
void read_elf();
void read_elf_header();
void read_section_headers();
void read_symtable();
void read_program_headers();
#endif
| true |
e67aa36d75fe57a5c85bea93157f1e9e3a3b7fd3 | C++ | Pentagon03/competitive-programming | /project-euler/volume07/319.cc | UTF-8 | 1,472 | 2.875 | 3 | [] | no_license | #include <bits/stdc++.h>
const int mod = 1000000000;
const int N = 1000000;
long t[N], d[N];
std::map<long, long> cache;
inline long mul_mod(long a, long b, long mod) {
if (mod < int(1e9)) return a * b % mod;
long k = (long)((long double)a * b / mod);
long res = a * b - k * mod;
res %= mod;
if (res < 0) res += mod;
return res;
}
long pow_mod(long a, long n, long m) {
long r = 1;
for (; n; n >>= 1) {
if (n & 1) r = mul_mod(r, a, m);
a = mul_mod(a, a, m);
}
return r;
}
void prepare() {
long p2 = 1, p3 = 1;
for (int i = 1; i < N; ++i) {
p2 = p2 * 2 % mod;
p3 = p3 * 3 % mod;
if (i == 1) d[i] = 1;
else d[i] += p3 - p2;
d[i] %= mod; d[i] += mod; d[i] %= mod;
for (int j = i + i; j < N; j += i) d[j] -= d[i];
t[i] = (t[i - 1] + d[i]) % mod;
}
}
long f(long n) {
long ret = pow_mod(3, n + 1, mod * 2) - pow_mod(2, n + 2, mod * 2) + 1;
ret %= mod * 2; ret += mod * 2; ret %= mod * 2;
return ret / 2;
}
// t(n) = (3^(n+1)-2^(n+2)+1)/2 - sum_{i=2}^{n} t(n/i)
long run(long n) {
if (n < N) return t[n];
if (cache.count(n)) return cache[n];
long ret = f(n);
for (long i = 2, j; i <= n; i = j + 1) {
j = n / (n / i);
ret -= run(n / i) * (j - i + 1) % mod;
}
ret %= mod; ret += mod; ret %= mod;
return cache[n] = ret;
}
int main() {
prepare();
std::cout << run(10) << std::endl;
std::cout << run(20) << std::endl;
std::cout << run(10000000000ll) << std::endl;
return 0;
}
| true |
b8c38182c2ce8b557c7366b28fe7c28b6c996d08 | C++ | jiandingzhe/treeface | /src/treeface/misc/StringCast.cpp | UTF-8 | 44,461 | 2.625 | 3 | [
"MIT"
] | permissive | #include "treeface/misc/StringCast.h"
#include <stdexcept>
using namespace treeface;
namespace treecore
{
template<>
bool fromString<treeface::MaterialType>( const treecore::String& string, treeface::MaterialType& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "raw") result = treeface::MATERIAL_RAW;
else if (str_lc == "scene_graph") result = treeface::MATERIAL_SCENE_GRAPH;
else if (str_lc == "screen_space") result = treeface::MATERIAL_SCREEN_SPACE;
else if (str_lc == "vector_graphics") result = treeface::MATERIAL_VECTOR_GRAPHICS;
else return false;
return true;
}
template<>
treecore::String toString<treeface::MaterialType>( treeface::MaterialType value )
{
switch (value)
{
case treeface::MATERIAL_RAW: return "raw";
case treeface::MATERIAL_SCENE_GRAPH: return "scene_graph";
case treeface::MATERIAL_SCREEN_SPACE: return "screen_space";
case treeface::MATERIAL_VECTOR_GRAPHICS: return "vector_graphics";
default:
throw std::invalid_argument( ( "invalid treeface material type enum: " + String( int(value) ) ).toRawUTF8() );
}
}
template<>
bool fromString<FREE_IMAGE_FORMAT>( const treecore::String& string, FREE_IMAGE_FORMAT& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "unknown") result = FIF_UNKNOWN;
else if (str_lc == "bmp") result = FIF_BMP;
else if (str_lc == "ico") result = FIF_ICO;
else if (str_lc == "jpg") result = FIF_JPEG;
else if (str_lc == "jpe") result = FIF_JPEG;
else if (str_lc == "jif") result = FIF_JPEG;
else if (str_lc == "jpeg") result = FIF_JPEG;
else if (str_lc == "jng") result = FIF_JNG;
else if (str_lc == "koa") result = FIF_KOALA;
else if (str_lc == "koala") result = FIF_KOALA;
else if (str_lc == "iff") result = FIF_IFF;
else if (str_lc == "lbm") result = FIF_LBM;
else if (str_lc == "mng") result = FIF_MNG;
else if (str_lc == "pbm") result = FIF_PBM;
else if (str_lc == "pbmraw") result = FIF_PBMRAW;
else if (str_lc == "pcd") result = FIF_PCD;
else if (str_lc == "pcx") result = FIF_PCX;
else if (str_lc == "pgm") result = FIF_PGM;
else if (str_lc == "pgmraw") result = FIF_PGMRAW;
else if (str_lc == "png") result = FIF_PNG;
else if (str_lc == "ppm") result = FIF_PPM;
else if (str_lc == "ppmraw") result = FIF_PPMRAW;
else if (str_lc == "ras") result = FIF_RAS;
else if (str_lc == "tga") result = FIF_TARGA;
else if (str_lc == "targa") result = FIF_TARGA;
else if (str_lc == "tif") result = FIF_TIFF;
else if (str_lc == "tiff") result = FIF_TIFF;
else if (str_lc == "wbmp") result = FIF_WBMP;
else if (str_lc == "psd") result = FIF_PSD;
else if (str_lc == "cut") result = FIF_CUT;
else if (str_lc == "xbm") result = FIF_XBM;
else if (str_lc == "xpm") result = FIF_XPM;
else if (str_lc == "dds") result = FIF_DDS;
else if (str_lc == "gif") result = FIF_GIF;
else if (str_lc == "hdr") result = FIF_HDR;
else if (str_lc == "g3") result = FIF_FAXG3;
else if (str_lc == "faxg3") result = FIF_FAXG3;
else if (str_lc == "sgi") result = FIF_SGI;
else if (str_lc == "exr") result = FIF_EXR;
else if (str_lc == "j2k") result = FIF_J2K;
else if (str_lc == "j2c") result = FIF_J2K;
else if (str_lc == "jp2") result = FIF_JP2;
else if (str_lc == "pfm") result = FIF_PFM;
else if (str_lc == "pct") result = FIF_PICT;
else if (str_lc == "pict") result = FIF_PICT;
else if (str_lc == "pic") result = FIF_PICT;
else if (str_lc == "raw") result = FIF_RAW;
else
return false;
return true;
}
template<>
treecore::String toString<FREE_IMAGE_FORMAT>( FREE_IMAGE_FORMAT arg )
{
switch (arg)
{
case FIF_UNKNOWN: return "unknown";
case FIF_BMP: return "bmp";
case FIF_ICO: return "ico";
case FIF_JPEG: return "jpg";
case FIF_JNG: return "jng";
case FIF_KOALA: return "koa";
case FIF_LBM: return "iff";
//case FIF_IFF:
case FIF_MNG: return "mng";
case FIF_PBM: return "pbm";
case FIF_PBMRAW: return "pbmraw";
case FIF_PCD: return "pcd";
case FIF_PCX: return "pcx";
case FIF_PGM: return "pgm";
case FIF_PGMRAW: return "pgmraw";
case FIF_PNG: return "png";
case FIF_PPM: return "ppm";
case FIF_PPMRAW: return "ppmraw";
case FIF_RAS: return "ras";
case FIF_TARGA: return "tga";
case FIF_TIFF: return "tif";
case FIF_WBMP: return "wbmp";
case FIF_PSD: return "psd";
case FIF_CUT: return "cut";
case FIF_XBM: return "xbm";
case FIF_XPM: return "xpm";
case FIF_DDS: return "dds";
case FIF_GIF: return "gif";
case FIF_HDR: return "hdr";
case FIF_FAXG3: return "g3";
case FIF_SGI: return "sgi";
case FIF_EXR: return "exr";
case FIF_J2K: return "j2k";
case FIF_JP2: return "jp2";
case FIF_PFM: return "pfm";
case FIF_PICT: return "pct";
case FIF_RAW: return "raw";
default: throw std::invalid_argument( ( "invalid FreeImage format enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
bool fromString<FREE_IMAGE_TYPE>( const treecore::String& string, FREE_IMAGE_TYPE& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "unknown") result = FIT_UNKNOWN;
else if (str_lc == "bitmap") result = FIT_BITMAP;
else if (str_lc == "uint16") result = FIT_UINT16;
else if (str_lc == "int16") result = FIT_INT16;
else if (str_lc == "uint32") result = FIT_UINT32;
else if (str_lc == "int32") result = FIT_INT32;
else if (str_lc == "float") result = FIT_FLOAT;
else if (str_lc == "double") result = FIT_DOUBLE;
else if (str_lc == "complex") result = FIT_COMPLEX;
else if (str_lc == "rgb16") result = FIT_RGB16;
else if (str_lc == "rgba16") result = FIT_RGBA16;
else if (str_lc == "rgbf") result = FIT_RGBF;
else if (str_lc == "rgbaf") result = FIT_RGBAF;
else
return false;
return true;
}
template<>
treecore::String toString<FREE_IMAGE_TYPE>( FREE_IMAGE_TYPE arg )
{
switch (arg)
{
case FIT_UNKNOWN: return "unknown";
case FIT_BITMAP: return "bitmap";
case FIT_UINT16: return "uint16";
case FIT_INT16: return "int16";
case FIT_UINT32: return "uint32";
case FIT_INT32: return "int32";
case FIT_FLOAT: return "float";
case FIT_DOUBLE: return "double";
case FIT_COMPLEX: return "complex";
case FIT_RGB16: return "rgb16";
case FIT_RGBA16: return "rgba16";
case FIT_RGBF: return "rgbf";
case FIT_RGBAF: return "rgbaf";
default:
throw std::invalid_argument( ( "invalid FreeImage type enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
bool fromString<FREE_IMAGE_COLOR_TYPE>( const treecore::String& string, FREE_IMAGE_COLOR_TYPE& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "miniswhite") result = FIC_MINISWHITE;
else if (str_lc == "minisblack") result = FIC_MINISBLACK;
else if (str_lc == "rgb") result = FIC_RGB;
else if (str_lc == "palette") result = FIC_PALETTE;
else if (str_lc == "rgbalpha") result = FIC_RGBALPHA;
else if (str_lc == "rgba") result = FIC_RGBALPHA;
else if (str_lc == "cmyk") result = FIC_CMYK;
else
return false;
return true;
}
template<>
treecore::String toString<FREE_IMAGE_COLOR_TYPE>( FREE_IMAGE_COLOR_TYPE arg )
{
switch (arg)
{
case FIC_MINISWHITE: return "miniswhite";
case FIC_MINISBLACK: return "minisblack";
case FIC_RGB: return "rgb";
case FIC_PALETTE: return "palette";
case FIC_RGBALPHA: return "rgba";
case FIC_CMYK: return "cmyk";
default:
throw std::invalid_argument( ( "invalid FreeImage color type enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
bool fromString<LineCap>( const String& str, LineCap& result )
{
String value_lc = str.toLowerCase();
if ( value_lc.contains( "butt" ) ) result = LINE_CAP_BUTT;
else if ( value_lc.contains( "round" ) ) result = LINE_CAP_ROUND;
else if ( value_lc.contains( "square" ) ) result = LINE_CAP_SQUARE;
else
return false;
return true;
}
template<>
bool fromString<LineJoin>( const String& str, LineJoin& result )
{
String value_lc = str.toLowerCase();
if ( value_lc.contains( "bevel" ) ) result = LINE_JOIN_BEVEL;
else if ( value_lc.contains( "miter" ) ) result = LINE_JOIN_MITER;
else if ( value_lc.contains( "round" ) ) result = LINE_JOIN_ROUND;
else
return false;
return true;
}
template<>
treecore::String toString<LineCap>( LineCap cap )
{
switch (cap)
{
case LINE_CAP_BUTT: return "butt";
case LINE_CAP_ROUND: return "round";
case LINE_CAP_SQUARE: return "square";
default:
throw std::invalid_argument( ( "invalid treeface line cap enum: " + String( int(cap) ) ).toRawUTF8() );
}
}
template<>
treecore::String toString<LineJoin>( LineJoin join )
{
switch (join)
{
case LINE_JOIN_BEVEL: return "bevel";
case LINE_JOIN_MITER: return "miter";
case LINE_JOIN_ROUND: return "round";
default:
throw std::invalid_argument( ( "invalid treeface line join enum: " + String( int(join) ) ).toRawUTF8() );
}
}
template<>
bool fromString<treeface::GLBufferType>( const treecore::String& string, treeface::GLBufferType& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "vertex" ||
str_lc == "array") result = TFGL_BUFFER_VERTEX;
else if (str_lc == "index" ||
str_lc == "element_array") result = TFGL_BUFFER_INDEX;
else if (str_lc == "pack" ||
str_lc == "pixel_pack") result = TFGL_BUFFER_PACK;
else if (str_lc == "unpack" ||
str_lc == "pixel_unpack") result = TFGL_BUFFER_UNPACK;
else if (str_lc == "read" ||
str_lc == "copy_read") result = TFGL_BUFFER_READ;
else if (str_lc == "write" ||
str_lc == "copy_write") result = TFGL_BUFFER_WRITE;
else if (str_lc == "feedback" ||
str_lc == "transform_feedback") result = TFGL_BUFFER_FEEDBACK;
else if (str_lc == "uniform") result = TFGL_BUFFER_UNIFORM;
else
return false;
return true;
}
template<>
bool fromString<treeface::GLBufferUsage>( const treecore::String& string, treeface::GLBufferUsage& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "stream_draw") result = TFGL_BUFFER_STREAM_DRAW;
else if (str_lc == "stream_read") result = TFGL_BUFFER_STREAM_READ;
else if (str_lc == "stream_copy") result = TFGL_BUFFER_STREAM_COPY;
else if (str_lc == "static_draw") result = TFGL_BUFFER_STATIC_DRAW;
else if (str_lc == "static_read") result = TFGL_BUFFER_STATIC_READ;
else if (str_lc == "static_copy") result = TFGL_BUFFER_STATIC_COPY;
else if (str_lc == "dynamic_draw") result = TFGL_BUFFER_DYNAMIC_DRAW;
else if (str_lc == "dynamic_read") result = TFGL_BUFFER_DYNAMIC_READ;
else if (str_lc == "dynamic_copy") result = TFGL_BUFFER_DYNAMIC_COPY;
else
return false;
return true;
}
template<>
bool fromString<treeface::GLImageFormat>( const treecore::String& string, treeface::GLImageFormat& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "alpha") result = TFGL_IMAGE_FORMAT_ALPHA;
else if (str_lc == "rgba") result = TFGL_IMAGE_FORMAT_RGBA;
else if (str_lc == "rgb") result = TFGL_IMAGE_FORMAT_RGB;
else if (str_lc == "rg") result = TFGL_IMAGE_FORMAT_RG;
else if (str_lc == "red") result = TFGL_IMAGE_FORMAT_RED;
else if (str_lc == "rgba_int") result = TFGL_IMAGE_FORMAT_RGBA_INT;
else if (str_lc == "rgb_int") result = TFGL_IMAGE_FORMAT_RGB_INT;
else if (str_lc == "rg_int") result = TFGL_IMAGE_FORMAT_RG_INT;
else if (str_lc == "red_int") result = TFGL_IMAGE_FORMAT_RED_INT;
else if (str_lc == "depth") result = TFGL_IMAGE_FORMAT_DEPTH;
else if (str_lc == "depth_stencil") result = TFGL_IMAGE_FORMAT_DEPTH_STENCIL;
else if (str_lc == "luminance_") result = TFGL_IMAGE_FORMAT_LUMINANCE;
else if (str_lc == "luminance_alpha") result = TFGL_IMAGE_FORMAT_LUMINANCE_ALPHA;
else
return false;
return true;
}
template<>
bool fromString<treeface::GLInternalImageFormat>( const treecore::String& string, treeface::GLInternalImageFormat& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "alpha") result = TFGL_INTERNAL_IMAGE_FORMAT_ALPHA;
else if (str_lc == "blue") result = TFGL_INTERNAL_IMAGE_FORMAT_BLUE;
else if (str_lc == "green") result = TFGL_INTERNAL_IMAGE_FORMAT_GREEN;
else if (str_lc == "red") result = TFGL_INTERNAL_IMAGE_FORMAT_RED;
else if (str_lc == "rgb") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB;
else if (str_lc == "rgba") result = TFGL_INTERNAL_IMAGE_FORMAT_RGBA;
else if (str_lc == "luminance_alpha") result = TFGL_INTERNAL_IMAGE_FORMAT_LUMINANCE_ALPHA;
else if (str_lc == "luminance") result = TFGL_INTERNAL_IMAGE_FORMAT_LUMINANCE;
else if (str_lc == "depth_component16" ||
str_lc == "depth16") result = TFGL_INTERNAL_IMAGE_FORMAT_DEPTH16;
else if (str_lc == "depth_component24" ||
str_lc == "depth24") result = TFGL_INTERNAL_IMAGE_FORMAT_DEPTH24;
else if (str_lc == "depth_component32f" ||
str_lc == "depth32f") result = TFGL_INTERNAL_IMAGE_FORMAT_DEPTH32F;
else if (str_lc == "depth24_stencil8") result = TFGL_INTERNAL_IMAGE_FORMAT_DEPTH24_STENCIL8;
else if (str_lc == "depth32f_stencil8") result = TFGL_INTERNAL_IMAGE_FORMAT_DEPTH32F_STENCIL8;
else if (str_lc == "r8" ||
str_lc == "red8") result = TFGL_INTERNAL_IMAGE_FORMAT_R8;
else if (str_lc == "r8_snorm" ||
str_lc == "red8_snorm") result = TFGL_INTERNAL_IMAGE_FORMAT_R8_SNORM;
else if (str_lc == "r16f" ||
str_lc == "red16f") result = TFGL_INTERNAL_IMAGE_FORMAT_R16F;
else if (str_lc == "r32f" ||
str_lc == "red32f") result = TFGL_INTERNAL_IMAGE_FORMAT_R32F;
else if (str_lc == "r16ui" ||
str_lc == "red16ui") result = TFGL_INTERNAL_IMAGE_FORMAT_R16UI;
else if (str_lc == "r16i" ||
str_lc == "red16i") result = TFGL_INTERNAL_IMAGE_FORMAT_R16I;
else if (str_lc == "r32ui" ||
str_lc == "red32ui") result = TFGL_INTERNAL_IMAGE_FORMAT_R32UI;
else if (str_lc == "r32i" ||
str_lc == "red32i") result = TFGL_INTERNAL_IMAGE_FORMAT_R32I;
else if (str_lc == "rg8") result = TFGL_INTERNAL_IMAGE_FORMAT_RG8;
else if (str_lc == "rg8_snorm") result = TFGL_INTERNAL_IMAGE_FORMAT_RG8_SNORM;
else if (str_lc == "rg16f") result = TFGL_INTERNAL_IMAGE_FORMAT_RG16F;
else if (str_lc == "rg32f") result = TFGL_INTERNAL_IMAGE_FORMAT_RG32F;
else if (str_lc == "rg8ui") result = TFGL_INTERNAL_IMAGE_FORMAT_RG8UI;
else if (str_lc == "rg8i") result = TFGL_INTERNAL_IMAGE_FORMAT_RG8I;
else if (str_lc == "rg16ui") result = TFGL_INTERNAL_IMAGE_FORMAT_RG16UI;
else if (str_lc == "rg16i") result = TFGL_INTERNAL_IMAGE_FORMAT_RG16I;
else if (str_lc == "rg32ui") result = TFGL_INTERNAL_IMAGE_FORMAT_RG32UI;
else if (str_lc == "rg32i") result = TFGL_INTERNAL_IMAGE_FORMAT_RG32I;
else if (str_lc == "rgb8") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB8;
else if (str_lc == "srgb8") result = TFGL_INTERNAL_IMAGE_FORMAT_SRGB8;
else if (str_lc == "rgb565") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB565;
else if (str_lc == "rgb8_snorm") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB8_SNORM;
else if (str_lc == "r11f_g11f_b10f") result = TFGL_INTERNAL_IMAGE_FORMAT_R11F_G11F_B10F;
else if (str_lc == "rgb9_e5") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB9_E5;
else if (str_lc == "rgb16f") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB16F;
else if (str_lc == "rgb32f") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB32F;
else if (str_lc == "rgb8ui") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB8UI;
else if (str_lc == "rgb8i") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB8I;
else if (str_lc == "rgb16ui") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB16UI;
else if (str_lc == "rgb16i") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB16I;
else if (str_lc == "rgb32ui") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB32UI;
else if (str_lc == "rgb32i") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB32I;
else if (str_lc == "rgba8") result = TFGL_INTERNAL_IMAGE_FORMAT_RGBA8;
else if (str_lc == "srgb8_alpha8") result = TFGL_INTERNAL_IMAGE_FORMAT_SRGB8_ALPHA8;
else if (str_lc == "rgba8_snorm") result = TFGL_INTERNAL_IMAGE_FORMAT_RGBA8_SNORM;
else if (str_lc == "rgb5_a1") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB5_A1;
else if (str_lc == "rgba4") result = TFGL_INTERNAL_IMAGE_FORMAT_RGBA4;
else if (str_lc == "rgb10_a2") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB10_A2;
else if (str_lc == "rgba16f") result = TFGL_INTERNAL_IMAGE_FORMAT_RGBA16F;
else if (str_lc == "rgba32f") result = TFGL_INTERNAL_IMAGE_FORMAT_RGBA32F;
else if (str_lc == "rgba8ui") result = TFGL_INTERNAL_IMAGE_FORMAT_RGBA8UI;
else if (str_lc == "rgba8i") result = TFGL_INTERNAL_IMAGE_FORMAT_RGBA8I;
else if (str_lc == "rgb10_a2ui") result = TFGL_INTERNAL_IMAGE_FORMAT_RGB10_A2UI;
else if (str_lc == "rgba16ui") result = TFGL_INTERNAL_IMAGE_FORMAT_RGBA16UI;
else if (str_lc == "rgba16i") result = TFGL_INTERNAL_IMAGE_FORMAT_RGBA16I;
else if (str_lc == "rgba32i") result = TFGL_INTERNAL_IMAGE_FORMAT_RGBA32I;
else if (str_lc == "rgba32ui") result = TFGL_INTERNAL_IMAGE_FORMAT_RGBA32UI;
else
return false;
return true;
}
template<>
bool fromString<treeface::GLImageDataType>( const String& str, treeface::GLImageDataType& result )
{
String str_lc = str.toLowerCase();
if (str_lc == "byte") result = TFGL_IMAGE_DATA_BYTE;
else if (str_lc == "unsigned_byte") result = TFGL_IMAGE_DATA_UNSIGNED_BYTE;
else if (str_lc == "short") result = TFGL_IMAGE_DATA_SHORT;
else if (str_lc == "unsigned_short" || str == "ushort") result = TFGL_IMAGE_DATA_UNSIGNED_SHORT;
else if (str_lc == "5_6_5") result = TFGL_IMAGE_DATA_UNSIGNED_SHORT_5_6_5;
else if (str_lc == "4_4_4_4") result = TFGL_IMAGE_DATA_UNSIGNED_SHORT_4_4_4_4;
else if (str_lc == "5_5_5_1") result = TFGL_IMAGE_DATA_UNSIGNED_SHORT_5_5_5_1;
else if (str_lc == "int") result = TFGL_IMAGE_DATA_INT;
else if (str_lc == "unsigned_int" || str == "uint") result = TFGL_IMAGE_DATA_UNSIGNED_INT;
else if (str_lc == "10f_11f_11f_rev") result = TFGL_IMAGE_DATA_UNSIGNED_INT_10F_11F_11F_REV;
else if (str_lc == "5_9_9_9_rev") result = TFGL_IMAGE_DATA_UNSIGNED_INT_5_9_9_9_REV;
else if (str_lc == "2_10_10_10_rev") result = TFGL_IMAGE_DATA_UNSIGNED_INT_2_10_10_10_REV;
else if (str_lc == "24_8") result = TFGL_IMAGE_DATA_UNSIGNED_INT_24_8;
else if (str_lc == "half_float") result = TFGL_IMAGE_DATA_HALF_FLOAT;
else if (str_lc == "float") result = TFGL_IMAGE_DATA_FLOAT;
else if (str_lc == "f32_24_8") result = TFGL_IMAGE_DATA_FLOAT_32_UNSIGNED_INT_24_8_REV;
else
return false;
return true;
}
template<>
bool fromString<treeface::GLPrimitive>( const treecore::String& string, treeface::GLPrimitive& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "points") result = TFGL_PRIMITIVE_POINTS;
else if (str_lc == "lines") result = TFGL_PRIMITIVE_LINES;
else if (str_lc == "line_strip") result = TFGL_PRIMITIVE_LINE_STRIP;
else if (str_lc == "line_loop") result = TFGL_PRIMITIVE_LINE_LOOP;
else if (str_lc == "triangles") result = TFGL_PRIMITIVE_TRIANGLES;
else if (str_lc == "triangle_strip") result = TFGL_PRIMITIVE_TRIANGLE_STRIP;
else if (str_lc == "triangle_fan") result = TFGL_PRIMITIVE_TRIANGLE_FAN;
else
return false;
return true;
}
template<>
bool fromString<treeface::GLTextureType>( const treecore::String& string, treeface::GLTextureType& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "2d") result = TFGL_TEXTURE_2D;
else if (str_lc == "3d") result = TFGL_TEXTURE_3D;
else if (str_lc == "2d_array") result = TFGL_TEXTURE_2D_ARRAY;
else if (str_lc == "cube") result = TFGL_TEXTURE_CUBE;
else
return false;
return true;
}
template<>
bool fromString<treeface::GLTextureFilter>( const treecore::String& string, treeface::GLTextureFilter& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "nearest") result = TFGL_TEXTURE_NEAREST;
else if (str_lc == "linear") result = TFGL_TEXTURE_LINEAR;
else if (str_lc == "nearest_mipmap_nearest") result = TFGL_TEXTURE_NEAREST_MIPMAP_NEAREST;
else if (str_lc == "nearest_mipmap_linear") result = TFGL_TEXTURE_NEAREST_MIPMAP_LINEAR;
else if (str_lc == "linear_mipmap_nearest") result = TFGL_TEXTURE_LINEAR_MIPMAP_NEAREST;
else if (str_lc == "linear_mipmap_linear") result = TFGL_TEXTURE_LINEAR_MIPMAP_LINEAR;
else
return false;
return true;
}
template<>
bool fromString<treeface::GLTextureWrap>( const treecore::String& string, treeface::GLTextureWrap& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "clamp_to_edge") result = TFGL_TEXTURE_CLAMP_TO_EDGE;
else if (str_lc == "mirrored_repeat") result = TFGL_TEXTURE_MIRRORED_REPEAT;
else if (str_lc == "repeat") result = TFGL_TEXTURE_REPEAT;
else
return false;
return true;
}
template<>
bool fromString<treeface::GLType>( const treecore::String& string, treeface::GLType& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "byte") result = TFGL_TYPE_BYTE;
else if (str_lc == "unsigned_byte" || str_lc == "ubyte") result = TFGL_TYPE_UNSIGNED_BYTE;
else if (str_lc == "float") result = TFGL_TYPE_FLOAT;
else if (str_lc == "float_vec2" || str_lc == "vec2f") result = TFGL_TYPE_FLOAT_VEC2;
else if (str_lc == "float_vec3" || str_lc == "vec3f") result = TFGL_TYPE_FLOAT_VEC3;
else if (str_lc == "float_vec4" || str_lc == "vec3f") result = TFGL_TYPE_FLOAT_VEC4;
else if (str_lc == "int") result = TFGL_TYPE_INT;
else if (str_lc == "int_vec2" || str_lc == "vec2i") result = TFGL_TYPE_INT_VEC2;
else if (str_lc == "int_vec3" || str_lc == "vec3i") result = TFGL_TYPE_INT_VEC3;
else if (str_lc == "int_vec4" || str_lc == "vec4i") result = TFGL_TYPE_INT_VEC4;
else if (str_lc == "unsigned_int" || str_lc == "uint") result = TFGL_TYPE_UNSIGNED_INT;
else if (str_lc == "unsigned_int_vec2" || str_lc == "vec2u") result = TFGL_TYPE_UNSIGNED_INT_VEC2;
else if (str_lc == "unsigned_int_vec3" || str_lc == "vec3u") result = TFGL_TYPE_UNSIGNED_INT_VEC3;
else if (str_lc == "unsigned_int_vec4" || str_lc == "vec4u") result = TFGL_TYPE_UNSIGNED_INT_VEC4;
else if (str_lc == "bool") result = TFGL_TYPE_BOOL;
else if (str_lc == "bool_vec2" || str_lc == "vec2b") result = TFGL_TYPE_BOOL_VEC2;
else if (str_lc == "bool_vec3" || str_lc == "vec3b") result = TFGL_TYPE_BOOL_VEC3;
else if (str_lc == "bool_vec4" || str_lc == "vec4b") result = TFGL_TYPE_BOOL_VEC4;
else if (str_lc == "float_mat2" || str_lc == "mat2f") result = TFGL_TYPE_FLOAT_MAT2;
else if (str_lc == "float_mat3" || str_lc == "mat3f") result = TFGL_TYPE_FLOAT_MAT3;
else if (str_lc == "float_mat4" || str_lc == "mat4f") result = TFGL_TYPE_FLOAT_MAT4;
else if (str_lc == "float_mat2x3" || str_lc == "mat2x3f") result = TFGL_TYPE_FLOAT_MAT2x3;
else if (str_lc == "float_mat2x4" || str_lc == "mat2x4f") result = TFGL_TYPE_FLOAT_MAT2x4;
else if (str_lc == "float_mat3x2" || str_lc == "mat3x2f") result = TFGL_TYPE_FLOAT_MAT3x2;
else if (str_lc == "float_mat3x4" || str_lc == "mat3x4f") result = TFGL_TYPE_FLOAT_MAT3x4;
else if (str_lc == "float_mat4x2" || str_lc == "mat4x2f") result = TFGL_TYPE_FLOAT_MAT4x2;
else if (str_lc == "float_mat4x3" || str_lc == "mat4x3f") result = TFGL_TYPE_FLOAT_MAT4x3;
else if (str_lc == "sampler_2d") result = TFGL_TYPE_SAMPLER_2D;
else if (str_lc == "sampler_3d") result = TFGL_TYPE_SAMPLER_3D;
else if (str_lc == "sampler_cube") result = TFGL_TYPE_SAMPLER_CUBE;
else if (str_lc == "sampler_2d_shadow") result = TFGL_TYPE_SAMPLER_2D_SHADOW;
else if (str_lc == "sampler_2d_array") result = TFGL_TYPE_SAMPLER_2D_ARRAY;
else if (str_lc == "sampler_2d_array_shadow") result = TFGL_TYPE_SAMPLER_2D_ARRAY_SHADOW;
else if (str_lc == "sampler_cube_shadow") result = TFGL_TYPE_SAMPLER_CUBE_SHADOW;
else if (str_lc == "int_sampler_2d") result = TFGL_TYPE_INT_SAMPLER_2D;
else if (str_lc == "int_sampler_3d") result = TFGL_TYPE_INT_SAMPLER_3D;
else if (str_lc == "int_sampler_cube") result = TFGL_TYPE_INT_SAMPLER_CUBE;
else if (str_lc == "int_sampler_2d_array") result = TFGL_TYPE_INT_SAMPLER_2D_ARRAY;
else if (str_lc == "unsigned_int_sampler_2d") result = TFGL_TYPE_UNSIGNED_INT_SAMPLER_2D;
else if (str_lc == "unsigned_int_sampler_3d") result = TFGL_TYPE_UNSIGNED_INT_SAMPLER_3D;
else if (str_lc == "unsigned_int_sampler_cube") result = TFGL_TYPE_UNSIGNED_INT_SAMPLER_CUBE;
else if (str_lc == "unsigned_int_sampler_2d_array") result = TFGL_TYPE_UNSIGNED_INT_SAMPLER_2D_ARRAY;
else
return false;
return true;
}
template<>
bool fromString<treeface::TextureImageSoloChannelPolicy>( const treecore::String& string, treeface::TextureImageSoloChannelPolicy& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "red") result = TEXTURE_IMAGE_SOLO_AS_RED;
else if (str_lc == "luminance") result = TEXTURE_IMAGE_SOLO_AS_LUMINANCE;
else if (str_lc == "alpha") result = TEXTURE_IMAGE_SOLO_AS_ALPHA;
else if (str_lc == "depth") result = TEXTURE_IMAGE_SOLO_AS_DEPTH;
else
return false;
return true;
}
template<>
bool fromString<treeface::TextureImageDualChannelPolicy>( const treecore::String& string, treeface::TextureImageDualChannelPolicy& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "red_green") result = TEXTURE_IMAGE_DUAL_AS_RED_GREEN;
else if (str_lc == "luminance_alpha") result = TEXTURE_IMAGE_DUAL_AS_LUMINANCE_ALPHA;
else if (str_lc == "depth_stencil") result = TEXTURE_IMAGE_DUAL_AS_DEPTH_STENCIL;
else
return false;
return true;
}
template<>
bool fromString<treeface::TextureImageIntDataPolicy>( const treecore::String& string, treeface::TextureImageIntDataPolicy& result )
{
String str_lc = string.toLowerCase();
if (str_lc == "float") result = TEXTURE_IMAGE_INT_TO_FLOAT;
else if (str_lc == "signed") result = TEXTURE_IMAGE_INT_AS_SIGNED;
else if (str_lc == "unsigned") result = TEXTURE_IMAGE_INT_AS_UNSIGNED;
else
return false;
return true;
}
template<>
treecore::String toString<treeface::GLBufferType>( treeface::GLBufferType arg )
{
switch (arg)
{
case TFGL_BUFFER_VERTEX: return "vertex";
case TFGL_BUFFER_INDEX: return "index";
case TFGL_BUFFER_PACK: return "pack";
case TFGL_BUFFER_UNPACK: return "unpack";
case TFGL_BUFFER_READ: return "read";
case TFGL_BUFFER_WRITE: return "write";
case TFGL_BUFFER_FEEDBACK: return "feedback";
case TFGL_BUFFER_UNIFORM: return "uniform";
default:
throw std::invalid_argument( ( "invalid treeface OpenGL buffer type enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
treecore::String toString<treeface::GLBufferUsage>( treeface::GLBufferUsage arg )
{
switch (arg)
{
case TFGL_BUFFER_STREAM_DRAW: return "stream_draw";
case TFGL_BUFFER_STREAM_READ: return "stream_read";
case TFGL_BUFFER_STREAM_COPY: return "stream_copy";
case TFGL_BUFFER_STATIC_DRAW: return "static_draw";
case TFGL_BUFFER_STATIC_READ: return "static_read";
case TFGL_BUFFER_STATIC_COPY: return "static_copy";
case TFGL_BUFFER_DYNAMIC_DRAW: return "dynamic_draw";
case TFGL_BUFFER_DYNAMIC_READ: return "dynamic_read";
case TFGL_BUFFER_DYNAMIC_COPY: return "dynamic_copy";
default:
throw std::invalid_argument( ( "invalid treeface OpenGL buffer usage enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
treecore::String toString<treeface::GLImageFormat>( treeface::GLImageFormat arg )
{
switch (arg)
{
case TFGL_IMAGE_FORMAT_ALPHA: return "alpha";
case TFGL_IMAGE_FORMAT_RGBA: return "rgba";
case TFGL_IMAGE_FORMAT_RGB: return "rgb";
case TFGL_IMAGE_FORMAT_RG: return "rg";
case TFGL_IMAGE_FORMAT_RED: return "red";
case TFGL_IMAGE_FORMAT_RGBA_INT: return "rgba_int";
case TFGL_IMAGE_FORMAT_RGB_INT: return "rgb_int";
case TFGL_IMAGE_FORMAT_RG_INT: return "rg_int";
case TFGL_IMAGE_FORMAT_RED_INT: return "red_int";
case TFGL_IMAGE_FORMAT_DEPTH: return "depth";
case TFGL_IMAGE_FORMAT_DEPTH_STENCIL: return "depth_stencil";
case TFGL_IMAGE_FORMAT_LUMINANCE: return "luminance_";
case TFGL_IMAGE_FORMAT_LUMINANCE_ALPHA: return "luminance_alpha";
default:
throw std::invalid_argument( ( "invalid treeface OpenGL image format enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
treecore::String toString<treeface::GLInternalImageFormat>( treeface::GLInternalImageFormat arg )
{
switch (arg)
{
case TFGL_INTERNAL_IMAGE_FORMAT_ALPHA: return "alpha";
case TFGL_INTERNAL_IMAGE_FORMAT_BLUE: return "blue";
case TFGL_INTERNAL_IMAGE_FORMAT_GREEN: return "green";
case TFGL_INTERNAL_IMAGE_FORMAT_RED: return "red";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB: return "rgb";
case TFGL_INTERNAL_IMAGE_FORMAT_RGBA: return "rgba";
case TFGL_INTERNAL_IMAGE_FORMAT_LUMINANCE_ALPHA: return "luminance_alpha";
case TFGL_INTERNAL_IMAGE_FORMAT_LUMINANCE: return "luminance";
case TFGL_INTERNAL_IMAGE_FORMAT_R8: return "r8";
case TFGL_INTERNAL_IMAGE_FORMAT_R8_SNORM: return "r8_snorm";
case TFGL_INTERNAL_IMAGE_FORMAT_R16F: return "r16f";
case TFGL_INTERNAL_IMAGE_FORMAT_R32F: return "r32f";
case TFGL_INTERNAL_IMAGE_FORMAT_R16UI: return "r16ui";
case TFGL_INTERNAL_IMAGE_FORMAT_R16I: return "r16i";
case TFGL_INTERNAL_IMAGE_FORMAT_R32UI: return "r32ui";
case TFGL_INTERNAL_IMAGE_FORMAT_R32I: return "r32i";
case TFGL_INTERNAL_IMAGE_FORMAT_RG8: return "rg8";
case TFGL_INTERNAL_IMAGE_FORMAT_RG8_SNORM: return "rg8_snorm";
case TFGL_INTERNAL_IMAGE_FORMAT_RG16F: return "rg16f";
case TFGL_INTERNAL_IMAGE_FORMAT_RG32F: return "rg32f";
case TFGL_INTERNAL_IMAGE_FORMAT_RG8UI: return "rg8ui";
case TFGL_INTERNAL_IMAGE_FORMAT_RG8I: return "rg8i";
case TFGL_INTERNAL_IMAGE_FORMAT_RG16UI: return "rg16ui";
case TFGL_INTERNAL_IMAGE_FORMAT_RG16I: return "rg16i";
case TFGL_INTERNAL_IMAGE_FORMAT_RG32UI: return "rg32ui";
case TFGL_INTERNAL_IMAGE_FORMAT_RG32I: return "rg32i";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB8: return "rgb8";
case TFGL_INTERNAL_IMAGE_FORMAT_SRGB8: return "srgb8";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB565: return "rgb565";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB8_SNORM: return "rgb8_snorm";
case TFGL_INTERNAL_IMAGE_FORMAT_R11F_G11F_B10F: return "r11f_g11f_b10f";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB9_E5: return "rgb9_e5";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB16F: return "rgb16f";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB32F: return "rgb32f";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB8UI: return "rgb8ui";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB8I: return "rgb8i";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB16UI: return "rgb16ui";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB16I: return "rgb16i";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB32UI: return "rgb32ui";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB32I: return "rgb32i";
case TFGL_INTERNAL_IMAGE_FORMAT_RGBA8: return "rgba8";
case TFGL_INTERNAL_IMAGE_FORMAT_SRGB8_ALPHA8: return "srgb8_alpha8";
case TFGL_INTERNAL_IMAGE_FORMAT_RGBA8_SNORM: return "rgba8_snorm";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB5_A1: return "rgb5_a1";
case TFGL_INTERNAL_IMAGE_FORMAT_RGBA4: return "rgba4";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB10_A2: return "rgb10_a2";
case TFGL_INTERNAL_IMAGE_FORMAT_RGBA16F: return "rgba16f";
case TFGL_INTERNAL_IMAGE_FORMAT_RGBA32F: return "rgba32f";
case TFGL_INTERNAL_IMAGE_FORMAT_RGBA8UI: return "rgba8ui";
case TFGL_INTERNAL_IMAGE_FORMAT_RGBA8I: return "rgba8i";
case TFGL_INTERNAL_IMAGE_FORMAT_RGB10_A2UI: return "rgb10_a2ui";
case TFGL_INTERNAL_IMAGE_FORMAT_RGBA16UI: return "rgba16ui";
case TFGL_INTERNAL_IMAGE_FORMAT_RGBA16I: return "rgba16i";
case TFGL_INTERNAL_IMAGE_FORMAT_RGBA32I: return "rgba32i";
case TFGL_INTERNAL_IMAGE_FORMAT_RGBA32UI: return "rgba32ui";
case TFGL_INTERNAL_IMAGE_FORMAT_DEPTH16: return "depth16";
case TFGL_INTERNAL_IMAGE_FORMAT_DEPTH24: return "depth24";
case TFGL_INTERNAL_IMAGE_FORMAT_DEPTH32F: return "depth32f";
case TFGL_INTERNAL_IMAGE_FORMAT_DEPTH24_STENCIL8: return "depth24_stencil8";
case TFGL_INTERNAL_IMAGE_FORMAT_DEPTH32F_STENCIL8: return "depth32f_stencil8";
default:
throw std::invalid_argument( ( "invalid treeface OpenGL internal image format enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
treecore::String toString<treeface::GLImageDataType>( treeface::GLImageDataType arg )
{
switch (arg)
{
case TFGL_IMAGE_DATA_BYTE: return "byte";
case TFGL_IMAGE_DATA_UNSIGNED_BYTE: return "unsigned_byte";
case TFGL_IMAGE_DATA_SHORT: return "short";
case TFGL_IMAGE_DATA_UNSIGNED_SHORT: return "unsigned_short";
case TFGL_IMAGE_DATA_UNSIGNED_SHORT_5_6_5: return "5_6_5";
case TFGL_IMAGE_DATA_UNSIGNED_SHORT_4_4_4_4: return "4_4_4_4";
case TFGL_IMAGE_DATA_UNSIGNED_SHORT_5_5_5_1: return "5_5_5_1";
case TFGL_IMAGE_DATA_INT: return "int";
case TFGL_IMAGE_DATA_UNSIGNED_INT: return "unsigned_int";
case TFGL_IMAGE_DATA_UNSIGNED_INT_10F_11F_11F_REV: return "10f_11f_11f_rev";
case TFGL_IMAGE_DATA_UNSIGNED_INT_5_9_9_9_REV: return "5_9_9_9_rev";
case TFGL_IMAGE_DATA_UNSIGNED_INT_2_10_10_10_REV: return "2_10_10_10_rev";
case TFGL_IMAGE_DATA_UNSIGNED_INT_24_8: return "24_8";
case TFGL_IMAGE_DATA_HALF_FLOAT: return "half_float";
case TFGL_IMAGE_DATA_FLOAT: return "float";
case TFGL_IMAGE_DATA_FLOAT_32_UNSIGNED_INT_24_8_REV: return "f32_24_8";
default:
throw std::invalid_argument( ( "invalid treeface OpenGL image data type enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
treecore::String toString<treeface::GLPrimitive>( treeface::GLPrimitive arg )
{
switch (arg)
{
case TFGL_PRIMITIVE_POINTS: return "points";
case TFGL_PRIMITIVE_LINES: return "lines";
case TFGL_PRIMITIVE_LINE_STRIP: return "line_strip";
case TFGL_PRIMITIVE_LINE_LOOP: return "line_loop";
case TFGL_PRIMITIVE_TRIANGLES: return "triangles";
case TFGL_PRIMITIVE_TRIANGLE_STRIP: return "triangle_strip";
case TFGL_PRIMITIVE_TRIANGLE_FAN: return "triangle_fan";
default:
throw std::invalid_argument( ( "invalid treeface OpenGL primitive enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
treecore::String toString<treeface::GLTextureFilter>( treeface::GLTextureFilter arg )
{
switch (arg)
{
case TFGL_TEXTURE_LINEAR: return "linear";
case TFGL_TEXTURE_LINEAR_MIPMAP_LINEAR: return "linear_mipmap_linear";
case TFGL_TEXTURE_LINEAR_MIPMAP_NEAREST: return "linear_mipmap_nearest";
case TFGL_TEXTURE_NEAREST: return "nearest";
case TFGL_TEXTURE_NEAREST_MIPMAP_LINEAR: return "nearest_mipmap_linear";
case TFGL_TEXTURE_NEAREST_MIPMAP_NEAREST: return "nearest mipmap_nearest";
default:
throw std::invalid_argument( ( "invalid treeface OpenGL texture filter enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
treecore::String toString<treeface::GLTextureType>( treeface::GLTextureType arg )
{
switch (arg)
{
case TFGL_TEXTURE_2D: return "2d";
case TFGL_TEXTURE_2D_ARRAY: return "2d_array";
case TFGL_TEXTURE_3D: return "3d";
case TFGL_TEXTURE_CUBE: return "cube";
default:
throw std::invalid_argument( ( "invalid treeface OpenGL texture type enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
treecore::String toString<treeface::GLTextureWrap>( treeface::GLTextureWrap arg )
{
switch (arg)
{
case TFGL_TEXTURE_CLAMP_TO_EDGE: return "clamp_to_edge";
case TFGL_TEXTURE_MIRRORED_REPEAT: return "mirrored_repeat";
case TFGL_TEXTURE_REPEAT: return "repeat";
default:
throw std::invalid_argument( ( "invalid treeface OpenGL texture wrap enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
treecore::String toString<treeface::GLType>( treeface::GLType arg )
{
switch (arg)
{
case TFGL_TYPE_BYTE: return "byte";
case TFGL_TYPE_UNSIGNED_BYTE: return "unsigned_byte";
case TFGL_TYPE_FLOAT: return "float";
case TFGL_TYPE_FLOAT_VEC2: return "float_vec2";
case TFGL_TYPE_FLOAT_VEC3: return "float_vec3";
case TFGL_TYPE_FLOAT_VEC4: return "float_vec4";
case TFGL_TYPE_INT: return "int";
case TFGL_TYPE_INT_VEC2: return "int_vec2";
case TFGL_TYPE_INT_VEC3: return "int_vec3";
case TFGL_TYPE_INT_VEC4: return "int_vec4";
case TFGL_TYPE_UNSIGNED_INT: return "unsigned_int";
case TFGL_TYPE_UNSIGNED_INT_VEC2: return "unsigned_int_vec2";
case TFGL_TYPE_UNSIGNED_INT_VEC3: return "unsigned_int_vec3";
case TFGL_TYPE_UNSIGNED_INT_VEC4: return "unsigned_int_vec4";
case TFGL_TYPE_BOOL: return "bool";
case TFGL_TYPE_BOOL_VEC2: return "bool_vec2";
case TFGL_TYPE_BOOL_VEC3: return "bool_vec3";
case TFGL_TYPE_BOOL_VEC4: return "bool_vec4";
case TFGL_TYPE_FLOAT_MAT2: return "float_mat2";
case TFGL_TYPE_FLOAT_MAT3: return "float_mat3";
case TFGL_TYPE_FLOAT_MAT4: return "float_mat4";
case TFGL_TYPE_FLOAT_MAT2x3: return "float_mat2x3";
case TFGL_TYPE_FLOAT_MAT2x4: return "float_mat2x4";
case TFGL_TYPE_FLOAT_MAT3x2: return "float_mat3x2";
case TFGL_TYPE_FLOAT_MAT3x4: return "float_mat3x4";
case TFGL_TYPE_FLOAT_MAT4x2: return "float_mat4x2";
case TFGL_TYPE_FLOAT_MAT4x3: return "float_mat4x3";
case TFGL_TYPE_SAMPLER_2D: return "sampler_2d";
case TFGL_TYPE_SAMPLER_3D: return "sampler_3d";
case TFGL_TYPE_SAMPLER_CUBE: return "sampler_cube";
case TFGL_TYPE_SAMPLER_2D_SHADOW: return "sampler_2d_shadow";
case TFGL_TYPE_SAMPLER_2D_ARRAY: return "sampler_2d_array";
case TFGL_TYPE_SAMPLER_2D_ARRAY_SHADOW: return "sampler_2d_array_shadow";
case TFGL_TYPE_SAMPLER_CUBE_SHADOW: return "sampler_cube_shadow";
case TFGL_TYPE_INT_SAMPLER_2D: return "int_sampler_2d";
case TFGL_TYPE_INT_SAMPLER_3D: return "int_sampler_3d";
case TFGL_TYPE_INT_SAMPLER_CUBE: return "int_sampler_cube";
case TFGL_TYPE_INT_SAMPLER_2D_ARRAY: return "int_sampler_2d_array";
case TFGL_TYPE_UNSIGNED_INT_SAMPLER_2D: return "unsigned_int_sampler_2d";
case TFGL_TYPE_UNSIGNED_INT_SAMPLER_3D: return "unsigned_int_sampler_3d";
case TFGL_TYPE_UNSIGNED_INT_SAMPLER_CUBE: return "unsigned_int_sampler_cube";
case TFGL_TYPE_UNSIGNED_INT_SAMPLER_2D_ARRAY: return "unsigned_int_sampler_2d_array";
default:
throw std::invalid_argument( ( "invalid treeface OpenGL type enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
treecore::String toString<treeface::TextureImageSoloChannelPolicy>( treeface::TextureImageSoloChannelPolicy arg )
{
switch (arg)
{
case TEXTURE_IMAGE_SOLO_AS_RED: return "red";
case TEXTURE_IMAGE_SOLO_AS_LUMINANCE: return "luminance";
case TEXTURE_IMAGE_SOLO_AS_ALPHA: return "alpha";
case TEXTURE_IMAGE_SOLO_AS_DEPTH: return "depth";
default:
throw std::invalid_argument( ( "invalid texture image 1-channel policy enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
treecore::String toString<treeface::TextureImageDualChannelPolicy>( treeface::TextureImageDualChannelPolicy arg )
{
switch (arg)
{
case TEXTURE_IMAGE_DUAL_AS_RED_GREEN: return "red_green";
case TEXTURE_IMAGE_DUAL_AS_LUMINANCE_ALPHA: return "luminance_alpha";
case TEXTURE_IMAGE_DUAL_AS_DEPTH_STENCIL: return "depth_stencil";
default:
throw std::invalid_argument( ( "invalid texture image 1-channel policy enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
template<>
treecore::String toString<treeface::TextureImageIntDataPolicy>( treeface::TextureImageIntDataPolicy arg )
{
switch (arg)
{
case TEXTURE_IMAGE_INT_TO_FLOAT: return "float";
case TEXTURE_IMAGE_INT_AS_SIGNED: return "signed";
case TEXTURE_IMAGE_INT_AS_UNSIGNED: return "unsigned";
default:
throw std::invalid_argument( ( "invalid texture image 1-channel policy enum: " + String( int(arg) ) ).toRawUTF8() );
}
}
} // namespace treeface
| true |
29820f0073e55f644a6da2fc8c6c2b48b7dd80af | C++ | JackThomson2/Bilging-Cpp | /Searcher.cpp | UTF-8 | 1,641 | 2.8125 | 3 | [] | no_license | //
// Created by Jack Thomson on 07/03/2021.
//
#include "Searcher.hpp"
float Search(Board board, byte max_depth, byte depth, byte move_number) {
float score = board.swap(move_number);
if (score < 0 || depth == 1) {
return score;
}
byte actual_depth = (max_depth - depth) + 1;
auto moves = board.inner_filter(actual_depth, score, move_number);
float max_score;
if (depth > 2) {
#pragma omp parallel for default(none) reduction(max:max_score) shared(board, moves, max_depth, depth)
for (auto i = 0; i < moves.position; i++) {
auto move = moves.moves[i];
auto inner_score = Search(board, max_depth, depth - 1, move);
max_score = max_score > inner_score ? max_score : inner_score;
}
} else {
for (auto i = 0; i < moves.position; i++) {
auto move = moves.moves[i];
auto inner_score = Search(board, max_depth, depth - 1, move);
max_score = max_score > inner_score ? max_score : inner_score;
}
}
return score;
}
MoveInfo GetBestMoveList(Board& board, byte depth) {
auto possible_moves = board.get_moves();
auto best_score = -9999;
auto best_move = 0;
#pragma omp parallel for default(none) reduction(max:best_score, best_move) shared(board, possible_moves, depth)
for (auto i = 0; i < possible_moves.position; i++) {
auto move = possible_moves.moves[i];
auto score = Search(board, depth, depth, move);
if (best_score < score) {
best_move = move;
best_score = score;
}
}
return MoveInfo(best_move, best_score);
} | true |
e01e73d0cb46b8f2ad936f113c16180c06feefdb | C++ | BlackCapCoder/factory | /src/Undergroundee.cpp | UTF-8 | 3,655 | 2.6875 | 3 | [] | no_license | #include "Undergroundee.h"
#include "Rendering.h"
#include <SDL2/SDL2_gfxPrimitives.h>
void Undergroundee::render (SDL_Renderer & rend, long time)
{
// ----------- Background
static constexpr float k = 0.14; // slope
SDL_SetRenderDrawColor (&rend, 16*5, 16*5, 16*1, 255);
SDL_FRect r = { 0, 0, 1, 1 };
switch (!entrance ? dir : dswap (dir))
{
case (DIR::E):
renderFillTrigon (rend, 1, 0, 0, k, 1, k);
renderFillTrigon (rend, 0, 1-k, 1, 1-k, 1, 1);
r.x = 0; r.y = k; r.w = 1; r.h = 1-k*2;
break;
case (DIR::W):
renderFillTrigon (rend, 0,0,1,k,0,k);
renderFillTrigon (rend, 0,1-k,1,1-k,0,1);
r.x = 0; r.y = k; r.w = 1; r.h = 1-k*2;
break;
case (DIR::N):
renderFillTrigon (rend, 0,0,k,0,k,1);
renderFillTrigon (rend, 1,0,1-k,0,1-k,1);
r.x = k; r.y = 0; r.w = 1-k*2; r.h = 1;
break;
case (DIR::S):
renderFillTrigon (rend, 0,1,k,1,k,0);
renderFillTrigon (rend, 1,1,1-k,1,1-k,0);
r.x = k; r.y = 0; r.w = 1-k*2; r.h = 1;
break;
}
SDL_RenderFillRectF (&rend, &r);
// ----------- Arrow
static constexpr float bw = 0.2; // brush width
static constexpr float bo = bw/2 * -1;
static constexpr float bq = bw/4;
// SDL_SetRenderDrawColor (&rend, 255, 255, 255, 255);
SDL_SetRenderDrawColor (&rend, 0, 0, 0, 255);
SDL_SetRenderDrawBlendMode (&rend, SDL_BlendMode::SDL_BLENDMODE_MUL);
if (entrance)
{
static constexpr float o = 0.4;
static constexpr float l = 0.8;
switch (dir)
{
case (DIR::W):
renderDrawLine (rend, bw, 1-o, k*o + bo, 1-l, 0.5 + bq);
renderDrawLine (rend, bw, 1-o, 1-k*o - bo, 1-l, 0.5 - bq);
break;
case (DIR::E):
renderDrawLine (rend, bw, o, k*o + bo, l, 0.5 + bq);
renderDrawLine (rend, bw, o, 1-k*o - bo, l, 0.5 - bq);
break;
case (DIR::N):
renderDrawLine (rend, bw, k*o + bo, 1-o, 0.5 + bq, 1-l);
renderDrawLine (rend, bw, 1-k*o - bo, 1-o, 0.5 - bq, 1-l);
break;
case (DIR::S):
renderDrawLine (rend, bw, k*o + bo, o, 0.5 + bq, l);
renderDrawLine (rend, bw, 1-k*o - bo, o, 0.5 - bq, l);
break;
}
}
else
{
static constexpr float o = 0.4;
static constexpr float l = 0.7;
switch (dir)
{
case (DIR::W):
renderDrawLine (rend, bw, 1-o, k*(1-o) + bo, 1-l, 0.5 + bq);
renderDrawLine (rend, bw, 1-o, 1-k*(1-o) - bo, 1-l, 0.5 - bq);
break;
case (DIR::E):
renderDrawLine (rend, bw, o, k*(1-o) + bo, l, 0.5 + bq);
renderDrawLine (rend, bw, o, 1-k*(1-o) - bo, l, 0.5 - bq);
break;
case (DIR::N):
renderDrawLine (rend, bw, k*(1-o) + bo, 1-o, 0.5 + bq, 1-l);
renderDrawLine (rend, bw, 1-k*(1-o) - bo, 1-o, 0.5 - bq, 1-l);
break;
case (DIR::S):
renderDrawLine (rend, bw, k*(1-o) + bo, o, 0.5 + bq, l);
renderDrawLine (rend, bw, 1-k*(1-o) - bo, o, 0.5 - bq, l);
break;
}
}
SDL_SetRenderDrawBlendMode (&rend, SDL_BlendMode::SDL_BLENDMODE_NONE);
// ----------- Shading
static constexpr float s = 0.07;
switch (!entrance ? dir : dswap (dir))
{
case (DIR::N):
r.x = 0; r.y = 0; r.w = 1; r.h = s;
break;
case (DIR::S):
r.x = 0; r.y = 1-s; r.w = 1; r.h = s;
break;
case (DIR::W):
r.x = 0; r.y = 0; r.w = s; r.h = 1;
break;
case (DIR::E):
r.x = 1-s; r.y = 0; r.w = s; r.h = 1;
break;
}
SDL_SetRenderDrawColor (&rend, 0, 0, 0, 255);
SDL_RenderFillRectF (&rend, &r);
}
| true |
9cad8bd847f2941d5352923f794913542b2a7db1 | C++ | taku-xhift/labo | /c++/CUIRolling/main.cpp | UTF-8 | 335 | 2.84375 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <unistd.h>
int main(void) {
while(1){
printf(" -\r");
usleep(100000);
fflush(stdout);
printf(" \\\r");
usleep(100000);
fflush(stdout);
printf(" |\r");
usleep(100000);
fflush(stdout);
printf(" /\r");
usleep(100000);
fflush(stdout);
}
}
| true |
d0c614ae6e8eb1144d49fbb092fda0efb0856723 | C++ | YoussefSaied/MagneticFrustration | /progprojet/trial/general/Dodec.cc | UTF-8 | 4,038 | 2.6875 | 3 | [
"MIT"
] | permissive | #include "Dodec.h"
#include "Vecteur3D.h"
#include "Plan.h"
#include "Dalle.h"
#include "Obstacle.h"
#include <cmath>
#include <vector>
#include <memory>
using namespace std;
unique_ptr<Dodec> Dodec:: cloneMe() const
{
return unique_ptr<Dodec>(new Dodec(*this));
}
unique_ptr<Obstacle> Dodec:: copie() const
{
return cloneMe();
}
bool Dodec:: is_inside(Vecteur3D const& x_i) const
{
if (position.distance(PointPlusProche(x_i)) > position.distance(x_i)) { return true; }
return false;
}
Vecteur3D Dodec:: PointPlusProche(Vecteur3D const& x_i) const
{
return x_i;
// wrong but not IMP for this simulation; just to remove warning;
}
vector<vector<Vecteur3D> > Dodec:: vertipositions() const
{
// They are clockwise
vector<vector<Vecteur3D> > vp; // vertixes positions
double a = (1 + sqrt(5)) / 2;
vp.push_back({ Vecteur3D(1 / a, 0, a), Vecteur3D(-1 / a, 0, a), Vecteur3D(-1, -1, 1), Vecteur3D(0, -a,
1 / a), Vecteur3D(1, -1, 1) }); // 1
vp.push_back({ Vecteur3D(-1, -1, 1), Vecteur3D(-a, -1 / a, 0), Vecteur3D(-1, -1, -1), Vecteur3D(0, -a,
-1 / a),
Vecteur3D(0, -a, 1 / a) }); // 2
vp.push_back({ Vecteur3D(0, -a, 1 / a), Vecteur3D(0, -a, -1 / a), Vecteur3D(1, -1, -1), Vecteur3D(a, -1 / a,
0),
Vecteur3D(1, -1, 1) }); // 3
vp.push_back({ Vecteur3D(1 / a, 0, a), Vecteur3D(1, -1, 1), Vecteur3D(a, -1 / a, 0), Vecteur3D(a, 1 / a,
0), Vecteur3D(1, 1,
1) }); // 4
vp.push_back({ Vecteur3D(1 / a, 0, -a), Vecteur3D(1, 1, -1), Vecteur3D(a, 1 / a, 0),
Vecteur3D(a, -1 / a, 0), Vecteur3D(1, -1, -1) }); // 5
vp.push_back({ Vecteur3D(1 / a, 0, -a), Vecteur3D(1, -1, -1), Vecteur3D(0, -a, -1 / a),
Vecteur3D(-1, -1, -1), Vecteur3D(-1 / a, 0, -a) }); // 6
vp.push_back({ Vecteur3D(1 / a, 0, -a), Vecteur3D(-1 / a, 0, -a), Vecteur3D(-1, 1, -1),
Vecteur3D(0, a, -1 / a), Vecteur3D(1, 1, -1) }); // 7
vp.push_back({ Vecteur3D(-1, -1, -1), Vecteur3D(-a, -1 / a, 0), Vecteur3D(-a, 1 / a, 0),
Vecteur3D(-1, 1, -1), Vecteur3D(-1 / a, 0, -a) }); // 8
vp.push_back({ Vecteur3D(-1, 1, 1), Vecteur3D(-a, 1 / a, 0), Vecteur3D(-a, -1 / a, 0), Vecteur3D(-1, -1, 1),
Vecteur3D(-1 / a, 0, a) }); // 9
vp.push_back({ Vecteur3D(-1, 1, 1), Vecteur3D(-1 / a, 0, a), Vecteur3D(1 / a, 0, a), Vecteur3D(1, 1, 1),
Vecteur3D(0, a, 1 / a) }); // 10
vp.push_back({ Vecteur3D(-1, 1, 1), Vecteur3D(0, a, 1 / a), Vecteur3D(0, a, -1 / a), Vecteur3D(-1, 1, -1),
Vecteur3D(-a, 1 / a, 0) }); // 11
vp.push_back({ Vecteur3D(1, 1, -1), Vecteur3D(0, a, -1 / a), Vecteur3D(0, a, 1 / a), Vecteur3D(1, 1, 1),
Vecteur3D(a, 1 / a, 0) }); // 12
/*for(int i =-1; i<2; i+=2){
for(int j =-1; j<2; j+=2){
for(int k =-1; k<2; k+=2){
vp.push_back(Vecteur3D(i,j,k));
vp.push_back(Vecteur3D(0,j*a,k/a));
vp.push_back(Vecteur3D(i/a,0,k*a));
vp.push_back(Vecteur3D(i*a,j/a,0));
}
}
}*/
// scaling
for (auto& i : vp) {
for (auto& j: i) {
j *= edge;
}
}
// rotate depending vecteur_1 (orientation vector)
Vecteur3D v1(1 / a, 0, a);
Vecteur3D v2(-1 / a, 0, a);
Vecteur3D v3(-1, -1, 1);
Vecteur3D o1(v1 - v2);
Vecteur3D o2(v2 - v3);
Vecteur3D axer0(o1 ^ o2); // orthogonal vector to canonical dodec face
Vecteur3D axer1(axer0 ^ vecteur_1); // rotation axis
double angle = acos((vecteur_1 * axer0) / ((vecteur_1.norme()) * axer0.norme()));
for (auto& i : vp) {
for (auto& j: i) {
j = j.rotate(angle, axer1);
}
}
// translate depending on position;
for (auto& i : vp) {
for (auto& j: i) {
j += position;
}
}
return vp;
} // Dodec::vertipositions
| true |
45a85f73fab6d783ff94448e7f0a9db6ba026084 | C++ | flameshimmer/leet2019.io | /Leet2019/WildcardMatching.cpp | UTF-8 | 2,934 | 3.28125 | 3 | [] | no_license | #include "stdafx.h"
//Given an input string (s) and a pattern (p), implement wildcard pattern
//matching with support for '?' and '*'.
//'?' Matches any single character.
//'*' Matches any sequence of characters (including the empty sequence).
//The matching should cover the entire input string (not partial).
//
//Note:
//s could be empty and contains only lowercase letters a-z.
//p could be empty and contains only lowercase letters a-z, and characters like ?
//or *.
//
//Example 1:
//Input:
//s = "aa"
//p = "a"
//Output: false
//Explanation: "a" does not match the entire string "aa".
//
//Example 2:
//Input:
//s = "aa"
//p = "*"
//Output: true
//Explanation: '*' matches any sequence.
//
//Example 3:
//Input:
//s = "cb"
//p = "?a"
//Output: false
//Explanation: '?' matches 'c', but the second letter is 'a', which does not
//match 'b'.
//
//Example 4:
//Input:
//s = "adceb"
//p = "*a*b"
//Output: true
//Explanation: The first '*' matches the empty sequence, while the second '*'
//matches the substring "dce".
//
//Example 5:
//Input:
//s = "acdcb"
//p = "a*c?b"
//Output: false
namespace Solution2019
{
namespace WildcardMatching
{
namespace UseC {
bool isMatch(const char* s, const char* p) {
const char* star = nullptr;
const char* ss = s;
while (*s) {
if (*s == *p || *p == '?') { s++; p++; continue; }
if (*p == '*') { star = p; p++; ss = s; continue; }
if (star) { p = star + 1; ss++; s = ss; continue; }
return false;
}
while (*p == '*') { p++; }
return !*p;
}
bool isMatch(string s, string p) {
return isMatch(s.c_str(), p.c_str());
}
}
namespace TwoDimensionalDP {
bool isMatch(string s, string p) {
int lens = s.size();
int lenp = p.size();
vector<vector<bool>> M(lens + 1, vector<bool>(lenp + 1));
M[0][0] = true;
for (int i = 1; i < lenp + 1 && p[i - 1] == '*'; i++) {
M[0][i] = true;
}
for (int i = 1; i < lens + 1; i++) {
for (int j = 1; j < lenp + 1; j++) {
if (s[i - 1] == p[j - 1] || p[j - 1] == '?') { M[i][j] = M[i - 1][j - 1]; }
else if (p[j - 1] == '*') { M[i][j] = M[i - 1][j] || M[i][j - 1]; }
}
}
return M[lens][lenp];
}
}
namespace OneDimensionalDP {
bool isMatch(string s, string p) {
int lens = s.size();
int lenp = p.size();
vector<bool> M(lens + 1, false);
M[0] = true;
for (int j = 1; j < lenp + 1; j++) {
bool pre = M[0];
M[0] = (M[0] && p[j - 1] == '*');
for (int i = 1; i < lens + 1; i++) {
bool temp = M[i];
if (p[j - 1] == '*') { M[i] = M[i - 1] || M[i]; }
else { M[i] = (s[i - 1] == p[j - 1] || p[j - 1] == '?') && pre; }
pre = temp;
}
}
return M[lens];
}
}
void Main() {
string test = "tst test test";
print(UseC::isMatch("addddceb","a*c?b"));
print(UseC::isMatch("addddceeb", "a*c?b"));
print(UseC::isMatch("acdcb", "a*c?b"));
}
}
}
| true |
baddb02849d119be5fdaad515721483a2d8839db | C++ | viscrisn/mit-algo-cpp | /CPP Projects/Top Coder/SRM 551 Live/250_try1.cpp | UTF-8 | 854 | 3.09375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<string>
#include<cmath>
#include<cctype>
#include<algorithm>
#include<sstream>
#include<queue>
#include<cstdlib>
#include<map>
#include<set>
using namespace std;
class ColorfulBricks
{
public:
int countLayouts(string mem)
{
char color1 = 'a';
char color2 = 'a';
color1 = mem[0];
for (int i=0;i<mem.size();i++ )
{
if(mem[i] != color1)
{
color2 = mem[i];
break;
}
}
for (int i=0;i<mem.size();i++ )
{
if((mem[i] != color1) && (mem[i] != color2))
{
return 0;
}
}
if(color2 =='a')
{
return 1;
}
return 2;
}
};
int main()
{
ColorfulBricks a;
cout<<a.countLayouts("AABC");
}
| true |
2841a44bb27a178cd5ddad51d9e778618d46062b | C++ | sahil32/DataStructureandAlgorithm | /practise/stupidq.cpp | UTF-8 | 515 | 2.90625 | 3 | [] | no_license | #include<iostream>
using namespace std;
long long lcm(int a,long long int b)
{
long long int temp1=a;
long long int temp2=b;
while(temp2!=0)
{
long long int newtemp=temp2;
temp2=temp1%temp2;
temp1=newtemp;
}
return (long long) temp1*((a/temp1)*(b/temp1));
}
long long int getlcm(int n)
{
long long int result =1;
for(int j=1;j<=n;++j)
{
result=lcm(j,result);
cout<<j<<" "<<result<<"\n";
}
return result;
}
int main()
{
int t=3;
int n;
while(t--)
{
cin>>n;
cout<<getlcm(n)<<endl;
}
}
| true |
4343bcd9ca52df3b44a186da7670885b0ee5811c | C++ | hamedmirlohi/Reverse-Characters | /Reverse/main.cpp | UTF-8 | 530 | 3.296875 | 3 | [] | no_license | //
// main.cpp
// Reverse
//
// Created by Hamed Mirlohi on 3/4/19.
// Copyright © 2019 Hamed Mirlohi. All rights reserved.
//
#include <iostream>
using namespace std;
void reverse(char word[])
{
unsigned long size = strlen(word);
char temp;
for (int i = 0; i < strlen(word) / 2; ++i, --size)
{
temp = word[i];
word[i] = word[size - 1];
word[size - 1] = temp;
}
}
int main(int argc, const char * argv[]) {
char word[] = "washington";
reverse(word);
cout<<word<<endl;
}
| true |
cc24ef7c0a12f630145f2c701aa2a49904ee5299 | C++ | niebayes/UZH-Robot-Perception | /include/matlab_port/find.h | UTF-8 | 2,193 | 3.09375 | 3 | [
"MIT"
] | permissive | #ifndef UZH_MATLAB_PORT_FIND_H_
#define UZH_MATLAB_PORT_FIND_H_
#include <algorithm> // std::transform, std::copy_if
#include <numeric> // std::iota
#include <tuple>
#include <vector>
#include "armadillo"
#include "matlab_port/nnz.h"
namespace uzh {
//@brief Remove zeros in an array.
std::vector<int> remove_zeros(const std::vector<int>& A) {
//! Alternative way.
// std::vector<int> A_(A.cbegin(), A.cend());
// std::vector<int>::const_iterator last_non_zero =
// std::remove_if(A_.begin(), A_.end(), [](int x) { return x != 0; });
// std::vector<int> A_no_zeros(A_.cbegin(), last_non_zero);
const auto num_non_zeros =
std::count_if(A.cbegin(), A.cend(), [](int x) { return x != 0; });
std::vector<int> A_no_zeros(num_non_zeros);
std::copy_if(A.cbegin(), A.cend(), A_no_zeros.begin(),
[](int x) { return x != 0; });
return A_no_zeros;
}
//@brief Imitate matlab's `[row, col, v] = find(A)` function. Find non-zero
// elements in an array A.
//@param A One dimensional array.
//@return row An array containing the row subscripts of the non-zero elements in
// A.
//@return col An array containing the column subscripts of the non-zero elements
// in A.
//@return v One dimensional array containing the non-zero elements with order
// being consistent with the original order in A. I.e. this function is stable.
std::tuple<std::vector<int> /*row*/, std::vector<int> /*col*/, arma::uvec /*v*/>
find(const arma::uvec& A) {
// Assure all elements are greater than or equal to 0.
assert(!arma::any(A < 0));
// Get row
const int num_nonzeros = uzh::nnz<arma::uword>(A);
std::vector<int> row(num_nonzeros, 1);
// Get col
std::vector<int> indices(A.n_elem);
std::iota(indices.begin(), indices.end(), 0);
std::transform(indices.begin(), indices.end(), indices.begin(),
[&A](int i) { return A(i) > 0 ? i : 0; });
std::vector<int> col = uzh::remove_zeros(indices);
if (A(0) != 0) col.insert(col.begin(), 0);
// Get v
arma::uvec v(num_nonzeros);
std::copy_if(A.cbegin(), A.cend(), v.begin(), [](int x) { return x > 0; });
return {row, col, v};
}
} // namespace uzh
#endif // UZH_MATLAB_PORT_FIND_H_ | true |
663ce56c138a2fdd90e385834616e52b3701a944 | C++ | mattylenepveu/MattTennis | /Matt's Tennis/project2D/StateMachine.h | UTF-8 | 3,149 | 2.96875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Renderer2d.h"
#include "DynamicArray.h"
#include "State.h"
#include "Stack.h"
using namespace aie;
class StateMachine
{
public:
//--------------------------------------------------------------------------------------
// Default Constructor.
//--------------------------------------------------------------------------------------
StateMachine();
//--------------------------------------------------------------------------------------
// Default Destructor.
//--------------------------------------------------------------------------------------
~StateMachine();
//--------------------------------------------------------------------------------------
// Calls the onUpdate function for the top state on the stack
//
// Paramaters:
// fDeltaTime: Keeps track of real time, used for movement and waiting periods
// m_2dRenderer: Is used for access to the renderer class
//--------------------------------------------------------------------------------------
void Update(float fDeltaTime, Renderer2D* m_2dRenderer);
//--------------------------------------------------------------------------------------
// Draws the state that is on top of the stack
//
// Parameters:
// m_2dRenderer: Accesses the renderer class to allow the state to be drawn
//--------------------------------------------------------------------------------------
void Draw(Renderer2D* m_2dRenderer);
//--------------------------------------------------------------------------------------
// Pushes the state onto the next state on top of the stack
//
// Parameters:
// nStateIndex: Refers to the state at the top of the stack
//--------------------------------------------------------------------------------------
void PushState(int nStateIndex);
//--------------------------------------------------------------------------------------
// Allows a state to be added to the top of the stack
//
// Parameters:
// nStateIndex: Refers to the top of the stack
// pState: Calls the state to be added
//--------------------------------------------------------------------------------------
void AddState(int nStateIndex, State* pState);
//--------------------------------------------------------------------------------------
// Pops the state off of the top of the stack back to the state previously top
//--------------------------------------------------------------------------------------
void PopState();
//--------------------------------------------------------------------------------------
// Resets the stack and erases all states on it
//--------------------------------------------------------------------------------------
void Reset();
//--------------------------------------------------------------------------------------
// Allows another state to run as well as the one on top
//
// Parameters:
// onoff: Allows the second to top state to run if true
//--------------------------------------------------------------------------------------
void SetBackground(bool onoff);
private:
DynamicArray<State*> m_StateList;
Stack<State*> m_CurrentStack;
bool bBackUpdate;
}; | true |
91fe4c4c5bf0626bfdcf7e3c2a241e748bdb0538 | C++ | chav0028/AC_GAM1546_FinalProject | /Source/Framework/ECS/Entity.h | UTF-8 | 1,293 | 2.90625 | 3 | [] | no_license | #pragma once
#include <vector>
#include <string>
class Scene;
class Component;
class TransformComponent;
class Entity
{
public:
Entity(Vector2 position, Vector2 size,Scene* ownerScene, std::string name);
~Entity();
virtual void loadContent();
virtual void update(double delta);
virtual void draw();
virtual void reset();
Scene* getSceneOwner(){ return m_SceneOwner; }
void addComponent(Component* component);
void removeComponent(Component* component);
Component* getComponent(unsigned int aIndex);
bool getEnabled(){ return m_Enabled; }
void setEnabled(bool aEnabledStatus){ m_Enabled = aEnabledStatus; }
void attachChild(Entity* child);
Entity* detachChild(const Entity& child);
Vector2 getPosition();
void setPosition(Vector2 position);
Vector2 getSize();
void setSize(Vector2 size);
Vector2 getScale();
void setScale(Vector2 scale);
private:
bool m_Enabled;
TransformComponent* m_TransformComponent;
std::vector<Component*>m_listOfComponents;
std::string m_entityName;
Entity* m_parent;
std::vector<Entity*> m_children;
virtual void updateCurrent(double delta);
void updateChildren(double delta);
virtual void drawCurrent();
void drawChildren();
Scene* m_SceneOwner;
};
| true |
30e9dfd0222a8ca7dd66eb3e4804298bc08fa15e | C++ | DinoEhman/Competitive-Programming | /Codeforces/466A.cpp | UTF-8 | 438 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
int main()
{
int m, n, a, b;
cin >> n >> m >> a >> b;
int extra = 0;
if (n > m)
{
if (n % m)
extra += min(a * (n % m), b);
}
int ticks = 1;
if (n > m)
{
ticks = n / m;
}
int mins = min(n * a, b * ticks + extra);
cout << mins << endl;
return 0;
} | true |
ed4d49dd6cc1c62e3902c49415e366a80cee39fb | C++ | Sookmyung-Algos/2021algos | /algos_semina/1st_semina/seminar_2/C_1145/kijh30123_1145.cpp | UTF-8 | 524 | 2.515625 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
using namespace std;
void init() {
cin.tie(0); cout.tie(0);
ios_base::sync_with_stdio(false);
}
int main() {
int N1, N2, N3, N4, N5;
cin >> N1 >> N2 >> N3 >> N4 >> N5;
int max = 1000000;
for (int i = 1; i <= max; i++) {
int count = 0;
if (i%N1 == 0) {
count++;
}
if (i%N2 == 0) {
count++;
}
if (i%N3 == 0) {
count++;
}
if (i%N4 == 0) {
count++;
}
if (i%N5 == 0) {
count++;
}
if (count >= 3) {
cout << i;
break;
}
}
return 0;
}
| true |
164b8984cd73745a55d6c1b64077440a12246af5 | C++ | Krebrov001/C-Experiments | /structs_and_objects/constructor_initializer_list_examples/initializer_list5_1.cpp | UTF-8 | 744 | 3.828125 | 4 | [] | no_license | /**
* @file initializer_list5_1.cpp
* @author Konstantin Rebrov
* @version 09/02/2018
*
* @section DESCRIPTION
*
* This program demonstrates the fifth reason why you should use constructor
* initializer lists.
* When you have a data member of a class with the same name as the parameter
* to the constructor.
* You want to initialize the data member with the parameter.
*/
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
class Base {
int _x; // data members of a class are private by default.
public:
Base(int _x) : _x(_x) {}
void print();
};
void Base::print()
{
cout << "_x: " << _x << endl;
}
int main()
{
Base b0(10);
b0.print();
Base b1(12);
b1.print();
return 0;
}
| true |
909ce3c75c2273837cdf6a60bd279499adf300e2 | C++ | Jonathan-Louis/Games2D | /Zombie Game/Agent.h | UTF-8 | 1,281 | 2.8125 | 3 | [] | no_license | #pragma once
#include <glm/glm.hpp>
#include <Bengine/SpriteBatch.h>
#include <string>
const float AGENT_WIDTH = 60.0f;
const float AGENT_RADIUS = AGENT_WIDTH / 2.0f;
//including classes for human and zombie to avoid circular includes with header files
class Human;
class Zombie;
//class used for detecting collision between objects
class Agent
{
public:
Agent();
//virtual destructor to call child destructors as well
virtual ~Agent();
//pure virtual class to force update to all derived classes
virtual void update(const std::vector<std::string>& levelData,
std::vector<Human*>& humans,
std::vector<Zombie*>& zombies) = 0;
//check for each object collision with level walls
bool collideWithLevel(const std::vector<std::string>& levelData);
bool collideWithAgent(Agent* agent);
void draw(Bengine::SpriteBatch& _spriteBatch);
//return true if agent dies
bool applyDamage(float damage);
//getter for positions
glm::vec2 getPosition() const { return _position; }
protected:
void checkTilePosition(const std::vector<std::string>& levelData, std::vector<glm::vec2>& collideTilePosition, float cornerX, float cornerY);
void collideWithTile(glm::vec2 tilePos);
glm::vec2 _position;
float _speed;
Bengine::Color _color;
float _health;
};
| true |
c0e954f39e1d14e3389e25e5610e5db36f612fcb | C++ | zzz0906/LeetCode | /2021_Nov/25.cpp | UTF-8 | 598 | 3.03125 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int maxSubArray(vector<int>& nums) {
int left = 0;
int right = 1;
int res = nums[0];
int sum = nums[0];
while (right < nums.size()){
res = max(res,sum);
cout << left << endl;
while (sum < 0 && left < right){
sum -= nums[left];
left ++;
}
while (left < right && nums[left] < 0){
left ++;
}
sum += nums[right];
right ++;
}
res = max(res,sum);
return res;
}
}; | true |
716814da9e8d941c485509083f24296cf7337ca2 | C++ | 3303550641/Curriculum-Book-information-management-system | /123/图书管理系统/Biz.h | GB18030 | 1,255 | 2.859375 | 3 | [] | no_license | #include<iostream.h>
#include<fstream.h>
#include<string.h>
#include"Library.h"
#include"Magazines.h"
#include"Teacher.h"
#include"Student.h"
class Biz{
public:
int addLibrary(Library &lib); //ͼ ¼ͱ
int updateLibrary(Library &lib); //ͼ
int deleteByIdLibrary(int id); //ͼ ɾ
void findByIdLibrary(int id); //ͼ ݱŲ
void findAllLibrary(); // ͼ
int addMagazines(Magazines &maga); //־ ¼ͱ
int updateMagazines(Magazines &maga); //־
int deleteByIdMagazines(int id); //־ ɾ
void findByIdMagazines(int id); // ־ ݱŲ
void findAllMagazines(); //־
int addStudent(Student &stu); //ѧ ¼ͱ
int updateStudent(Student &stu); // ѧ
int deleteByIdStudent(int id); //ѧ ɾ
void findByIdStudent(int id); //ѧ ݱŲ
void findAllStudent(); //ѧ
int addTeacher(Teacher &tea); //ʦ ¼ͱ
int updateTeacher(Teacher &tea); //ʦ
int deleteByIdTeacher(int id); //ʦ ɾ
void findByIdTeacher(int id); //ʦ ݱŲ
void findAllTeacher(); //ʦ
}; | true |
50b6ef7774025b70c2e926063f20c68af6a4b1a8 | C++ | bbernardoni/Nib | /Nib/core/object.cpp | UTF-8 | 713 | 3.15625 | 3 | [
"MIT"
] | permissive | #include "object.h"
void Object::draw(RenderTarget& target, RenderStates states) const{
states.transform *= getTransform();
for(auto drawable: drawables)
target.draw(*drawable, states);
for(auto child: children)
target.draw(*child, states);
}
void Object::addChild(Object* child){
children.push_back(child);
}
void Object::addDrawable(Drawable* drawable){
drawables.push_back(drawable);
}
void Object::removeChild(Object* child){
children.remove(child);
}
void Object::removeDrawable(Drawable* drawable){
drawables.remove(drawable);
}
void Object::updateChildren(){
for(auto child: children)
child->update();
}
void Object::preDrawChildren(){
for(auto child: children)
child->preDraw();
}
| true |
e111a40c6f4c29f2d3faa816b0c1aeaf52d7a655 | C++ | Azurelol/Algorithms | /Algorithms/Algorithms/Sorting.hpp | UTF-8 | 1,843 | 3.921875 | 4 | [] | no_license | #include "Sorting.h"
namespace Algorithms
{
template<typename T>
void Sorting::BubbleSort(std::vector<T> & array)
{
// Set the flag to true for the first pass
bool continueSorting = true;
for (int i = 0; i < array.size() && continueSorting; i++)
{
// If there is no swaps on this iteration, do not continue
continueSorting = false;
// Now iterate through the array from start to end looking for swaps
// [array.size() - 1] is used because we are 0-index ho!
for (int j = 0; j < array.size() - 1; j++)
{
// If the next element is lesser than the current one
if (array[j + 1] < array[j])
{
auto temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
continueSorting = true;
}
}
}
}
template <typename T>
void Sorting::SelectionSort(std::vector<T>& array)
{
// During each pass, the unsorted element with the smallest
// value is moved to its proper position in the array
int minIndex;
for (int i = 0; i < array.size() - 1; i++)
{
// We will start looking for the smallest element starting from
// the current index
minIndex = i;
// We will iterate through the rest of the array from left to right,
// looking for an element smaller than the current smallest
for (int j = i + 1; j < array.size(); j++)
{
// If the element at the index is smaller than the current index
// update the index
if (array[j] < array[minIndex])
{
minIndex = j;
}
}
// Now let's place the element with the smallest index at this position.
// This will be done by swapping.
auto tmp = array[i];
array[i] = array[minIndex];
array[minIndex] = tmp;
}
}
}
| true |
733ceb0f76861ff6bec4303576ed1cdb48bfeeda | C++ | Arvinhahaha/C | /[二叉树]FBI树2.cpp | GB18030 | 1,479 | 3.296875 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<string.h>
int cnt;
typedef struct TreeNode {
char s[1025];
struct TreeNode* left;
struct TreeNode* right;
}*BinTree;
BinTree CreateTree(char* s1)
{
char p[513], q[513];
BinTree root = (BinTree)malloc(sizeof(struct TreeNode));
strcpy(root->s, s1);
if (strlen(s1) == 1) { //ݹ߽Ϊַʣ1λ
root->left = root->right = NULL;
return root;
}
int mid = strlen(s1) / 2;
strncpy(p, s1, mid); //pΪַ벿
p[mid] = '\0'; //strncpy()'\0'
strcpy(q, s1 + mid); //qΪַҰ벿
root->left = CreateTree(p);
root->right = CreateTree(q);
return root;
}
void PostorderTraversal(BinTree T) //
{
if (T) {
PostorderTraversal(T->left);
PostorderTraversal(T->right);
int sign = 0, flag = 0;
for (int i = 0; i < strlen(T->s); i++) {
if (T->s[i] == '0') sign = 1; //signжǷ0
if (T->s[i] == '1') flag = 1; //flagжǷ1
}
if (sign && flag) printf("F");
else if (sign && !flag) printf("B");
else printf("I");
}
}
int main()
{
int n;
scanf("%d", &n);
char s[1025];
scanf("%s", s);
BinTree T;
T = CreateTree(s);
PostorderTraversal(T);
return 0;
}
| true |
695d64e79b4390696433a5deef676059a79a2417 | C++ | housewithinahouse/Build-A-Bot | /Lines/Followy/Followy.ino | UTF-8 | 4,067 | 3.453125 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | /*
* This is a very simple line following robot.
* The only feature is that it rams up its speed
* if it doesn't see a line.
*
* Edwin Fallwell, MCPL 3/25/18
*/
// We've attached a daughter board to our Feather. This additional board.
// also known as a Wing, or a Shield if we were using an Arduino, needs a
// library to drive it. This statement includes this library so that we have access to
// it in the rest of our program.
#include <Adafruit_MotorShield.h>
// We need to create an object representing the Adafruit Motor Shield. We do this by
// creating an object of the type "Adafruit_MotorShield" named AFMS.
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// We're also creating two objects of the type "Adafruit_DCMotor", one for each of the
// motors on our line following robot.
Adafruit_DCMotor *L_MOTOR = AFMS.getMotor(3);
Adafruit_DCMotor *R_MOTOR = AFMS.getMotor(4);
// Sensors
int leftSensor = A2;
int rightSensor = A1;
// This time, we're going to adjust our speed over time, so we need some variables to hold this
// information. We've got three valuse here to store our current speed, our maximum speed,
// and our default speed. Each of these has been set up with an inital value that I found to work
// from testing.
int currentSpeed = 0;
int maxSpeed = 100;
int defaultSpeed = 60;
// We also need some variables to store information used in line detection + logic. These are the
// threshold that determines if the reading we are getting from the sensor is detecting a line, and
// a special type of variable called a boolean, which stores either the value true or false. We are using
// this to store the state of if the line has been detected.
int lineThreshold = 400; //this set to something a little more logical. Testing will decide.
bool lineDetectedFlag = false;
void setup() {
/* board first boots up. In this sketch, we need to
* do two things, initalize the AFMS object + set the
* currentSpeed to the defaultSpeed.
*/
AFMS.begin(); // create with the default frequency 1.6KHz
// turn on motors
L_MOTOR->setSpeed(0);
L_MOTOR->run(RELEASE);
R_MOTOR->setSpeed(0);
R_MOTOR->run(RELEASE);
currentSpeed = defaultSpeed;
// set the current speed to default.
Serial.begin(9600);
}
void loop() {
/* The loop section of your code will be run through
* continuously, from top to bottom. In this example,
* we want to robot to rotate in a circle. We set the
* speed for each of the motors and then tell each of the
* motors to run.
*/
// First, we set the speed of the motors.
L_MOTOR->setSpeed(currentSpeed);
R_MOTOR->setSpeed(currentSpeed);
// Then we check the sensors. If both the left & the
if((analogRead(rightSensor) < lineThreshold) && (analogRead(leftSensor) < lineThreshold)){
//don't see no line at all
L_MOTOR->run(FORWARD);
R_MOTOR->run(FORWARD);
lineDetectedFlag = false;
}
else if((analogRead(rightSensor) < lineThreshold) && (analogRead(leftSensor) > lineThreshold)){
//leftSensor detects line
L_MOTOR->run(BACKWARD);
R_MOTOR->run(FORWARD);
lineDetectedFlag = true;
}
else if((analogRead(rightSensor) > lineThreshold) && (analogRead(leftSensor) < lineThreshold)){
//rightSensor detects line
L_MOTOR->run(FORWARD);
R_MOTOR->run(BACKWARD);
lineDetectedFlag = true;
}
else{
//both see line/nothing
L_MOTOR->run(RELEASE);
R_MOTOR->run(RELEASE);
}
/* This part ramps up the speed until a line is detected.
* If a line is detected, drop the speed back down to default speed to avoid
* over shooting the line.
*/
// if(lineDetectedFlag){ //if we've detected a line
// currentSpeed = defaultSpeed; //slow back down
// }
// else{
// if(currentSpeed < maxSpeed){ //if we're going slower than max speed
// currentSpeed += 1; //accelerate by 1
// }
// }
// Serial.print("right: ");
// Serial.println(analogRead(rightSensor));
// Serial.print("left: ");
// Serial.println(analogRead(leftSensor));
}
| true |
a7aadf883f0dd6a913d28a736b150d1ed93a20e2 | C++ | anroysko/contestlib | /src/datastruct/convhull/sqrt_hull/main.cpp | UTF-8 | 687 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
using ll = long long;
#include "code.cpp"
void solve() {
int n, q;
cin >> n >> q;
vector<Line> lines(n);
for (auto& pr : lines) cin >> pr.a >> pr.b;
SqrtHull hull(lines);
for (int qi = 0; qi < q; ++qi) {
string op;
cin >> op;
if (op == "add") {
int a, b;
ll d;
cin >> a >> b >> d;
hull.rangeAdd(a, b, d);
} else if (op == "min") {
int a, b;
ll x;
cin >> a >> b >> x;
ll res = hull.rangeMin(a, b, x);
cout << res << '\n';
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
for (int ti = 0; ti < t; ++ti) {
solve();
}
}
| true |
9e249952b1f38c33b5a53fd350fbfd5af1ac1517 | C++ | bobstine/lang_C | /oldC/mgs/ranges/range_ops.h | UTF-8 | 9,855 | 2.890625 | 3 | [] | no_license | // $Id: range_ops.h,v 1.2 2002/06/17 14:35:09 bob Exp $ -*- c++ -*-
/*
15 Mar 02 ... Created to hold the un-localized functions of ranges.
*/
#ifndef _RANGE_OPS_H_
#define _RANGE_OPS_H_
#ifdef __APPLE__
#include "patch_iterator.h"
#endif
#include "range_traits.h"
#include <iostream>
////////////////////////////// Range versions of algorithms //////////////////////
template <class Range>
inline typename range_traits<Range>::iterator
min_element(const Range& range)
{
return min_element(begin(range), end(range));
}
template <class Range>
inline typename range_traits<Range>::iterator
max_element(const Range& range)
{
return max_element(begin(range), end(range));
}
template <class Range, class I>
inline I copy (const Range& range, I it)
{
return copy(begin(range), end(range), it);
}
template <class Range, class F>
inline F for_each (const Range& range, F f)
{
return for_each(begin(range), end(range), f);
}
namespace{
template <class Range,class Tag>
inline typename range_traits<Range>::value_type
accumulate_unrolled(Range range, typename range_traits<Range>::value_type init,Tag)
{
// the following is 6 times slower than our own loop!
// For some reason, its a lot faster to do it here that call the STL.
// return accumulate(begin(range), end(range), init);
for(typename range_traits<Range>::iterator i = begin(range); i != end(range); ++i)
init = init + *i;
return init;
}
// In spite of the "natural version" of the following running blazingly fast, using it here is is amazing slow!
// int length = end(range) - begin(range);
// for(int i = 0;i < length;++i)
// init = init + *(beg + i);
// RANGE: Time for length 200 was 23.46
// RANGE: Time for length 2000 was 36.48
// RANGE: Time for length 20000 was 36.47
// generic unrolled 6 times code:
// RANGE: Time for length 200 was 3.26
// RANGE: Time for length 2000 was 9.55
// RANGE: Time for length 20000 was 9.45
// generic not-unrolled code:
// RANGE: Time for length 200 was 6.35
// RANGE: Time for length 2000 was 11.06
// RANGE: Time for length 20000 was 10.96
template <class Range>
inline typename range_traits<Range>::value_type
accumulate_unrolled(Range range, typename range_traits<Range>::value_type init,std::random_access_iterator_tag)
{
typename range_traits<Range>::iterator i = begin(range);
if(end(range) - begin(range) > 6)
{
typename range_traits<Range>::iterator last = end(range) - 5;
while(i < last)
{
init = init + *i; ++i;
init = init + *i; ++i;
init = init + *i; ++i;
init = init + *i; ++i;
init = init + *i; ++i;
}
}
for(;i != end(range);++i)
init = init + *i;
return init;
}
}
/*
using end(range)
RANGE_IP: Time for length 200 was 6.43 giving avg 49.9387
RANGE_IP: Time for length 2000 was 7.18 giving avg 500.405
RANGE_IP: Time for length 20000 was 6.61 giving avg 5000.24
3.0:
RANGE_IP: Time for length 200 was 5.18 giving avg 49.9387
RANGE_IP: Time for length 2000 was 6.26 giving avg 500.405
RANGE_IP: Time for length 20000 was 5.37 giving avg 5000.24
A slight/big improvement if end(Range) uses a const reference
RANGE_IP: Time for length 200 was 4.76 giving avg 49.9387
RANGE_IP: Time for length 2000 was 5.59 giving avg 500.405
RANGE_IP: Time for length 20000 was 4.94 giving avg 5000.24
3.0:
RANGE_IP: Time for length 200 was 2.68 giving avg 49.9387
RANGE_IP: Time for length 2000 was 2.93 giving avg 500.405
RANGE_IP: Time for length 20000 was 2.84 giving avg 5000.24
A big improvement by using "ending" instead of end(range):
RANGE_IP: Time for length 200 was 2.01 giving avg 49.9387
RANGE_IP: Time for length 2000 was 2.12 giving avg 500.405
RANGE_IP: Time for length 20000 was 2.96 giving avg 5000.24
3.0:
RANGE_IP: Time for length 200 was 2.36 giving avg 49.9387
RANGE_IP: Time for length 2000 was 2.56 giving avg 500.405
RANGE_IP: Time for length 20000 was 2.76 giving avg 5000.24
Also a big/slight improvement by using range.second:
RANGE_IP: Time for length 200 was 2.22 giving avg 49.9387
RANGE_IP: Time for length 2000 was 2.03 giving avg 500.405
RANGE_IP: Time for length 20000 was 2.76 giving avg 5000.24
3.0:
RANGE_IP: Time for length 200 was 2.12 giving avg 49.9387
RANGE_IP: Time for length 2000 was 2.56 giving avg 500.405
RANGE_IP: Time for length 20000 was 2.76 giving avg 5000.24
removing the return from operator++() doesn't help:
RANGE_IP: Time for length 200 was 2.04 giving avg 49.9387
RANGE_IP: Time for length 2000 was 2.22 giving avg 500.405
RANGE_IP: Time for length 20000 was 2.84 giving avg 5000.24
TARGET:
STL_IP: Time for length 200 was 1.45 giving avg 49.8428
STL_IP: Time for length 2000 was 1.57 giving avg 500.043
STL_IP: Time for length 20000 was 1.69 giving avg 5002.44
3.0:
STL_IP: Time for length 200 was 1.35 giving avg 49.8428
STL_IP: Time for length 2000 was 1.44 giving avg 500.043
STL_IP: Time for length 20000 was 1.49 giving avg 5002.44
*/
template <class Range>
inline typename range_traits<Range>::value_type
simple_accumulate (const Range& range, typename range_traits<Range>::value_type init)
{
// for(typename range_traits<Range>::iterator i = begin(range); i != end(range); ++i) // very slow
for(typename range_traits<Range>::iterator i = begin(range); i != range.second; ++i) // runs fast, but ugly
// typename range_traits<Range>::iterator ending = end(range);
// for(typename range_traits<Range>::iterator i = begin(range); i != ending; ++i) // runs fast
init = init + *i;
return init;
}
// Unrolled version
template <class Range>
inline typename range_traits<Range>::value_type
accumulate (const Range& range, typename range_traits<Range>::value_type init)
{
return accumulate_unrolled(range,init,typename range_traits<Range>::iterator_category());
}
template <class R1, class R2, class C>
inline C inner_product (const R1& x, const R2& y, C initial)
{
return inner_product (begin(x), end(x), begin(y), initial);
}
template <class I1, class I2, class I3, class C>
inline C weighted_inner_product (std::pair<I1,I1> x, std::pair<I2,I2> y, std::pair<I3,I3> wts, C initial)
{
return inner_product (x, make_binary_range(std::multiplies<double>(),y,wts), initial);
}
template <class R1, class R2, class R3, class C>
inline C weighted_inner_product (const R1& x, const R2& y, const R3& wts, C initial)
{
return inner_product (x, make_binary_range(std::multiplies<double>(),y,wts), initial);
}
template <class R1, class R2, class UnaryOp>
inline void
transform (const R1& x, const R2& y, UnaryOp f)
{
transform(begin(x), end(x), begin(y), f);
}
template <class I1, class I2, class I3, class BinaryOp>
inline void
transform (std::pair<I1,I1> x, std::pair<I2,I2> y, std::pair<I3,I3> z, BinaryOp f)
{
transform(begin(x), end(x), begin(y), begin(z), f);
}
///////////////////// Accumulate a table //////////////////////////////
template <class Range1, class Range2>
inline Range2
accumulate_table(const Range1& table, const Range2& init)
{
for(typename range_traits<Range1>::iterator i = begin(table); i != end(table); ++i)
transform(*i, init, init, std::plus<double>());
return init;
}
namespace range_ops
{
//////////////////////////////// Range output ///////////////////////////////////
// Would like for it to look like this...
// template <class Range>
// inline ostream&
// operator<<(ostream& os, Range r)
// {
// copy(begin(r), end(r), ostream_iterator<typename range_traits<Range>::value_type>(os, " "));
// os << endl;
// return os;
// }
template <class Iter>
inline std::ostream&
operator<<(std::ostream& os, std::pair<Iter,Iter> range)
{
copy(range.first, range.second, std::ostream_iterator<typename std::iterator_traits<Iter>::value_type>(os, " "));
os << std::endl;
return os;
}
//////////////////////// Operator + - / * /////////////////////////////////////////////////////////
// COMPRESS OPERATOR: as in APL (+/[1 2 3]) looks like (plus() | v)
template <class Op,class Range>
inline
typename range_traits<Range>::value_type
operator|(Op o, const Range& range)
{
assert(begin(range) != end(range)); // we don't know what to do with an empty range
typename range_traits<Range>::iterator start = begin(range);
typename range_traits<Range>::iterator finish = end(range);
typename range_traits<Range>::value_type init = *start;
++start;
return std::accumulate(start,finish,init,o);
}
template <class Range1,class Range2>
inline
typename binary_range_traits<std::multiplies<typename range_traits<Range1>::value_type>, Range1, Range2>::range
operator*(const Range1& range1, const Range2& range2)
{
return make_binary_range(std::multiplies<typename range_traits<Range1>::value_type>(), range1, range2);
}
template <class Range1,class Range2>
inline
typename binary_range_traits<std::divides<typename range_traits<Range1>::value_type>, Range1, Range2>::range
operator/(const Range1& range1, const Range2& range2)
{
return make_binary_range(std::divides<typename range_traits<Range1>::value_type>(), range1, range2);
}
template <class Range1,class Range2>
inline
typename binary_range_traits<std::plus<typename range_traits<Range1>::value_type>, Range1, Range2>::range
operator+(const Range1& range1, const Range2& range2)
{
return make_binary_range(std::plus<typename range_traits<Range1>::value_type>(), range1, range2);
}
template <class Range1,class Range2>
inline
typename binary_range_traits<std::minus<typename range_traits<Range1>::value_type>, Range1, Range2>::range
operator-(const Range1& range1, const Range2& range2)
{
return make_binary_range(std::minus<typename range_traits<Range1>::value_type>(), range1, range2);
}
}
#endif
| true |
d6a9734815e98a14d0c395eb663179e5db3d1e6a | C++ | cailun01/leetcode | /solutions/leetcode_36_solution_2.cc | UTF-8 | 3,188 | 3.609375 | 4 | [] | no_license | #include "headers.h"
/* 36 有效的数独
请你判断一个 9x9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)
数独部分空格内已填入了数字,空白格用 '.' 表示。
注意:
一个有效的数独(部分已被填充)不一定是可解的。
只需要根据以上规则,验证已经填入的数字是否有效即可。
示例1:
输入:board =
[["5","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
输出:true
示例 2:
输入:board =
[["8","3",".",".","7",".",".",".","."]
,["6",".",".","1","9","5",".",".","."]
,[".","9","8",".",".",".",".","6","."]
,["8",".",".",".","6",".",".",".","3"]
,["4",".",".","8",".","3",".",".","1"]
,["7",".",".",".","2",".",".",".","6"]
,[".","6",".",".",".",".","2","8","."]
,[".",".",".","4","1","9",".",".","5"]
,[".",".",".",".","8",".",".","7","9"]]
输出:false
解释:除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。
但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。
*/
/* 遍历一次
现在,我们完成了这个算法的所有准备工作:
遍历数独。
检查看到每个单元格值是否已经在当前的行 / 列 / 子数独中出现过:
如果出现重复,返回 false。
如果没有,则保留此值以进行进一步跟踪。
返回 true。
https://leetcode-cn.com/problems/valid-sudoku/solution/you-xiao-de-shu-du-by-leetcode/
*/
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
// 每一行数字1~9的出现情况,row[1][0]为true,表示第1行,数字1出现过了
vector<vector<bool>> row(9, vector<bool>(9, 0));
// 每一列数字1~9的出现情况,col[1][0]为true,表示第1列,数字1出现过了
vector<vector<bool>> col(9, vector<bool>(9, 0));
// 把9*9分为9个3*3的子数独,每个子数独中数字1~9的出现情况
// 子数独索引换算: (i / 3) * 3 + j / 3;
vector<vector<bool>> box(9, vector<bool>(9, 0));
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.'){
continue;
}
// 减'1'使得val比board[i][j]对应的数小1
// 使val的值在0~8之间,与row, col, box的第2维索引一一对应
int val = board[i][j] - '1';
// 子数独索引换算
int box_index = (i / 3) * 3 + j / 3;
if (row[i][val] || col[j][val] || box[box_index][val]) {
return false;
}
row[i][val] = true;
col[j][val] = true;
box[box_index][val] = true;
}
}
return true;
}
};
| true |
846b5150e7b6a4c0594d8f133f5389ccd8239707 | C++ | willcassella/RealTournament | /RealTournament/include/RealTournament/SpawnPad.h | UTF-8 | 1,313 | 2.859375 | 3 | [
"MIT"
] | permissive | // SpawnPad.h - Copyright 2013-2016 Will Cassella, All Rights Reserved
#pragma once
#include <Core/Reflection/SubClassOf.h>
#include <Engine/Entity.h>
namespace real_tournament
{
using namespace willow;
class SpawnPad final : public Entity
{
///////////////////////
/// Information ///
public:
REFLECTABLE_CLASS
EXTENDS(Entity)
/////////////////
/// Types ///
public:
enum PerformSpawn
{
/** Resets the timer to 'spawn_timer_start'. */
Reset_Timer,
/** The timer continues where it is. */
Keep_Timer,
/** The timer is set to '0'. */
Stop_Timer,
};
//////////////////
/// Fields ///
public:
/** The type of Entity to spawn. */
SubClassOf<Entity> spawn_type;
/** The vertical offset to spawn the object at. */
float vertical_offset = 3.f;
/** The amount of time that passes between each spawn ('0' for no timer, only spawns when told). */
float spawn_timer_start = 0.f;
/** The amount of time until the object spawns ('0' to disable). */
float spawn_timer = 0.f;
///////////////////
/// Methods ///
public:
/** Spawns the object.
* 'mode' - whether to reset the timer or not. */
Entity* perform_spawn(PerformSpawn mode);
protected:
void on_initialize() override;
private:
void on_update(float dt);
};
}
| true |
982217fcd5577b4c0ceac3c1fc98de642e01abcb | C++ | hogansung/leetcode | /cplusplus/p503.cpp | UTF-8 | 527 | 2.8125 | 3 | [] | no_license | class Solution {
public:
vector<int> nextGreaterElements(vector<int>& nums) {
int n = nums.size();
vector<int> ret(n, -1);
stack<pair<int,int>> st;
for (int i = 0; i < 2 * n; i++) {
while (st.size() and st.top().first < nums[i%n]) {
auto p = st.top(); st.pop();
if (p.second < n) {
ret[p.second] = nums[i%n];
}
}
st.emplace(nums[i%n], i);
}
return ret;
}
};
| true |
7dbe29ce9c3ecbfc108e96bfb823bc5e50367764 | C++ | terngkub/computor_v2 | /test/evaluator_test.cpp | UTF-8 | 13,324 | 2.828125 | 3 | [] | no_license | #include <boost/test/unit_test.hpp>
#include "ast.hpp"
#include "evaluator.hpp"
#include "parser.hpp"
BOOST_AUTO_TEST_SUITE(ts_evaluator)
std::string get_result(std::vector<std::string> v)
{
computorv2::evaluator evaluate;
std::string result_str;
for (auto & str : v)
{
std::transform(str.begin(), str.end(), str.begin(), [](unsigned char c){ return std::tolower(c); });
ast::input res;
if (!phrase_parse(str.begin(), str.end(), grammar::input, boost::spirit::x3::ascii::space, res))
throw std::runtime_error("invalid syntax");
result_str = evaluate(res, str);
}
return result_str;
}
BOOST_AUTO_TEST_SUITE(ts_correction)
BOOST_AUTO_TEST_CASE(tc_assignation)
{
// Test erreur élémentaire
BOOST_CHECK_THROW(get_result({"x == 2"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"x = 23edd23-+-+"}), std::runtime_error);
// Test erreur semi-avancé
BOOST_CHECK_THROW(get_result({"= 2"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"3 = 4"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"x = g"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"f(x = 2"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"x = [[4,2]"}), std::runtime_error);
// Test erreur avancé
BOOST_TEST(get_result({"x = --2", "x = ?"}) == "2");
BOOST_CHECK_THROW(get_result({"f(x) = x * 2", "t = f(x)"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"i = 2"}), std::runtime_error);
// Test valide élémentaire
BOOST_TEST(get_result({"x = 2", "x = ?"}) == "2");
BOOST_TEST(get_result({"y = 4i", "y = ?"}) == "4i");
BOOST_TEST(get_result({"z = [[2,3];[3,5]]", "z = ?"}) == "[[2, 3]; [3, 5]]");
// Test valide semi-avancé
BOOST_TEST(get_result({"x = 2", "y = x", "y = ?"}) == "2");
BOOST_TEST(get_result({"x = 2", "x = 5", "x = ?"}) == "5");
BOOST_TEST(get_result({"A = [[2,3]]", "B = A", "B = ?"}) == ("[[2, 3]]"));
// Test valide avancé
BOOST_TEST(get_result({"x = 2", "y = x * [[4,2]]", "f(z) = z * y", "f(z) = ?"}) == "[[8, 4]] * z");
BOOST_TEST(get_result({"x = 2", "f(x) = x * 5", "f(x) = ?"}) == "10");
}
BOOST_AUTO_TEST_CASE(tc_calculatoire)
{
// Test valide élémentaire
BOOST_TEST(get_result({"2 + 2 = ?"}) == "4");
BOOST_TEST(get_result({"3 * 4 = ?"}) == "12");
BOOST_TEST(get_result({"x = 2", "x + 2 = ?"}) == "4");
BOOST_CHECK_THROW(get_result({"2 / 0 = ?"}), std::runtime_error);
BOOST_TEST(get_result({"1 + 1.5 = ?"}) == "2.5");
// Test valide semi-avancé
BOOST_TEST(get_result({"x = 2 * i", "x ^ 2 = ?"}) == "-4");
BOOST_TEST(get_result({"A = [[2,3];[3,4]]", "B = [[1,0];[0,1]]", "A ** B = ?"}) == "[[2, 3]; [3, 4]]");
BOOST_TEST(get_result({"f(x) = x + 2", "p = 4", "f(p) = ?"}) == "6");
// Test valide avancé
BOOST_TEST(get_result({"4 - 3 - ( 2 * 3 ) ^ 2 * ( 2 - 4 ) + 4 = ?"}) == "77");
BOOST_TEST(get_result({"f(x) = 2*(x + 3*(x-4))", "p = 2", "f(3) - f(p) + 2 = ?"}) == "10");
BOOST_TEST(get_result({"f(x) = 2*x*i", "f(2) = ?"}) == "4i");
}
BOOST_AUTO_TEST_SUITE_END() // ts_correction
// Value Resolution
BOOST_AUTO_TEST_SUITE(ts_value_resolution)
BOOST_AUTO_TEST_CASE(tc_complex)
{
BOOST_TEST(get_result({"3 + 4i = ?"}) == "3 + 4i");
BOOST_TEST(get_result({"(3 + 4i) * (5 + 6i) = ?"}) == "-9 + 38i");
BOOST_TEST(get_result({"(1 + i)^3 = ?"}) == "-2 + 2i");
BOOST_TEST(get_result({"0^10 = ?"}) == "0");
BOOST_TEST(get_result({"0^0 = ?"}) == "1");
}
BOOST_AUTO_TEST_CASE(tc_matrix)
{
BOOST_CHECK_THROW(get_result({"[[x]] = ?"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"[[[[1, 2]]]] = ?"}), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(tc_expression)
{
// plus sign in front of double
BOOST_CHECK_THROW(get_result({"+3 = ?"}), std::runtime_error);
BOOST_TEST(get_result({"x +3 = ?"}) == "x + 3");
BOOST_TEST(get_result({"x^3 = ?"}) == "x^3");
BOOST_TEST(get_result({"(2x)^3 = ?"}) == "8x^3");
BOOST_TEST(get_result({"(x + 1)(x - 1)(x + 1) = ?"}) == "x^3 + x^2 - x - 1");
BOOST_TEST(get_result({"(x + 1)(x - 1) = ?"}) == "x^2 - 1");
BOOST_CHECK_THROW(get_result({"f(x) = 10^x", "f(2147) = ?"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"f(x) = 10^x", "f(-2147) = ?"}), std::runtime_error);
}
BOOST_AUTO_TEST_SUITE_END() // ts_value_resolution
// Variable Assignation
BOOST_AUTO_TEST_SUITE(ts_varialbe_assignation)
BOOST_AUTO_TEST_CASE(tc_complex)
{
BOOST_TEST(get_result({"a = 3"}) == "3");
BOOST_TEST(get_result({"a = 3", "a = ?"}) == "3");
BOOST_TEST(get_result({"a = 2.13i"}) == "2.13i");
BOOST_TEST(get_result({"a = 2.13i", "a = ?"}) == "2.13i");
BOOST_TEST(get_result({"a = 3.14 + 4.15i"}) == "3.14 + 4.15i");
BOOST_TEST(get_result({"a = 3.14 + 4.15i", "a = ?"}) == "3.14 + 4.15i");
}
BOOST_AUTO_TEST_CASE(tc_matrix)
{
BOOST_TEST(get_result({"m = [[1,2]]"}) == "[[1, 2]]");
BOOST_TEST(get_result({"m = [[1,2];[3,4]]"}) == "[[1, 2]; [3, 4]]");
BOOST_CHECK_THROW(get_result({"m = [[1,2];[3,4,5]]"}), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(tc_variable)
{
BOOST_TEST(get_result({"a = 3.14", "b = a", "b = ?"}) == "3.14");
BOOST_TEST(get_result({"a = 3.14", "a = a"}) == "3.14");
BOOST_TEST(get_result({"a = 3.14", "b = a", "a = b", "a = ?"}) == "3.14");
BOOST_TEST(get_result({"a = 3.14", "b = a", "a = b", "b = ?"}) == "3.14");
BOOST_CHECK_THROW(get_result({"a = a"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"a = b"}), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(tc_function)
{
BOOST_TEST(get_result({"f(x) = x * 3", "a = f(10)", "a = ?"}) == "30");
BOOST_TEST(get_result({"f(x) = x * 3", "a = -f(10)", "a = ?"}) == "-30");
BOOST_TEST(get_result({"f(x) = x ** [[1,0];[0,1]]", "a = f([[1,2];[3,4]])", "a = ?"}) == "[[1, 2]; [3, 4]]");
}
BOOST_AUTO_TEST_CASE(tc_expression)
{
BOOST_TEST(get_result({"a = (12 * 3) / 4", "a = ?"}) == "9");
BOOST_TEST(get_result({"a = 1 + i", "b = 1 - i", "c = a * b", "c = ?"}) == "2");
}
BOOST_AUTO_TEST_CASE(tc_reassign)
{
BOOST_TEST(get_result({"a = 3.14", "a = 42", "a = ?"}) == "42");
BOOST_TEST(get_result({"a = 3.14", "b = a", "a = 42", "a = ?"}) == "42");
BOOST_TEST(get_result({"a = 3.14", "b = a", "a = 42", "b = ?"}) == "3.14");
}
BOOST_AUTO_TEST_CASE(tc_double_letters)
{
BOOST_TEST(get_result({"xx = ?"}) == "xx");
BOOST_TEST(get_result({"ii = ?"}) == "ii");
BOOST_TEST(get_result({"xx = 3", "xx = ?"}) == "3");
BOOST_TEST(get_result({"ii = 3", "ii = ?"}) == "3");
}
BOOST_AUTO_TEST_CASE(tc_uppercase)
{
BOOST_TEST(get_result({"varA = 3", "varA = ?"}) == "3");
BOOST_TEST(get_result({"varA = 3", "vara = ?"}) == "3");
BOOST_TEST(get_result({"vara = 3", "varA = ?"}) == "3");
BOOST_TEST(get_result({"2I = ?"}) == "2i");
BOOST_TEST(get_result({"iI = ?"}) == "ii");
BOOST_TEST(get_result({"iI = 3", "ii = ?"}) == "3");
}
BOOST_AUTO_TEST_CASE(tc_other)
{
BOOST_CHECK_THROW(get_result({"a b = 42"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"a b(x) = 42"}), std::runtime_error);
}
BOOST_AUTO_TEST_SUITE_END() // ts_variable_assignation
// Function Assignation
BOOST_AUTO_TEST_SUITE(ts_function_assignation)
BOOST_AUTO_TEST_CASE(tc_printing)
{
BOOST_TEST(get_result({"f(x) = x"}) == "x");
BOOST_TEST(get_result({"f(x) = 3x"}) == "3 * x");
BOOST_TEST(get_result({"f(x) = x + 1"}) == "x + 1");
BOOST_TEST(get_result({"f(x) = x * -1"}) == "x * -1");
BOOST_TEST(get_result({"f(x) = 3x + 2i"}) == "3 * x + 2 * i");
BOOST_TEST(get_result({"f(x) = (x + 1)^3"}) == "(x + 1) ^ 3");
BOOST_TEST(get_result({"f(x) = x ** x"}) == "x ** x");
BOOST_TEST(get_result({"f(x) = x ** [[1,2];[3,4]] * 3"}) == "x ** [[1, 2]; [3, 4]] * 3");
BOOST_TEST(get_result({"f(x) = 3x", "g(x) = f(x)"}) == "(3 * (x))");
BOOST_TEST(get_result({"f(x) = 3x", "g(x) = 4f(x)"}) == "4 * (3 * (x))");
}
BOOST_AUTO_TEST_CASE(tc_basic)
{
BOOST_TEST(get_result({"f(x) = (x + 3)^2 * 4 % 5"}) == "(x + 3) ^ 2 * 4 % 5");
BOOST_TEST(get_result({"functionName(x) = x + 1", "functionname(x) = ?"}) == "x + 1");
BOOST_TEST(get_result({"functionname(x) = x + 1", "functionName(x) = ?"}) == "x + 1");
BOOST_TEST(get_result({"i(x) = x + 1", "i(x) = ?"}) == "x + 1");
}
BOOST_AUTO_TEST_CASE(tc_unassigned_value)
{
BOOST_CHECK_THROW(get_result({"f(x) = y"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"f(x) = x + y"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"f(x) = g(x)"}), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(tc_reassign)
{
BOOST_TEST(get_result({"f(x) = x + 1", "f(x) = x + 2", "f(x) = ?"}) == "x + 2");
BOOST_TEST(get_result({"f(x) = x + 1", "g(x) = x + 2", "f(x) = g(x)", "f(x) = ?"}) == "x + 2");
// change f
BOOST_TEST(get_result({"f(x) = x + 1", "g(x) = f(x)", "f(x) = x + 2", "g(x) = ?"}) == "x + 1");
BOOST_TEST(get_result({"f(x) = x + 1", "g(x) = f(x)", "f(x) = x + 2", "f(x) = ?"}) == "x + 2");
// change g
BOOST_TEST(get_result({"f(x) = x + 1", "g(x) = f(x)", "g(x) = x + 2", "g(x) = ?"}) == "x + 2");
BOOST_TEST(get_result({"f(x) = x + 1", "g(x) = f(x)", "g(x) = x + 2", "f(x) = ?"}) == "x + 1");
}
BOOST_AUTO_TEST_CASE(tc_loop)
{
BOOST_CHECK_THROW(get_result({"f(x) = f(x)"}), std::runtime_error);
BOOST_TEST(get_result({"f(x) = x", "g(x) = f(x)", "f(x) = g(x)", "f(x) = ?"}) == "x");
BOOST_TEST(get_result({"f(x) = x", "g(x) = f(x)", "f(x) = g(x)", "g(x) = ?"}) == "x");
}
BOOST_AUTO_TEST_CASE(tc_composite)
{
BOOST_TEST(get_result({"f(x) = x + 1", "g(x) = x ^ 2", "g(f(x)) = ?"}) == "x^2 + 2x + 1");
BOOST_TEST(get_result({"f(x) = 1 / x", "g(x) = x ^ 2", "g(f(x)) = ?"}) == "x^-2");
BOOST_TEST(get_result({"f(x) = x + 1", "g(x) = x ^ 2", "h(x) = x * 3", "h(f(x) + g(x)) = ?"}) == "3x^2 + 3x + 3");
BOOST_CHECK_THROW(get_result({"f(x) = 1 / (x + 1)", "g(x) = x ^ 2", "g(f(x)) = ?"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"f(x) = x + 1", "g(f(x)) = x ^ 2"}), std::runtime_error);
}
BOOST_AUTO_TEST_SUITE_END() // ts_variable_assignation
// Polynomial Resolution
BOOST_AUTO_TEST_SUITE(ts_polynomial_resolution)
BOOST_AUTO_TEST_CASE(tc_zero_degree)
{
BOOST_CHECK_THROW(get_result({"3.14 = 0 ?"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"x - x = 0 ?"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"x^0 = 0 ?"}), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(tc_one_degree)
{
BOOST_TEST(get_result({"x = 0 ?"}) == "x = 0");
BOOST_TEST(get_result({"x + 3.14 = 0 ?"}) == "x = -3.14");
BOOST_TEST(get_result({"x + 3.14 + 2.56i = 0 ?"}) == "x = -3.14 - 2.56i");
BOOST_TEST(get_result({"x^2 - x^2 + x + 3.14 = 0 ?"}) == "x = -3.14");
BOOST_TEST(get_result({"x^2 / x + 3.14 = 0 ?"}) == "x = -3.14");
// Polynomial resolution only handle the last result of expression
BOOST_TEST(get_result({"x^2 / x = 0 ?"}) == "x = 0");
}
BOOST_AUTO_TEST_CASE(tc_two_degree)
{
BOOST_TEST(get_result({"x^2 + 2x + 1 = 0 ?"}) == "x = -1");
BOOST_TEST(get_result({"x^2 + 3x + 2 = 0 ?"}) == "x = -1, -2");
BOOST_TEST(get_result({"2x^2 + 5x + 3 = 0 ?"}) == "x = -1, -1.5");
BOOST_TEST(get_result({"x^2 - 4 = 0 ?"}) == "x = 2, -2");
BOOST_TEST(get_result({"4x^2 - 4 = 0 ?"}) == "x = 1, -1");
}
BOOST_AUTO_TEST_CASE(tc_invalid)
{
// invalid input
BOOST_CHECK_THROW(get_result({"x ** 3 = 0 ?"}), std::runtime_error);
// invalid degree
BOOST_CHECK_THROW(get_result({"x^3 = 0 ?"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"x^-1 = 0 ?"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"x/x^2 = 0 ?"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"x^2 * x = 0 ?"}), std::runtime_error);
BOOST_CHECK_THROW(get_result({"x/x = 0 ?"}), std::runtime_error);
}
BOOST_AUTO_TEST_SUITE_END() // ts_polynomial_resolution
// Other
BOOST_AUTO_TEST_SUITE(ts_other)
BOOST_AUTO_TEST_CASE(tc_list)
{
// list_variables
BOOST_TEST(get_result({"list_variables"}) == "no assigned variable");
BOOST_TEST(get_result({"ab = 3", "cd = 4", "list_variables"}) == "ab = 3\n cd = 4");
// list_functions
BOOST_TEST(get_result({"list_functions"}) == "no defined function");
BOOST_TEST(get_result({"f(x) = x + 1", "g(x) = f(x)", "list_functions"}) == "f(x) = x + 1\n g(x) = ((x) + 1)");
// combine
BOOST_TEST(get_result({"a = 3", "b = 4", "f(x) = x + a + b", "g(x) = f(x) + x + 5"}) == "((x) + 3 + 4) + x + 5");
BOOST_TEST(get_result({"a = 3", "b = 4", "f(x) = x + a + b", "g(x) = f(x + 1) + x + 5"}) == "((x + 1) + 3 + 4) + x + 5");
BOOST_TEST(get_result({"a = 3", "b = 4", "f(x) = x + a + b", "g(x) = f(6) + x + 5"}) == "((6) + 3 + 4) + x + 5");
BOOST_TEST(get_result({"a = 3", "b = 4", "f(x) = x + 1", "g(x) = 3x + 2", "h(x) = g(f(x))"}) == "(3 * (((x) + 1)) + 2)");
BOOST_TEST(get_result({"a = 3", "b = 4", "f(x) = x + 1", "g(x) = 3x + 2", "h(x) = g(f(x + 6 + a))"}) == "(3 * (((x + 6 + 3) + 1)) + 2)");
BOOST_TEST(get_result({"a = 3", "b = 4", "f(x) = x + 1", "g(x) = 3x + 2", "h(x) = g(f(x + 6 + a) + g(x + b))"}) == "(3 * (((x + 6 + 3) + 1) + (3 * (x + 4) + 2)) + 2)");
}
BOOST_AUTO_TEST_SUITE_END() // ts_other
BOOST_AUTO_TEST_SUITE_END() // ts_evaluator
| true |
d17be12a242b41fc940086a41f33559f181e5c2c | C++ | sygh-JP/FbxModelViewer | /SharedUtility/MyUtils/MyMathConsts.hpp | UTF-8 | 2,251 | 2.5625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "MyMathTypes.hpp"
namespace MyMath
{
const float F_PI = 3.14159265358979323846f;
const double D_PI = 3.14159265358979323846;
const float F_2PI = 2.0f * F_PI;
const double D_2PI = 2.0 * D_PI;
const float F_PIDIV2 = 0.5f * F_PI;
const double D_PIDIV2 = 0.5 * D_PI;
const float F_PIDIV4 = 0.25f * F_PI;
const double D_PIDIV4 = 0.25 * D_PI;
// <DirectXColors.h> には DirectX::Colors::White などの定義済みカラーが定義されているが、型が XMVECTORF32 なので注意。
const MyMath::Vector4F COLOR4F_WHITE(1,1,1,1);
const MyMath::Vector4F COLOR4F_BLACK(0,0,0,1);
const MyMath::Vector4F COLOR4F_TRANSPARENT(0,0,0,0);
// D3DX Math, XNA Math, DirectXMath のデフォルト コンストラクタは怠惰で、ゴミデータが入ったままになる。
// GLM (OpenGL Mathematics) は、以前のバージョンではデフォルト コンストラクタによりゼロ ベクトルや単位行列が生成されていたが、
// 新しいバージョンでは未初期化となるように仕様変更された。
const Vector2I ZERO_VECTOR2I(0, 0);
const Vector3I ZERO_VECTOR3I(0, 0, 0);
const Vector4I ZERO_VECTOR4I(0, 0, 0, 0);
const Vector2F ZERO_VECTOR2F(0, 0);
const Vector3F ZERO_VECTOR3F(0, 0, 0);
const Vector4F ZERO_VECTOR4F(0, 0, 0, 0);
const Vector3F FLTMAX_VECTOR3F(+FLT_MAX, +FLT_MAX, +FLT_MAX);
const Vector3F FLTMIN_VECTOR3F(-FLT_MAX, -FLT_MAX, -FLT_MAX);
const QuaternionF NO_ROTATION_QUATERNIONF(0, 0, 0, 1);
const MatrixF ZERO_MATRIXF(0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0);
const MatrixF IDENTITY_MATRIXF(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1);
const Matrix4x4F ZERO_MATRIX4X4F(0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0);
const Matrix4x4F IDENTITY_MATRIX4X4F(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1);
//const Matrix4x3F ZERO_MATRIX4X3F(0,0,0, 0,0,0, 0,0,0, 0,0,0);
//const Matrix4x3F IDENTITY_MATRIX4X3F(1,0,0, 0,1,0, 0,0,1, 0,0,0);
const ColorRgba ColorRgbaWhite(0xFF, 0xFF, 0xFF);
const ColorRgba ColorRgbaBlack(0, 0, 0);
}
//#define USE_LEFT_HAND_COORD_SYS
// 一般的なモデリング ツールや OpenGL のデフォルトに合わせるならば、右手系を採用しておいたほうがいい。
| true |
208efb94a04b26a7a72514408f04cdf5ce39e3ab | C++ | Tommy0603/HW5 | /6.33/source/Main.cpp | UTF-8 | 939 | 3.65625 | 4 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#define SIZE 100
int binarySearch(int key, int* a, int right, int left);
int main(void)
{
int a[SIZE] ;
int right = SIZE;
int left = 1;
int x;
int key;
int element;
for (x = 0; x < SIZE; x++)
{
a[x] = 2 * x;
}
printf("Enter integer search key:\n");
scanf_s("%d", &key);
element = binarySearch(key, a, right, left);
if (element != -1)
{
printf("Found value in element %d\n", element);
}
else
{
printf("Value not found\n");
}
system("pause");
return 0;
}
int binarySearch(int key, int* a, int right, int left)
{
int mid = (left + right) / 2;
if (left > right)
{
return -1;
}
else if (key == a[mid])
{
return mid;
}
else if (key < a[mid])
{
right = mid - 1;
mid = (left + right) / 2;
return binarySearch(key, a, right, left);
}
else if(key > a[mid])
{
left = mid + 1;
mid = (left + right) / 2;
return binarySearch(key, a, right, left);
}
} | true |
0eb173e8920c5e43a07f5b118a85ad23180921c4 | C++ | MArsalanKhan/CNavSystem3 | /CWaypoint.cpp | UTF-8 | 3,889 | 3.515625 | 4 | [] | no_license | /*
* CWaypoint.cpp
*
* Created on: 7.11.2015
* Author: Arsalan
*/
#include "cWaypoint.h"
#include <iostream>
using namespace std;
#include<math.h>
/* Implementation of the Constructor of CWaypoint & printing addresses of Object and attributes*/
cWaypoint::cWaypoint(string name,double latitude,double longitude)
{
// setting the attributes using set function and chaecking the range of latitude and longitude
set(name,latitude,longitude);
#ifdef SHOWADDRESS
cout<<"The object has been created at address"<<this<<endl;
cout<<"The name is"<<" "<<m_name<<" "<<"Created at an address"<<&m_name<<endl;
cout<<"The Latitude of"<<" "<<m_name<<" "<<"is"<<" "<<m_latitude<<" "<<"Created at an address"<<&m_latitude<<endl;
cout<<"The Longitude of"<<" "<<m_name<<" "<<"is"<<" "<<m_longitude<<" "<<"Created at an address"<<&m_longitude<<endl;
#endif
}
// Implementing the Set method ,checking and assigning the correct values to the attributes
void cWaypoint::set(string name,double latitude,double longitude)
{
m_name=name;
if(latitude >=-90 && latitude<=90 )
{
m_latitude=latitude;
}
else
{
m_latitude=0;
}
if(longitude >=-180 && longitude<=180 )
{
m_longitude=longitude;
}
else
{
m_longitude=0;
}
}
//printing the name,latitude and longitude by checking the format choose by the user
//Implementing Print Method which takes format 1 0r 2 as parameter and print values either in decimal or degree,minute and second format
void cWaypoint::print(int format)
{
int deg;
int mm;
double ss;
if(format==1)
{
//cout<<"The Latitude of "<<m_name<<m_latitude<<endl;
//cout<<"The Longitude is"<<m_name<<m_longitude<<endl<<endl;
}
else if(format==2)
{
//converting latitude from decimal to degree min sec foramt
transformLatitude2degmmss(deg,mm,ss);
//converting latitude from decimal to degree min sec foramt
transformLongitude2degmmss(deg,mm,ss);
}
else
{
cout<<"Kindly read the Manual"<<endl;
}
}
//implementation of transformLatitude2degmmss
void cWaypoint:: transformLatitude2degmmss(int °,int &mm,double &ss)
{
deg=(int)m_latitude;
mm=((m_latitude)-(deg))*(60);
ss=(((m_latitude)-(deg))-(mm/60.0))*(3600);
//cout<<m_name<<" "<<"on latitude "<<"=";
//cout<<deg<<"deg"<<" "<<mm<<"min"<<" "<<ss<<"sec";
}
// Transformation of longitude in degree,minutes,and seconds
void cWaypoint:: transformLongitude2degmmss(int °,int &mm,double &ss)
{
deg=(int)m_longitude;
mm=((m_longitude)-(deg))*(60);
ss=(((m_longitude)-(deg))-(mm/60.0))*(3600);
//cout<<" "<<"and longitude=";
//cout<<deg<<"deg"<<" "<<mm<<"min"<<" "<<ss<<"s"<<" "<<endl;
}
string cWaypoint::getName() const
{
//cout<<m_name<<endl;
return m_name;
}
double cWaypoint::getLatitude()
{
//cout<<"The latitude of "<<m_name<<" is "<<m_latitude<<endl;
return m_latitude ;
}
double cWaypoint::getLongitude()
{
//cout<<"The Longitude of "<<m_name<<" is"<<" "<<m_longitude<<endl;
return m_longitude;
}
//getting all data by reference in a single call
void cWaypoint::getAllDataByReference(string &name,double &latitude,double &longitude) const
{
name=m_name;
latitude=m_latitude;
longitude=m_longitude;
}
//implemnting calculate distance function
double cWaypoint::calculateDistance(const cWaypoint &wp)
{
double distance;
distance= R*acos(sin(m_latitude*(PI/180))*sin(wp.m_latitude*(PI/180))+cos(m_latitude*(PI/180))*cos(wp.m_latitude*(PI/180))*cos(wp.m_longitude*(PI/180)-m_longitude*(PI/180)));
return distance ;
}
//overloaded operator to print the waypoint from print function of CRoute
ostream& operator<<(ostream & out,cWaypoint &wp)
{
//wp.print(2);
return out;
}
| true |
03cd193af77dc88daec0911fb86e8378a016a86b | C++ | faxinwang/OJ_PAT | /C4_GPLT/L1_10.cpp | UTF-8 | 351 | 2.78125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int min(int a,int b,int c){
return a<b?(a<c?a:c):(b<c?b:c);
}
int max(int a,int b,int c){
return a>b?(a>c?a:c):(b>c?b:c);
}
int main(){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
int min_=min(a,b,c);
int max_=max(a,b,c);
int mid_=(a+b+c)-(max_+min_);
printf("%d->%d->%d\n",min_,mid_,max_);
return 0;
}
| true |
a464f263076cae7e7bab366dc2a809194ff827f1 | C++ | manosgior/A-plus-plus-Programming-Language | /function_actions.cpp | UTF-8 | 43,110 | 2.65625 | 3 | [] | no_license | #include "function_actions.h"
#include "defines_header.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define BON "\e[1m"
#define BOFF "\e[0m"
Object* Manage_stmt_default() {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_STMT));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_ERROR));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
return tmp;
}
Object* Manage_program(Object* stmts) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_PROGRAM));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_PROGRAM));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
if(stmts != nullptr)
tmp->set(AST_TAG_CHILD, Value(stmts));
return tmp;
}
Object* Manage_stmts_stmtsR_stmt(Object* stmtsR, Object* stmt) {
if(stmtsR == nullptr){
stmtsR = new Object();
stmtsR->set(AST_TAG_TYPE_KEY, Value(AST_TAG_STMTS));
stmtsR->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_STMTS));
stmtsR->set(AST_TAG_LINE_KEY, Value((double)yylineno));
stmtsR->set(AST_TAG_NUMCHILDREN, Value((double)0));
}
auto numChildren = (*stmtsR)[AST_TAG_NUMCHILDREN]->toNumber();
stmtsR->set(numChildren, Value(stmt));
stmtsR->set(AST_TAG_NUMCHILDREN, Value(numChildren + 1));
return stmtsR;
}
Object* Manage_stmts() {
return nullptr;
}
Object* Manage_stmt_expr_SEMICOLON(Object* e) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_STMT));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_STMT));
tmp->set(AST_TAG_LINE_KEY, Value((*e)[AST_TAG_LINE_KEY]->toNumber()));
tmp->set(AST_TAG_CHILD, Value(e));
return tmp;
}
Object* Manage_stmt_whilestmt(Object* e){
Object* newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_LINE_KEY, Value((*e)[AST_TAG_LINE_KEY]->toNumber()));
assert( strcmp( (*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_WHILESTMT) == 0 );
newNode->set(AST_TAG_CHILD, Value(e));
return newNode;
}
Object* Manage_stmt_forstmt(Object* e){
Object* newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_LINE_KEY, Value((*e)[AST_TAG_LINE_KEY]->toNumber()));
assert( strcmp( (*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_FORSTMT) == 0 );
newNode->set(AST_TAG_CHILD, Value(e));
return newNode;
}
Object* Manage_stmt_returnstmt(Object* e){
Object* newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_LINE_KEY, Value((*e)[AST_TAG_LINE_KEY]->toNumber()));
assert( strcmp( (*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_RETURNSTMT) == 0 );
newNode->set(AST_TAG_CHILD, Value(e));
return newNode;
}
Object* Manage_stmt_SEMICOLON(){
Object* newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
return newNode;
}
Object* Manage_stmt_funcdef(Object* e){
Object* newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_LINE_KEY, Value(Value((*e)[AST_TAG_LINE_KEY]->toNumber())));
assert( strcmp( (*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_FUNCDEF) == 0 );
newNode->set(AST_TAG_CHILD, Value(e));
return newNode;
}
Object* Manage_stmt_ifstmt(Object* e){
Object* newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_LINE_KEY, Value(Value((*e)[AST_TAG_LINE_KEY]->toNumber())));
assert( strcmp( (*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_IFSTMT) == 0 );
newNode->set(AST_TAG_CHILD, Value(e));
return newNode;
}
Object* Manage_stmt_BREAK_SEMICOLON(){
Object* newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
Object* breakNode = new Object();
breakNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_BREAKSTMT));
breakNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_BREAKSTMT));
breakNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_CHILD, Value(breakNode));
return newNode;
}
Object* Manage_stmt_CONTINUE(){
Object* newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
Object* continueNode = new Object();
continueNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_CONTINUESTMT));
continueNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_CONTINUESTMT));
continueNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_CHILD, Value(continueNode));
return newNode;
}
Object* Manage_stmt_block(Object* e){
Object* newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_STMT));
newNode->set(AST_TAG_LINE_KEY, Value(Value((*e)[AST_TAG_LINE_KEY]->toNumber())));
assert( strcmp( (*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_BLOCK) == 0 );
newNode->set(AST_TAG_CHILD, Value(e));
return newNode;
}
Object* Manage_expr_assignexpr(Object* e) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_EXPR));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_EXPR));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_CHILD, Value(e));
return tmp;
}
Object* Manage_expr_exprL_ARITH_OPERATOR_exprR(Object *exprL, const char* op, Object* exprR){
Object* newNode = new Object();
assert( strcmp((*exprL)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_EXPR) == 0);
assert( strcmp((*exprR)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_EXPR) == 0);
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_EXPR));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_ARITHEXPR));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_LEFTEXPR, Value(exprL));
newNode->set(AST_TAG_RIGHTEXPR, Value(exprR));
newNode->set(AST_TAG_ARITHOP_TYPE, Value(op));
return newNode;
}
Object* Manage_expr_exprL_REL_OPERATOR_exprR(Object* exprL, const char* op, Object* exprR){
Object* newNode = new Object();
assert( strcmp((*exprL)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_EXPR) == 0);
assert( strcmp((*exprR)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_EXPR) == 0);
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_EXPR));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_RELEXPR));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_LEFTEXPR, Value(exprL));
newNode->set(AST_TAG_RIGHTEXPR, Value(exprR));
newNode->set(AST_TAG_RELOP_TYPE, Value(op));
return newNode;
}
Object* Manage_expr_exprL_AND_exprR(Object* exprL, Object* exprR){
Object* newNode = new Object();
assert( strcmp((*exprL)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_EXPR) == 0);
assert( strcmp((*exprR)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_EXPR) == 0);
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_EXPR));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_BOOLEXPR));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_LEFTEXPR, Value(exprL));
newNode->set(AST_TAG_RIGHTEXPR, Value(exprR));
newNode->set(AST_TAG_BOOLOP_TYPE, Value("and"));
return newNode;
}
Object* Manage_expr_exprL_OR_exprR(Object* exprL, Object* exprR){
Object* newNode = new Object();
assert( strcmp((*exprL)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_EXPR) == 0);
assert( strcmp((*exprR)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_EXPR) == 0);
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_EXPR));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_BOOLEXPR));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_LEFTEXPR, Value(exprL));
newNode->set(AST_TAG_RIGHTEXPR, Value(exprR));
newNode->set(AST_TAG_BOOLOP_TYPE, Value("or"));
return newNode;
}
Object* Manage_expr_term(Object* e){
Object* newNode = new Object();
assert( strcmp((*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_TERM) == 0);
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_EXPR));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_EXPR));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_CHILD, Value(e));
return newNode;
}
Object* Manage_term_LEFT_PAREN_expr_RIGHT_PAREN(Object* e){
Object* newNode = new Object();
assert( strcmp((*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_EXPR) == 0);
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_TERM));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_TERM_PARENS_EXPR));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_EXPR, Value(e));
return newNode;
}
Object* Manage_term_MINUS_expr(Object* e){
Object* newNode = new Object();
assert( strcmp((*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_EXPR) == 0);
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_TERM));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_TERM_MINUS_EXPR));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_EXPR, Value(e));
return newNode;
}
Object* Manage_term_NOT_expr(Object* e){
Object* newNode = new Object();
assert( strcmp((*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_EXPR) == 0);
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_TERM));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_TERM_NOT_EXPR));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_EXPR, Value(e));
return newNode;
}
Object* Manage_term_PLUS_PLUS_lvalue(Object* lvalue){
Object* newNode = new Object();
assert( strcmp((*lvalue)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_LVALUE) == 0);
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_TERM));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_TERM_PLUS_PLUS_LVALUE));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_LVALUE, Value(lvalue));
return newNode;
}
Object* Manage_term_MINUS_MINUS_lvalue(Object* lvalue){
Object* newNode = new Object();
assert( strcmp((*lvalue)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_LVALUE) == 0);
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_TERM));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_TERM_MINUS_MINUS_LVALUE));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_LVALUE, Value(lvalue));
return newNode;
}
Object* Manage_term_lvalue_PLUS_PLUS(Object* lvalue){
Object* newNode = new Object();
assert( strcmp((*lvalue)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_LVALUE) == 0);
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_TERM));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_TERM_LVALUE_PLUS_PLUS));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_LVALUE, Value(lvalue));
return newNode;
}
Object* Manage_term_lvalue_MINUS_MINUS(Object* lvalue){
Object* newNode = new Object();
assert( strcmp((*lvalue)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_LVALUE) == 0);
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_TERM));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_TERM_LVALUE_MINUS_MINUS));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_LVALUE, Value(lvalue));
return newNode;
}
Object* Manage_term_primary(Object* value) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_TERM));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_TERM));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_CHILD, Value(value));
return tmp;
}
Object* Manage_assignexpr_lvalue_ASSIGNMENT_expr(Object* lvalue, Object* expression) {
Object* tmp = new Object();
assert(!strcmp((*lvalue)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_LVALUE));
assert(!strcmp((*expression)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_EXPR));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_EXPR));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_ASSIGNEXPR));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_LVALUE, Value(lvalue));
tmp->set(AST_TAG_EXPR, Value(expression));
return tmp;
}
Object* Manage_primary_quasiquotes(Object* e) {
Object *newNode = new Object();
assert(!strcmp((*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_QUASIQUOTES));
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_PRIMARY));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_PRIMARY));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_CHILD, Value(e));
return newNode;
}
Object* Manage_primary_escape(Object* e) {
Object* newNode = new Object();
assert(!strcmp((*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_ESCAPE));
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_PRIMARY));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_PRIMARY));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_CHILD, Value(e));
return newNode;
}
Object* Manage_primary_inline(Object* e) {
Object *newNode = new Object();
assert(!strcmp((*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_INLINE));
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_PRIMARY));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_PRIMARY));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_CHILD, Value(e));
return newNode;
}
Object* Manage_primary_unparsed(Object* e) {
Object *newNode = new Object();
assert(!strcmp((*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_UNPARSED));
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_PRIMARY));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_PRIMARY));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_CHILD, Value(e));
return newNode;
}
Object* Manage_primary_compiledstring(Object* e) {
Object *newNode = new Object();
assert(!strcmp((*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_COMPILEDSTRING));
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_PRIMARY));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_PRIMARY));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_CHILD, Value(e));
return newNode;
}
Object* Manage_primary_call(Object* e) {
Object* tmp = new Object();
assert(!strcmp((*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_CALL));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_PRIMARY));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_PRIMARY));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_CHILD, Value(e));
return tmp;
}
Object* Manage_primary_objectdef(Object* e) {
Object* tmp = new Object();
assert(!strcmp((*e)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_OBJECTDEF));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_PRIMARY));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_PRIMARY));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_CHILD, Value(e));
return tmp;
}
Object* Manage_primary_lvalue(Object* lvalue) {
Object* tmp = new Object();
assert(!strcmp((*lvalue)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_LVALUE));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_PRIMARY));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_PRIMARY));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_CHILD, Value(lvalue));
return tmp;
}
Object* Manage_primary_LEFT_PAREN_funcdef_RIGHT_PAREN(Object* funcdef) {
Object* tmp = new Object();
assert(!strcmp((*funcdef)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_FUNCDEF));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_PRIMARY));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_PRIMARY));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_CHILD, Value(funcdef));
return tmp;
}
Object* Manage_primary_const(Object* value) {
Object* tmp = new Object();
assert(!strcmp((*value)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_CONST));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_PRIMARY));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_PRIMARY));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_CHILD, Value(value));
return tmp;
}
Object* Manage_lvalue_ID(char *id) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_LVALUE));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_LVALUE_ID));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_ID, Value(id));
return tmp;
}
Object* Manage_lvalue_DOUBLE_COLON_ID(char *id) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_LVALUE));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_LVALUE_GLOBAL_ID));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_GLOBALID, Value(id));
return tmp;
}
Object* Manage_lvalue_LOCAL_ID(char *id) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_LVALUE));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_LVALUE_LOCAL_ID));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_LOCALID, Value(id));
return tmp;
}
Object* Manage_lvalue_member(Object* member) {
Object* tmp = new Object();
assert(!strcmp((*member)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_MEMBER));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_LVALUE));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_LVALUE_MEMBER));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_MEMBER, Value(member));
return tmp;
}
Object* Manage_member_lvalue_DOT_ID(Object* lvalue, char *id) {
Object* tmp = new Object();
assert(!strcmp((*lvalue)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_LVALUE));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_MEMBER));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_MEMBER_ID));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_CALLER, Value(lvalue));
tmp->set(AST_TAG_ID, Value(id));
return tmp;
}
Object* Manage_lvalue_DOT_DOLLAR_IDENT(Object* lvalue, char* dollar_ident) {
Object* tmp = new Object();
assert(!strcmp((*lvalue)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_LVALUE));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_MEMBER));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_MEMBER_ID));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_CALLER, Value(lvalue));
tmp->set(AST_TAG_ID, Value(dollar_ident));
return tmp;
}
Object* Manage_member_lvalue_LEFT_BRACKET_expr_RIGHT_BRACKET(Object* lvalue, Object* expr) {
Object* tmp = new Object();
assert(!strcmp((*lvalue)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_LVALUE));
assert(!strcmp((*expr)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_EXPR));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_MEMBER));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_MEMBER_EXPR));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_CALLER, Value(lvalue));
tmp->set(AST_TAG_EXPR, Value(expr));
return tmp;
}
Object* Manage_member_call_DOT_ID(Object* call, char *id) {
Object* tmp = new Object();
assert(!strcmp((*call)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_CALL));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_MEMBER));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_MEMBER_ID));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_CALLER, Value(call));
tmp->set(AST_TAG_ID, Value(id));
return tmp;
}
Object* Manage_call_DOT_DOLLAR_IDENT(Object* call, char* dollar_ident) {
Object* tmp = new Object();
assert(!strcmp((*call)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_CALL));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_MEMBER));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_MEMBER_ID));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_CALLER, Value(call));
tmp->set(AST_TAG_ID, Value(dollar_ident));
return tmp;
}
Object* Manage_member_call_LEFT_BRACKET_expr_RIGHT_BRACKET(Object* call, Object* expr) {
Object* tmp = new Object();
assert(!strcmp((*call)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_CALL));
assert(!strcmp((*expr)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_EXPR));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_MEMBER));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_MEMBER_EXPR));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_CALLER, Value(call));
tmp->set(AST_TAG_EXPR, Value(expr));
return tmp;
}
Object* Manage_call_callRight_LEFT_PAREN_elist_RIGHT_PAREN(Object* callRight, Object* elist) {
Object* tmp = new Object();
assert(!strcmp((*callRight)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_CALL));
if (elist != nullptr)
assert(!strcmp((*elist)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_ELIST));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_CALL));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_MULTICALL));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_CALL, Value(callRight));
if (elist != nullptr)
tmp->set(AST_TAG_ELIST, Value(elist));
return tmp;
}
Object* Manage_call_lvalue_callsuffix(Object* lvalue, Object* callsuffix) {
Object* tmp = new Object();
assert(!strcmp((*lvalue)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_LVALUE));
assert(!strcmp((*callsuffix)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_CALLSUFFIX));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_CALL));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_CALL));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_LVALUE, Value(lvalue));
tmp->set(AST_TAG_CALLSUFFIX, Value(callsuffix));
return tmp;
}
Object* Manage_LEFT_PAREN_funcdef_RIGHT_PAREN_LEFT_PAREN_elist_RIGHT_PAREN(Object* funcdef, Object* elist) {
Object* tmp = new Object();
assert(!strcmp((*funcdef)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_FUNCDEF));
if (elist != nullptr)
assert(!strcmp((*elist)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_ELIST));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_CALL));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_FDEFCALL));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_FUNCDEF, Value(funcdef));
if (elist != nullptr)
tmp->set(AST_TAG_ELIST, Value(elist));
return tmp;
}
Object* Manage_callsuffix_normcall(Object* normcall) {
Object* tmp = new Object();
assert(!strcmp((*normcall)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_NORMCALL));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_CALLSUFFIX));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_NORMCALLSUFFIX));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_NORMCALL, Value(normcall));
return tmp;
}
Object* Manage_callsuffix_methodcall(Object* methodcall) {
Object* tmp = new Object();
assert(!strcmp((*methodcall)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_METHODCALL));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_CALLSUFFIX));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_METHODCALLSUFFIX));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_METHODCALL, Value(methodcall));
return tmp;
}
Object* Manage_normcall_LEFT_PAREN_elist_RIGHT_PAREN(Object* elist) {
Object* tmp = new Object();
if (elist != nullptr)
assert(!strcmp((*elist)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_ELIST));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_NORMCALL));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_NORMCALL));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
if (elist != nullptr)
tmp->set(AST_TAG_ELIST, Value(elist));
return tmp;
}
Object* Manage_methodcall_DOT_DOT_ID_LEFT_PAREN_elist_RIGHT_PAREN(char *id, Object* elist) {
Object* tmp = new Object();
if (elist != nullptr)
assert(!strcmp((*elist)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_ELIST));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_METHODCALL));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_METHODCALL));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_ID, Value(id));
if (elist != nullptr) tmp->set(AST_TAG_ELIST, Value(elist));
return tmp;
}
Object* Manage_elist() {
return nullptr;
}
Object* Manage_elist_elistnotempty(Object* elist) {
Object* tmp = new Object();
assert(!strcmp((*elist)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_ELISTNOTEMPTY));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_ELIST));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_ELIST));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_ELISTNOTEMPTY, Value(elist));
bool idflag = false;
for (unsigned int i = 0; i < (*elist)[AST_TAG_NUMCHILDREN]->toNumber(); i++) {
auto argName = (*(*((*elist)[i])).toObjectNoConst())[AST_TAG_ID];
if (idflag && argName == nullptr) {
error(ErrorType::Error, yylineno, "A++ Syntax Error: positional arguments after keyword arguments are not allowed\n");
}
if (!idflag && argName != nullptr) idflag = true;
}
return tmp;
}
Object* Manage_commalist() {
return nullptr;
}
Object* Manage_commalist_COMMA_argument_commalist(Object* elist, Object* arg) {
if (elist != nullptr)
assert(!strcmp((*elist)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_ELISTNOTEMPTY));
else {
elist = new Object();
elist->set(AST_TAG_TYPE_KEY, Value(AST_TAG_ELISTNOTEMPTY));
elist->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_ELISTNOTEMPTY));
elist->set(AST_TAG_LINE_KEY, Value((double)yylineno));
elist->set(AST_TAG_NUMCHILDREN, Value((double)0));
}
auto numChildren = (*elist)[AST_TAG_NUMCHILDREN]->toNumber();
elist->set(numChildren, Value(arg));
elist->set(AST_TAG_NUMCHILDREN, Value(numChildren + 1));
return elist;
}
Object* Manage_argument_expr(Object *expr) {
Object* arg = new Object();
arg->set(AST_TAG_TYPE_KEY, Value(AST_TAG_ARGUMENT));
arg->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_ARGUMENT));
arg->set(AST_TAG_LINE_KEY, Value((double)yylineno));
arg->set(AST_TAG_EXPR, Value(expr));
return arg;
}
Object* Manage_argument_ID_COLON_expr(char *id, Object *expr) {
Object* arg = new Object();
arg->set(AST_TAG_TYPE_KEY, Value(AST_TAG_ARGUMENT));
arg->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_ARGUMENT));
arg->set(AST_TAG_LINE_KEY, Value((double)yylineno));
arg->set(AST_TAG_ID, Value(id));
arg->set(AST_TAG_EXPR, Value(expr));
return arg;
}
Object* Manage_objectdef_LEFT_BRACKET_objectdinner_RIGHT_BRACKET(Object* cont) {
Object* tmp = new Object();
if (cont != nullptr)
assert(!strcmp((*cont)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_OBJECTDINNER));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_OBJECTDEF));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_OBJECTDEF));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
if (cont != nullptr) tmp->set(AST_TAG_OBJECTDINNER, Value(cont));
return tmp;
}
Object* Manage_objelistnotempty_COMMA_expr_objcommalist(Object *objcommalist, Object *expr) {
if (objcommalist != nullptr)
assert(!strcmp((*objcommalist)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_OBJELISTNOTEMPTY));
else {
objcommalist = new Object();
objcommalist->set(AST_TAG_TYPE_KEY, Value(AST_TAG_OBJELISTNOTEMPTY));
objcommalist->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_OBJELISTNOTEMPTY));
objcommalist->set(AST_TAG_LINE_KEY, Value((double)yylineno));
objcommalist->set(AST_TAG_NUMCHILDREN, Value((double)0));
}
auto numChildren = (*objcommalist)[AST_TAG_NUMCHILDREN]->toNumber();
objcommalist->set(numChildren, Value(expr));
objcommalist->set(AST_TAG_NUMCHILDREN, Value(numChildren + 1));
return objcommalist;
}
Object* Manage_objectdinner_objelistnotempty(Object* elist) {
Object* tmp = new Object();
if (elist != nullptr)
assert(!strcmp((*elist)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_OBJELISTNOTEMPTY));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_OBJECTDINNER));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_CONT_LIST));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_OBJELISTNOTEMPTY, Value(elist));
return tmp;
}
Object* Manage_objectdinner_indexed(Object* indexed) {
Object* tmp = new Object();
assert(!strcmp((*indexed)[AST_TAG_TYPE_KEY]->toString(), AST_TAG_COMMAINDEXED));
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_OBJECTDINNER));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_CONT_INDEXED));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_INDEXED, Value(indexed));
return tmp;
}
Object* Manage_objectdinner() {
return nullptr;
}
Object* Manage_objcommalist() {
return nullptr;
}
Object* Manage_indexed_indexedelem_commaindexed(Object* indexed, Object* elem) {
assert(false);
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_INDEXED));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_INDEXED));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
if (indexed != nullptr)
tmp->set(AST_TAG_COMMAINDEXED, Value(indexed));
tmp->set(AST_TAG_INDEXEDELEM, Value(elem));
return tmp;
}
Object* Manage_commaindexed() {
return nullptr;
}
Object* Manage_commaindexed_COMMA_indexedelem_commaindexed(Object* indexed, Object* elem) {
if (indexed == nullptr) {
indexed = new Object();
indexed->set(AST_TAG_TYPE_KEY, Value(AST_TAG_COMMAINDEXED));
indexed->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_COMMAINDEXED));
indexed->set(AST_TAG_LINE_KEY, Value((double)yylineno));
indexed->set(AST_TAG_NUMCHILDREN, Value((double)0));
}
auto numChildren = (*indexed)[AST_TAG_NUMCHILDREN]->toNumber();
indexed->set(numChildren, Value(elem));
indexed->set(AST_TAG_NUMCHILDREN, Value(numChildren + 1));
return indexed;
}
Object* Manage_indexedelem_LEFT_BRACE_expr_COLON_expr_RIGHT_BRACE(Object* key, Object* value) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_INDEXEDELEM));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_INDEXEDELEM));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_OBJECT_KEY, Value(key));
tmp->set(AST_TAG_OBJECT_VALUE, Value(value));
return tmp;
}
Object* Manage_funcdef_funcprefix_LEFT_PAREN_idlist_RIGHT_PAREN_block(Object* funcprefix, Object* idlist, Object *block) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_FUNCDEF));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_FUNCDEF));
tmp->set(AST_TAG_LINE_KEY, Value((*funcprefix)[AST_TAG_LINE_KEY]->toNumber()));
tmp->set(AST_TAG_FUNCPREFIX, Value(funcprefix));
std::map<std::string, bool> idMap = std::map<std::string, bool>();
if (idlist != nullptr) {
tmp->set(AST_TAG_IDLIST, Value(idlist));
auto numFormals = (*idlist)[AST_TAG_NUMCHILDREN]->toNumber();
bool idflag = false;
for (unsigned int i = 0; i < numFormals; i++) {
auto currFormalName = (*((*idlist)[i]->toObjectNoConst()))[AST_TAG_ID]->toString();
if (idMap.find(currFormalName) == idMap.end())
idMap[currFormalName] = true;
else
error(ErrorType::Error, yylineno, "A++ Syntax Error: same argument many times\n");
auto formalExpr = (*((*idlist)[i]->toObjectNoConst()))[AST_TAG_EXPR];
if (idflag && formalExpr == nullptr) {
error(ErrorType::Error, yylineno, "A++ Syntax Error: required arguments cannot be after optional arguments\n");
}
if (!idflag && formalExpr != nullptr) idflag = true;
}
}
tmp->set(AST_TAG_BLOCK, Value(block));
return tmp;
}
Object* Manage_funcprefix_FUNCTION_funcname(Object* value) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_FUNCPREFIX));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_FUNCPREFIX));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
if (value != nullptr)
tmp->set(AST_TAG_CHILD, Value(value));
return tmp;
}
Object* Manage_funcname(){
return nullptr;
}
Object* Manage_funcname_ID(char *id) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_FUNCNAME));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_FUNCNAME_ID));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_ID, Value(id));
return tmp;
}
Object* Manage_const_numconst(double value) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_CONST));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_CONST_NUMCONST));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_VALUE, Value(value));
return tmp;
}
Object* Manage_const_strconst(char *value) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_CONST));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_CONST_STRCONST));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_VALUE, Value(value));
return tmp;
}
Object* Manage_const_nil() {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_CONST));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_CONST_NIL));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_VALUE, Value(Value::NilType));
return tmp;
}
Object* Manage_const_boolconst(bool value) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_CONST));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_CONST_BOOLCONST));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_VALUE, Value(value));
return tmp;
}
Object* Manage_idlist() {
return nullptr;
}
Object* Manage_commaidlist() {
return nullptr;
}
Object* Manage_commaidlist_formal_COMMA(Object* value, Object* formal) {
if (value == nullptr) {
value = new Object();
value->set(AST_TAG_TYPE_KEY, Value(AST_TAG_COMMAIDLIST));
value->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_COMMAIDLIST));
value->set(AST_TAG_LINE_KEY, Value((double)yylineno));
value->set(AST_TAG_NUMCHILDREN, Value((double)0));
}
auto numChildren = (*value)[AST_TAG_NUMCHILDREN]->toNumber();
value->set(numChildren, Value(formal));
value->set(AST_TAG_NUMCHILDREN, Value(numChildren + 1));
return value;
}
Object *Manage_formal_ID(char *id){
Object* formal = new Object();
formal->set(AST_TAG_TYPE_KEY, Value(AST_TAG_FORMAL));
formal->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_FORMAL));
formal->set(AST_TAG_LINE_KEY, Value((double)yylineno));
formal->set(AST_TAG_ID, Value(id));
return formal;
}
Object *Manage_formal_ID_ASSIGNMENT_expr(char *id, Object *expr){
Object* formal = new Object();
formal->set(AST_TAG_TYPE_KEY, Value(AST_TAG_FORMAL));
formal->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_FORMAL));
formal->set(AST_TAG_LINE_KEY, Value((double)yylineno));
formal->set(AST_TAG_ID, Value(id));
formal->set(AST_TAG_EXPR, Value(expr));
return formal;
}
Object* Manage_ifprefix_LEFT_PAREN_expr_RIGHT_PAREN(Object* value) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_IFPREFIX));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_IFPREFIX));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_EXPR, Value(value));
return tmp;
}
Object* Manage_ifstmt_ifprefix_stmt(Object* ifprefix, Object* stmt) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_IFSTMT));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_IFSTMT));
tmp->set(AST_TAG_LINE_KEY, Value((*ifprefix)[AST_TAG_LINE_KEY]->toNumber()));
tmp->set(AST_TAG_IFPREFIX, Value(ifprefix));
tmp->set(AST_TAG_IFSTMT_IFBODY, Value(stmt));
return tmp;
}
Object* Manage_ifstmt_ifprefix_stmt_elseprefix_stmt(Object* ifprefix, Object* elseprefix, Object* ifstmt, Object* elsestmt) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_IFSTMT));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_IFSTMT));
tmp->set(AST_TAG_LINE_KEY, Value((*ifprefix)[AST_TAG_LINE_KEY]->toNumber()));
tmp->set(AST_TAG_IFPREFIX, Value(ifprefix));
tmp->set(AST_TAG_ELSEPREFIX, Value(elseprefix));
tmp->set(AST_TAG_IFSTMT_IFBODY, Value(ifstmt));
tmp->set(AST_TAG_IFSTMT_ELSEBODY, Value(elsestmt));
return tmp;
}
Object* Manage_elseprefix_ELSE() {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_ELSEPREFIX));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_ELSEPREFIX));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
return tmp;
}
Object* Manage_whilestart_WHILE() {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_WHILESTART));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_WHILESTART));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
return tmp;
}
Object* Manage_whilecond_LEFT_PAREN_expr_RIGHT_PAREN(Object* value) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_WHILECOND));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_WHILECOND));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_EXPR, Value(value));
return tmp;
}
Object* Manage_while_whilestart_whilecond_stmt(Object* whilestart, Object* whilecond, Object* stmt) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_WHILESTMT));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_WHILESTMT));
tmp->set(AST_TAG_LINE_KEY, Value((*whilestart)[AST_TAG_LINE_KEY]->toNumber()));
tmp->set(AST_TAG_WHILESTART, Value(whilestart));
tmp->set(AST_TAG_WHILECOND, Value(whilecond));
tmp->set(AST_TAG_STMT, Value(stmt));
return tmp;
}
Object* Manage_block_LEFT_BRACE_stmts_RIGHT_BRACE(Object* stmts) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_BLOCK));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_BLOCK));
if (stmts != nullptr) {
tmp->set(AST_TAG_STMTS, Value(stmts));
tmp->set(AST_TAG_LINE_KEY, Value((*stmts)[AST_TAG_LINE_KEY]->toNumber()));
}
else
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
return tmp;
}
Object* Manage_forprefix_FOR_LEFT_PAREN_elist_SEMICOLON_expr_SEMICOLON(Object* elist, Object* expr) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_FORPREFIX));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_FORPREFIX));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
if (elist != nullptr)
tmp->set(AST_TAG_ELIST, Value(elist));
tmp->set(AST_TAG_EXPR, Value(expr));
return tmp;
}
Object* Manage_forstmt_forprefix_elist_RIGHT_PAREN_stmt (Object* forprefix, Object *elist, Object *stmt) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_FORSTMT));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_FORSTMT));
tmp->set(AST_TAG_LINE_KEY, Value((*forprefix)[AST_TAG_LINE_KEY]->toNumber()));
tmp->set(AST_TAG_FORPREFIX, Value(forprefix));
if (elist != nullptr)
tmp->set(AST_TAG_ELIST, Value(elist));
tmp->set(AST_TAG_STMT, Value(stmt));
return tmp;
}
Object* Manage_returnstmt_RETURN_expr_SEMICOLON(Object* value) {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_RETURNSTMT));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_RETURNSTMT));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
tmp->set(AST_TAG_EXPR, Value(value));
return tmp;
}
Object* Manage_returnstmt_RETURN_SEMICOLON() {
Object* tmp = new Object();
tmp->set(AST_TAG_TYPE_KEY, Value(AST_TAG_RETURNSTMT));
tmp->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_RETURNSTMT));
tmp->set(AST_TAG_LINE_KEY, Value((double)yylineno));
return tmp;
}
Object* Manage_quasiquotes_LEFT_QUASI_QUOTE_quotedrules_RIGHT_QUASI_QUOTE(Object *quotedrules){
Object *newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_QUASIQUOTES));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_QUASIQUOTES));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_CHILD, Value(quotedrules));
return newNode;
}
Object* Manage_quotedrules(Object *contents) {
Object *newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_QUOTEDRULES));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_QUOTEDRULES));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
if(contents != nullptr)
newNode->set(AST_TAG_CHILD, Value(contents));
return newNode;
}
Object* Manage_escape_TILDA_ID(char* id) {
Object *newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_ESCAPE));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_ESCAPE_ID));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_ID, Value(id));
return newNode;
}
Object* Manage_escape_TILDA_LEFT_PAREN_expr_RIGHT_PAREN(Object* expr) {
Object *newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_ESCAPE));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_ESCAPE_EXPR));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_EXPR, Value(expr));
return newNode;;
}
Object* Manage_inline_EXCLAMATION_MARK_LEFT_PAREN_expr_RIGHT_PAREN(Object* expr) {
Object* newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_INLINE));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_INLINE));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_CHILD, Value(expr));
return newNode;
}
Object* Manage_unparsed_SHARP_LEFT_PAREN_expr_RIGHT_PAREN(Object* expr) {
Object* newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_UNPARSED));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_UNPARSED));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_CHILD, Value(expr));
return newNode;
}
Object* Manage_compiledstring_AT_LEFT_PAREN_expr_RIGHT_PAREN(Object* expr) {
Object* newNode = new Object();
newNode->set(AST_TAG_TYPE_KEY, Value(AST_TAG_COMPILEDSTRING));
newNode->set(AST_TAG_SUBTYPE_KEY, Value(AST_TAG_COMPILEDSTRING));
newNode->set(AST_TAG_LINE_KEY, Value((double)yylineno));
newNode->set(AST_TAG_CHILD, Value(expr));
return newNode;
} | true |
9fc46cf07ea36f5ecdae7181157987108572edc1 | C++ | Minakshi-probuz/cPlusPlus | /pract41.cpp | UTF-8 | 373 | 2.765625 | 3 | [] | no_license | /*
A
B B
C C C
*/
#include<iostream>
using namespace std;
int main(){
char ch='A';
//int space=3;
for(int i=1;i<=3;i++){
for (int j = 3; j >=i; j--)
{
cout<<" ";
}
for(int k=1;k<=i;k++){
cout<<ch<<" ";
}cout<<endl;
//space--;
ch++;;
}
} | true |
d8639b21c58d45a7017162f31c2956a523d72854 | C++ | yingziyu-llt/OI | /c/vjudge/DP/数位DP/hud 2089_DFS.cpp | UTF-8 | 910 | 2.609375 | 3 | [] | no_license | #include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
int len;
int dight[9];
int make_dight(int n)
{
len = 1;
memset(dight,0,sizeof(dight));
while(n)
{
dight[len] = n % 10;
n /= 10;
len++;
}
len--;
return len;
}
long long f[9][10];
int dfs(int dep,bool limit,bool is6)
{
if(!dep) return 1;
if(!limit && f[dep][is6] != -1) return f[dep][is6];
int bit = limit ? dight[dep] : 9;
int ans = 0;
for(int i = 0;i <= bit;i++)
{
if(i == 4 || i == 2 && is6) continue;
ans += dfs(dep - 1,limit && i == bit,i == 6);
}
if(!limit) f[dep][is6] = ans;
return ans;
}
int solve(int n)
{
long long ans = 0;
int len = make_dight(n);
memset(f,-1,sizeof(f));
return dfs(len,1,0);
}
int main()
{
int m,n;
while(1)
{
scanf("%d%d",&m,&n);
if(m == 0 && n == 0) break;
printf("%d\n",solve(n) - solve(m - 1));
}
return 0;
} | true |
0c87a990b90eb3c3545b362d591bc3ad2e036743 | C++ | ashbob999/Advent-of-Code | /cpp/2020/day08.cpp | UTF-8 | 2,540 | 3.09375 | 3 | [] | no_license | #include "../aocHelper.h"
enum class instruction_type : int
{
nop = 0,
jmp = 1,
acc = 2
};
enum class stopped_type : int
{
infinte_loop = 0,
out_of_bounds = 1
};
struct VM
{
vector<pair<instruction_type, int>> instructions;
int accumulator = 0;
int pc = 0;
int* seen;
int swap_index = -1;
VM(char*& input)
{
while (*input != '\0')
{
instruction_type it;
if (*input == 'n')
{
it = instruction_type::nop;
}
else if (*input == 'a')
{
it = instruction_type::acc;
}
else if (*input == 'j')
{
it = instruction_type::jmp;
}
input += 4;
int sign = 0;
if (*input == '+')
{
sign = 1;
}
else if (*input == '-')
{
sign = -1;
}
input++;
int number = numericParse<int>(input);
instructions.emplace_back(it, sign * number);
input++;
}
seen = new int[instructions.size()]{};
}
stopped_type run()
{
while (true)
{
// check for out of bounds
if (pc == instructions.size())
{
return stopped_type::out_of_bounds;
}
// check if instruction has been seen
if (seen[pc])
{
return stopped_type::infinte_loop;
}
// get instruction
auto& op = instructions[pc];
auto code = op.first;
if (swap_index == pc)
{
code = (instruction_type) ((int) code ^ 1);
}
// mark instruction as seen
seen[pc] = 1;
switch (code)
{
case instruction_type::nop:
{
pc++;
break;
}
case instruction_type::jmp:
{
pc += op.second;
break;
}
case instruction_type::acc:
{
accumulator += op.second;
pc++;
break;
}
default:
break;
}
}
}
void reset()
{
accumulator = 0;
pc = 0;
fill(seen, seen + instructions.size(), 0);
swap_index = -1;
}
~VM()
{
delete seen;
}
};
class Day08 : public BaseDay
{
public:
Day08() : BaseDay("08") {}
result_type solve() override
{
long long part1 = 0, part2 = 0;
// parse input
VM vm(input);
// part 1
vm.run();
part1 = vm.accumulator;
// part 2
for (int i = 0; i < vm.instructions.size(); i++)
{
if (vm.instructions[i].first != instruction_type::acc)
{
vm.reset();
vm.swap_index = i;
auto result = vm.run();
if (result == stopped_type::out_of_bounds)
{
part2 = vm.accumulator;
break;
}
}
}
return { part1, part2 };
}
};
| true |
56bf51d3c608dfc7907f6e59192130da5776188a | C++ | jmaack24/VortexSim | /src/SphereFlow.cpp | UTF-8 | 1,970 | 2.796875 | 3 | [] | no_license | /*******************************************************************************
* \class SphereFlow
*
* \brief Computes the flow field for point vortices on the unit sphere --
* explicitly assumes 3D
*
* Author: Jonathan Maack
*
******************************************************************************/
#include "SphereFlow.h"
#include "Constants.h"
#include "Logger.h"
#include "Timer.h"
SphereFlow::SphereFlow(Logger *ln, Timer *tm):
FlowComputer(),
log(ln),
timer(tm)
{}
SphereFlow::~SphereFlow()
{
timer = 0;
log = 0;
}
void SphereFlow::computeFlow(Storage *str, FlowField *ret)
{
ret->clearFlow();
unsigned num = str->size();
unsigned i;
unsigned j;
double temp;
double coefficient;
double x1, x2, x3, y1, y2, y3;
double flow1[3];
double flow2[3];
PointVortex *pv1;
PointVortex *pv2;
for (i = 0; i < num; ++i)
{
pv1 = str->retrieve(i);
x1 = pv1->getPos(0);
x2 = pv1->getPos(1);
x3 = pv1->getPos(2);
for (j = i + 1; j < num; ++j)
{
pv2 = str->retrieve(j);
y1 = pv2->getPos(0);
y2 = pv2->getPos(1);
y3 = pv2->getPos(2);
// Compute common multiplier between the two vortices
temp = x1*y1 + x2*y2 + x3*y3; // dot product
coefficient = 1.0/(Constants::FOUR_PI*(1 - temp));
// Compute flow
temp = y2*x3 - y3*x2; // cross product
flow1[0] = pv2->getVort() * temp;
flow2[0] = pv1->getVort() * temp;
temp = y3*x1 - y1*x3;
flow1[1] = pv2->getVort() * temp;
flow2[1] = pv1->getVort() * temp;
temp = y1*x2 - y2*x1;
flow1[2] = pv2->getVort() * temp;
flow2[2] = pv1->getVort() * temp;
// Add flows
ret->addFlow(i, flow1);
ret->addFlow(j, flow2);
}
}
timer->stamp(Timer::FLOW);
}
| true |
1bec4fb126201e475af4db50f424f493c5b4d50a | C++ | bajaj99prashant/algorithms-implementation | /data-structures/linked-list/linkedlist.cpp | UTF-8 | 2,619 | 4.09375 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct Node {
int data;
Node* link;
};
Node* head;// global variable that can be accessed anywhere
// inserting a node at the end
void insertEnd(int x){
Node* temp = new Node();
temp->data = x;
temp->link = NULL;
Node* temp1 = head;// when we declare temp1 like this it takes the instance of the head and any modification in temp1 is also a modification in head without changing what head points to
while (temp1->link != NULL){
temp1 = temp1->link;
}
temp1->link = temp;
}
// inserting node at particular position
void insertNth(int x, int pos){
Node* temp = new Node();
temp->data = x;
temp->link = NULL;
if (pos == 1){
temp->link = head;
head = temp;
return;
}
Node* temp1 = head;
for (int i = 0; i<pos-2; i++){
temp1 = temp1->link;
}
temp->link = temp1->link;
temp1->link = temp;
}
// inserting node at the begining of the list
void insertBegin(int x){
Node* temp = new Node();
temp->data = x;
temp->link = head;
head = temp;
}
// delete a node at nth position
void deleteNode(int pos){
Node* temp = head;
if (pos == 1){
head = temp->link;// head now points to second node
delete temp;
return;
}
for (int i = 0; i<pos-2; i++){
temp = temp->link;
}
// temp points to (n - 1)th node
Node* temp1 = temp->link;// nth node
temp->link = temp1->link;// fixed the link part of the linked list
delete temp1;// deletes the unrequired nth linking part from the heap frame
}
// printing out the linked list
void print(){
cout << "elements in the link list ";
Node* temp = head;
if (temp == NULL){
cout << "Linked List is empty \n";
}else {
while (temp != NULL){
cout << temp->data << " ";
temp = temp->link;
}
}
cout << "\n";
}
// main function
int main()
{
head = NULL;// creating empty list
insertBegin(2);
insertBegin(3);
insertBegin(4);
insertBegin(5);
insertBegin(6);// list is 6, 5, 4, 3, 2
print();
int n;
cout << "position at which the node in linked list is to be deleted:\n";
cin >> n;
deleteNode(n);
print();
}
/*
concept of linked list
the only information we have of linked list is the address to which head of the linked list points
struct Node {
int data;
Node* nextNode;
};
address of the head node gives us access to the complete list
the main drawback of linked list is that we cannot read any element in constant amount of time
insertion also takes place in big-Oh of n
deletion also takes place in big-Oh of n
only advantage linked list provides is that it is dynamic and can be increased and decreased in the size
*/
| true |
cbca36be206e7b6ae05e276394ce4e96de108d0a | C++ | 11AbhijithROY/IPMP | /week2/Array_Prob2.cpp | UTF-8 | 553 | 3.421875 | 3 | [] | no_license | //Hashing method
int getOddOccurrence(int arr[], int n) {
// code here
unordered_map<int, int> umap;
for(int i = 0;i < n;i++) {
umap[arr[i]]++;
}
for(auto i : umap) {
if(i.second%2 != 0) {
return i.first;
}
}
return -1;
}
//XOR method - better method
int getOddOccurrence(int arr[], int n) {
// code here
int res = 0;
for(int i = 0;i < n;i++)
res = res ^ arr[i];
return res;
} | true |
2fe33d62df98a54b0279f9b888e41363dd65a0f7 | C++ | GUDHI/gudhi-devel | /src/Coxeter_triangulation/include/gudhi/Permutahedral_representation/Integer_combination_iterator.h | UTF-8 | 2,805 | 2.5625 | 3 | [
"MIT"
] | permissive | /* This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
* See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
* Author(s): Siargey Kachanovich
*
* Copyright (C) 2019 Inria
*
* Modification(s):
* - YYYY/MM Author: Description of the modification
*/
#ifndef PERMUTAHEDRAL_REPRESENTATION_INTEGER_COMBINATION_ITERATOR_H_
#define PERMUTAHEDRAL_REPRESENTATION_INTEGER_COMBINATION_ITERATOR_H_
#include <vector>
#include <boost/range/iterator_range.hpp>
namespace Gudhi {
namespace coxeter_triangulation {
typedef unsigned uint;
/** \brief Class that allows the user to generate combinations of
* k elements in a set of n elements.
* Based on the algorithm by Mifsud.
*/
class Integer_combination_iterator
: public boost::iterator_facade<Integer_combination_iterator, std::vector<uint> const,
boost::forward_traversal_tag> {
using value_t = std::vector<uint>;
private:
friend class boost::iterator_core_access;
bool equal(Integer_combination_iterator const& other) const { return (is_end_ && other.is_end_); }
value_t const& dereference() const { return value_; }
void increment() {
uint j1 = 0;
uint s = 0;
while (value_[j1] == 0 && j1 < k_) j1++;
uint j2 = j1 + 1;
while (value_[j2] == bounds_[j2]) {
if (bounds_[j2] != 0) {
s += value_[j1];
value_[j1] = 0;
j1 = j2;
}
j2++;
}
if (j2 >= k_) {
is_end_ = true;
return;
}
s += value_[j1] - 1;
value_[j1] = 0;
value_[j2]++;
uint i = 0;
while (s >= bounds_[i]) {
value_[i] = bounds_[i];
s -= bounds_[i];
i++;
}
value_[i++] = s;
}
public:
template <class Bound_range>
Integer_combination_iterator(const uint& n, const uint& k, const Bound_range& bounds)
: value_(k + 2), is_end_(n == 0 || k == 0), k_(k) {
bounds_.reserve(k + 2);
uint sum_radices = 0;
for (auto b : bounds) {
bounds_.push_back(b);
sum_radices += b;
}
bounds_.push_back(2);
bounds_.push_back(1);
if (n > sum_radices) {
is_end_ = true;
return;
}
uint i = 0;
uint s = n;
while (s >= bounds_[i]) {
value_[i] = bounds_[i];
s -= bounds_[i];
i++;
}
value_[i++] = s;
while (i < k_) value_[i++] = 0;
value_[k] = 1;
value_[k + 1] = 0;
}
// Used for the creating an end iterator
Integer_combination_iterator() : is_end_(true), k_(0) {}
private:
value_t value_; // the dereference value
bool is_end_; // is true when the current integer combination is the final one
uint k_;
std::vector<uint> bounds_;
};
} // namespace coxeter_triangulation
} // namespace Gudhi
#endif
| true |
1bd76d560fb76f7459c88aebcfe13aac0402b3cb | C++ | mashai/CaanooPlatformer | /Source/CDieOffscreenComponent.h | UTF-8 | 691 | 2.59375 | 3 | [] | no_license | #ifndef CDIE_OFFSCREEN_COMPONENT_H
#define CDIE_OFFSCREEN_COMPONENT_H
#include "CComponent.h"
#include "CKillComponent.h"
#include "CPositionComponent.h"
class CDieOffscreenComponent : public CComponent{
public:
//Constructor
CDieOffscreenComponent();
//Destructor
~CDieOffscreenComponent(){};
//onExecute - executes the component
void onExecute();
//onComponentAdded - informs component another component was added to entity
void onComponentAdded(CComponent* component);
protected:
CKillComponent* m_kill;
CPositionComponent* m_position;
};
#endif // CDIE_OFFSCREEN_COMPONENT_H
| true |
14923359c59a7b358bc05c06ea2e1bd575e35f15 | C++ | Shyguy226/csci13600-labs | /lab_11/funcs.cpp | UTF-8 | 1,181 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <cctype>
#include <sstream>
#include <string>
#include <locale>
using std::string;
void printRange(int left, int right){
if(left > right)
std::cout << std::endl;
else{
std::cout << left << " ";
printRange(left+1, right);
}
return;
}
int sumRange(int left, int right){
if(left > right){
return 0;
}
else{
return left + sumRange(left+1, right);
}
return 0;
}
int sumArrayInRange(int *arr, int left, int right){
if(left > right){
return 0;
}
else{
return arr[left] + sumArrayInRange(arr, left+1, right);
}
return 0;
}
int sumArray(int *arr, int size){
int ans = 0;
ans = sumArrayInRange(arr, 0, size-1);
return ans;
}
bool alphanum (char c){
if(isalnum(c))
return true;
else
return false;
}
bool isAlphanumeric(string s){
if(s.length()==1){
if(alphanum(s[0]))
return true;
}
if(alphanum(s[0]))
return isAlphanumeric(s.substr(1));
else
return false;
}
bool nestedParens(string s){
if(s.length()==0){
return true;
}
if(s[0]=='(' && s[s.length()-1]==')'){
return nestedParens(s.substr(1,s.length()-2));
}
else
return false;
}
| true |
325b04ec17e2820659a5774a794ef2b0285f140b | C++ | d0iasm/aoj-libraries | /DSL/range-query/range_minimum_query.cpp | UTF-8 | 1,163 | 3.109375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int n, q;
class RangeMinimumQuery {
private:
int* tree;
public:
int size;
RangeMinimumQuery(int n) {
size = 1; while(size < n) size *= 2;
tree = new int[2*size - 1];
for (int i=0; i < 2*size - 1; i++) tree[i] = INT_MAX;
}
void update(int i, int x);
int find(int s, int t, int i, int l, int r);
};
void RangeMinimumQuery::update(int i, int x) {
i += size - 1;
tree[i] = x;
while (i > 0) {
i = (i - 1) / 2;
tree[i] = min(tree[2*i+1], tree[2*i+2]);
}
}
int RangeMinimumQuery::find(int s, int t, int i, int l, int r) {
if (r < s || t < l) return INT_MAX;
if (s <= l && r <= t) return tree[i];
int vl = find(s, t, 2*i+1, l, (l+r)/2);
int vr = find(s, t, 2*i+2, (l+r)/2+1, r);
return min(vl, vr);
}
int main () {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
cin >> n >> q;
RangeMinimumQuery* RmQ = new RangeMinimumQuery(n);
int com, x, y;
for (int i=0; i < q; i++) {
cin >> com >> x >> y;
if (com == 0) {
RmQ -> update(x ,y);
} else {
cout << RmQ -> find(x, y, 0, 0, RmQ -> size - 1) << '\n';
}
}
return 0;
}
| true |
ed5d4f8ef5e52f4a8911ca8eb40e98f2883d54cd | C++ | vsroy/Data-Structures-and-Algorithms | /Cumulative Problems/Parenthesis_Checker_Using_Stack.cpp | WINDOWS-1252 | 1,008 | 4.40625 | 4 | [] | no_license | /*Given an expression string exp. Examine whether the pairs and the orders of {,},(,),[,] are correct in exp.*/
#include<iostream>
#include<string>
#include<stack>
using namespace std;
bool CheckBalancedParenthesis(string& str)
{
stack<char> parenthesisStack;
for (int i = 0; i < str.size(); i++)
{
if (str[i] == '(' || str[i] == '{' || str[i] == '[')
parenthesisStack.push(str[i]);
else
{
if (str[i] == ')')
{
if (parenthesisStack.top() != '(')
return false;
else
parenthesisStack.pop();
}
else if (str[i] == '}')
{
if (parenthesisStack.top() != '{')
return false;
else
parenthesisStack.pop();
}
else if (str[i] == ']')
{
if (parenthesisStack.top() != '[')
return false;
else
parenthesisStack.pop();
}
}
}
if (!parenthesisStack.empty())
return false;
else
return true;
}
int main()
{
string expr = "{()}[]";
cout << CheckBalancedParenthesis(expr);
return 0;
} | true |
dc414beb1c347c34e013135f1474f0f2d1cc0ec1 | C++ | nanlan2017/lang-cpp | /TemplateLang/haskell_to_cpp.h | GB18030 | 5,841 | 3.4375 | 3 | [] | no_license | #ifndef h_haskell2cpp
#define h_haskell2cpp
#include "prelude.h"
/* [Haskell]
type Uri = String
type LocalName = String
type NameClass = AnyName
| QName Uri LocalName
| NsName Uri
| NameClassChoice NameClass NameClass
*/
/*
In C++, the variants of NameClass are not connected directly.
Each of them is defined as a separate struct.
The members of each data type are given via template parameters.
~~~~~~~~~~~~ We are using structs everywhere now: both functions and data types are defined via template structs.
*/
using Str = const char*; //! ǻ
using Uri = Str;
using LocalName = Str;
//! ޱҪ⼸Ͷ̳NameClassͣ
// None of these types will be instantiated, so they do not require a complete definition.
//~~~~ ģҪʵ͡ ͱҪʵ
struct AnyName;
template <Str U, Str L>
struct QName { //todo ֵ // QNameijԱֵ
static_constexpr Str Uri = U;
static_constexpr Str LocalName = L;
};
template <Str U> //! Non-type parameter
struct NsName {
static_constexpr Str Uri = U;
};
template <typename NC1, typename NC2> //! type parameter
struct NameClassChoice {
using NameClass1 = NC1; //todo һ͡Ǹֵ
using NameClass2 = NC2;
};
//x============================================================================================================================
constexpr int strCmp_constexpr(char const * s1, char const * s2)
{
return ((0 == *s1) && (0 == *s2))
? 0
: ((*s1 == *s2) || ((*s1 == ' ') && (*s2 == '_')))
? strCmp_constexpr(s1 + 1, s2 + 1)
: (*s1 - *s2);
}
//x============================================================================================================================
/*
//todo Haskellеÿһֺõġpattern" <-----------> MetaTemplateеһģػ
contains :: NameClass -> QName -> Bool
contains AnyName _ = True
contains (QName ns1 ln1) (QName ns2 ln2) = (ns1 == ns2) && (ln1 == ln2)
contains (NsName ns1) (QName ns2 _) = (ns1 == ns2)
contains (NameClassChoice nc1 nc2) n = (contains nc1 n) || (contains nc2 n)
*/
// contains :: Type -> Type -> Bool
template <typename NameClass, typename QName>
struct contains;
//! contains<AnyName,T> ---> @T
template <Str U, Str L>
struct contains<AnyName, QName<U,L>> { //! ~~~~~~~~~~~~ӦȶСȻѲIJϣ
static_constexpr bool value = true;
};
//! contains<QName<ns1,ln1>, QName<ns2,ln2>> ----> @ns1,@ns2,@ln1,@ln2
template <Str U1, Str L1, Str U2, Str L2>
struct contains<QName<U1, L1>, QName<U2, L2>> {
static_constexpr bool value = strCmp_constexpr(U1, U2) == 0 && strCmp_constexpr(L1, L2) == 0;
};
//! contains<NsName<ns1>,... ȫHaskellpatternдһ
//todo [Haskell]==========> (QName ns1 ln1) ģʽƥһNameClassֵ
//todo [C++Meta]==========> QName<ns1,ns2> ƥһֵ
//todo -------->~~~~~~~~~~~~ ǿԽ reverse(List) Listͨƥ Cons<head,Tail>ģ--------֪Listָ Cons<h,t>
template <Str U1, Str U2, Str L2>
struct contains<NsName<U1>,QName<U2,L2>> {
static_constexpr bool value = strCmp_constexpr(U1, U2) == 0;
};
template <typename NameClass1, typename NameClass2,Str U2, Str L2>
struct contains<NameClassChoice<NameClass1,NameClass2>,QName<U2,L2>> {
static_constexpr bool value = contains<NameClass1,QName<U2,L2>>::value
|| contains<NameClass2,QName<U2,L2>>::value;
};
//x============================================================================================================================
constexpr char xhtmlNS[] = "http://www.w3.org/1999/xhtml";
constexpr char divLocalName[] = "div";
constexpr char pLocalName[] = "p";
template<int i>
struct ShowInt
{
enum { val = i};
};
inline void test_basicsss()
{
constexpr int i = strCmp_constexpr("abcdefg", "ab");
constexpr int j = 6;
int arrt[i]; // i ȷʵDZڼֵ
auto i2 = ShowInt<i>::val; //! dependent name ????
auto i3 = ShowInt<4>::val;
auto i4 = ShowInt<j>::val;
static_assert(!false, "wrong!");
//static_assert(!true, "wrong!");
static_assert(i, "wrong");
}
inline void testContainsAnyName() {
using PQName = QName<xhtmlNS, pLocalName>;
static_assert(contains<AnyName,PQName>::value, "AnyName should match PQName.");
//static_assert(!contains<AnyName,PQName>::value, "AnyName should match PQName."); //! failed!
}
inline void testContainsQName() {
using PQName = QName<xhtmlNS, pLocalName>;
using DivQName = QName<xhtmlNS, divLocalName>;
constexpr bool r = contains<DivQName, PQName>::value; // false
//static_assert(contains<DivQName,PQName>::value, "DivPQName should not match PQName."); //! failed!
static_assert(!contains<DivQName,PQName>::value, "DivPQName should not match PQName.");
}
inline void testContainsNsName() {
using PQName = QName<xhtmlNS, pLocalName>;
using HtmlNsName = NsName<xhtmlNS>;
static_assert(contains<HtmlNsName,PQName>::value, "HtmlNsName should match PQName.");
//static_assert(!contains<HtmlNsName,PQName>::value, "HtmlNsName should match PQName."); //! failed!
}
inline void testContainsNameClassChoice() {
using PQName = QName<xhtmlNS, pLocalName>;
using DivQName = QName<xhtmlNS, divLocalName>;
using HtmlNsName = NsName<xhtmlNS>;
using NameChoice = NameClassChoice<DivQName,HtmlNsName>;
static_assert(contains<NameChoice,PQName>::value, "NameChoice should match PQName.");
}
#endif
| true |
7ead0f6351f8c106c71237b38b5808a4f65d9df3 | C++ | descrip/competitive-programming | /ccc/sol/2006/s5.cpp | UTF-8 | 2,493 | 2.515625 | 3 | [] | no_license | /* Was stuck on this question for a while, got this great hash table idea.
* But my idea it still times out. So I went and looked at the mmhs solution.
* Apparently they looped to an arbitrary number of 50, and if they couldn't find it, they just printed -1.
* So I'm going to put this question off for a while.
*/
#include <set>
#include <bitset>
#include <vector>
#include <cstdio>
using namespace std;
#define pb push_back
typedef long long ll;
typedef unsigned long long ull;
#define scan(x) do{while((x=getchar())<'0'); for(x-='0'; '0'<=(_=getchar()); x=(x<<3)+(x<<1)+_-'0');}while(0)
char _;
int m, n, a, b, c;
int gton(const vector<vector<bool>> &v){
bitset<20> bs;
int pos = 0;
for (int i = n - 1; i >= 0; --i)
for (int j = m - 1; j >= 0; --j)
bs.set(pos++, v[i][j]);
return bs.to_ullong();
}
vector<vector<bool>> ntog(ull a){
bitset<20> bs (a);
int cnt = 19;
vector<vector<bool>> v (n, vector<bool> (m));
for (int i = n - 1; i >= 0; --i)
for (int j = m - 1; j >= 0; --j)
v[i][j] = bs[cnt--];
return v;
}
int nei(const vector<vector<bool>> v, int x, int y){
int cnt = 0;
for (int i = max(y-1,0); i <= min(y+1,n-1); ++i)
for (int j = max(x-1,0); j <= min(x+1,m-1); ++j)
if ((x != j && y != i) && v[i][j])
++cnt;
return cnt;
}
void prog(vector<vector<bool>> &v){
vector<pair<int,int>> kill, born;
for (int y = 0; y < n; ++y)
for (int x = 0; x < m; ++x)
if (v[x][y] && (nei(v,x,y) < a || nei(v,x,y) > b))
kill.pb({x,y});
else if (!v[x][y] && nei(v,x,y) > c)
born.pb({x,y});
for (auto i : kill)
v[i.second][i.first] = false;
for (auto i : born)
v[i.second][i.first] = true;
}
int main(){
scanf("%d %d %d %d %d",&m,&n,&a,&b,&c);
vector<vector<bool>> query (n, vector<bool>(m));
char buff;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j){
scanf("%c",&buff);
query[i][j] = (buff == '.' ? false : true);
}
vector<short> ans (1 << (m*n), 9999);
for (int i = 0; i < ans.size(); ++i){
if (ans[i] == 9999){
vector<vector<bool>> curr = ntog(i);
vector<int> aff;
set<int> prev;
int cnt = 0;
while (true){
++cnt;
prev.insert(gton(curr));
prog(curr);
int j = gton(curr);
if (j == i || prev.count(gton(curr))){
for (auto k : aff)
ans[k] = 9999;
break;
}
else{
if (cnt < ans[j]){
ans[j] = cnt;
aff.pb(j);
}
}
//printf("%d\n",i);
}
}
}
printf("%d\n",(ans[gton(query)] == 9999 ? 0 : ans[gton(query)]));
return 0;
}
| true |
40b8ad199a6caf102d64be1c7f0f91f817bf4a85 | C++ | erosnick/TheRayTracerChallenge | /TheRayTracerChallenge/utils.h | UTF-8 | 686 | 2.640625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <random>
inline float Q_rsqrt(float number) {
long i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = *(long*)&y; // evil floating point bit level hacking
i = 0x5f3759df - (i >> 1); // what the fuck?
y = *(float*)&i;
y = y * (threehalfs - (x2 * y * y)); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
inline double randomDouble() {
static std::uniform_real_distribution<double> distribution(0.0, 1.0);
static std::mt19937_64 generator;
return distribution(generator);
} | true |
b2ef5124639aac58892b1fa2be77b33a6ab4f0b1 | C++ | novostary/codes | /LeetCode/String/implement-strstr.cpp | UTF-8 | 486 | 2.953125 | 3 | [] | no_license | #include <string>
using std::string;
// Runtime: 8 ms
// Best: 4 ms
// https://leetcode.com/discuss/38998/explained-4ms-easy-c-solution KMP
class Solution {
public:
int strStr(string haystack, string needle) {
int size1 = haystack.size(), size2 = needle.size();
for (int i = 0; i < size1 - size2 + 1; i++) {
int j = 0;
for (; j < size2; j++) {
if (haystack.at(i + j) != needle.at(j)) {
break;
}
}
if (j == size2) {
return i;
}
}
return -1;
}
}; | true |
68cc8dc2bd9b44579b7c07025067f340ef07e692 | C++ | moonseokchoi-kr/CupheadCloneGame | /Client/CUI.h | UHC | 1,533 | 2.625 | 3 | [] | no_license | #pragma once
#include "CObject.h"
class CUI :
public CObject
{
public:
CUI(bool _cameraAffeted);
CUI(const CUI& _origin);
~CUI();
public:
// CObject() ӵ
virtual void Update() override;
virtual void Render(HDC _dc);
virtual void FinalUpdate();
virtual void MouseOn();
virtual void MouseLButtonDown();
virtual void MouseLButtonUp();
virtual void MouseLButtonClicked();
public:
const vector<CUI*>& GetChilds() { return m_childUIs; }
CUI* GetParent() { return m_parentUI; }
Vec2 GetFinalPos() { return m_finalPos; }
bool IsCameraAffed() { return m_cameraAffected; }
bool IsMouseOn() { return m_mouseOn; }
bool IsLButtonDown() { return m_lButtonDown; }
bool IsSelect() { return m_select; }
virtual void MouseOnCheck();
void AddChild(CUI* _childUI) { m_childUIs.push_back(_childUI); _childUI->m_parentUI = this; }
virtual CUI* Clone() = 0;
private:
void renderChild(HDC _dc);
void updateChild();
void finalUpdateChild();
private:
vector<CUI*> m_childUIs; //ڽ UI
CUI* m_parentUI; //θ UI nullptr̸ ֻ
Vec2 m_finalPos; //ġ
bool m_cameraAffected; //ī
bool m_mouseOn; //콺 öִ
bool m_lButtonDown; //콺ʹư Ŭߴ
bool m_select; // Ǿ
friend class CUIManager;
};
| true |
24985466a19a931c5a4c15234b4df73949df54ca | C++ | khbence/COVIDAgentModel | /src/agentData/globalStates.cpp | UTF-8 | 874 | 2.546875 | 3 | [] | no_license | #include "globalStates.h"
#include "customExceptions.h"
namespace states {
__host__ __device__ SIRD& operator++(SIRD& e) {
return e = static_cast<SIRD>(static_cast<int>(e) + 1);
}
[[nodiscard]] states::WBStates parseWBState(const std::string& rawState) {
if (rawState.length() != 1) { throw IOAgentTypes::InvalidWBStateInSchedule(rawState); }
char s = static_cast<char>(std::toupper(rawState.front()));
switch (s) {
case 'W':
return states::WBStates::W;
case 'N':
return states::WBStates::N;
case 'M':
return states::WBStates::M;
case 'S':
return states::WBStates::S;
case 'D':
return states::WBStates::D;
default:
throw IOAgentTypes::InvalidWBStateInSchedule(rawState);
}
}
}// namespace states
| true |
e0ee326e9a0b54de6a84c06f6534fa5d93c431ef | C++ | gergelyn/Prog1 | /labdaifnelkul.cpp | UTF-8 | 821 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <ncurses.h>
#include <unistd.h>
#include <curses.h>
using namespace std;
int main()
{
int xj = 0, xk = 0, yj = 0, yk = 0;
int mx = 80 * 2, my = 24 * 2;
WINDOW *myScreen;
myScreen = initscr();
noecho();
cbreak();
nodelay(myScreen, true);
for (;;)
{
xj = (xj - 1) % mx;
xk = (xk + 1) % mx;
yj = (yj - 1) % my;
yk = (yk + 1) % my;
clear();
mvprintw(0, 0, "--------------------------------------------------------------------------------");
mvprintw(abs((yj + (my - yk)) / 2), abs((xj + (mx - xk)) / 2), "X");
mvprintw(24, 0, "--------------------------------------------------------------------------------");
refresh();
usleep(20000);
}
return 0;
} | true |
2d9327ae843e928745f1c53fdd280c922be8fd40 | C++ | 3013216006/ACM | /17-7-27/test.cpp | UTF-8 | 239 | 2.765625 | 3 | [] | no_license | #include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
vector<int> v;
int main(){
for(int i=0;i<10;i++)
v.push_back(i);
for(int i=0;i<=10;i++){
cout << lower_bound(v.begin(),v.end(),i)-v.begin() << endl;
}
}
| true |
9c42837861495c64e953d31e41ef94eaf7ce4091 | C++ | Tuuby/AMSDogBot | /PioneerBV/SharedMemory/Shared_Memory.h | ISO-8859-1 | 805 | 2.796875 | 3 | [] | no_license | #ifndef _SHARED_MEMORY_H
#define _SHARED_MEMORY_H
#include "windows.h"
#include <string>
#include <iostream>
using namespace std;
class Shared_Memory
{
public:
//(De-)Konstruktor
Shared_Memory();
~Shared_Memory();
//Initialisierungsfunktion fr den Speicher
void SM_Init();
//Entladen des Speichers
void SM_Close();
//liefert einen Zeiger auf die Speicherzelle mit best. Index
float* SM_GetFloat(int index);
//setzt eine Speicherzelle auf einen best. Wert
void SM_SetFloat(int index, float wert);
//liefert die Anzahl der verfgbaren Speicherzellen
int SM_Getfloat_anzahl();
private:
HANDLE map; // Shared Memory
HANDLE mutex; // Synchronisationsobjekt
int float_anzahl; //Anzahl der zu erstellenden Float-Zellen
LPSTR com; //Zeiger auf den gemappten Specher
};
#endif | true |
98a20a137788ee7642d198b99fb7fc626d9dc3df | C++ | Karaokruk/sia_td3 | /src/mesh.cpp | UTF-8 | 9,686 | 2.515625 | 3 | [] | no_license | #include "mesh.h"
#include "bvh.h"
#include "shader.h"
#include <cstdio>
#include <fstream>
#include <iostream>
#include <sstream>
#include <pmp/SurfaceNormals.h>
using namespace std;
using namespace Eigen;
using namespace pmp;
Mesh::~Mesh() {
if (_ready) {
glDeleteBuffers(7, _vbo);
glDeleteVertexArrays(1, &_vao);
}
delete _bvh;
}
void Mesh::load(const string &filename) {
cout << "Loading: " << filename << endl;
read(filename);
SurfaceNormals::compute_face_normals(*this);
SurfaceNormals::compute_vertex_normals(*this);
// vertex properties
auto vpositions = get_vertex_property<Point>("v:point");
assert(vpositions);
auto vnormals = get_vertex_property<Normal>("v:normal");
assert(vnormals);
auto texcoords = get_vertex_property<TexCoord>("v:texcoord");
if (!texcoords) {
texcoords = add_vertex_property<TexCoord>("v:texcoord");
this->texcoords().setZero();
}
auto colors = get_vertex_property<Color>("v:color");
if (!colors) {
colors = add_vertex_property<Color>("v:color");
this->colors().setOnes();
}
add_vertex_property<int>("v:mask");
this->masks().fill(0);
auto vdisp = add_vertex_property<Vector3f>("v:disp");
for (auto v : vertices())
vdisp[v] = Vector3f::Zero();
auto vcurvatures = add_vertex_property<float>("v:mean_curvature");
for (auto v : vertices())
vcurvatures[v] = 0;
// face iterator
SurfaceMesh::FaceIterator fit, fend = faces_end();
// vertex circulator
SurfaceMesh::VertexAroundFaceCirculator fvit, fvend;
pmp::Vertex v0, v1, v2;
for (fit = faces_begin(); fit != fend; ++fit) {
fvit = fvend = vertices(*fit);
v0 = *fvit;
++fvit;
v2 = *fvit;
do {
v1 = v2;
++fvit;
v2 = *fvit;
_indices.push_back(v0.idx());
_indices.push_back(v1.idx());
_indices.push_back(v2.idx());
} while (++fvit != fvend);
}
updateNormals();
updateBoundingBox();
updateBVH();
}
void Mesh::createGrid(int m, int n) {
clear();
_indices.clear();
_indices.reserve(2 * 3 * m * n);
reserve(m * n, 3 * m * n, 2 * m * n);
float dx = 1. / float(m - 1);
float dy = 1. / float(n - 1);
Eigen::Array<pmp::Vertex, Dynamic, Dynamic> ids(m, n);
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
ids(i, j) = add_vertex(Point(double(i) * dx, double(j) * dy, 0.));
add_vertex_property<Vector3f>("v:color");
add_vertex_property<Vector3f>("v:normal");
add_vertex_property<Vector2f>("v:texcoord");
add_vertex_property<int>("v:mask");
colors().fill(1);
masks().fill(0);
texcoords() = positions().topRows(2);
for (int i = 0; i < m - 1; ++i) {
for (int j = 0; j < n - 1; ++j) {
pmp::Vertex v0, v1, v2, v3;
v0 = ids(i + 0, j + 0);
v1 = ids(i + 1, j + 0);
v2 = ids(i + 1, j + 1);
v3 = ids(i + 0, j + 1);
add_triangle(v0, v1, v2);
add_triangle(v0, v2, v3);
_indices.push_back(v0.idx());
_indices.push_back(v1.idx());
_indices.push_back(v2.idx());
_indices.push_back(v0.idx());
_indices.push_back(v2.idx());
_indices.push_back(v3.idx());
}
}
updateNormals();
updateBoundingBox();
updateBVH();
}
void Mesh::init() {
glGenVertexArrays(1, &_vao);
glGenBuffers(7, _vbo);
updateVBO();
_ready = true;
}
void Mesh::updateAll() {
updateNormals();
updateBoundingBox();
updateBVH();
updateVBO();
}
void Mesh::updateNormals() {
SurfaceNormals::compute_face_normals(*this);
SurfaceNormals::compute_vertex_normals(*this);
}
void Mesh::updateVBO() {
glBindVertexArray(_vao);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vbo[VBO_IDX_FACE]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(int) * _indices.size(),
_indices.data(), GL_STATIC_DRAW);
VertexProperty<Point> vertices =
get_vertex_property<Point>("v:point");
int n_vertices = vertices.vector().size();
if (vertices) {
glBindBuffer(GL_ARRAY_BUFFER, _vbo[VBO_IDX_POSITION]);
glBufferData(GL_ARRAY_BUFFER, sizeof(Point) * n_vertices,
vertices.vector()[0].data(), GL_STATIC_DRAW);
}
VertexProperty<Normal> vnormals =
get_vertex_property<Normal>("v:normal");
if (vnormals) {
glBindBuffer(GL_ARRAY_BUFFER, _vbo[VBO_IDX_NORMAL]);
glBufferData(GL_ARRAY_BUFFER, sizeof(Normal) * n_vertices,
vnormals.vector()[0].data(), GL_STATIC_DRAW);
}
VertexProperty<TexCoord> texcoords =
get_vertex_property<TexCoord>("v:texcoord");
if (texcoords) {
glBindBuffer(GL_ARRAY_BUFFER, _vbo[VBO_IDX_TEXCOORD]);
glBufferData(GL_ARRAY_BUFFER, sizeof(TexCoord) * n_vertices,
texcoords.vector()[0].data(), GL_STATIC_DRAW);
}
VertexProperty<Color> colors =
get_vertex_property<Color>("v:color");
if (colors) {
glBindBuffer(GL_ARRAY_BUFFER, _vbo[VBO_IDX_COLOR]);
glBufferData(GL_ARRAY_BUFFER, sizeof(Color) * n_vertices,
colors.vector()[0].data(), GL_STATIC_DRAW);
}
VertexProperty<int> masks = get_vertex_property<int>("v:mask");
if (masks) {
glBindBuffer(GL_ARRAY_BUFFER, _vbo[VBO_IDX_MASK]);
glBufferData(GL_ARRAY_BUFFER, sizeof(int) * n_vertices,
masks.vector().data(), GL_STATIC_DRAW);
}
VertexProperty<Vector3f> disp =
get_vertex_property<Vector3f>("v:disp");
if (disp) {
glBindBuffer(GL_ARRAY_BUFFER, _vbo[VBO_IDX_DISP]);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vector3f) * n_vertices,
disp.vector()[0].data(), GL_STATIC_DRAW);
}
glBindVertexArray(0);
}
void Mesh::updateBoundingBox() {
_bbox.setNull();
VertexProperty<Point> vertices =
get_vertex_property<Point>("v:point");
for (const auto &p : vertices.vector())
_bbox.extend(static_cast<Vector3f>(p));
}
void Mesh::updateBVH() {
if (_bvh)
delete _bvh;
_bvh = new BVH;
_bvh->build(this, 10, 100);
}
void Mesh::draw(const Shader &shader) {
if (!_ready)
init();
glBindVertexArray(_vao);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vbo[VBO_IDX_FACE]);
int vertex_loc = shader.getAttribLocation("vtx_position");
auto vertices = get_vertex_property<Point>("v:point");
if (vertex_loc >= 0 && vertices) {
glBindBuffer(GL_ARRAY_BUFFER, _vbo[VBO_IDX_POSITION]);
glVertexAttribPointer(vertex_loc, 3, GL_FLOAT, GL_FALSE, 0, (void *)0);
glEnableVertexAttribArray(vertex_loc);
}
int color_loc = shader.getAttribLocation("vtx_color");
auto colors = get_vertex_property<Color>("v:color");
if (color_loc >= 0 && colors) {
glBindBuffer(GL_ARRAY_BUFFER, _vbo[VBO_IDX_COLOR]);
glVertexAttribPointer(color_loc, 3, GL_FLOAT, GL_FALSE, 0, (void *)0);
glEnableVertexAttribArray(color_loc);
}
int normal_loc = shader.getAttribLocation("vtx_normal");
auto vnormals = get_vertex_property<Normal>("v:normal");
if (normal_loc >= 0 && vnormals) {
glBindBuffer(GL_ARRAY_BUFFER, _vbo[VBO_IDX_NORMAL]);
glVertexAttribPointer(normal_loc, 3, GL_FLOAT, GL_FALSE, 0, (void *)0);
glEnableVertexAttribArray(normal_loc);
}
int texCoord_loc = shader.getAttribLocation("vtx_texcoord");
auto texcoords = get_vertex_property<TexCoord>("v:texcoord");
if (texCoord_loc >= 0 && texcoords) {
glBindBuffer(GL_ARRAY_BUFFER, _vbo[VBO_IDX_TEXCOORD]);
glVertexAttribPointer(texCoord_loc, 2, GL_FLOAT, GL_FALSE, 0, (void *)0);
glEnableVertexAttribArray(texCoord_loc);
}
int mask_loc = shader.getAttribLocation("vtx_mask");
auto masks = get_vertex_property<int>("v:mask");
if (mask_loc >= 0 && masks) {
glBindBuffer(GL_ARRAY_BUFFER, _vbo[VBO_IDX_MASK]);
glVertexAttribPointer(mask_loc, 1, GL_INT, GL_FALSE, 0, (void *)0);
glEnableVertexAttribArray(mask_loc);
}
int disp_loc = shader.getAttribLocation("vtx_disp");
auto vdisps = get_vertex_property<Vector3f>("v:disp");
if (disp_loc >= 0 && vdisps) {
glBindBuffer(GL_ARRAY_BUFFER, _vbo[VBO_IDX_DISP]);
glVertexAttribPointer(disp_loc, 3, GL_FLOAT, GL_FALSE, 0, (void *)0);
glEnableVertexAttribArray(disp_loc);
}
glDrawElements(GL_TRIANGLES, _indices.size(), GL_UNSIGNED_INT, 0);
if (vertex_loc >= 0)
glDisableVertexAttribArray(vertex_loc);
if (color_loc >= 0)
glDisableVertexAttribArray(color_loc);
if (normal_loc >= 0)
glDisableVertexAttribArray(normal_loc);
if (texCoord_loc >= 0)
glDisableVertexAttribArray(texCoord_loc);
if (mask_loc >= 0)
glDisableVertexAttribArray(mask_loc);
if (disp_loc >= 0)
glDisableVertexAttribArray(disp_loc);
glBindVertexArray(0);
}
bool Mesh::intersectFace(const Ray &ray, Hit &hit, int faceId) const {
auto vertices = get_vertex_property<Point>("v:point").vector();
Vector3f v0 = static_cast<Vector3f>(vertices[_indices[faceId * 3 + 0]]);
Vector3f v1 = static_cast<Vector3f>(vertices[_indices[faceId * 3 + 1]]);
Vector3f v2 = static_cast<Vector3f>(vertices[_indices[faceId * 3 + 2]]);
Vector3f e1 = v1 - v0;
Vector3f e2 = v2 - v0;
Eigen::Matrix3f M;
M << -ray.direction, e1, e2;
Vector3f tuv = M.inverse() * (ray.origin - v0);
float t = tuv(0), u = tuv(1), v = tuv(2);
if (t > 0 && u >= 0 && v >= 0 && (u + v) <= 1 && t < hit.t()) {
hit.setT(t);
hit.setFaceId(faceId);
hit.setBaryCoords(Vector3f(1. - u - v, u, v));
return true;
}
return false;
}
bool Mesh::intersect(const Ray &ray, Hit &hit) const {
if (_bvh) {
// use the BVH !!
return _bvh->intersect(ray, hit);
} else {
// brute force !!
bool ret = false;
float tMin, tMax;
Vector3f normal;
if ((!::intersect(ray, _bbox, tMin, tMax, normal)) || tMin > hit.t())
return false;
for (uint i = 0; i < n_faces(); ++i) {
ret = ret | intersectFace(ray, hit, i);
}
return ret;
}
}
| true |
9b64bd98493164e8d43d115c76e9b58c934b781c | C++ | Ali-Omrani/Advanced-Programming | /Assignment5/pair.h | UTF-8 | 286 | 2.6875 | 3 | [] | no_license | #ifndef _PAIR_
#define _PAIR_
#include <iostream>
class Pair
{
public:
Pair(const double _x,const double _y);
double get_x() const;
double get_y() const;
void set_y (const double _y);
double& get_y_refrence();
void print_pair() const;
private:
double x;
double y;
};
#endif | true |
07ee42dfe135b5ccedc001366dd82327391e4c9b | C++ | Mohamed-Eid/ProblemSolving--Arabic | /Material/3.cpp | UTF-8 | 709 | 2.875 | 3 | [] | no_license |
///3- Preprocessing: Prefix(cumulative) sum.
A = 2 5 5 3 5 2
Query: O(N)
- What is the sum of elements in A[0:4]
- What is the sum of elements in A[2:5]
- How many times did 5 appear in A[1:3]
0 1 2 3 4 5
A = 2 5 5 3 5 2
prefix_sum = 2 7 12 15 20 22
sum A[0:4] = prefix_sum[4]
sum A[2:5] = prefix_sum[5] - prefix_sum[1]
0 1 2 3 4 5
A = 2 5 5 3 5 2
prefix_fives = 0 1 2 2 3 3
if(A[i] == 5) prefix[i] = prefix[i-1]+1;
else prefix[i] = prefix[i-1];
fives[1:3] = prefix_fives[3] - prefix_fives[0]
///The equilibrium problem:
2 4 6 3 5 6 2
| true |
84f11b57732cb538ef85b36ec9b4bb7a7f041e96 | C++ | gonglixue/RangeScanLine | /RangeScanOO/ActiveEdge.cpp | UTF-8 | 5,498 | 2.546875 | 3 | [] | no_license | #include "ActiveEdge.h"
ActiveEdge::ActiveEdge(Edge* e1, Edge* e2)
{
// 初始时与两条边交于一点,e1与e2应有共同的上端点 NOOOO!
//if (abs(e1->x_ - e2->x_) < 0.0001)
//{
// printf("ActiveEdge::ActiveEdge: two edges should have the same up end point.\n");
// exit(1);
//}
// 如果两边有相同的上端点,扫描线每向下处理一个单位,e1x的增量小于d2x,e1为左,增量小的为左
if (fabs(e1->x_ - e2->x_) < 0.00001 && fabs(e1->y_up - e2->y_up)<0.00001)
{
if (e1->dx_ < e2->dx_)
{
xl_ = e1->x_;
dxl_ = e1->dx_;
dyl_ = e1->dy_;
xr_ = e2->x_;
dxr_ = e2->dx_;
dyr_ = e2->dy_;
edge_l_ = e1;
edge_r_ = e2;
}
else {
xl_ = e2->x_;
dxl_ = e2->dx_;
dyl_ = e2->dy_;
xr_ = e1->x_;
dxr_ = e1->dx_;
dyr_ = e1->dy_;
edge_l_ = e2;
edge_r_ = e1;
}
}
else {
// 没有相同的上端点,则x_小的为左
if (e1->x_ < e2->x_)
{
xl_ = e1->x_;
dxl_ = e1->dx_;
dyl_ = e1->dy_;
xr_ = e2->x_;
dxr_ = e2->dx_;
dyr_ = e2->dy_;
edge_l_ = e1;
edge_r_ = e2;
}
else {
xl_ = e2->x_;
dxl_ = e2->dx_;
dyl_ = e2->dy_;
xr_ = e1->x_;
dxr_ = e1->dx_;
dyr_ = e1->dy_;
edge_l_ = e2;
edge_r_ = e1;
}
}
zl_ = edge_l_->z_up_;
if (fabs(e1->in_poly_->c_) < 0.00001)
dzx_ = 0; // 沿x方向不改变z?
else
dzx_ = -1.0 * e1->in_poly_->a_ / e1->in_poly_->c_;
if (fabs(e1->in_poly_->c_) < 0.00001)
dzx_ = 0;
else
dzy_ = -1.0 * e1->in_poly_->b_ / e1->in_poly_->c_;
poly_id_ = e1->in_poly_->id_;
next_ = NULL;
}
ActiveEdge::ActiveEdge(Edge* e1, Edge* e2, int scan_y)
{
// 初始时与两条边交于一点,e1与e2应有共同的上端点 NOOOO!
//if (abs(e1->x_ - e2->x_) < 0.0001)
//{
// printf("ActiveEdge::ActiveEdge: two edges should have the same up end point.\n");
// exit(1);
//}
// 如果两边有相同的上短线, 扫描线每向下处理一个单位,e1x的增量小于d2x,e1为左
//if (fabs(e1->x_ - e2->x_) < 0.00001 && fabs(e1->y_up - e2->y_up))
//{
// if (e1->dx_ < e2->dx_)
// {
// xl_ = e1->x_ + (scan_y - e1->y_up) * e1->dx_;
// dxl_ = e1->dx_;
// dyl_ = e1->dy_ - (scan_y - e1->y_up);
// xr_ = e2->x_ + (scan_y - e2->y_up)*e2->dx_;
// dxr_ = e2->dx_;
// dyr_ = e2->dy_ - (scan_y - e2->y_up);
// edge_l_ = e1;
// edge_r_ = e2;
// }
// else {
// xl_ = e2->x_ + (scan_y - e2->y_up) * e2->dx_;
// dxl_ = e2->dx_;
// dyl_ = e2->dy_ - (scan_y - e2->y_up);
// xr_ = e1->x_ + (scan_y - e1->y_up)*e1->dx_;
// dxr_ = e1->dx_;
// dyr_ = e1->dy_ - (scan_y - e1->y_up);
// edge_l_ = e2;
// edge_r_ = e1;
// }
//}
//else {
// 没有相同的上端点,则【当前x_】小的为左
float cur_x_e1, cur_x_e2;
cur_x_e1 = e1->x_ + (scan_y - int(e1->y_up+0.5))*1.0 * e1->dx_;
cur_x_e2 = e2->x_ + (scan_y - int(e2->y_up+0.5))*1.0 * e2->dx_;
if (cur_x_e1 < cur_x_e2) // e1为左
{
xl_ = cur_x_e1;
dxl_ = e1->dx_;
dyl_ = e1->dy_ - (scan_y - int(e1->y_up+0.5));
xr_ = cur_x_e2;
dxr_ = e2->dx_;
dyr_ = e2->dy_ - (scan_y - int(e2->y_up+0.5));
edge_l_ = e1;
edge_r_ = e2;
}
else {
xl_ = cur_x_e2;
dxl_ = e2->dx_;
dyl_ = e2->dy_ - (scan_y - int(e2->y_up+0.5));
xr_ = cur_x_e1;
dxr_ = e1->dx_;
dyr_ = e1->dy_ - (scan_y - int(e1->y_up+0.5));
edge_l_ = e2;
edge_r_ = e1;
}
//}
if (dxl_ > 0 && xl_ > edge_l_->x_down_)
xl_ = edge_l_->x_down_;
else if (dxl_ < 0 && xl_ < edge_l_->x_down_)
xl_ = edge_l_->x_down_;
if (dxr_ > 0 && xr_ > edge_r_->x_down_)
xr_ = edge_r_->x_down_;
else if (dxr_ < 0 && xr_ < edge_r_->x_down_)
xr_ = edge_r_->x_down_;
//zl_ = e1->z_up_;
if (fabs(e1->in_poly_->c_) < 0.00001)
dzx_ = 0; // 沿x方向不改变z?
else
dzx_ = -1.0 * e1->in_poly_->a_ / e1->in_poly_->c_;
if (fabs(e1->in_poly_->c_) < 0.00001)
dzx_ = 0;
else
dzy_ = -1.0 * e1->in_poly_->b_ / e1->in_poly_->c_;
//zl_ = e1->z_up_ + dzx_ * (xl_ - edge_l_->x_) + dzy_;
zl_ = edge_l_->z_up_ + dzx_ * (xl_ - edge_l_->x_) + dzy_ * (scan_y - int(edge_l_->y_up+0.5)); //?
poly_id_ = e1->in_poly_->id_;
next_ = NULL;
}
ActiveEdge::ActiveEdge(ActiveEdge* update_from_ae)
{
dxl_ = update_from_ae->dxl_;
xl_ = update_from_ae->xl_ + dxl_;
dyl_ = update_from_ae->dyl_ - 1;
dxr_ = update_from_ae->dxr_;
xr_ = update_from_ae->xr_ + dxr_;
dyr_ = update_from_ae->dyr_ - 1;
// 需要考虑当斜率接近于0,dx超级大的情况??
if (dxl_ > 0 && xl_ > update_from_ae->edge_l_->x_down_)
xl_ = update_from_ae->edge_l_->x_down_;
else if (dxl_ < 0 && xl_ < update_from_ae->edge_l_->x_down_)
xl_ = update_from_ae->edge_l_->x_down_;
if (dxr_ > 0 && xr_ > update_from_ae->edge_r_->x_down_)
xr_ = update_from_ae->edge_r_->x_down_;
else if (dxr_ < 0 && xr_ < update_from_ae->edge_r_->x_down_)
xr_ = update_from_ae->edge_r_->x_down_;
//zl_ = zl_ + dzx_ * dxl_ + dzy_;
zl_ = update_from_ae->zl_ + update_from_ae->dzx_ * update_from_ae->dxl_ + update_from_ae->dzy_;
dzx_ = update_from_ae->dzx_;
dzy_ = update_from_ae->dzy_;
poly_id_ = update_from_ae->poly_id_;
edge_l_ = update_from_ae->edge_l_;
edge_r_ = update_from_ae->edge_r_;
next_ = NULL;
}
void ActiveEdge::CopyFrom(ActiveEdge* next)
{
xl_ = next->xl_;
dxl_ = next->dxl_;
dyl_ = next->dyl_;
xr_ = next->xr_;
dxr_ = next->dxr_;
dyr_ = next->dyr_;
zl_ = next->zl_;
dzx_ = next->dzx_;
dzy_ = next->dzy_;
poly_id_ = next->poly_id_;
edge_l_ = next->edge_l_; //?
edge_r_ = next->edge_r_;
} | true |
7592a20f5561f78435c3b694af18670bee2de3eb | C++ | dheerajkhatri/bajinga | /interviewbit/makeTree.cpp | UTF-8 | 1,045 | 3.265625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* getNode(int val){
TreeNode *newnode = new TreeNode(val);
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}
void inorder(TreeNode* root){
if(root){
if(root->left)inorder(root->left);
cout<<root->val<<endl;
if(root->right)inorder(root->right);
}
}
int main(int argc,char*argv[]){
int len = atoi(argv[1]),pos=0,num1,num2;
vector<TreeNode*>makeTree;
TreeNode *head;
TreeNode *node1 = getNode(atoi(argv[2]));
makeTree.push_back(node1);
head = node1;
for(int i=1;i<len;++i,++pos){
num1 = atoi(argv[i+2]);
i++;
num2 = atoi(argv[i+2]);
if(num1!=-1){
TreeNode *newnode = getNode(num1);
makeTree[pos]->left = newnode;
makeTree.push_back(newnode);
}
if(num2!=-1){
TreeNode *newnode = getNode(num2);
makeTree[pos]->right = newnode;
makeTree.push_back(newnode);
}
}
inorder(head);
//cout<<endl;
} | true |
8eb68e8f410a5014ba07c8a614cf35182ef5d494 | C++ | adinosaur/minihttpd | /include/Base/Logger.cc | UTF-8 | 1,809 | 2.984375 | 3 | [] | no_license | #include "Logger.h"
#include <assert.h>
#include <pthread.h>
#include <string>
using namespace std;
// 日志分隔符
char Logger::seperator = '|';
// 日志记录级别
int Logger::_curruct_level = TRACE;
// 日志输出文件
ostream& Logger::_output(cerr);
// instance数组
vector<Logger*> Logger::_instances(LEVEL_SIZE, nullptr);
// 阻塞队列
BlockingQueue<string> Logger::_queue;
// 映射表
vector<string> Logger::_strLevelMap = {"TRACE", "DEBUG", "INFO", "WARN", "ERROR"};
Logger* Logger::instance(int level)
{
assert(level >= 0 && level < LEVEL_SIZE);
if (_instances[level] == nullptr)
_instances[level] = new Logger(level);
return _instances[level];
}
void Logger::destroy()
{
for (auto p : _instances)
delete p;
}
const string& Logger::strLevel()
{
return _strLevelMap[_level];
}
void Logger::thread_func()
{
while(1)
{
const string& msg = _queue.front();
_output << msg << endl;
_queue.pop_front();
}
}
void Logger::append(const string& log)
{
_queue.push_back(log);
}
void Logger::logging(const string& file, int line, const string& content)
{
if (_level >= _curruct_level)
{
std::string msg;
msg.append(Helper::date());
msg.push_back(seperator);
msg.append(Helper::time());
msg.push_back(seperator);
msg.append(std::to_string(pthread_self()));
msg.push_back(seperator);
msg.append(strLevel());
msg.push_back(seperator);
msg.append(content);
msg.push_back(seperator);
msg.append(file);
msg.push_back(':');
msg.append(std::to_string(line));
msg.push_back(seperator);
// 插入阻塞队列
_queue.push_back(msg);
}
}
| true |
ad63b832f5768c9aa6888d0cb9d00c5fc931a0ad | C++ | antoniospoletojr/Image-Processing | /Isodata/main.cpp | UTF-8 | 6,658 | 3.015625 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <vector>
#include <numeric>
#include <math.h>
#include <opencv2/opencv.hpp>
#include <stdlib.h>
#include <time.h>
using namespace cv;
using namespace std;
#define K 3 //numero di cluster iniziali
#define VAR_THRESHOLD 1000 //se aumenta, diminiuisce il numero di clusters prodotti (ammettiamo clusters più eterogenei)
#define SIZE_THRESHOLD 5 //se aumenta, ammettiamo che un numero maggiore di clusters si fondano
#define SUB_CLUSTERS 3 //nella fase di splitting dividiamo il cluster in SUB_CLUSTERS
class Pixel
{
public:
Point coords;
Vec3b color;
Pixel(){}
Pixel(Point p, Vec3b color)
{
this->coords = p;
this->color = color;
}
};
class Cluster
{
public:
Vec3b mean;
vector<Pixel> pixels;
Cluster(Pixel pixel)
{
this->mean = pixel.color;
}
inline void addPixel(Pixel pixel)
{
pixels.push_back(pixel);
}
void calculateMean()
{
Vec3f mean;
for(auto pixel: pixels)
{
mean[0]+=pixel.color[0];
mean[1]+=pixel.color[1];
mean[2]+=pixel.color[2];
}
mean[0] = mean[0]/(pixels.size());
mean[1] = mean[1]/(pixels.size());
mean[2] = mean[2]/(pixels.size());
this->mean = mean;
}
float getVar()
{
Vec3f variance;
for(int i=0; i<pixels.size();i++)
{
variance[0] += pow(pixels.at(i).color[0] - this->mean[0], 2);
variance[1] += pow(pixels.at(i).color[1] - this->mean[1], 2);
variance[2] += pow(pixels.at(i).color[2] - this->mean[2], 2);
}
variance[0] = variance[0]/pixels.size();
variance[1] = variance[1]/pixels.size();
variance[2] = variance[2]/pixels.size();
return (variance[0]+variance[1]+variance[2])/3;
}
inline int getSize()
{
return this->pixels.size();
}
inline void color(Mat& image)
{
for(auto pixel : this->pixels)
{
Point& coords = pixel.coords;
image.at<Vec3b>(coords) = this->mean;
}
}
inline static float euclideanDistance(Vec3b p1, Vec3b p2)
{
return norm(p1,p2);
}
};
Mat image;
vector<Pixel> pixels;
vector<Cluster> clusters;
void populateClusters(vector<Cluster>& inoutClusters, const vector<Pixel> dataset)
{
float distance, minDistance;
int index;
for(int k=0; k<inoutClusters.size();k++)
{
inoutClusters.at(k).pixels.clear();
}
for(int i=0; i<dataset.size(); i++)
{
minDistance = FLT_MAX;
for(int j=0; j<inoutClusters.size(); j++)
{
distance = Cluster::euclideanDistance(inoutClusters.at(j).mean, dataset.at(i).color);
if(distance<minDistance)
{
minDistance = distance;
index = j;
}
}
inoutClusters.at(index).addPixel(dataset.at(i));
}
for(int k=0; k<inoutClusters.size(); k++)
inoutClusters.at(k).calculateMean();
}
void init()
{
int N = image.rows;
int M = image.cols;
for(int i=0; i<N; i++)
for(int j=0; j<M; j++)
pixels.push_back(Pixel(Point(j,i), image.at<Vec3b>(i,j)));
for(int k=0; k<K; k++)
clusters.push_back(Cluster(pixels.at((k*(N-1)*(M-1))/K)));
populateClusters(clusters,pixels);
}
void splitCluster(vector<int>& indexes)
{
vector<Pixel> dataset;
vector<Cluster> splittedClusters;
sort(indexes.begin(),indexes.end(),[](int l, int r){return l>r;});
//per ogni cluster da splittare
for(int i=0; i<indexes.size(); i++)
{
//prendi indice del cluster da eliminare
int clusterIndex = indexes.at(i);
//ricopia tutti i pixel del cluster
dataset = clusters.at(clusterIndex).pixels;
//dataset.insert(dataset.end(), tempPixels.begin(), tempPixels.end());
//cancella il cluster perchè verrà splittato in 3 clusters
clusters.erase(clusters.begin()+clusterIndex);
//crea 3 nuovi clusters
for(int j=0; j<3; j++)
{
//setta i centroidi in maniera omogenea
Pixel& centroid = dataset.at(j*dataset.size()/3);
//pusha i centroidi in nuovi clusters
splittedClusters.push_back(centroid);
}
populateClusters(splittedClusters,dataset);
//aggiungiamo i nuovi clusters splittati al vettore di clusters
clusters.insert(clusters.end(), splittedClusters.begin(), splittedClusters.end());
splittedClusters.clear();
}
indexes.clear();
}
void merge(vector<int>& indexes)
{
//se i clusters sono dispari, effettua il merge fino al cluster n-1 (cioè mergia a 2 a 2, e lascia l'ultimo penzolante);
int n = indexes.size();
if(n%2!=0)
n--;
//ordiniamo in senso decrescente per evitare cancellazioni fuori range sul vettore clusters
sort(indexes.begin(),indexes.end(),[](int l, int r){return l>r;});
for(int i=0; i<n; i+=2)
{
vector<Pixel>& curr = clusters.at(indexes.at(i)).pixels;
vector<Pixel>& next = clusters.at(indexes.at(i+1)).pixels;
next.insert(next.end(),curr.begin(),curr.end());
clusters.erase(clusters.begin()+indexes.at(i));
}
indexes.clear();
}
void isodata()
{
init();
bool converge;
vector<int> indexes;
do
{
converge = false;
for(int k=0; k<clusters.size(); k++)
{
if(clusters.at(k).getVar()>VAR_THRESHOLD)
{
converge = true;
//memorizza gli indici di cluster da splittare (varianza troppo grande)
indexes.push_back(k);
}
}
splitCluster(indexes);
for(int k=0; k<clusters.size(); k++)
{
if(clusters.at(k).getSize()<SIZE_THRESHOLD)
{
converge = true;
indexes.push_back(k);
}
}
merge(indexes);
for(int k=0; k<clusters.size(); k++)
{
clusters.at(k).calculateMean();
}
}while(converge);
cout << "Numero di clusters: " << clusters.size();
for(auto c: clusters)
{
c.color(image);
}
imshow("isodata",image);
imwrite("isodata.jpg",image);
}
int main(int argc, char** argv )
{
const char* fileName = "recinto.jpg";
image = imread(fileName, IMREAD_COLOR);//immagine presa in input
if (!image.data)
{
printf("No image data \n");
return -1;
}
isodata();
waitKey(0);
return 0;
}
| true |
40475c2ccb019072a50cd4d5ca4964e1ce37b359 | C++ | jrsala/Peano | /NegativeNumber.hpp | UTF-8 | 1,042 | 2.9375 | 3 | [] | no_license | #ifndef NEGATIVENUMBER_H
#define NEGATIVENUMBER_H
#include "Add.hpp"
#include "Mul.hpp"
/**
* Minus
*/
template<typename A>
struct Minus_
{
static constexpr int value = -A::value;
typedef Minus_<A> result;
};
template<>
struct Minus_<Zero>
{
typedef Zero result;
};
template<typename A>
struct Minus_<Minus_<A> >
{
typedef A result;
};
template<typename A>
using Minus = typename Minus_<A>::result;
/**
* Addition with negative integers
*/
template<typename A, typename B>
struct Add_<Minus_<A>, Minus_<B> >
{
typedef Minus<Add<A, B> > result;
};
template<typename A, typename B>
struct Add_<Minus_<A>, B>
{
typedef Add<B, Minus<A> > result;
};
/**
* Multiplication with negative integers
*/
template<typename A, typename B>
struct Mul_<Minus_<A>, Minus_<B> >
{
typedef Mul<A, B> result;
};
template<typename A, typename B>
struct Mul_<Minus_<A>, B>
{
typedef Minus<Mul<A, B> > result;
};
#endif // NEGATIVENUMBER_H
| true |
2450a4a900a40cf54c08c72e3ee1011b36e3ab39 | C++ | xvallspl/Examples-Books-and-Exercises | /Books/CrackingtCI/Ch8-Recursion/02.numberPaths.cpp | UTF-8 | 1,203 | 3.53125 | 4 | [] | no_license | /*Imagine a robot sitting on the upper left hand corner of an NxN grid.
The robot can only move in two directions: right and down How many possible
paths are there for the robot?
FOLLOW UP
Imagine certain squares are “off limits”, such that the robot can not step on
them Design an algorithm to get all possible paths for the robot*/
#include <iostream>
#include <list>
using namespace std;
//Objective not clear. If it is to get on the other corner...
int numberPaths(int dimH, int dimV){
if(dimV==0 && dimH==0){
return 1;
}
int lR=(dimH!=0)? numberPaths(dimH-1, dimV): 0;
int lD=(dimV!=0)? numberPaths(dimH, dimV-1): 0;
return( lR+ lD);
}
//follow up..
typedef struct bannedCell
{
int h;
int v;
} bannedCell;
list<bannedCell> bannedList;
bool banned(int dimH, int dimV){
for (list<bannedCell>::iterator it = bannedList.begin(); it != bannedList.end(); it++){
if(it->h==dimH && it->v==dimV)
return true;
}
return false;
}
int numberPathsWithBanned(int dimH, int dimV){
if(banned(dimH, dimV)){
return 0;
}
if(dimV==0 && dimH==0){
return 1;
}
int lR=(dimH!=0)? numberPaths(dimH-1, dimV): 0;
int lD=(dimV!=0)? numberPaths(dimH, dimV-1): 0;
return( lR+ lD);
}
| true |
4f5fbad5636d9edaad2e0b837715786ec262cd72 | C++ | fulviocrivellaro/cpp-2048-ai | /2048.Core/MilGrid.cpp | UTF-8 | 3,476 | 3.03125 | 3 | [] | no_license | #include "MilGrid.h"
#include "TileLineIterator.h"
#include <time.h>
#include <cstdlib>
#include <math.h>
namespace MilCore
{
MilGrid::MilGrid()
{
srand((unsigned int)time(NULL));
resetGrid();
}
void MilGrid::resetGrid()
{
for (tilePtr r = 0; r < SIZE; ++r)
{
for (tilePtr c = 0; c < SIZE; ++c)
{
mGrid[c][r] = 0;
}
}
}
void MilGrid::addRandomTile()
{
TILE* tiles[SIZE*SIZE];
unsigned int count = 0;
for (tilePtr r = 0; r < SIZE; ++r)
{
for (tilePtr c = 0; c < SIZE; ++c)
{
if (mGrid[c][r] == 0)
{
tiles[count++] = &mGrid[c][r];
}
}
}
if (count)
{
int pos = rand() % count;
int val = rand() % 10;
*tiles[pos] = val > 8 ? 2 : 1;
}
}
bool MilGrid::canMove(Direction direction) const
{
for (tilePtr lineIndex=0; lineIndex<SIZE; ++lineIndex)
{
if (canMoveLine(lineIndex, direction))
{
return true;
}
}
return false;
}
unsigned int MilGrid::move(const Direction direction)
{
int points = 0;
for (tilePtr i=0; i<SIZE; ++i)
{
points += moveLine(getLine(i, direction));
}
return points;
}
TileLineIterator MilGrid::getLine(const tilePtr lineIndex, const Direction direction)
{
return TileLineIterator(this, lineIndex, direction);
}
const ConstTileLineIterator MilGrid::getConstLine(const tilePtr lineIndex, const Direction direction) const
{
return ConstTileLineIterator(this, lineIndex, direction);
}
bool MilGrid::isStalled() const
{
if (canMove(Direction::Down)) return false;
if (canMove(Direction::Up)) return false;
if (canMove(Direction::Left)) return false;
if (canMove(Direction::Right)) return false;
return true;
}
bool MilGrid::canMoveLine(const ConstTileLineIterator& line) const
{
for (tilePtr iPos=SIZE-1; iPos>0; --iPos)
{
if (line[iPos] == 0 && !isLineEmpty(line, iPos)
|| line[iPos] != 0 && line[iPos] == line[iPos-1])
{
return true;
}
}
return false;
}
bool MilGrid::canMoveLine(const tilePtr lineIndex, const Direction direction) const
{
return canMoveLine(getConstLine(lineIndex, direction));
}
bool MilGrid::isLineEmpty(const ConstTileLineIterator& line) const
{
return isLineEmpty(line, SIZE);
}
bool MilGrid::isLineEmpty(const ConstTileLineIterator& line, const tilePtr count) const
{
for (tilePtr i=0; i<count; ++i)
{
if (line[i] != 0)
{
return false;
}
}
return true;
}
// move
unsigned int MilGrid::moveLine(TileLineIterator& line)
{
if (isLineEmpty(line))
{
return 0;
}
int points = 0;
squeezeLine(line);
for (tilePtr iPos=SIZE-1; iPos>0; --iPos)
{
if (line[iPos] != 0 && line[iPos] == line[iPos-1])
{
// increment point
++line[iPos];
points += (int)pow(2.0f, line[iPos]);
// shift others
for (tilePtr iShift=iPos-1; iShift>0; --iShift)
{
line[iShift] = line[iShift-1];
}
line[0] = 0;
}
}
return points;
}
// squeeze a line
void MilGrid::squeezeLine(TileLineIterator& line)
{
if (isLineEmpty(line))
{
return;
}
for (tilePtr iPos=SIZE-1; iPos>0; --iPos)
{
while (line[iPos] == 0 && !isLineEmpty(line, iPos))
{
// shift others
for (tilePtr iShift=iPos; iShift>0; --iShift)
{
line[iShift] = line[iShift-1];
}
line[0] = 0;
}
}
}
} | true |
248ac462e3b8e37f4f26c162aca8befbcb87e523 | C++ | Txusheng/OpenCVFrame | /OpenCVFrame/MyAlgorithms.cpp | UTF-8 | 335 | 2.828125 | 3 | [] | no_license | #include "MyAlgorithms.h"
float CalChiSquareDis(vector<float> vA, vector<float> vB)
{
float sum = 0;
if (vA.size() != vB.size())
{
return -1;
}
for (int i = 0; i < vA.size(); i++)
{
if (vA[i] == 0 && vB[i] == 0)
{
continue;
}
else
{
sum += powf(vA[i] - vB[i], 2) / (vA[i] + vB[i]);
}
}
return sum;
}
| true |
72bb9fe88ef621bce06af961f715f67840df2d78 | C++ | eala/leetcode | /test/test/testSolution.cpp | UTF-8 | 2,060 | 2.6875 | 3 | [] | no_license | #include <vector>
#include "solution.h"
#include "testSolution.h"
#include "LeetcodeConfig.h"
//using ::testing::Return;
using namespace std;
SolTest::SolTest() {
/*
// Have qux return true by default
ON_CALL(m_bar,qux()).WillByDefault(Return(true));
// Have norf return false by default
ON_CALL(m_bar,norf()).WillByDefault(Return(false));
*/
}
SolTest::~SolTest() {};
void SolTest::SetUp() {};
void SolTest::TearDown() {};
TEST_F(SolTest, solReturnTwoSum)
{
int numsArr[4] = { 2, 7, 11, 15 };
vector<int> nums(&numsArr[0], &numsArr[0] + 4);
int goldenArr[2] = { 0, 1};
vector<int> golden(&goldenArr[0], &goldenArr[0] + 2);
int target = 9;
EXPECT_EQ(twoSum(nums,target), golden);
}
// Add_two_sum
TEST_F(SolTest, TwoSumTestIsSampleCorrect) {
int numsArr[4] = { 2, 7, 11, 15 };
vector<int> nums(&numsArr[0], &numsArr[0] + 4);
int goldenArr[2] = { 0, 1};
vector<int> golden(&goldenArr[0], &goldenArr[0] + 2);
int target = 9;
EXPECT_EQ(twoSum(nums,target), golden);
}
// ZigZag_Coversion
TEST_F(SolTest, ZigZag_Conversion_Test_SampleStringCorrect) {
EXPECT_STREQ(convert("sample", 3).c_str(), "slapem");
}
TEST_F(SolTest, ZigZag_Conversion_Test_IsLongPatternCorrect) {
EXPECT_STREQ(convert("bwbyvuwpzbbubozknyxuflsgagtjikxjjyjeufutixpjlqvaotuwemehuxsdkpotpyzjdtcostxdkvfaozwuocdkavn", 78).c_str(), "bwbyvuwpzbbubozknyxuflsgagtjikxjjyjeufutixpjlqvaotuwemehuxsdkpotpnyvzajkddtccoouswtzxodakfv");
}
TEST_F(SolTest, ZigZag_Conversion_Test_TestPAYPALISHIRING) {
EXPECT_STREQ(convert("PAYPALISHIRING", 3).c_str(), "PAHNAPLSIIGYIR");
}
TEST_F(SolTest, ZigZag_Conversion_Test_TestSingleRowAB) {
EXPECT_STREQ(convert("AB", 3).c_str(), "AB");
}
TEST_F(SolTest, ZigZag_Conversion_Test_TestTwoRowABC) {
EXPECT_STREQ(convert("ABC", 2).c_str(), "ACB");
}
TEST_F(SolTest, ZigZag_Conversion_Test_TestABCDEF) {
EXPECT_STREQ(convert("ABCDEF", 5).c_str(), "ABCDFE");
cout << "library version: " << LEETCODE_VERSION_MAJOR << "." << LEETCODE_VERSION_MINOR << endl;
}
| true |
620218036163338d52c6c6c95e08473f080878b0 | C++ | shreyarandive/game-combat-simulation | /PatrolBoat.h | UTF-8 | 448 | 2.515625 | 3 | [] | no_license | //
// PatrolBoat.h
// CombatSimulation
//
// Copyright © 2019 Shreya Randive. All rights reserved.
//
class PatrolBoat : public Ships
{
int health = 100;
static const int damage = 50;
//const int attack_range = 1;
public:
int getHealth() { return health;}
int getDamage() { return damage; }
//int getAttackRange() { return attack_range; }
void reduceHealth(int damage) { health = health - damage; }
};
| true |
0c8a7a2d94ecad6fcb62864f23d1cd4d4ca40246 | C++ | hongwei7/netpro | /epoll.h | UTF-8 | 1,813 | 2.546875 | 3 | [] | no_license | #ifndef __NETPRO__EPOLL__H
#define __NETPRO__EPOLL__H
#include <sys/epoll.h>
#include <assert.h>
#include <string.h>
#include <memory>
#include "dbg.h"
#include "noncopyable.h"
#include "threadPool.h"
#include "tcpconn.h"
const int EPOLL_INIT_SIZE = 5;
const int MAX_CLIENTS = 60000;
class epoll : public noncopyable {
public:
epoll() : epfd(epoll_create(EPOLL_INIT_SIZE)){
assert(epfd > 0);
};
int getepfd() const { return epfd; }
virtual ~epoll() {
close(epfd);
}
public:
struct epoll_event eventsList[MAX_CLIENTS];
private:
int epfd;
};
template<typename T>
class event {
public:
event(epoll* ep, int cli, T* wk, bool sock)
: epollTree(ep), cliFd(cli), tcpPtr(wk){
memset(&event_impl, 0, sizeof(event_impl));
if(sock) event_impl.events = EPOLLIN;
else event_impl.events = EPOLLIN | EPOLLET;
event_impl.data.fd = cli;
int ret = epoll_ctl(epollTree->getepfd(), EPOLL_CTL_ADD, cliFd, &event_impl);
if (ret == -1) {
perror("create event");
exit(-1);
}
assert(ret == 0);
}
void addWrite(){
dbg("MOD EVENT");
event_impl.events |= EPOLLOUT;
assert(epoll_ctl(epollTree->getepfd(), EPOLL_CTL_MOD, cliFd, &event_impl) == 0);
}
const int getfd() const { return cliFd; }
const int getEvent() const { return event_impl.events; }
void destroy() {
int ret = epoll_ctl(epollTree->getepfd(), EPOLL_CTL_DEL, cliFd, nullptr);
if (ret == -1) {
perror("delete epoll_event");
}
assert(ret == 0);
}
~event(){
dbg("EVENT DECRACE");
delete tcpPtr;
}
public:
T* tcpPtr;
private:
struct epoll_event event_impl;
epoll* epollTree;
int cliFd;
};
#endif
| true |
d3e15a4d642e9382301c08b83e5fd72a797481ee | C++ | trmrsh/cpp-ultracam | /src/plot.cc | UTF-8 | 30,674 | 2.75 | 3 | [] | no_license | /*
!!begin
!!title Plots an ultracam file
!!author T.R. Marsh
!!created 20 April 2001
!!revised 06 July 2007
!!root plot
!!index plot
!!descr plots an Ultracam data frame
!!css style.css
!!class Programs
!!class Display
!!head1 plot - displays an ultracam image
!!emph{plot} provides some basic display capability to look at Ultracam frames. If you
want something better, it would be best to convert to FITS and use 'gaia' or 'ds9'.
See also !!ref{cplot.html}{cplot} for a version of 'plot' which allows interaction with
a cursor.
!!head2 Invocation
plot data [device] nccd ([stack]) xleft xright ylow yhigh iset (ilow ihigh)/(plow phigh) [width aspect reverse cheight font lwidth]
applot (aperture) [fwhm hwidth readout gain symm beta sigrej onedsrch (fwhm1d hwidth1d) fdevice]!!break
!!head2 Command line arguments
!!table
!!arg{data}{Ultracam data file or a list of Ultracam files. If the program fails to open
it as an ultracam file, it will assume that it is a list.}
!!arg{device}{Display device}
!!arg{nccd}{The particular CCD to display, 0 for the whole lot}
!!arg{stack}{Stacking direcion when plotting more than on CCD. Either in 'X' or 'Y'}
!!arg{xleft xright}{X range to plot}
!!arg{ylow yhigh}{Y range to plot}
!!arg{iset}{'A', 'D' or 'P' according to whether you want to set the intensity limits
automatically (= min to max), directly or with percentiles.}
!!arg{ilow ihigh}{If iset='d', ilow and ihigh specify the intensity range to plot}
!!arg{plow phigh}{If iset='p', plow and phigh are percentiles to set the intensity range,
e.g. 10, 99}
!!arg{width}{Width of plot in inches. 0 for the default width.}
!!arg{aspect}{aspectd ratio (y/x) of the plot panel}
!!arg{reverse}{true/false to reverse the measuring of black and white.}
!!arg{cheight}{Character height, as a multiple of the default}
!!arg{font}{Character font, 1-4 PGPLOT fonts}
!!arg{lwidth}{Line width, integer multiple of default}
!!arg{applot}{true to plot an aperture file.}
!!arg{aperture}{If applot, this is the aperture file to plot.}
!!end
!!begin
!!title Plots an ultracam file and puts up a cursor
!!author T.R. Marsh
!!created 06 January 2005
!!revised 09 March 2006
!!root cplot
!!index cplot
!!descr plots an Ultracam data frame and allows examination with a cursor
!!css style.css
!!class Programs
!!class Display
!!head1 cplot - displays an ultracam image
!!emph{cplot} provides some basic display capability to look and examine at Ultracam frames.
The profile fitting requires the data to be bias-subtracted to work completely correctly.
This command also provides a way of examining statistics of an image.
!!head2 Invocation
cplot data [device] nccd (cursor [stack]) xleft xright ylow yhigh iset (ilow ihigh)/(plow phigh) [width aspect reverse cheight font]
applot (aperture) [fwhm hwidth readout gain symm beta sigrej onedsrch (fwhm1d hwidth1d) fdevice]!!break
!!head2 Command line arguments
!!table
!!arg{data}{Ultracam data file or a list of Ultracam files. If the program fails to open
it as an ultracam file, it will assume that it is a list.}
!!arg{device}{Display device}
!!arg{nccd}{The particular CCD to display, 0 for the whole lot}
!!arg{cursor}{Enable the cursor, but only for single CCD plots}
!!arg{stack}{Stacking direcion when plotting more than on CCD. Either in 'X' or 'Y'}
!!arg{xleft xright}{X range to plot}
!!arg{ylow yhigh}{Y range to plot}
!!arg{iset}{'A', 'D' or 'P' according to whether you want to set the intensity limits
automatically (= min to max), directly or with percentiles.}
!!arg{ilow ihigh}{If iset='d', ilow and ihigh specify the intensity range to plot}
!!arg{plow phigh}{If iset='p', plow and phigh are percentiles to set the intensity range,
e.g. 10, 99}
!!arg{width}{Width of plot in inches. 0 for the default width.}
!!arg{aspect}{aspectd ratio (y/x) of the plot panel}
!!arg{reverse}{true/false to reverse the measuring of black and white.}
!!arg{cheight}{Character height, as a multiple of the default}
!!arg{font}{Character font, 1-4 PGPLOT fonts}
!!arg{lwidth}{Line width, integer multiple of default}
!!arg{applot}{true to plot an aperture file.}
!!arg{aperture}{If applot, this is the aperture file to plot.}
!!arg{fwhm}{This is the first of several parameters associated with profile fits (gaussian
or moffat profiles). fwhm is the initial FWHM to use in either case.}
!!arg{hwidth}{The half-width of the region to be used when fitting a target. Should be larger
than the fwhm, but not so large as to include multiple targets if possible.}
!!arg{readout}{Readout noise, RMS ADU in order for the program to come back with an uncertainty.}
!!arg{gain}{Gain, electrons/ADU, again for uncertainty estimates}
!!arg{symm}{Yes/no for symmetric versus ellliptical profile fits}
!!arg{beta}{The beta parameter of the moffat fits.}
!!arg{sigrej}{The fits can include rejection of poor pixels. This is the threshold, meaured in sigma. Should not
be too small.}
!!arg{onedsrch}{Yes if you want an initial 1D search to be made. This is tolerant of poor positioning of the start point,
but potentially vulnerable to problems with multiple targets. What happens is that a box around the
cursor position is collpased in X and Y and then the peak in each direction is located using cross-correlation
with a gaussian of FWHM=fwhm1D. This new position is then used to define the fitting region and initial position for
the 2D gaussian fit.}
!!arg{fwhm1d}{This is the FWHM used in the 1D search. It does not have to match the FWHM of the target necessarily.
In particular a somewhat larger value is less sensitive to initial position errors.}
!!arg{hwidth1d}{The half-width of the region to be used for searching for a target. The wider
this is, the more chance of finding a target from a sloppy start position, but also the more chance of
peaking up on a spurious target.}
!!arg{rstar}{If you carry out fits, the program also extracts a flux. It scales the aperture radii by the seeing.
'rstar' gives the multiple of the seeing to use for the target.}
!!arg{rsky1}{If you carry out fits, the program also extracts a flux. It scales the aperture radii by the seeing.
'rsky1' gives the multiple of the seeing to use for the inner radius of the sky annulus.}
!!arg{rsky2}{If you carry out fits, the program also extracts a flux. It scales the aperture radii by the seeing.
'rsky2' gives the multiple of the seeing to use for the outer radius of the sky annulus.}
!!arg{fdevice}{Plot device for showing Moffat & symmetrical gaussian fits.
Should be different from the image plot device. e.g. "/xs" or "2/xs" if
image plot device = "1/xs" otherwise the program will go belly up for reasons that
I cannot quite track down. 'null' to ignore.}
!!arg{xbox}{The 'S' show command gives a few simple stats for the region the cursor is
centered on such as the mean and median. This parameter specifies the half-size in X that will be used
in terms of binned pixels. If the nearest pixel is at ix, the a range ix-xbox to ix+xbox will
be used, but truncated at the edge of the window.}
!!arg{xbox}{The 'S' show command gives a few simple stats for the region the cursor is
centered on such as the mean and median. This parameter specifies the half-size in Y that will be used
in terms of binned pixels. If the nearest pixel is at iy, the a range iy-ybox to iy+ybox will
be used, but truncated at the edge of the window.}
!!table
!!head2 Cursor commands
The cursor options are as follows
!!table
!!arg{I}{For 'In'. Zooms in around the current cursor position by a factor of 2}
!!arg{O}{For 'Out'. Zooms out around the current cursor position by a factor of 2}
!!arg{G}{For Gaussian. Performs a 2D gaussian fit. This proceeds
as follows: first, a search is made over a box centred on the cursor position by collapsing in X and Y
and performing a 1D gaussian cross-correlation. Then using this updated position, a 2D gaussian fit is made.
This can either be symmetric or elliptical in shape. Note that the uncertainties reported rely on accurate
readout and gain parameters having been supplied. There is one subtle feature of the gaussian fits: it
fits to a blurred model profile as a way of preventing fits ot cosmic rays. Many other
parameters are hidden command-line parameters that can be set if you specify 'prompt' on the command-line.}
!!arg{M}{For Moffat. Performs a 2D Moffat profile fit, in much the same way as the Gaussian fit, but
only symmetric Moffat profiles are allowed for. Starting parameters are hidden; specify prompt if you
want to alter them.}
!!arg{L}{For Levels. Change the plot levels.}
!!arg{W}{For Whole. Display whole CCD.}
!!arg{S}{Shows value of pixel corresponding to cursor position (no graphics scaling -- it gives you
the true value), along with a few simple stats on the surrounding region specified using the hidden xbox and
ybox parameters. These are the mean, rms, median, minimum and maximum values. The box is truncated at the edges.}
!!arg{Q}{Quit}
!!table
!!end
*/
#include <climits>
#include <cstdlib>
#include <cfloat>
#include <string>
#include <map>
#include <vector>
#include "cpgplot.h"
#include "trm/constants.h"
#include "trm/subs.h"
#include "trm/format.h"
#include "trm/input.h"
#include "trm/plot.h"
#include "trm/frame.h"
#include "trm/aperture.h"
#include "trm/mccd.h"
#include "trm/reduce.h"
#include "trm/ultracam.h"
int main(int argc, char* argv[]){
using Ultracam::Input_Error;
using Ultracam::Ultracam_Error;
try{
// Construct Input object
Subs::Input input(argc, argv, Ultracam::ULTRACAM_ENV, Ultracam::ULTRACAM_DIR);
std::string command = argv[0];
size_t slash = command.find_last_of('/');
if(slash != std::string::npos) command.erase(0,slash+1);
// sign-in input variables
input.sign_in("data", Subs::Input::GLOBAL, Subs::Input::PROMPT);
input.sign_in("device", Subs::Input::LOCAL, Subs::Input::NOPROMPT);
input.sign_in("nccd", Subs::Input::LOCAL, Subs::Input::PROMPT);
if(command == "cplot")
input.sign_in("cursor", Subs::Input::LOCAL, Subs::Input::PROMPT);
input.sign_in("stack", Subs::Input::GLOBAL, Subs::Input::NOPROMPT);
input.sign_in("xleft", Subs::Input::GLOBAL, Subs::Input::PROMPT);
input.sign_in("xright", Subs::Input::GLOBAL, Subs::Input::PROMPT);
input.sign_in("ylow", Subs::Input::GLOBAL, Subs::Input::PROMPT);
input.sign_in("yhigh", Subs::Input::GLOBAL, Subs::Input::PROMPT);
input.sign_in("iset", Subs::Input::GLOBAL, Subs::Input::PROMPT);
input.sign_in("ilow", Subs::Input::GLOBAL, Subs::Input::PROMPT);
input.sign_in("ihigh", Subs::Input::GLOBAL, Subs::Input::PROMPT);
input.sign_in("plow", Subs::Input::GLOBAL, Subs::Input::PROMPT);
input.sign_in("phigh", Subs::Input::GLOBAL, Subs::Input::PROMPT);
input.sign_in("width", Subs::Input::LOCAL, Subs::Input::NOPROMPT);
input.sign_in("aspect", Subs::Input::LOCAL, Subs::Input::NOPROMPT);
input.sign_in("reverse", Subs::Input::LOCAL, Subs::Input::NOPROMPT);
input.sign_in("cheight", Subs::Input::LOCAL, Subs::Input::NOPROMPT);
input.sign_in("font", Subs::Input::LOCAL, Subs::Input::NOPROMPT);
input.sign_in("lwidth", Subs::Input::LOCAL, Subs::Input::NOPROMPT);
input.sign_in("applot", Subs::Input::LOCAL, Subs::Input::PROMPT);
input.sign_in("aperture",Subs::Input::GLOBAL, Subs::Input::PROMPT);
// Interactive settings
if(command == "cplot"){
input.sign_in("fwhm", Subs::Input::GLOBAL, Subs::Input::NOPROMPT);
input.sign_in("hwidth", Subs::Input::GLOBAL, Subs::Input::NOPROMPT);
input.sign_in("readout", Subs::Input::GLOBAL, Subs::Input::NOPROMPT);
input.sign_in("gain", Subs::Input::GLOBAL, Subs::Input::NOPROMPT);
input.sign_in("symm", Subs::Input::GLOBAL, Subs::Input::NOPROMPT);
input.sign_in("beta", Subs::Input::GLOBAL, Subs::Input::NOPROMPT);
input.sign_in("sigrej", Subs::Input::GLOBAL, Subs::Input::NOPROMPT);
input.sign_in("onedsrch",Subs::Input::GLOBAL, Subs::Input::NOPROMPT);
input.sign_in("fwhm1d", Subs::Input::GLOBAL, Subs::Input::NOPROMPT);
input.sign_in("hwidth1d",Subs::Input::GLOBAL, Subs::Input::NOPROMPT);
input.sign_in("rstar", Subs::Input::LOCAL, Subs::Input::NOPROMPT);
input.sign_in("rsky1", Subs::Input::LOCAL, Subs::Input::NOPROMPT);
input.sign_in("rsky2", Subs::Input::LOCAL, Subs::Input::NOPROMPT);
input.sign_in("fdevice", Subs::Input::LOCAL, Subs::Input::NOPROMPT);
input.sign_in("xbox", Subs::Input::LOCAL, Subs::Input::NOPROMPT);
input.sign_in("ybox", Subs::Input::LOCAL, Subs::Input::NOPROMPT);
}
// Get inputs
std::string name;
input.get_value("data", name, "run001", "file or file list to plot");
std::string device;
input.get_value("device", device, "/xs", "plot device");
// Read file or list
std::vector<std::string> flist;
if(Ultracam::Frame::is_ultracam(name)){
flist.push_back(name);
}else{
std::ifstream istr(name.c_str());
while(istr >> name){
flist.push_back(name);
}
istr.close();
if(flist.size() == 0) throw Input_Error("No file names loaded");
}
// Read first file for establishing defaults
Ultracam::Frame frame(flist[0]);
size_t nccd = 1;
if(frame.size() > 1){
if(command == "cplot"){
input.get_value("nccd", nccd, size_t(1), size_t(1), frame.size(), "CCD number to plot");
}else{
input.get_value("nccd", nccd, size_t(0), size_t(0), frame.size(), "CCD number to plot (0 for all)");
}
}
char stackdirn;
if(nccd == 0){
input.get_value("stack", stackdirn, 'X', "xXyY", "stacking direction for image display (X or Y)");
stackdirn = toupper(stackdirn);
}
float x1, x2, y1, y2;
if(nccd){
x2 = frame[nccd-1].nxtot()+0.5;
y2 = frame[nccd-1].nytot()+0.5;
}else{
x2 = frame.nxtot()+0.5;
y2 = frame.nytot()+0.5;
}
input.get_value("xleft", x1, 0.5f, 0.5f, x2, "left X limit of plot");
input.get_value("xright", x2, x2, 0.5f, x2, "right X limit of plot");
input.get_value("ylow", y1, 0.5f, 0.5f, y2, "lower Y limit of plot");
input.get_value("yhigh", y2, 0.5f, 0.5f, y2, "upper Y limit of plot");
char iset;
input.get_value("iset", iset, 'a', "aAdDpP",
"set intensity a(utomatically), d(irectly) or with p(ercentiles)?");
iset = toupper(iset);
float ilow, ihigh, plow, phigh;
if(iset == 'D'){
input.get_value("ilow", ilow, 0.f, -FLT_MAX, FLT_MAX, "lower intensity limit");
input.get_value("ihigh", ihigh, 1000.f, -FLT_MAX, FLT_MAX, "upper intensity limit");
}else if(iset == 'P'){
input.get_value("plow", plow, 1.f, 0.f, 100.f, "lower intensity limit percentile");
input.get_value("phigh", phigh, 99.f, 0.f, 100.f, "upper intensity limit percentile");
plow /= 100.;
phigh /= 100.;
}
float width;
input.get_value("width", width, 0.f, 0.f, 100.f, "width of plot in inches (0 for default)");
float aspect;
if(width == 0.f)
input.get_value("aspect", aspect, 0.6f, 0.f, 100.f, "aspect ratio of plot (0 for default)");
else
input.get_value("aspect", aspect, 0.6f, 1.e-2f, 100.f, "aspect ratio of plot");
bool reverse;
input.get_value("reverse", reverse, false, "do you want to reverse black and white?");
float cheight;
input.get_value("cheight", cheight, 1.f, 0.f, 100.f, "character height (multiple of default)");
int font;
input.get_value("font", font, 1, 1, 4, "character font (1-4)");
int lwidth;
input.get_value("lwidth", lwidth, 1, 1, 40, "line width (multiple of default)");
bool aflag;
input.get_value("applot", aflag, false, "do you want to overplot some apertures?");
std::string aperture;
Ultracam::Maperture apers;
if(aflag){
input.get_value("aperture", aperture, "aperture", "aperture file to plot");
apers = Ultracam::Maperture(aperture);
}
bool allccds = (nccd == 0);
if(nccd) nccd--;
// Profile fits
float fwhm, readout, gain, beta, sigrej, fwhm1d;
float rstar, rsky1, rsky2;
int hwidth, hwidth1d, xbox, ybox;
bool symm, initial_search;
std::string fdevice;
if(command == "cplot"){
input.get_value("fwhm", fwhm, 10.f, 2.f, 1000.f, "initial FWHM for gaussian & moffat profile fits");
input.get_value("hwidth", hwidth, int(fwhm)+1, 2, INT_MAX, "half-width of region for profile fits (unbinned pixels)");
input.get_value("readout", readout, 4.f, 0.f, FLT_MAX, "readout noise for profile fits (RMS ADU)");
input.get_value("gain", gain, 1.f, 0.01f, 100.f, "electrons/ADU for profile fits");
input.get_value("symm", symm, true, "force symmetric profile fits?");
input.get_value("beta", beta, 3.f, 1.f, 1000.f, "default beta exponent for moffat fits");
input.get_value("sigrej", sigrej, 5.f, 0.f, FLT_MAX, "threshold for masking pixels (in sigma)");
input.get_value("onedsrch", initial_search, true, "carry out an initial 1D position tweak?");
if(initial_search){
input.get_value("fwhm1d", fwhm1d, fwhm, 2.f, 1000.f, "FWHM for 1D search");
input.get_value("hwidth1d", hwidth1d, hwidth, int(fwhm1d)+1, INT_MAX, "half-width of 1D search region");
}
input.get_value("rstar", rstar, 1.5f, 0.f, 1000.f, "target aperture scale factor");
input.get_value("rsky1", rsky1, 2.5f, rstar, 1000.f, "inner sky scale factor");
input.get_value("rsky2", rsky2, 3.5f, rsky1, 1000.f, "outer sky scale factor");
input.get_value("fdevice", fdevice, "2/xs", "plot device for profile fits ('null' to ignore)");
input.get_value("xbox", xbox, 2, 0, 10000, "half-size of stats region in X");
input.get_value("ybox", ybox, 2, 0, 10000, "half-size of stats region in Y");
}
// Save defaults now because one often wants to terminate this program early
input.save();
std::vector<Ultracam::sky_mask> skymask;
// Open plot
Subs::Plot plot(device);
if(aspect > 0) cpgpap(width, aspect);
if(reverse){
cpgscr( 0, 1., 1., 1.);
cpgscr( 1, 0., 0., 0.);
}
cpgsch(cheight);
cpgslw(lwidth);
cpgscf(font);
Subs::Plot fplot;
Ultracam::Frame dvar, bad, gain_frame;
std::vector<std::pair<int,int> > zapped;
Reduce::Meanshape shape;
Subs::Format cform(8);
for(size_t ifile=0; ifile<flist.size(); ifile++){
// Read data
Ultracam::Frame data(flist[ifile]);
// Override the checking of junk blue if only one file being plotted
if(flist.size() == 1){
Subs::Header::Hnode *hnode = data.find("Frame.bad_blue");
if((hnode->has_data() ? hnode->value->get_bool() : false)){
std::cerr << "The blue data are junk (u-band coadd mode) but will be plotted anyway" << std::endl;
hnode->value->set_value(false);
}
}
if(!allccds && nccd >= data.size())
throw Input_Error("File = " + flist[ifile] + "CCD number = " + Subs::str(nccd+1) + " too large cf " + Subs::str(data.size()) );
if(aflag && data.size() != apers.size())
throw Input_Error("File = " + flist[ifile] + "Data and aperture files have different numbers of CCDs!");
// All set, lets plot.
Ultracam::plot_images(data, x1, x2, y1, y2, allccds, stackdirn, iset, ilow, ihigh, plow, phigh, true, flist[ifile], nccd, true);
if(aflag) Ultracam::plot_apers(apers, x1, x2, y1, y2, allccds, stackdirn, nccd);
// interaction
if(command == "cplot"){
// Create variance frame
dvar = data;
dvar.max(0);
dvar /= gain;
dvar += readout*readout;
// Create 'bad pixel' frame, all zero
bad = data;
bad = 0.;
gain_frame = data;
gain_frame = gain;
std::cout << "Position the cursor and hit the appropriate letter to zoom in/out\n"
<< "or measure the FWHM of a star\n" << std::endl;
// Now aperture addition loop
char ret;
float x, y;
while(ret != 'Q'){
ret = 'X';
// Next lines define the prompt:
std::cout << "\nI(n), O(ut), G(aussian), M(offat), L(evels), W(hole), S(how), Q(uit)" << std::endl;
// Now get cursor input.
if(!cpgcurs(&x,&y,&ret)) throw Ultracam_Error("Cursor error");
ret = toupper(ret);
if(ret == 'I'){
// Zoom in
float xr = (x2-x1)/2., yr = (y2-y1)/2.;
x1 = x - xr/2.;
x2 = x + xr/2.;
y1 = y - yr/2.;
y2 = y + yr/2.;
cpgeras();
Ultracam::plot_images(data, x1, x2, y1, y2, allccds, stackdirn, iset, ilow, ihigh,
plow, phigh, true, flist[ifile], nccd, true);
if(aflag) Ultracam::plot_apers(apers, x1, x2, y1, y2, allccds, stackdirn, nccd);
}else if(ret == 'O'){
// Zoom out
float xr = (x2-x1)/2., yr = (y2-y1)/2.;
x1 = x - 2.*xr;
x2 = x + 2.*xr;
y1 = y - 2.*yr;
y2 = y + 2.*yr;
cpgeras();
Ultracam::plot_images(data, x1, x2, y1, y2, allccds, stackdirn, iset, ilow, ihigh, plow, phigh,
true, flist[ifile], nccd, true);
if(aflag) Ultracam::plot_apers(apers, x1, x2, y1, y2, allccds, stackdirn, nccd);
}else if(ret == 'W'){
// Reset frame
x1 = 0.5;
x2 = data[nccd].nxtot()+0.5;
y1 = 0.5;
y2 = data[nccd].nytot()+0.5;
cpgeras();
Ultracam::plot_images(data, x1, x2, y1, y2, allccds, stackdirn, iset, ilow, ihigh, plow, phigh,
true, flist[ifile], nccd, true);
if(aflag) Ultracam::plot_apers(apers, x1, x2, y1, y2, allccds, stackdirn, nccd);
}else if(ret == 'L'){
std::string entry;
float i1n, i2n;
std::cout << "Enter upper and lower levels [" << ilow << "," << ihigh << "]: ";
getline(std::cin,entry);
if(entry != ""){
std::istringstream ist(entry);
ist >> i1n >> i2n;
if(ist){
ilow = i1n;
ihigh = i2n;
iset = 'D';
}else{
std::cerr << "Invalid entry. No change made." << std::endl;
}
}
// Re-plot
cpgeras();
Ultracam::plot_images(data, x1, x2, y1, y2, allccds, stackdirn, iset, ilow, ihigh, plow, phigh,
true, flist[ifile], nccd, true);
if(aflag) Ultracam::plot_apers(apers, x1, x2, y1, y2, allccds, stackdirn, nccd);
}else if(ret == 'G' || ret == 'M'){
// Profile fit section.
try{
if(fdevice != "null" && !fplot.is_open()) fplot.open(fdevice);
// obtain initial value of 'a'
double a = 1./2./Subs::sqr(fwhm/Constants::EFAC);
Ultracam::Ppars profile;
if(ret == 'G'){
// Gaussian fit section.
std::cout << "\nFitting 2D gaussian ...\n" << std::endl;
profile.set(0., x, y, 0., a, 0., a, symm);
}else if(ret == 'M'){
// Moffat fit section.
std::cout << "\nFitting moffat profile ...\n" << std::endl;
profile.set(0., x, y, 0., a, 0., a, beta, symm);
}
Ultracam::Iprofile iprofile;
Ultracam::fit_plot_profile(data[nccd], dvar[nccd], profile, initial_search, true, x, y, skymask,
fwhm1d, hwidth1d, hwidth, fplot, sigrej, iprofile, true);
// adjust defaults for next time
x = profile.x;
y = profile.y;
fwhm = iprofile.fwhm;
if(ret == 'M') beta = profile.beta;
// Create an aperture
Ultracam::Aperture aper(profile.x, profile.y, 0.f, 0.f, rstar*fwhm, rsky1*fwhm, rsky2*fwhm);
// Set the shape parameters
if(ret == 'G'){
shape.profile_fit_method = Reduce::GAUSSIAN;
shape.extraction_weights = Reduce::GAUSSIAN;
}else if(ret == 'M'){
shape.profile_fit_method = Reduce::MOFFAT;
shape.extraction_weights = Reduce::MOFFAT;
}
shape.fwhm = fwhm;
shape.a = profile.a;
shape.b = profile.b;
shape.c = profile.c;
shape.beta = profile.beta;
float counts, sigma, sky;
int nsky, nrej, worst;
Reduce::ERROR_CODES ecode;
// Extract the flux
Ultracam::extract_flux(data[nccd], dvar[nccd], bad[nccd], gain_frame[nccd],
bad[nccd], aper, Reduce::CLIPPED_MEAN, 2.8, Reduce::VARIANCE,
Reduce::NORMAL, zapped, shape, 1e5, 1e5, counts, sigma,
sky, nsky, nrej, ecode, worst);
if(sigma == -1.){
std::cout << "Aperture photometry failed with error code = " << ecode << std::endl;
}else{
std::cout << "Aperture photometry: " << cform(counts) << " +/- " << cform(sigma) << " counts above sky in radius " << cform(rstar*fwhm) << " pixels\n" << std::endl;
}
// Return focus to image plot
plot.focus();
cpgsfs(2);
if(symm){
// Overplot circle of radius FWHM
cpgsci(Subs::GREEN);
cpgcirc(profile.x, profile.y, fwhm);
cpgpt1(profile.x, profile.y, 1);
cpgsci(Subs::WHITE);
}else{
// Overplot ellipse
cpgsci(Subs::GREEN);
float cosa = cos(Constants::TWOPI*iprofile.angle/360.);
float sina = sin(Constants::TWOPI*iprofile.angle/360.);
float xi, yi, x, y;
xi = iprofile.fwhm_max;
yi = 0.;
x = profile.x + cosa*xi - sina*yi;
y = profile.y + sina*xi + cosa*yi;
cpgmove(x,y);
const int NPLOT=200;
for(int np=0; np<NPLOT; np++){
xi = iprofile.fwhm_max*cos(Constants::TWOPI*(np+1)/NPLOT);
yi = iprofile.fwhm_min*sin(Constants::TWOPI*(np+1)/NPLOT);
x = profile.x + cosa*xi - sina*yi;
y = profile.y + sina*xi + cosa*yi;
cpgdraw(x, y);
}
cpgpt1(profile.x, profile.y, 1);
cpgsci(Subs::WHITE);
}
}
catch(const Ultracam_Error& err){
std::cerr << err << std::endl;
}
catch(const Subs::Subs_Error& err){
std::cerr << err << std::endl;
}
// return focus to image plot
plot.focus();
}else if(ret == 'S'){
try{
int wfind;
const Ultracam::Windata& win = data[nccd].enclose(x,y,wfind);
int ix = int(win.xcomp(x) + 0.5);
int iy = int(win.ycomp(y) + 0.5);
Subs::Format form(6);
std::cout << "\nAbsolute position = (" << x << "," << y << ")" << std::endl;
std::cout << "Window " << wfind+1 << ", relative pixel (" << ix << "," << iy << "), value = " << form(win[iy][ix]) << std::endl;
// Generate stats window
int llx = std::max(0, ix - xbox);
int lly = std::max(0, iy - ybox);
int nx = std::min(win.nx(), ix + xbox - llx + 1);
int ny = std::min(win.ny(), iy + ybox - lly + 1);
// Report in terms of window pixels
std::cout << 2*xbox+1 << "x" << 2*ybox+1 << " box centred on " << ix << "," << iy << " covers X: " << llx << " to " << llx+nx-1 << ", Y: " << lly << " to " << lly+ny-1;
if(2*xbox+1 != nx && 2*ybox+1 != ny){
std::cout << ", relative window coordinates (truncated in X & Y)" << std::endl;
}else if(2*xbox+1 != nx){
std::cout << " relative window coordinates (truncated in X)" << std::endl;
}else if(2*ybox+1 != ny){
std::cout << " relative window coordinates (truncated in Y)" << std::endl;
}else{
std::cout << " relative window coordinates" << std::endl;
}
llx = win.llx() + llx*win.xbin();
lly = win.lly() + lly*win.ybin();
Ultracam::Window stats(llx, lly, nx, ny, win.xbin(), win.ybin(), win.nxtot(), win.nytot());
std::cout << "Absolute region covered X: " << stats.xccd(llx) << " to " << stats.xccd(llx+nx-1) << ", Y: " << stats.yccd(lly) << " to " << stats.yccd(lly+ny-1) << std::endl;
// Copy over data
Ultracam::Windata twin = win.window(stats);
float medval = twin.median();
float mean = twin.mean();
float rms = twin.rms();
std::cout << "npix = " << nx*ny << ", mean = " << form(mean) << ", rms = " << form(rms) << ", median = " << form(medval) << ", min = " << twin.min() << ", max = " << twin.max() << std::endl;
}
catch(const Ultracam::Ultracam_Error& err){
std::cerr << err << std::endl;
}
}
}
}
}
}
catch(const Ultracam::Input_Error& err){
std::cerr << "Ultracam::Input_Error exception:" << std::endl;
std::cerr << err << std::endl;
}
catch(const Ultracam::Ultracam_Error& err){
std::cerr << "Ultracam::Ultracam_Error exception:" << std::endl;
std::cerr << err << std::endl;
}
catch(const Subs::Subs_Error& err){
std::cerr << "Subs::Subs_Error exception:" << std::endl;
std::cerr << err << std::endl;
}
catch(const std::string& err){
std::cerr << err << std::endl;
}
}
| true |
18d3ef3fe267a9df9ff748ca8ffcc3c838d1e4c9 | C++ | keleron/2DSPP | /code/rect.cpp | UTF-8 | 577 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include "extras.h"
#include <vector>
#include <string>
Rect::Rect(int idd, int ww, int hh)
{
id = idd;
w = ww;
h = hh;
}
void Rect::rotate(){
if (rot == false){
right.x = left.x + h;
right.y = left.y + w;
} else {
right.x = left.x + w;
right.y = left.y + h;
}
rot = !rot;
return;
}
string Rect::print()
{
return "(" + to_string(w) + "," + to_string(h) + ")";
}
void Rect::set(int x, int y){
left.x = x;
left.y = y;
right.x = x+w;
right.y = y+h;
} | true |
6a4e47f8bac9f1b798fa557fba0f2ac5f9b0136a | C++ | bss9395/bss9395.github.io | /_en/Computer/Tools/Pointer_Inline.cpp | UTF-8 | 4,644 | 3.0625 | 3 | [] | no_license | /* Pointer_Inline.cpp
Author: BSS9395
Update: 2023-05-25T16:02:00+08@China-China-Guangdong-Zhanjiang+08
Design: Pointer Inline
*/
#include <iostream>
#include <string>
using namespace std;
//////////////////////////////////////////////////////////////////////////////
#define _Delete(pointer) (delete pointer, pointer = nullptr)
//////////////////////////////////////////////////////////////////////////////
#define _self _instance
#define _Counter(Pointer_, Member_) \
Member_* _instance = nullptr; \
int* _count = new int{1}; \
Member_* operator->() { \
return _instance; \
} \
//////////////////////////////////////////////////////////////////////////////
#define _Assign_Constructor(Pointer_, Member_) \
Pointer_(const Pointer_& share) { \
fprintf(stderr, "[%s:%d, %s]\n", __FILE__, __LINE__, __FUNCTION__); \
_instance = share._instance; \
_count = share._count; \
(*_count) += 1; \
} \
//////////////////////////////////////////////////////////////////////////////
#define _Copy_Constructor(Pointer_, Member_) \
Pointer_& operator=(const Pointer_& share) { \
fprintf(stderr, "[%s:%d, %s]\n", __FILE__, __LINE__, __FUNCTION__); \
if (this == &share) { \
return (*this); \
} \
_instance = share._instance; \
_count = share._count; \
(*_count) += 1; \
} \
//////////////////////////////////////////////////////////////////////////////
#define _Virtual_Destructor(Pointer_, Member_) \
virtual ~Pointer_() { \
fprintf(stderr, "[%s:%d, %s]\n", __FILE__, __LINE__, __FUNCTION__); \
(*_count) -= 1; \
if (false == (1 <= (*_count))) { \
fprintf(stderr, "delete _instance; delete _count;\n"); \
delete((Member_ *)_instance), _instance = nullptr; \
delete _count, _count = nullptr; \
} \
} \
//////////////////////////////////////////////////////////////////////////////
#define _Inline(Pointer_, Member_) \
_Counter(Pointer_, Member_) \
_Assign_Constructor(Pointer_, Member_) \
_Copy_Constructor(Pointer_, Member_) \
_Virtual_Destructor(Pointer_, Member_) \
//////////////////////////////////////////////////////////////////////////////
class Type {
public:
struct Member {
wstring _key = L"";
wstring _value = L"";
Member(const wstring& key, const wstring& value) {
_key = key;
_value = value;
}
};
public:
Type(const wstring& key, const wstring& value) {
fprintf(stderr, "[%s:%d, %s]\n", __FILE__, __LINE__, __FUNCTION__);
_self = new Member(key, value);
}
_Inline(Type, Member)
public:
static void _Test_Pointer_Inline() {
Type share = Type(L"abc", L"ABC");
fwprintf(stdout, L"share->_count=%d, share->_datum=%ls\n", *(share._count), share->_key.data());
share->_key = L"def";
share->_value = L"DEF";
Type copy = share;
fwprintf(stdout, L"share->_count=%d, share->_datum=%ls\n", *(share._count), share->_key.data());
fwprintf(stdout, L"copy ->_count=%d, copy ->_datum=%ls\n", *(copy._count) , copy->_key.data() );
}
};
int main(int argc, char* argv[]) {
Type::_Test_Pointer_Inline();
return 0;
}
| true |
f943ab588df414aa7f4103251ecdd0b3d8b33962 | C++ | innocentboy/myrepository | /src/codee/tc/dp/SRM468_DV1_L2.cpp | UTF-8 | 2,402 | 3.125 | 3 | [] | no_license | /**
http://community.topcoder.com/stat?c=problem_statement&pm=10765&rd=14183
SOL:
http://apps.topcoder.com/wiki/display/tc/SRM+468
*/
/**
INPUT:
//
3
4 6 8
1 7 4
1
//
3
4 6 8
1 11 4
1
//
3
4 6 8
1 11 4
2
OUTPUT:
//
12
//
//
14
//
//
11
//
14
122365
*/
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <cmath>
#define N 4000004
using namespace std;
int flight[N],road[N];
int n,k;
/**
METHOD 1:
USING RECURANCE RELATION FOR SOLVING THE QUESTION.
*/
int solve(int index,int k,int flying)
{
int i,j,l,m,ret=99999;
if(index==n-1)
{
j=road[index];
if(k>0||(k==0&&flying==1)){
i=flight[index];
return min(i,j);
}
return j;
}
if(k>0||(k==0&&flying==1))
{
if(flying==1)
{
ret=min(ret,min(solve(index+1,k,1)+flight[index],
solve(index+1,k,0)+road[index]));
}
else
{
ret=min(ret,min(solve(index+1,k-1,1)+flight[index],
solve(index+1,k,0)+road[index]));
}
}
else
{
ret=0;
for(i=index;i<n;i++)
ret+=road[i];
}
return ret;
}
/**
METHOD 2:
USING DP FOR SOLVING THE QUESTION.
*/
void solveDP()
{
int i,j,l,m,f;
/**
[first] signifies the storage for current one(i&1), and the vales from stored second one.(!i&1)
[second] 0 signifies that it's not in flying mod and 1 signifies that it's in flying mod.e
[third]
*/
int dp[2][2][41];
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
for(l=0;l<=41;l++)
dp[i][j][l]=0;
}
for(i=0;i<n;i++)
{
/**
f==1 signifies that it's in flight mod. ans f==0 signifies that it's nt flying..
*/
for(f=0;f<2;f++)
{
for(j=0;j<=k;j++)
{
int &best=dp[!(i&1)][f][j];
best=dp[i&1][0][j]+road[i];
if(f==1)
best=min(best,dp[i&1][1][j]+flight[i]);
else if(j>0)
best=min(best,dp[i&1][1][j-1]+flight[i]);
}
}
}
printf("\nAns:%d\n",dp[(i&1)][0][k]);
}
int main()
{
printf("\ndriver of king or road is running..\n");
int i,j,l,m;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&road[i]);
for(i=0;i<n;i++)
scanf("%d",&flight[i]);
scanf("%d",&k);
/**
Using METHOD1:
*/
i=solve(0,k-1,1);
j=solve(0,k,0);
printf("\nAns:%d\n",min(i,j));
/**
Using METHOD 2:
*/
solveDP();
return 0;
}
| true |
676564f12ba1310b104d0ff826fd52050e552151 | C++ | prajneya/IOI | /ioi-training-master/Code Chef/Number of Factors.cpp | UTF-8 | 877 | 2.6875 | 3 | [] | no_license | /*
Created By: Malvika Joshi
Problem: NUMFACT
Link: http://www.codechef.com/problems/NUMFACT
*/
#include <stdio.h>
#include <string.h>
#define MAXL 1000000
#define MAXP 80000
#define MAXN 10
bool fac[MAXL];
int primes[MAXP];
short count[MAXP];
int P,N;
int init(){
int i,j;
for(i = 2; i*i < MAXL; i++){
if(fac[i]) continue;
for(j = i*i; j < MAXL; j += i) fac[j] = 1;
primes[P++] = i;
}
for(; i < MAXL; i++){
if(fac[i]) continue;
primes[P++] = i;
}
return P;
}
int main(){
int i,t,n,p;
long long sol;
init();
scanf("%d",&t);
while(t--){
scanf("%d",&N);
memset(count, 0, sizeof(short)*MAXP);
for(i = 0; i < N; i++){
scanf("%d",&n);
for(p = 0; p < P; ++p){
while(!(n%primes[p])){
++count[p];
n /= primes[p];
}
}
}
sol = 1;
for(p = 0; p < P; ++p) sol *= (count[p]+1);
printf("%lld\n",sol);
}
return 0;
}
| true |
4002e77d2e44fc177a7a89815232b6ac951be3bf | C++ | HenningEggertz/Arduino | /Mats/matstest.ino | UTF-8 | 2,663 | 2.671875 | 3 | [] | no_license | unsigned char cmd[9],checksumma;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
cmd[0] = 1; // adress i sändpaketet läggs i cmd[0]
cmd[1] = 3; //kommando -"- cmd[1]
cmd[2] = 0; // kommandotyp -" cmd[2]
cmd[3] = 0; // motor -"- cmd[3]
// value = antal steg består av 4 bytes
cmd[4] = 0;//(unsigned char)((value>> 24) & 0xFF); // byte 1 läggs i cmd[4] // beräknar innehållet i byte 1
cmd[5] = 0;//(unsigned char)((value>> 16) & 0xFF); // byte 2 -"- cmd[5} // -"- byte 2
cmd[6] = 0;//(unsigned char)((value>> 8) & 0xFF); // byte 3 -"- cmd[6] // -"- byte 3
cmd[7] = 0;//(unsigned char)((value>> 0) & 0xFF); // byte 4 -"- cmd[7] // -"- byte 4
checksumma = 0; // nollställer checksumma
for(int i=0;i<8;i++){ //
checksumma+= cmd[i]; // summera de 8 byten och lägg i checksumma
}
cmd[8] = checksumma; // lägg checksumma i cmd[9]
for(int i = 0; i<9;i++){
//Serial.print();
Serial.write(cmd[i]); // skriv ut alla 9 byten till motorn
}
delay(5000);
cmd[0] = 1; // adress i sändpaketet läggs i cmd[0]
cmd[1] = 1; //kommando -"- cmd[1]
cmd[2] = 0; // kommandotyp -" cmd[2]
cmd[3] = 0; // motor -"- cmd[3]
// value = antal steg består av 4 bytes
cmd[4] = 0;//(unsigned char)((value>> 24) & 0xFF); // byte 1 läggs i cmd[4] // beräknar innehållet i byte 1
cmd[5] = 0;//(unsigned char)((value>> 16) & 0xFF); // byte 2 -"- cmd[5} // -"- byte 2
cmd[6] = 3;//(unsigned char)((value>> 8) & 0xFF); // byte 3 -"- cmd[6] // -"- byte 3
cmd[7] = 232;//(unsigned char)((value>> 0) & 0xFF); // byte 4 -"- cmd[7] // -"- byte 4
checksumma = 0; // nollställer checksumma
for(int i=0;i<8;i++){ //
checksumma+= cmd[i]; // summera de 8 byten och lägg i checksumma
}
cmd[8] = checksumma; // lägg checksumma i cmd[9]
for(int i = 0; i<9;i++){
//Serial.print();
Serial.write(cmd[i]); // skriv ut alla 9 byten till motorn
}
delay(5000);
}
| true |
7b0a2b9aae51a79b3cddbbe5820060cc28df76a0 | C++ | akhtamov/PMT | /OOP/container.h | UTF-8 | 643 | 2.59375 | 3 | [] | no_license |
#include <fstream>
#include <iostream>
#include <string>
#include "shape.h"
using namespace std;
class List
{
public:
Shape* shape;
//Rectangle * rectangle;
//Circle * circle;
// Triangle * triangle;
List* prev;
List* next;
static List* initialization();
static List* addElement(List* current, List* head);
static int getLength(List* head);
void sortByPerimeter(List* head);
List* readFromFile(ifstream& in, List* head);
void writeToFile(ofstream& out, List* head);
void writeRectanglesToFile(ofstream& out, List* head);
void multimethod(ofstream& out, List* head);
};
| true |
e7a04b1d55bdbf69b2e1a8fabcaec56c59dcbde7 | C++ | DanielWhite94/Tremor | /engine/src/udppacket.h | UTF-8 | 695 | 2.640625 | 3 | [] | no_license | #ifndef TREMORENGINE_UDPPACKET_H
#define TREMORENGINE_UDPPACKET_H
#include <cstdint>
#include <SDL2/SDL.h>
#include <SDL2/SDL_net.h>
namespace TremorEngine {
class UdpPacket {
public:
struct PlayerEntry {
float x, y, z, yaw;
};
UdpPacket();
UdpPacket(uint32_t id);
~UdpPacket();
bool initFromRecvData(const UDPpacket &rawPacket);
bool initSendData(UDPpacket &rawPacket); // rawPacket.data and rawPacket.maxlen should be set beforehand, len is filled in
bool addPlayerEntry(const PlayerEntry &playerEntry);
uint32_t id;
int playerCount;
PlayerEntry players[256]; // TODO: Avoid hardcoded/magic number array size here and when accessed
private:
};
};
#endif
| true |
6342c26f00c80cf3f21f15361614d5566b84185f | C++ | xuhw16/master_coder | /sort_algorithm.cpp | UTF-8 | 4,450 | 3.484375 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
/*
input: n //size of sorted numbers
[x1,x2,x3..xn]//vector to be sort
sort algorithm:
bubble sort: o(n^2),stable sort.
insert sort: o(n^2),stable sort.
merge sort:o(nlog(n)),table sort.(not in place)
heap sort:o(nlog(n)),distable sort. (in place)
quick_sort:o(nlog(n)),distable sort. (in place)
cout_sort:o(n),stable (input no more than k)
*/
//bubble sort
void bubble_sort(vector<int>&result) {
int nums = result.size();
for (int i = 0; i < nums - 1; i++) {
for (int j = 0; j < nums - i - 1; j++) {
if (result[j] > result[j + 1])
swap(result[j], result[j + 1]);
}
}
}
//insert sort
void insert_sort(vector<int> &result) {
int nums = result.size();
for (int i = 1; i < nums; i++) {
int tmp = result[i];
int j = i - 1;
while (j > 0 && tmp < result[j]) {
result[j + 1] = result[j];
--j;
}
result[j + 1] = tmp;
}
}
//merge sort
void merge_all(vector<int>&result, vector<int>left_re, vector<int>right_re) {
int n = result.size();
int l = left_re.size();
int r = right_re.size();
int lr = 0, lf = 0;
for (int i = 0; i < n; i++) {
while (lr < r&&lf < l) {
if (left_re[lf] <= right_re[lr]) {
result[i] = left_re[lf];
++lf;
++i;
}
else {
result[i] = right_re[lr];
++lr;
++i;
}
}
while (lr < r) {
result[i] = right_re[lr];
++lr;
++i;
}
while(lf<l){
result[i] = left_re[lf];
++lf;
++i;
}
}
}
void merge_sort(vector<int>&result) {
int nums = result.size();
if (nums == 1)return;
vector<int>left_re(result.begin(), result.begin() + nums / 2);
vector<int>right_re(result.begin() + nums / 2,result.end());
merge_sort(left_re);
merge_sort(right_re);
merge_all(result, left_re, right_re);
}
//heap_sort
void heap_keep(vector<int> &result, int i,int last) {
int target = i;
if (2 * i + 1 <= last&&result[2 * i + 1] > result[i])
target = 2 * i + 1;
if (2 * i + 2 <= last&&result[2 * i + 2] > result[target])
target = 2 * i + 2;
if (target != i) {
swap(result[target], result[i]);
heap_keep(result, target,last);
}
}
void heap_create(vector<int>&result) {
int nums = result.size();
for (int i = nums/ 2-1; i >= 0; i--) {
heap_keep(result, i,nums-1);
}
}
void heap_sort(vector<int>&result) {
int nums = result.size();
heap_create(result);
int j = nums - 1;
for (int i = nums - 1; i >= 0; i--) {
swap(result[0], result[j]);
j--;
heap_keep(result, 0,j);
}
}
//quick_sort
int sort_partion(vector<int>&result, int left, int right) {
int x = result[right];
int i = left - 1;
for (int j = left; j < right; j++) {
if (result[j] < x) {
i++;
swap(result[i], result[j]);
}
}
swap(result[i + 1], result[right]);
return i + 1;
}
void quick_sort(vector<int>&result,int left,int right) {
if (left < right) {
int q = sort_partion(result, left, right);
quick_sort(result, left, q - 1);
quick_sort(result, q + 1, right);
}
}
//counting sort
//input no more than k
vector<int> cout_sort(vector<int>result,int k) {
int nums = result.size();
vector<int> re(nums, 0);
vector<int> tmp(k+1, 0);
for (int i = 0; i < nums; i++) {
tmp[result[i]] += 1;
}
for (int i = 1; i <tmp.size(); i++) {
tmp[i] += tmp[i - 1];
}
for (int i = nums - 1; i >= 0; i--) {
re[tmp[result[i]]-1] = result[i];
tmp[result[i]]--;
}
return re;
}
//radix sort
//based on cout_sort
void rcout_sort(vector<int>&result, vector<int>&res,int k) {
int nums = result.size();
vector<int> re(nums, 0);
vector<int> tmp(k+1, 0);
for (int i = 0; i < nums; i++) {
tmp[result[i]] += 1;
}
for (int i = 1; i <tmp.size(); i++) {
tmp[i] += tmp[i - 1];
}
for (int i = nums - 1; i >= 0; i--) {
re[tmp[result[i]]-1] = res[i];
tmp[result[i]]--;
}
res=re;
}
void radix_sort(vector<int>&result,int d) {
for (int i = 0; i < d; i++) {
vector<int> tmp(result.size(), 0);
for (int j = 0; j < result.size(); j++) {
int tm = result[j];
int k = i;
while (k >0) {
tm/= 10;
k--;
}
tm %= 10;
tmp[j]=tm;
}
rcout_sort(tmp, result, 9);
}
}
int main() {
//input
int n = 0;
cin >> n;
vector<int>result(n, 0);
for (int i = 0; i < result.size(); i++)
cin >> result[i];
radix_sort(result,9);
//cout_sort(result,10);
//quick_sort(result,0,result.size()-1);
//heap_sort(result);
//merge_sort(result);
//insert_sort(result);
//bubble_sort(result);
//output
for (int i = 0; i < result.size(); i++)
cout << result[i] << " ";
return 0;
} | true |
fb407c76ff821518c5731a6f58a2cb303462e38d | C++ | chrisoldwood/COM | /ClassFactory.hpp | UTF-8 | 1,154 | 2.515625 | 3 | [
"MIT"
] | permissive | ////////////////////////////////////////////////////////////////////////////////
//! \file ClassFactory.hpp
//! \brief The ClassFactory class declaration.
//! \author Chris Oldwood
// Check for previous inclusion
#ifndef COM_CLASSFACTORY_HPP
#define COM_CLASSFACTORY_HPP
#if _MSC_VER > 1000
#pragma once
#endif
namespace COM
{
////////////////////////////////////////////////////////////////////////////////
//! The singleton coclass factory.
class ClassFactory : public ObjectBase<IClassFactory>
{
public:
//! Construction from a CLSID.
ClassFactory(const CLSID& rCLSID);
//! Destructor.
~ClassFactory();
DEFINE_INTERFACE_TABLE(IClassFactory)
IMPLEMENT_INTERFACE(IID_IClassFactory, IClassFactory)
END_INTERFACE_TABLE()
IMPLEMENT_IUNKNOWN()
//
// IClassFactory methods.
//
//! Create an instance object of the class.
virtual HRESULT COMCALL CreateInstance(IUnknown* pOuter, const IID& rIID, void** ppInterface);
//! Lock the COM server.
virtual HRESULT COMCALL LockServer(BOOL fLock);
private:
//
// Members.
//
CLSID m_oCLSID; //!< The CLSID to manufacture objects of.
};
//namespace COM
}
#endif // COM_CLASSFACTORY_HPP
| true |
e75339e4cdd74b4dbe1ec63b0bd17791672efd24 | C++ | WinstonLy/Job | /TestProject/data_structure/List/List.cpp | UTF-8 | 1,828 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include "List.h"
#include "Coordinate.h"
using namespace std;
CList::CList(int size)
{
m_iSize = size;
m_pList = new Coordinate[m_iSize];
m_iLength = 0;
}
CList::~CList()
{
delete []m_pList;
m_pList = NULL;
}
void CList::ClearList()
{
m_iLength = 0;
}
bool CList::ListEmpty()
{
if(0 == m_iLength)
{
return true;
}
else
{
return false;
}
}
int CList::ListLength()
{
return m_iLength;
}
bool CList::GetElem(int i, Coordinate *elem)
{
if(i < 0 || i > m_iSize)
{
return false;
}
*elem = m_pList[i];
return true;
}
int CList::LocateElem(Coordinate *elem)
{
for(int i = 0; i < m_iLength; i++)
{
if(m_pList[i] == *elem)
{
return i;
}
}
return -1;
}
bool CList::PriorElem(Coordinate *currentElem, Coordinate *preElem)
{
int temp = LocateElem(currentElem);
if(-1 == temp)
{
return false;
}
else
{
if(0 == temp)
{
return false;
}
else
{
*preElem = m_pList[temp - 1];
return true;
}
}
}
bool CList::NextElem(Coordinate *currentElem, Coordinate *nextElem)
{
int temp = LocateElem(currentElem);
if(-1 == temp)
{
return false;
}
else
{
if(m_iLength - 1 == temp)
{
return false;
}
else
{
*nextElem = m_pList[temp + 1];
return true;
}
}
}
void CList::ListTraverse()
{
for(int i = 0; i < m_iLength; i++)
{
cout << m_pList[i] << endl;
}
}
bool CList::ListInsert(int i, Coordinate *elem)
{
if(i < 0 || i > m_iLength)
{
return false;
}
m_iLength++;
for(int k = m_iLength - 1; k > i; k--)
{
m_pList[k] = m_pList[k - 1];
}
m_pList[i] = *elem;
return true;
}
bool CList::ListDelete(int i, Coordinate *elem)
{
if(i < 0 || i >= m_iLength)
{
return false;
}
*elem = m_pList[i];
m_iLength--;
for(int k = i; k < m_iLength; k++)
{
m_pList[k] = m_pList[k + 1];
}
return true;
}
| true |
d66b6c91bdcca20dc3e672612f10cbfcf77274b8 | C++ | meijieman/CPPHub | /aurora/alpha/CCar.cpp | UTF-8 | 628 | 3.265625 | 3 | [] | no_license | //
// Created by Administrator on 2019/2/11.
//
#include <iostream>
using namespace std;
// 轮胎
class CTyre {
private:
int radius;
int width;
public:
CTyre(){}
CTyre(int r, int w) : radius(r), width(w) {}
};
class CEngine {
};
class CCar {
private:
int price;
CTyre tyre;
CEngine engine;
public:
CCar();
CCar(int p, int tr, int tw);
void string(){
cout << price << endl;
}
};
CCar::CCar() {}
CCar::CCar(int p, int tr, int tw) : price(p), tyre(tr, tw) {
}
int main() {
CCar car(2000, 17, 255);
car.string();
CCar c;
c.string();
return 0;
} | true |
f20ffa388f83515d0aec88f05ab8a22959495ba3 | C++ | AmiraNoaman/DataStructure_RestaurantSimulation | /Restaurant/Rest/Order.h | UTF-8 | 1,451 | 3.09375 | 3 | [] | no_license | #ifndef __ORDER_H_
#define __ORDER_H_
#include "..\Defs.h"
#include <cmath>
class Order
{
protected:
int ID; //Each order has a unique ID (from 1 --> 999 )
ORD_TYPE type; //order type: Normal, Frozen, VIP
REGION Region; //Region of this order
int Distance; //The distance (in meters) between the order location and the resturant
double totalMoney; //Total order money
int ArrTime, ServTime, FinishTime,WaitingTime; //arrival, service start, and finish times
double priority; // indication to priority the higher the number the faster you should serve
public:
Order(int at,int ID, ORD_TYPE r_Type, REGION r_region,int dist, double money);
int GetID();
int GetArrTime();
int GetWaitingTime();
ORD_TYPE GetType() const;
REGION GetRegion() const;
void SetDistance(int d);
int GetDistance() const;
double getpriority();
void setServTime(int speed);
int getServTime();
void setWaitingTime(int Assigningtimestep);
int getWaitingTime();
void setFinishTime();
int getFinishTime()const;
bool operator>(Order*& O)const;
bool operator<(Order*&O)const;
bool operator<=(Order*&O)const;
bool operator>=(Order*&O)const;
double setVIPpriority(); // function that calculates the priority of the VIP order according to its arrival time, money and distance
void setTotalMoney(double);
double getTotalMoney() const;
void setType(ORD_TYPE ord);
double getVIPpriority();
virtual ~Order();
};
#endif | true |
5a7a57b0fba22431c52e7f4ee92d60b386e423fa | C++ | weilaidb/qtexample | /map_key_is_arrayORstruct/main2.cpp | GB18030 | 4,738 | 3.890625 | 4 | [] | no_license | ///******************************************************************
// mapĻ
// C++ Mapsһֹʽؼ/ֵ
// begin() ָmapͷĵ
// clear( ɾԪ
// count() ָԪسֵĴ
// empty() mapΪtrue
// end() ָmapĩβĵ
// equal_range() Ŀĵ
// erase() ɾһԪ
// find() һԪ
// get_allocator() map
// insert() Ԫ
// key_comp() رȽԪkeyĺ
// lower_bound() ؼֵ>=Ԫصĵһλ
// max_size() ؿɵԪظ
// rbegin() һָmapβ
// rend() һָmapͷ
// size() mapԪصĸ
// swap() map
// upper_bound() ؼֵ>Ԫصĵһλ
// value_comp() رȽԪvalueĺ
//====================================================================
//1map
// map<int, string> mapStudent;
//2map
// mapStudent.insert(pair<int, string>(1, "student_one"));
// mapStudent.insert(map<int, string>::value_type(2, "student_two"));
// mapStudent[3] = "student_three";
//********************************************************************/
//#pragma warning (disable:4786)
//#include <map>
//#include <string>
//#include <iostream>
//using namespace std;
//int main()
//{
// map<int, string> mapStudent;
// cout<<"ֲ뷽ʽ"<<endl;
// mapStudent.insert(pair<int, string>(1, "student_one"));
// mapStudent.insert(map<int, string>::value_type(2, "student_two"));
// mapStudent[3] = "student_three";
// mapStudent.insert(map<int, string>::value_type(4, "student_four"));
// pair<map<int,string>::iterator,bool> InsertPair; //жǷɹ
// InsertPair = mapStudent.insert(map<int,string>::value_type(5,"student_five"));
// if(InsertPair.second == true)
// {
// //cout<<InsertPair.first.operator++<<endl; //⣿֪ôӦõһ
// }
// cout<<"ֱʽ"<<endl;
// map<int, string>::iterator iter;
// for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)
// {
// cout<<iter->first<<" "<<iter->second<<endl;
// }
// map<int, string>::reverse_iterator iters;
// for(iters = mapStudent.rbegin(); iters != mapStudent.rend(); iters++)
// {
// cout<<iters->first<<" "<<iters->second<<endl;
// } //
// cout<<"ʽ:"<<endl;
// for(unsigned int iIndex=0;iIndex < mapStudent.size();iIndex++) //size()سԱĸ
// {
// cout<<mapStudent[iIndex]<<endl;
// }
// cout<<mapStudent.count(1)<<endl; //count()жϹؼǷڣ1ʾڣ0
// iter = mapStudent.find(1); //find()ؼִʱλõĵend()صĵ
// if( iter != mapStudent.end() )
// {
// cout<<"ݴڣ"<<iter->first<<" "<<iter->second<<endl;
// mapStudent.erase(iter); //õɾ
// }
// else
// {
// cout<<"ݲڣ"<<endl;
// }
// int n = mapStudent.erase(3); //ùؼɾɾ˻᷵10
// iter = mapStudent.lower_bound(2); //2ĵ
// cout<<iter->second<<endl;
// iter = mapStudent.upper_bound(2); //3ĵ
// cout<<iter->second<<endl;
// /*Equal_rangeһpairpairһLower_boundصĵpairڶUpper_boundصĵȵĻ˵mapвؼ*/
// pair<map<int,string>::iterator,map<int,string>::iterator> MapPair;
// MapPair = mapStudent.equal_range(2);
// if( MapPair.first == MapPair.second )
// {
// cout<<"Do not find"<<endl;
// }
// else
// {
// cout<<"Find"<<endl;
// }
// MapPair = mapStudent.equal_range(3);
// if( MapPair.first == MapPair.second )
// {
// cout<<"Do not find"<<endl;
// }
// else
// {
// cout<<"Find"<<endl;
// }
// //ɾһǰպļϣSTL
// mapStudent.erase(mapStudent.begin(), mapStudent.end());
// return 0;
//}
| true |
912733b4da1d61f6573a4a9bdb557566ee143143 | C++ | stone725/CompetitiveProgramming | /AtCoder/joi2006yo/joi2006yo_b.cpp | UTF-8 | 535 | 3.140625 | 3 | [] | no_license | #include <iostream>
#include <map>
using namespace std;
int main()
{
int n;
cin >> n;
map<char, char> change;
for (int i = 0; i < n; i++)
{
char from, to;
cin >> from >> to;
change[from] = to;
}
int m;
cin >> m;
for (int i = 0; i < m; i++)
{
char c;
cin >> c;
if (change.count(c))
{
cout << change[c];
}
else
{
cout << c;
}
}
cout << "\n";
} | true |
2dacfcf5a38853772b58150ff5ee4e2d83e6c525 | C++ | SecurityExceptionGames/SEGlibCPP2019w | /SEGlibCPP/SEGlibCPP/Headers/org/segames/library/io/file_attributes.h | UTF-8 | 3,424 | 3.15625 | 3 | [] | no_license | #pragma once
#include <org/segames/library/util/array_list.h>
#ifndef SEG_API_SYSTEM_DIR_SEPARATOR
#ifdef _WIN32
#define SEG_API_SYSTEM_DIR_SEPARATOR_CHAR '\\'
#define SEG_API_SYSTEM_DIR_SEPARATOR "\\"
#else
#define SEG_API_SYSTEM_DIR_SEPARATOR_CHAR '/'
#define SEG_API_SYSTEM_DIR_SEPARATOR "/"
#endif
#endif
namespace org
{
namespace segames
{
namespace library
{
/*
A class storing the attributes of a file, initialized on creation, copied on copy.
* @author Philip Rosberg
* @since 2018-11-05
* @edited 2019-05-12
*/
class SEG_API FileAttributes :
public Object
{
protected:
/*
True if the file exists.
*/
bool m_exists;
/*
True if the file is a directory.
*/
bool m_directory;
/*
The length/size of the file.
*/
size_t m_length;
/*
The file path.
*/
std::string m_path;
/*
The file path dissected.
*/
ArrayList<std::string> m_dissectedPath;
protected:
/*
Loads the attributes using the windows library.
* @param[in] path The path of the file
*/
virtual void loadAttribWindows(const char* path);
public:
/*
Creates an empty file attributes object in the local path of the executable.
*/
FileAttributes();
/*
Loads the file attributes for the given path.
* @param[in] path The path of the file
*/
explicit FileAttributes(const char* path);
/*
Loads the file attributes for the given path.
* @param[in] path The path of the file
*/
explicit FileAttributes(const std::string& path);
/*
Returns true if the file exists.
*/
virtual bool exists() const;
/*
Returns true if the given file is a directory.
*/
virtual bool isDirectory() const;
/*
Returns the length of the file in num. bytes.
*/
virtual size_t length() const;
/*
Returns the file path (absolute).
*/
virtual std::string& getPath() const;
/*
Retruns the path dissected into all sub-parts.
*/
virtual ArrayList<std::string>& getPathDissection() const;
/*
Sets if the file exists or not.
WARNING! THIS METHOD ONLY CHANGES THE ATTRIBUTE OBJECT AND NOT THE FILE ON THE SYSTEM!
* @param[in] flag True if the file exists
*/
virtual void setExisting(const bool flag);
/*
Sets if the file is a directory or not.
WARNING! THIS METHOD ONLY CHANGES THE ATTRIBUTE OBJECT AND NOT THE FILE ON THE SYSTEM!
* @param[in] float True if the file is a directory
*/
virtual void setDirectory(const bool flag);
/*
Sets the file representation length.
WARNING! THIS METHOD ONLY CHANGES THE ATTRIBUTE OBJECT AND NOT THE FILE ON THE SYSTEM!
* @param[in] length The length of the file
*/
virtual void setLength(const size_t length);
/*
Sets the path of the file representation.
WARNING! THIS METHOD ONLY CHANGES THE ATTRIBUTE OBJECT AND NOT THE FILE ON THE SYSTEM!
* @param[in] path The path
*/
virtual void setPath(const std::string& path);
/*
Updates the file attributes.
*/
virtual void update();
/*
Returns a hash code from the path.
*/
virtual size_t hashCode() const override;
/*
Returns a string representation of the file attributes.
*/
virtual std::string toString() const override;
};
}
}
} | true |
d189f1080cb38ba4f6940866dd876fc69b1764df | C++ | acsm66/catninja | /Ninja.h | UTF-8 | 549 | 2.546875 | 3 | [] | no_license | #pragma once
#include "stdafx.h"
#include "SpriteSheet.h"
class Ninja {
public:
enum Direction { DIR_NONE, DIR_RIGHT, DIR_LEFT };
Ninja(int maxSpeed, int maxPaceLevel, int xSize);
void init(SDL_Renderer *renderer, int initX, int initY);
void setDirection(Direction dir);
void refresh();
private:
void calculateSpeed();
void calculatePosition();
SpriteSheet _spriteSheet;
int _maxSpeed;
int _maxPaceLevel;
int _paceStep;
int _xSize;
int _curSpeed;
SDL_Rect _curPos;
Direction _prevDir;
Direction _curDir;
Uint32 _startDir;
};
| true |
9a1f1b5b418be1172c83828276408fc807badc19 | C++ | ibestvina/reAligner | /reAligner/FragmentReader.h | UTF-8 | 2,281 | 3.28125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <iostream>
#include <istream>
#include <string>
#include <fstream>
#include <list>
#include <map>
#include "FileReader.h"
class FragmentReader :
public FileReader
{
std::istream &inStream;
std::map<int, Fragment*> fragments;
std::map<std::string, int> stringIDtoID;
public:
FragmentReader(std::istream &inputStream) :inStream(inputStream)
{
}
~FragmentReader()
{
}
/**
* Takes string that might have lowercase letters and makes them uppercase.
*/
std::string toUpperCase(std::string s) {
for (int i = 0; i < (int)s.size(); ++i) {
if (s[i] >= 'a' && s[i] <= 'z') {
s[i] = s[i] - 'a' + 'A';
}
}
return s;
}
/**
* Goes through input file line by line and reads all fragments, saves them to list and returns.
* If fragment is divided on multiple lines concates them together.
*/
std::map<int, Fragment*> GetAllFragments(){
std::string currentSequence = "";
int counter = 1;
bool reading = false;
while (!inStream.eof())
{
std::string sLine;
std::getline(inStream, sLine);
if (sLine[0] == '>' || sLine[0] == '@') {
if (currentSequence != "" && fragments.size() > 0) {
fragments[counter]->setLength(currentSequence.size());
fragments[counter]->setSequence(toUpperCase(currentSequence));
currentSequence = "";
counter++;
}
//fragments->push_back(new Fragment(counter++,sLine.substr(1)));
std::string name = "";
char chown='\0';
std::istringstream L(sLine);
L >> chown; //remove >
L >> name; //read till whitespace
fragments[counter] = new Fragment(counter, name);
stringIDtoID[name] = counter;
reading = true;
}
else if (sLine[0] == '+') {
reading = false;
}
else {
if (reading == true) {
currentSequence += sLine;
}
}
}
if (currentSequence != "") {
fragments[counter]->setLength(currentSequence.size());
fragments[counter]->setSequence(toUpperCase(currentSequence));
}
return fragments;
}
Fragment* get(int id) {
return fragments[id];
}
Fragment* get(std::string name) {
return fragments[stringIDtoID[name]];
}
std::map<int, Fragment*> toMap()
{
std::map<int, Fragment*> retMap;
for (Fragment *F : *fragments)
{
retMap[F->getId()] = F;
}
return retMap;
}
};
| true |
dfbc9cb46b4cefe774bc5e65a34e9bfbb92709cc | C++ | okiochan/coding-help | /OTHER/cтруктуры/lca_and_jump.cpp | UTF-8 | 1,081 | 2.640625 | 3 | [] | no_license |
int up[N][L], tin[N], tout[N], len[N];
int timer, l;
void dfs(int v, int p)
{
tin[v] = timer++;
up[v][0] = p;
len[v] = len[p] + 1;
for(int i=1; i<=l; i++)
{
int pr = up[v][i-1];
up[v][i] = up[pr][i-1];
}
for(int i=0; i<g[v].size(); i++)
{
int to = g[v][i];
if(to != p)
dfs(to,v);
}
tout[v] = timer++;
}
//a -> b
bool upper(int a, int b)
{
return (tin[a] <= tin[b] && tout[a] >= tout[b]);
}
int lca(int a, int b)
{
if( upper(a,b)) return a;
if( upper(b,a)) return b;
for(int i=l; i >=0; i--)
{
if(upper( up[a][i], b)) continue;
a = up[a][i];
}
return up[a][0];
}
int dist(int v1, int v2, int par)
{
return (len[v1]-len[par] + len[v2]-len[par]);
}
int down_par_on_dist(int v, int par, int d)
{
if(d == 0) return par;
if(d == dist(v,par,par)) return v;
for(int i=l; i >=0; i--)
{
int cur = up[v][i];
if(upper( cur, par) || dist(cur,par,par) < d) continue;
v = cur;
}
if(dist(v,par,par) == d) return v;
return 0;
}
void init(int n, int s)
{
l=1;
while((1<<l) <= n) l++;
memset(len,-1,sizeof(len));
dfs(s,s);
}
| true |
f97a7aeaf819fd6a2b1ab0f18ac54c5bbc6f8f80 | C++ | itsanshulverma/du-cs-undergrad-course | /Semester2/DiscreteStructures/Practicals/02-set2/main.cpp | UTF-8 | 4,036 | 3.859375 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Set
{
public:
int elements[100];
int size = 0;
Set();
void input();
void print();
bool subset_of(Set);
Set union_with(Set);
Set intersection_with(Set);
Set complement(Set);
Set difference(Set);
Set difference_sym(Set);
void cartesian_prod(Set);
private:
void addElement(int);
bool has(int i);
};
Set::Set()
{
}
void Set::input()
{
int itrCount;
cout << "\nEnter the size of set : ";
cin >> itrCount;
cout << "Enter the elements of set : ";
for (int i = 0; i < itrCount; i++)
{
int e;
cin >> e;
this->addElement(e);
}
cout << endl;
}
bool Set::has(int n)
{
for (int i = 0; i < size; i++)
{
if (n == elements[i])
{
return true;
break;
}
}
return false;
}
void Set::addElement(int n)
{
if (!has(n))
{
elements[size] = n;
++size;
}
}
bool Set::subset_of(Set set)
{
int count = 0;
for (int i = 0; i < this->size; i++)
{
for (int j = 0; j < set.size; j++)
{
if (this->elements[i] == set.elements[j])
{
count++;
break;
}
}
}
if (count == size)
return true;
else
return false;
}
Set Set::union_with(Set set)
{
Set temp;
for (int i = 0; i < size; i++)
{
temp.addElement(elements[i]);
}
for (int i = 0; i < set.size; i++)
{
temp.addElement(set.elements[i]);
}
return temp;
}
Set Set::intersection_with(Set set)
{
Set temp;
for (int i = 0; i < size; i++)
{
if (set.has(elements[i]))
temp.addElement(elements[i]);
}
return temp;
}
Set Set::complement(Set uni_set)
{
Set temp;
for (int i = 0; i < uni_set.size; i++)
{
if (!has(uni_set.elements[i]))
temp.addElement(uni_set.elements[i]);
}
return temp;
}
Set Set::difference(Set set)
{
Set temp;
for (int i = 0; i < size; i++)
{
if (!set.has(elements[i]))
temp.addElement(elements[i]);
}
return temp;
}
Set Set::difference_sym(Set set)
{
Set unionSet = union_with(set);
Set intrSet = intersection_with(set);
return unionSet.difference(intrSet);
}
void Set::cartesian_prod(Set set)
{
cout << endl
<< "{ ";
for (int i = 0; i < size; i++)
{
for (int j = 0; j < set.size; j++)
{
cout << "{" << elements[i] << "," << set.elements[j] << "} ";
}
}
cout << "}" << endl
<< endl
<< endl;
}
void Set::print()
{
cout << "{";
for (int i = 0; i < size; i++)
{
if (i == 0)
cout << elements[i];
else
cout << "," << elements[i];
}
cout << "} ";
}
int main()
{
Set setA = Set();
setA.input();
cout << "--> Set A : ";
setA.print();
Set setB = Set();
setB.input();
cout << "--> Set B : ";
setB.print();
if (setA.subset_of(setB))
cout << "\n\n--> Set A is a subset of Set B.\n";
else
cout << "\n\n--> Set A is not a subset of Set B.\n";
cout << endl
<< "--> Set A union Set B : ";
setA.union_with(setB).print();
cout << "\n\n--> Set A intersection Set B : ";
setA.intersection_with(setB).print();
cout << "\n\n--> Let Universal Set be ";
Set universalSet = setA.union_with(setB);
universalSet.print();
cout << endl
<< "--> Complement of Set A (A') : ";
setA.complement(universalSet).print();
cout << endl
<< "--> Complement of Set B (B') : ";
setB.complement(universalSet).print();
cout << "\n\n--> Set A difference Set B : ";
setA.difference(setB).print();
cout << "\n\n--> Set A symmetric difference Set B : ";
setA.difference_sym(setB).print();
cout << "\n\n--> Cartesian product of Set A and Set B : ";
setA.cartesian_prod(setB);
return 0;
} | true |
dc83bcd15010aefe9461edfb282df98917af3e80 | C++ | colinw7/CSVG | /include/CSVGClip.h | UTF-8 | 871 | 2.703125 | 3 | [
"MIT"
] | permissive | #ifndef CSVGClip_H
#define CSVGClip_H
#include <CSVGInheritVal.h>
#include <COptVal.h>
#include <CFillType.h>
class CSVG;
class CSVGClip {
public:
using FillType = CSVGInheritValT<CFillType>;
public:
CSVGClip(CSVG &svg) :
svg_(svg), rule_() {
}
CSVGClip(const CSVGClip &clip) :
svg_(clip.svg_), rule_(clip.rule_) {
}
CSVGClip &operator=(const CSVGClip &clip) {
rule_ = clip.rule_;
return *this;
}
void setRule(const std::string &rule_str);
void setRule(const FillType &rule) { rule_.setValue(rule); }
bool getRuleValid() const {
return rule_.isValid();
}
FillType getRule() const {
if (rule_.isValid())
return rule_.getValue();
else
return FillType(FILL_TYPE_EVEN_ODD);
}
void reset() {
rule_.setInvalid();
}
private:
CSVG& svg_;
COptValT<FillType> rule_;
};
#endif
| true |
41da1c8a7e4f537369bb8678bf2c6e53f8e7842b | C++ | AnthonyDas/HackerRank | /HackerRank/Problem Solving/Data Structures/Queues/Castle on the Grid.cpp | UTF-8 | 2,138 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <utility> // std::make_pair
#include <unordered_set>
// #include <functional> // std::hash
int key(const std::pair<int, int> &pt) {
// return std::hash<int>()(x) ^ std::hash<int>()(y);
return (pt.first * 100) + pt.second; // Max n = 100
}
void move_in_dir(const std::vector<std::string> &grid, std::queue<std::pair<int, int> > &q, std::unordered_set<int> &visited,
bool &dir_avail, const std::pair<int, int> ¤t, const int &x_offset, const int &y_offset) {
if (dir_avail) {
std::pair<int, int> pt(current.first + x_offset, current.second + y_offset);
if (pt.first >= 0 && pt.first < grid.size() && pt.second >= 0 && pt.second < grid.size() &&
grid[pt.first][pt.second] == '.') {
if (visited.find(key(pt)) == visited.end()) {
visited.insert(key(pt));
q.push(pt);
}
}
else {
dir_avail = false;
}
}
}
// Complete the minimumMoves function below.
int minimumMoves(const std::vector<std::string> &grid, const int &startX, const int &startY,
const int &goalX, const int &goalY) {
const std::pair<int, int> start(startX, startY);
std::queue<std::pair<int, int> > q;
q.push(start);
std::unordered_set<int> visited;
visited.insert(key(start));
int move_count = 0, remaining_in_level = q.size();
while (!q.empty()) {
std::pair<int, int> current = q.front();
q.pop();
// std::cout << move_count << " " << remaining_in_level << " " << current.first << " " << current.second << std::endl;
// Have we reached the destination?
if (current.first == goalX && current.second == goalY) {
return move_count;
}
bool north = true, east = true, south = true, west = true;
for (int i = 1; i < grid.size(); ++i) {
move_in_dir(grid, q, visited, north, current, 0, -i);
move_in_dir(grid, q, visited, east, current, i, 0);
move_in_dir(grid, q, visited, south, current, 0, i);
move_in_dir(grid, q, visited, west, current, -i, 0);
}
// Have we finished traversing at current depth?
if (!(--remaining_in_level)) {
remaining_in_level = q.size();
++move_count;
}
}
return -1;
} | true |
9aa5a0c988484fc06b7143ffea15af8c93278ad9 | C++ | JqkerN/Artificial-Intelligence-dd2380 | /A2_duckhunt_hmm/HMM1/printVector.cpp | UTF-8 | 403 | 3.125 | 3 | [] | no_license | # include "printVector.hpp"
using namespace std;
void print_float_vector(vector<float> A)
{
int idx = 2;
for (int r = 0; r < A[0]; r++) {
for (int c = 0; c < A[1]; c++) {
cout << A[idx++] << ' ';
}
cout << endl;
}
cout << " " << endl;
}
void print_sequence(vector<float> A)
{
for (int r = 0; r < A[0]; r++) {
cout << A[r+1] << ' ';
}
cout << endl;
cout << " " << endl;
}
| true |
297c3949b0586c04d1ecf4cad828dcb6df3bcbcc | C++ | AfrikyanA/Homeworks | /10daysOfSuffering/Lesson6/ex1.cpp | UTF-8 | 207 | 2.71875 | 3 | [] | no_license | #include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main () {
int arr[5] = {0};
for ( int i = 5-1; i >= 0; --i ) {
cout << "\t" << arr[i];
}
cout << endl ;
}
| true |
abf8e877890b2da0d9cad9ac3d486f22b448114c | C++ | PeterStalmach/Tetris | /shape.h | WINDOWS-1250 | 1,587 | 2.796875 | 3 | [] | no_license | #ifndef shape_h
#define shape_h
class Shape
{
public:
int polohaX, polohaY, tvar,natoc,polohapoleriadok,polohapolestlpec;
// premenn polohaX a polohaY uchovvaj sradnice polohy tvaru vzhadom na hern mapu/obrazovka/konzola
// premenn polohariadok a polohastlpec uchovvaj sradnice polohy tvaru vzhadom na vector pole s nzvom pole/toto pole uchovva polohy u dopadnutch predchdzajcich tvarov
// premenn natoc uchovva aktulne natocenie tvaru - tvar sa otaca v smere hodinovych ruciciek vzdy o 90stupnov/ toto predstavuj hodnoty 1,2,3,4
void drawcube(int x, int y); // vykreslenie kocky so zadanm sradnc prvho bodu
void erasecube(int x, int y);
void drawhalfplus(int x, int y, int rot);
void erasehalfplus(int x, int y, int rot);
void drawbigL(int x, int y, int rot);
void erasebigL(int x, int y, int rot);
void drawsmallL(int x, int y, int rot);
void erasesmallL(int x, int y, int rot);
void drawstick(int x, int y, int rot);
void erasestick(int x, int y, int rot);
Shape(int x, int y, int t, int rot);
void godown(int tvar, int rot); // posunutie tvaru na hernej ploche doprava
void goleft(int tvar, int rot); // posunutie tvaru na hernej ploche dolava
void goright(int tvar, int rot); // posunutie tvaru na hernej ploche dole/urchlenie padania tvaru
void drawnextshape(int x, int y, int t, int rot); // iba nakrelenie, aky tvar bude nasledovat
void eraseshape(int t, int rot); // vymazanie tvaru po dopade/na hernu plochu sa dopadnute tvary potom vykresluju cez vector pole
};
#endif
| true |
17a02857714da63b3860ac1ea64ff3aa56853dd3 | C++ | Juanp-Romero/Programacion-J1_21_1 | /c++/Classes_abstractas.cpp | UTF-8 | 1,238 | 3 | 3 | [] | no_license | /******************************************************************************
Name: Clases Abstractas
Author: Juan Romero
Date: 14/09/2021
Purpose:
Usage: Plug and place
*******************************************************************************/
#include <stdio.h>
#include <iostream>
using namespace std;
#include <iomanip>
class computador{
public:
int ram = 4;
double rom = 10000;
virtual void boot_mode_seq() = 0; // Método abstracto / virtual
private:
string usuario = "admin";
string passw = "1234" ;
};
class Acer : public computador{
public:
string motherboard = "Asus Rock 580";
void boot_mode_seq() { // definición de clase abstraca
cout << "Reinicio + f12" <<endl;
};
private:
};
class Lenovo : public computador{
public:
string motherboard = "Asus Rock 580";
void boot_mode_seq() { // definición de clase abstraca
cout << "Reinicio + f8" <<endl;
};
private:
};
int main() {
setlocale(LC_ALL, "spanish");
Acer Acer505;
Acer505.boot_mode_seq();
//cout <<" El computador tiene una memoria rom de: "<< Acer505.rom <<endl;
Lenovo Yoga202;
Yoga202.boot_mode_seq(); // método polimorfismo (definición del )
return 0;
}
| true |
1a43c346539d9d3aece848d254743b7a94a7cd28 | C++ | CanCanZeng/ceres_solver_practice | /include/SLAM/frame_database.h | UTF-8 | 682 | 3.0625 | 3 | [] | no_license | #ifndef SLAM_FRAME_DATABASE_H
#define SLAM_FRAME_DATABASE_H
#include <iostream>
#include <vector>
namespace SLAM
{
class Frame;
class FrameDatabase
{
public:
~FrameDatabase();
void AddFrame(Frame* frame) { frames_.push_back(frame);}
// void EraseFrame(Frame* frame);
inline size_t size() {return frames_.size();}
Frame* operator[](size_t i) {return frames_[i];}
std::vector<Frame*> frames_;
};
FrameDatabase::~FrameDatabase()
{
for(size_t i=0, iEnd=frames_.size(); i<iEnd; ++i)
{
if(frames_[i] != nullptr)
{
delete frames_[i];
frames_[i] = nullptr;
}
}
}
}
#endif // SLAM_FRAME_DATABASE_H
| true |
011c68c847a95c9afc2f98ca15aa7596d43a88ef | C++ | duansuperman/Solve-OOP-exercises | /Bài tập hướng đối tượng/30.Template 2/Source.cpp | UTF-8 | 977 | 3.15625 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
int ucln(int a, int b);
class Phanso{
int tu, mau;
public:
void Nhap(){
cin >> tu >> mau;
}
void Xuat(){
if (mau < 0){
tu *= -1;
mau *= -1;
}
int uc = ucln(tu, mau);
tu /= uc;
mau /= uc;
cout << tu << "/" << mau << endl;
}
Phanso(){
tu = 0;
mau = 1;
}
friend istream & operator>>(istream &is, Phanso &a){
cin >> a.tu >> a.mau;
}
Phanso operator+(Phanso a){
Phanso tong;
tong.tu = tu*a.mau + mau*a.tu;
tong.mau = mau*a.mau;
return tong;
}
};
int ucln(int a, int b){
if (a < 0){
a *= -1;
}
if (b < 0){
b *= -1;
}
while (a != b){
if (a>b){
a -= b;
}
else{
b -= a;
}
}
return a;
}
int main(){
char k;
cin >> k;
if (k == 'a'){
int tong = 0;
int a;
while (cin >> a){
tong += a;
}
cout << tong << endl;
}
else{
Phanso tong;
Phanso a;
while (cin >> a){
tong = tong + a;
}
tong.Xuat();
}
//system("pause");
return 0;
} | true |