blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
6c1fa9f5e0a9bcb34ce8cb48277778391679f1c7
569c6b959101aea574f14ef7a2930b9a74b57103
/Best Time to Buy and Sell Stock II.cpp
879b79a52664f00ef9d747ebba95b4cf35f55d75
[]
no_license
sripadhse/Arrays
4519292d6e6bf1d0ae6da0e90fbea51263575d77
4a36c8ae18ae7da4ba6ce00ffe9757f9718fa460
refs/heads/main
2023-05-03T17:08:50.049663
2021-05-28T10:27:42
2021-05-28T10:27:42
371,664,097
0
0
null
null
null
null
UTF-8
C++
false
false
248
cpp
class Solution { public: int maxProfit(vector<int>& prices) { int result = 0; for (int i = 1; i < prices.size(); ++i) { result += max(0, prices[i] - prices[i - 1]); } return result; } };
[ "noreply@github.com" ]
noreply@github.com
d1d7a4134bd9ba608ae8529243447a250025160f
a0b56f17bbf3b57bcd57e75af8b7e319a43a71fa
/com/win32comext/adsi/src/PyIDsObjectPicker.cpp
5681b875f41086085bb353e536f8efaea9434e6b
[]
no_license
vmuriart/pywin32
be1848f0e4d0e938331c6e76a98260edaa9ba52c
57815f6b4a273ef522366c9308dbcd932812379c
refs/heads/master
2021-01-10T01:29:22.709507
2016-02-04T01:07:45
2017-03-13T03:14:34
50,973,124
1
2
null
null
null
null
UTF-8
C++
false
false
20,784
cpp
/* * FILE : C:\pywin32-220\pywin32-220\com\win32comext\adsi\src\PyIDsObjectPicker.cpp * * This file was automatically generated by : * Simplified Wrapper and Interface Generator (SWIG) * Version 1.1 (Patch 5) * * Portions Copyright (c) 1995-1998 * The University of Utah and The Regents of the University of California. * Permission is granted to distribute this file in any manner provided * this notice remains intact. * * Do not make changes to this file--changes will be lost! * */ #define SWIGCODE /* Implementation : PYTHON */ #define SWIGPYTHON #include <string.h> #include <stdlib.h> /*********************************************************************** * $Header$ * swig_lib/python/python.cfg * * This file contains coded needed to add variable linking to the * Python interpreter. C variables are added as a new kind of Python * datatype. * * Also contains supporting code for building python under Windows * and things like that. * * $Log$ * Revision 1.1 2000/03/14 23:34:06 mhammond * Needed to modify a standard Swig file to avoid the 'extern "C"' around Python.h (which gets upset when it tries to include whcar.h as part of the new Unicode patches) * ************************************************************************/ #include "Python.h" /* Definitions for Windows/Unix exporting */ #if defined(__WIN32__) # if defined(_MSC_VER) # define SWIGEXPORT(a,b) __declspec(dllexport) a b # else # if defined(__BORLANDC__) # define SWIGEXPORT(a,b) a _export b # else # define SWIGEXPORT(a,b) a b # endif # endif #else # define SWIGEXPORT(a,b) a b #endif #ifdef SWIG_GLOBAL #ifdef __cplusplus #define SWIGSTATIC extern "C" #else #define SWIGSTATIC #endif #endif #ifndef SWIGSTATIC #define SWIGSTATIC static #endif #ifdef NEED_SWIG_VARLINK typedef struct { char *name; PyObject *(*get_attr)(void); int (*set_attr)(PyObject *); } swig_globalvar; typedef struct swig_varlinkobject { PyObject_HEAD swig_globalvar **vars; int nvars; int maxvars; } swig_varlinkobject; /* ---------------------------------------------------------------------- swig_varlink_repr() Function for python repr method ---------------------------------------------------------------------- */ static PyObject * swig_varlink_repr(swig_varlinkobject *v) { v = v; return PyString_FromString("<Global variables>"); } /* --------------------------------------------------------------------- swig_varlink_print() Print out all of the global variable names --------------------------------------------------------------------- */ static int swig_varlink_print(swig_varlinkobject *v, FILE *fp, int flags) { int i = 0; flags = flags; fprintf(fp,"Global variables { "); while (v->vars[i]) { fprintf(fp,"%s", v->vars[i]->name); i++; if (v->vars[i]) fprintf(fp,", "); } fprintf(fp," }\n"); return 0; } /* -------------------------------------------------------------------- swig_varlink_getattr This function gets the value of a variable and returns it as a PyObject. In our case, we'll be looking at the datatype and converting into a number or string -------------------------------------------------------------------- */ static PyObject * swig_varlink_getattr(swig_varlinkobject *v, char *n) { int i = 0; char temp[128]; while (v->vars[i]) { if (strcmp(v->vars[i]->name,n) == 0) { return (*v->vars[i]->get_attr)(); } i++; } sprintf(temp,"C global variable %s not found.", n); PyErr_SetString(PyExc_NameError,temp); return NULL; } /* ------------------------------------------------------------------- swig_varlink_setattr() This function sets the value of a variable. ------------------------------------------------------------------- */ static int swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { char temp[128]; int i = 0; while (v->vars[i]) { if (strcmp(v->vars[i]->name,n) == 0) { return (*v->vars[i]->set_attr)(p); } i++; } sprintf(temp,"C global variable %s not found.", n); PyErr_SetString(PyExc_NameError,temp); return 1; } statichere PyTypeObject varlinktype = { /* PyObject_HEAD_INIT(&PyType_Type) Note : This doesn't work on some machines */ PyObject_HEAD_INIT(0) 0, "varlink", /* Type name */ sizeof(swig_varlinkobject), /* Basic size */ 0, /* Itemsize */ 0, /* Deallocator */ (printfunc) swig_varlink_print, /* Print */ (getattrfunc) swig_varlink_getattr, /* get attr */ (setattrfunc) swig_varlink_setattr, /* Set attr */ 0, /* tp_compare */ (reprfunc) swig_varlink_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_mapping*/ 0, /* tp_hash */ }; /* Create a variable linking object for use later */ SWIGSTATIC PyObject * SWIG_newvarlink(void) { swig_varlinkobject *result = 0; result = PyMem_NEW(swig_varlinkobject,1); varlinktype.ob_type = &PyType_Type; /* Patch varlinktype into a PyType */ result->ob_type = &varlinktype; /* _Py_NewReference(result); Does not seem to be necessary */ result->nvars = 0; result->maxvars = 64; result->vars = (swig_globalvar **) malloc(64*sizeof(swig_globalvar *)); result->vars[0] = 0; Py_XINCREF((PyObject *) result); return ((PyObject*) result); } SWIGSTATIC void SWIG_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { swig_varlinkobject *v; v= (swig_varlinkobject *) p; if (v->nvars >= v->maxvars -1) { v->maxvars = 2*v->maxvars; v->vars = (swig_globalvar **) realloc(v->vars,v->maxvars*sizeof(swig_globalvar *)); if (v->vars == NULL) { fprintf(stderr,"SWIG : Fatal error in initializing Python module.\n"); exit(1); } } v->vars[v->nvars] = (swig_globalvar *) malloc(sizeof(swig_globalvar)); v->vars[v->nvars]->name = (char *) malloc(strlen(name)+1); strcpy(v->vars[v->nvars]->name,name); v->vars[v->nvars]->get_attr = get_attr; v->vars[v->nvars]->set_attr = set_attr; v->nvars++; v->vars[v->nvars] = 0; } #else #define SWIG_newvarlink() Py_None #endif /* SWIG_NEED_VARLINK */ #ifdef NEED_SWIG_PTR /***************************************************************************** * $Header$ * * swigptr.swg * * This file contains supporting code for the SWIG run-time type checking * mechanism. The following functions are available : * * SWIG_RegisterMapping(char *origtype, char *newtype, void *(*cast)(void *)); * * Registers a new type-mapping with the type-checker. origtype is the * original datatype and newtype is an equivalent type. cast is optional * pointer to a function to cast pointer values between types (this * is typically used to cast pointers from derived classes to base classes in C++) * * SWIG_MakePtr(char *buffer, void *ptr, char *typestring); * * Makes a pointer string from a pointer and typestring. The result is returned * in buffer which is assumed to hold enough space for the result. * * char * SWIG_GetPtr(char *buffer, void **ptr, char *type) * * Gets a pointer value from a string. If there is a type-mismatch, returns * a character string to the received type. On success, returns NULL. * * * You can remap these functions by making a file called "swigptr.swg" in * your the same directory as the interface file you are wrapping. * * These functions are normally declared static, but this file can be * can be used in a multi-module environment by redefining the symbol * SWIGSTATIC. *****************************************************************************/ #include <stdlib.h> #ifdef SWIG_GLOBAL #ifdef __cplusplus #define SWIGSTATIC extern "C" #else #define SWIGSTATIC #endif #endif #ifndef SWIGSTATIC #define SWIGSTATIC static #endif /* SWIG pointer structure */ typedef struct SwigPtrType { char *name; /* Datatype name */ int len; /* Length (used for optimization) */ void *(*cast)(void *); /* Pointer casting function */ struct SwigPtrType *next; /* Linked list pointer */ } SwigPtrType; /* Pointer cache structure */ typedef struct { int stat; /* Status (valid) bit */ SwigPtrType *tp; /* Pointer to type structure */ char name[256]; /* Given datatype name */ char mapped[256]; /* Equivalent name */ } SwigCacheType; /* Some variables */ static int SwigPtrMax = 64; /* Max entries that can be currently held */ /* This value may be adjusted dynamically */ static int SwigPtrN = 0; /* Current number of entries */ static int SwigPtrSort = 0; /* Status flag indicating sort */ static int SwigStart[256]; /* Starting positions of types */ /* Pointer table */ static SwigPtrType *SwigPtrTable = 0; /* Table containing pointer equivalences */ /* Cached values */ #define SWIG_CACHESIZE 8 #define SWIG_CACHEMASK 0x7 static SwigCacheType SwigCache[SWIG_CACHESIZE]; static int SwigCacheIndex = 0; static int SwigLastCache = 0; /* Sort comparison function */ static int swigsort(const void *data1, const void *data2) { SwigPtrType *d1 = (SwigPtrType *) data1; SwigPtrType *d2 = (SwigPtrType *) data2; return strcmp(d1->name,d2->name); } /* Binary Search function */ static int swigcmp(const void *key, const void *data) { char *k = (char *) key; SwigPtrType *d = (SwigPtrType *) data; return strncmp(k,d->name,d->len); } /* Register a new datatype with the type-checker */ SWIGSTATIC void SWIG_RegisterMapping(char *origtype, char *newtype, void *(*cast)(void *)) { int i; SwigPtrType *t = 0,*t1; /* Allocate the pointer table if necessary */ if (!SwigPtrTable) { SwigPtrTable = (SwigPtrType *) malloc(SwigPtrMax*sizeof(SwigPtrType)); SwigPtrN = 0; } /* Grow the table */ if (SwigPtrN >= SwigPtrMax) { SwigPtrMax = 2*SwigPtrMax; SwigPtrTable = (SwigPtrType *) realloc((char *) SwigPtrTable,SwigPtrMax*sizeof(SwigPtrType)); } for (i = 0; i < SwigPtrN; i++) if (strcmp(SwigPtrTable[i].name,origtype) == 0) { t = &SwigPtrTable[i]; break; } if (!t) { t = &SwigPtrTable[SwigPtrN]; t->name = origtype; t->len = strlen(t->name); t->cast = 0; t->next = 0; SwigPtrN++; } /* Check for existing entry */ while (t->next) { if ((strcmp(t->name,newtype) == 0)) { if (cast) t->cast = cast; return; } t = t->next; } /* Now place entry (in sorted order) */ t1 = (SwigPtrType *) malloc(sizeof(SwigPtrType)); t1->name = newtype; t1->len = strlen(t1->name); t1->cast = cast; t1->next = 0; t->next = t1; SwigPtrSort = 0; } /* Make a pointer value string */ SWIGSTATIC void SWIG_MakePtr(char *_c, const void *_ptr, char *type) { static char _hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; unsigned long _p, _s; char _result[20], *_r; /* Note : a 64-bit hex number = 16 digits */ _r = _result; _p = (unsigned long) _ptr; if (_p > 0) { while (_p > 0) { _s = _p & 0xf; *(_r++) = _hex[_s]; _p = _p >> 4; } *_r = '_'; while (_r >= _result) *(_c++) = *(_r--); } else { strcpy (_c, "NULL"); } if (_ptr) strcpy (_c, type); } /* Define for backwards compatibility */ #define _swig_make_hex SWIG_MakePtr /* Function for getting a pointer value */ SWIGSTATIC char *SWIG_GetPtr(char *_c, void **ptr, char *_t) { unsigned long _p; char temp_type[256]; char *name; int i, len; SwigPtrType *sp,*tp; SwigCacheType *cache; int start, end; _p = 0; /* Pointer values must start with leading underscore */ if (*_c == '_') { _c++; /* Extract hex value from pointer */ while (*_c) { if ((*_c >= '0') && (*_c <= '9')) _p = (_p << 4) + (*_c - '0'); else if ((*_c >= 'a') && (*_c <= 'f')) _p = (_p << 4) + ((*_c - 'a') + 10); else break; _c++; } if (_t) { if (strcmp(_t,_c)) { if (!SwigPtrSort) { qsort((void *) SwigPtrTable, SwigPtrN, sizeof(SwigPtrType), swigsort); for (i = 0; i < 256; i++) { SwigStart[i] = SwigPtrN; } for (i = SwigPtrN-1; i >= 0; i--) { SwigStart[(int) (SwigPtrTable[i].name[1])] = i; } for (i = 255; i >= 1; i--) { if (SwigStart[i-1] > SwigStart[i]) SwigStart[i-1] = SwigStart[i]; } SwigPtrSort = 1; for (i = 0; i < SWIG_CACHESIZE; i++) SwigCache[i].stat = 0; } /* First check cache for matches. Uses last cache value as starting point */ cache = &SwigCache[SwigLastCache]; for (i = 0; i < SWIG_CACHESIZE; i++) { if (cache->stat) { if (strcmp(_t,cache->name) == 0) { if (strcmp(_c,cache->mapped) == 0) { cache->stat++; *ptr = (void *) _p; if (cache->tp->cast) *ptr = (*(cache->tp->cast))(*ptr); return (char *) 0; } } } SwigLastCache = (SwigLastCache+1) & SWIG_CACHEMASK; if (!SwigLastCache) cache = SwigCache; else cache++; } /* We have a type mismatch. Will have to look through our type mapping table to figure out whether or not we can accept this datatype */ start = SwigStart[(int) _t[1]]; end = SwigStart[(int) _t[1]+1]; sp = &SwigPtrTable[start]; while (start < end) { if (swigcmp(_t,sp) == 0) break; sp++; start++; } if (start >= end) sp = 0; /* Try to find a match for this */ if (sp) { while (swigcmp(_t,sp) == 0) { name = sp->name; len = sp->len; tp = sp->next; /* Try to find entry for our given datatype */ while(tp) { if (tp->len >= 255) { return _c; } strncpy(temp_type,tp->name,255); strncat(temp_type,_t+len,255-tp->len); if (strcmp(_c,temp_type) == 0) { strcpy(SwigCache[SwigCacheIndex].mapped,_c); strcpy(SwigCache[SwigCacheIndex].name,_t); SwigCache[SwigCacheIndex].stat = 1; SwigCache[SwigCacheIndex].tp = tp; SwigCacheIndex = SwigCacheIndex & SWIG_CACHEMASK; /* Get pointer value */ *ptr = (void *) _p; if (tp->cast) *ptr = (*(tp->cast))(*ptr); return (char *) 0; } tp = tp->next; } sp++; /* Hmmm. Didn't find it this time */ } } /* Didn't find any sort of match for this data. Get the pointer value and return the received type */ *ptr = (void *) _p; return _c; } else { /* Found a match on the first try. Return pointer value */ *ptr = (void *) _p; return (char *) 0; } } else { /* No type specified. Good luck */ *ptr = (void *) _p; return (char *) 0; } } else { if (strcmp (_c, "NULL") == 0) { *ptr = (void *) 0; return (char *) 0; } *ptr = (void *) 0; return _c; } } /* Compatibility mode */ #define _swig_get_hex SWIG_GetPtr #else #define SWIG_RegisterMapping(a,b,c) #endif // NEED_SWIG_PTR static PyObject* t_output_helper(PyObject* target, PyObject* o) { PyObject* o2; PyObject* o3; if (!target) { target = o; } else if (target == Py_None) { Py_DECREF(Py_None); target = o; } else { if (!PyTuple_Check(target)) { o2 = target; target = PyTuple_New(1); PyTuple_SetItem(target, 0, o2); } o3 = PyTuple_New(1); PyTuple_SetItem(o3, 0, o); o2 = target; target = PySequence_Concat(o2, o3); Py_DECREF(o2); Py_DECREF(o3); } return target; } #include "PyWinTypes.h" #ifdef NEED_PYWINOBJECTS_H #include "PyWinObjects.h" #endif #include "tchar.h" typedef BOOL BOOLAPI; typedef DWORD DWORDAPI; #define PyHANDLE HANDLE // Use a #define so we can undef it later if we need the true defn. //typedef HANDLE PyHKEY; #include "PythonCOM.h" #define SWIG_PYTHONCOM typedef long HRESULT_KEEP; typedef long HRESULT_KEEP_INFO; #define MAKE_OUTPUT_INTERFACE(source, target, iid) \ { \ PyObject *o; \ o = PyCom_PyObjectFromIUnknown(*source, iid, FALSE /* bAddRef */); \ if (target==NULL) \ target = o; \ else if (target == Py_None) { /* has been incref'd already!*/ \ Py_DECREF(Py_None); \ target = o; \ } else { \ if (!PyList_Check(target)) { \ PyObject *o2 = target; \ target = PyList_New(0); \ PyList_Append(target,o2); \ Py_XDECREF(o2); \ } \ PyList_Append(target,o); \ Py_XDECREF(o); \ } \ } #include "pyadsiutil.h" extern PyObject *OleSetADSIError(HRESULT hr, IUnknown *pUnk, REFIID iid); #include "Objsel.h" #include "PyIDsObjectPicker.h" extern BOOL PyObject_AsDSOP_SCOPE_INIT_INFOs(PyObject *ob, DSOP_SCOPE_INIT_INFO**p, ULONG *n); #define SWIG_THIS_IID IID_IDsObjectPicker PyIDsObjectPicker::PyIDsObjectPicker(IUnknown *pDisp) : PyIUnknown(pDisp) { ob_type = &type; } PyIDsObjectPicker::~PyIDsObjectPicker() { } IDsObjectPicker *PyIDsObjectPicker::GetI(PyObject *self) { return (IDsObjectPicker *)PyIUnknown::GetI(self); } // @pyswig |Initialize|Initializes the IDsObjectPicker interface with information about the scopes, filters, and options used by the object picker dialog box. PyObject *PyIDsObjectPicker::Initialize(PyObject *self, PyObject *args) { HRESULT hr; PyObject *ret; PyObject *obTargetComputer; PyObject *obScopeInfos; IDsObjectPicker *_swig_self; if ((_swig_self=GetI(self))==NULL) return NULL; PyObject *obAttributeNames = Py_None; DSOP_INIT_INFO ii; memset(&ii, sizeof(ii), 0); ii.cbSize = sizeof(ii); if (!PyArg_ParseTuple(args, "OO|lO:Initialize", &obTargetComputer, // @pyparm <o PyUnicode>|targetComputer|| &obScopeInfos, // @pyparm <o PyDSOP_SCOPE_INIT_INFOs>|scopeInfos|| &ii.flOptions, // @pyparm int|options|0| &obAttributeNames)) // @pyparm [<o PyUnicode>, ...]|attrNames|None| return NULL; if (!PyWinObject_AsWCHAR(obTargetComputer, (WCHAR **)&ii.pwzTargetComputer, TRUE)) goto done; if (!PyObject_AsDSOP_SCOPE_INIT_INFOs(obScopeInfos, &ii.aDsScopeInfos, &ii.cDsScopeInfos)) goto done; if (!PyWinObject_AsWCHARArray(obAttributeNames, (WCHAR ***)&ii.apwzAttributeNames, &ii.cAttributesToFetch, TRUE)) goto done; Py_BEGIN_ALLOW_THREADS hr = _swig_self->Initialize(&ii); Py_END_ALLOW_THREADS if (FAILED(hr)) PyCom_BuildPyException(hr, _swig_self, IID_IDsObjectPicker); else { ret = Py_None; Py_INCREF(ret); } done: PyWinObject_FreeWCHAR((WCHAR *)ii.pwzTargetComputer); PyWinObject_FreeWCHARArray((WCHAR **)ii.apwzAttributeNames, ii.cAttributesToFetch); return ret; } PyObject *PyIDsObjectPicker::InvokeDialog(PyObject *self, PyObject *args) { PyObject * _resultobj; HRESULT _result; HWND _arg0; IDataObject ** _arg1; IDataObject * temp; PyObject * _obj0 = 0; { _arg1 = &temp; } IDsObjectPicker *_swig_self; if ((_swig_self=GetI(self))==NULL) return NULL; if(!PyArg_ParseTuple(args,"O:InvokeDialog",&_obj0)) return NULL; { if (!PyWinObject_AsHANDLE(_obj0, (HANDLE *)&_arg0)) return NULL; } { Py_BEGIN_ALLOW_THREADS _result = (HRESULT )_swig_self->InvokeDialog(_arg0,_arg1); Py_END_ALLOW_THREADS if (FAILED(_result)) { #ifndef SWIG_THIS_IID #error This interface must have SWIG_THIS_IID defined! #endif return OleSetADSIError(_result, _swig_self, SWIG_THIS_IID); } }{ _resultobj = Py_None; Py_INCREF(Py_None); } { MAKE_OUTPUT_INTERFACE(_arg1, _resultobj, IID_IDataObject) } return _resultobj; } static PyMethodDef IDsObjectPickerMethods[] = { { "InvokeDialog", PyIDsObjectPicker::InvokeDialog, 1 }, { "Initialize", PyIDsObjectPicker::Initialize, 1 }, { NULL, NULL } }; PyComTypeObject PyIDsObjectPicker::type("PyIDsObjectPicker", &PyIUnknown::type, sizeof(PyIDsObjectPicker), IDsObjectPickerMethods, GET_PYCOM_CTOR(PyIDsObjectPicker)); #ifndef SWIG_PYTHONCOM /* This code only valid if non COM SWIG builds */ #ifndef PYCOM_EXPORT PyDict_SetItemString(d,"UNICODE", PyInt_FromLong( #ifdef UNICODE 1 #else 0 #endif )); #endif PyWinGlobals_Ensure(); PyDict_SetItemString(d, "error", PyWinExc_ApiError); #endif SWIG_PYTHONCOM
[ "victor.m.uriarte@intel.com" ]
victor.m.uriarte@intel.com
7acedda9b0204b6a5c927898476fbb32a0ae9ba1
c99e20650b5c178e229dce2a796d74532e68647b
/15651.cpp
afcef1d29b6d6fed7549f75318345e0cf9fce90c
[ "Apache-2.0" ]
permissive
Wookhwang/BaekJoon-
8c94d58240b54c90f5e51c387f89300b7b6fb955
1dfc9783a70318b5c4a6fe796878f767b30af3ed
refs/heads/master
2020-11-30T12:26:27.596307
2020-04-27T17:23:09
2020-04-27T17:23:09
230,396,717
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
630
cpp
/* BaekJoon 15651 Problem name : N°ú M(3) category : back tracking */ #include <iostream> #include <vector> #define endl '\n' using namespace std; bool arr[10]; int N; int M; vector<int> V; void dfs(int count) { if (count == M) { for (int i = 0; i < V.size(); i++) { cout << V[i] << " "; } cout << endl; return; } for (int i = 1; i <= N; i++) { arr[i] = true; V.push_back(i); dfs(count + 1); arr[i] = false; V.pop_back(); } } int main() { cin.tie(NULL); cout.tie(NULL); ios_base::sync_with_stdio(false); cin >> N >> M; dfs(0); return 0; }
[ "noreply@github.com" ]
noreply@github.com
87a08da1a3ce77c97080962aa97dac96449b91fd
ac35049e5a491a3fa4c3b56343096a4115cf5c20
/src/core/types/shared_haplotype.hpp
cbf05fde00152f63a19af77a2b637a37a1df98db
[ "MIT" ]
permissive
iamh2o/octopus
c9123281b4906e178d406b9aab187bafe6167a71
09ebd28945026556e77d73f1dcd8f0212265183c
refs/heads/develop
2023-07-09T08:46:42.934415
2021-07-30T14:01:37
2021-07-30T14:01:37
395,281,376
0
0
MIT
2021-08-12T10:31:27
2021-08-12T10:31:26
null
UTF-8
C++
false
false
3,983
hpp
// Copyright (c) 2015-2021 Daniel Cooke // Use of this source code is governed by the MIT license that can be found in the LICENSE file. #ifndef shared_haplotype_hpp #define shared_haplotype_hpp #include <memory> #include <utility> #include <type_traits> #include <functional> #include "concepts/mappable.hpp" #include "concepts/comparable.hpp" #include "haplotype.hpp" namespace octopus { class SharedHaplotype : public Mappable<SharedHaplotype> , public Comparable<SharedHaplotype> { public: using MappingDomain = Haplotype::MappingDomain; SharedHaplotype() = delete; SharedHaplotype(const Haplotype& haplotype) : haplotype_ {std::make_shared<Haplotype>(haplotype)} {} SharedHaplotype(Haplotype&& haplotype) : haplotype_ {std::make_shared<Haplotype>(std::move(haplotype))} {} SharedHaplotype(const std::shared_ptr<Haplotype>& haplotype) : haplotype_ {haplotype} {} SharedHaplotype(const SharedHaplotype&) = default; SharedHaplotype& operator=(const SharedHaplotype&) = default; SharedHaplotype(SharedHaplotype&&) = default; SharedHaplotype& operator=(SharedHaplotype&&) = default; ~SharedHaplotype() = default; Haplotype& haplotype() noexcept { return *haplotype_; } const Haplotype& haplotype() const noexcept { return *haplotype_; } operator Haplotype&() noexcept { return haplotype(); } operator const Haplotype&() const noexcept { return haplotype(); } decltype(auto) mapped_region() const noexcept { return haplotype().mapped_region(); } decltype(auto) contains(const ContigAllele& allele) const { return haplotype().contains(allele); } decltype(auto) contains(const Allele& allele) const { return haplotype().contains(allele); } decltype(auto) includes(const ContigAllele& allele) const { return haplotype().includes(allele); } decltype(auto) includes(const Allele& allele) const { return haplotype().includes(allele); } decltype(auto) sequence(const ContigRegion& region) const { return haplotype().sequence(region); } decltype(auto) sequence(const GenomicRegion& region) const { return haplotype().sequence(region); } decltype(auto) sequence() const noexcept { return haplotype().sequence(); } decltype(auto) sequence_size(const ContigRegion& region) const { return haplotype().sequence_size(region); } decltype(auto) sequence_size(const GenomicRegion& region) const { return haplotype().sequence_size(region); } decltype(auto) difference(const SharedHaplotype& other) const { return haplotype().difference(other.haplotype()); } decltype(auto) cigar() const { return haplotype().cigar(); } friend bool operator==(const SharedHaplotype& lhs, const SharedHaplotype& rhs) noexcept { return lhs.haplotype_ == rhs.haplotype_ || lhs.haplotype() == rhs.haplotype(); } private: std::shared_ptr<Haplotype> haplotype_; }; inline bool operator<(const SharedHaplotype& lhs, const SharedHaplotype& rhs) { return lhs.haplotype() < rhs.haplotype(); } template <typename MappableType, typename HaplotypeType> std::enable_if_t<std::is_same<MappableType, SharedHaplotype>::value, SharedHaplotype> copy(const HaplotypeType& haplotype, const GenomicRegion& region) { return {std::make_shared<Haplotype>(copy<Haplotype>(haplotype.haplotype(), region))}; } } // namespace octopus namespace std { template <> struct hash<octopus::SharedHaplotype> { size_t operator()(const octopus::SharedHaplotype& haplotpe) const { return hash<octopus::Haplotype>{}(haplotpe.haplotype()); } }; } // namespace std namespace boost { template <> struct hash<octopus::SharedHaplotype> : std::unary_function<octopus::SharedHaplotype, std::size_t> { std::size_t operator()(const octopus::SharedHaplotype& h) const { return std::hash<octopus::SharedHaplotype>{}(h); } }; } // namespace boost #endif
[ "dcooke@well.ox.ac.uk" ]
dcooke@well.ox.ac.uk
dfea87cc7ab98bef890d792286102296bd0c8b77
cecd8cb33c5413c3b7b13471e853043e1f08ac4a
/bottom_view.cpp
9d5ecf1a3bf2ff80fc534e9277be8d86ecdf2161
[]
no_license
Mahinder4519/Third-PR
c5e414ad077b48c40d9030111cbcc3166cb65321
d2c3de6fbfa6c5e374923a4391ce4e941ee318f7
refs/heads/main
2023-08-31T21:34:37.795625
2021-10-26T20:21:46
2021-10-26T20:21:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,207
cpp
#include<bits/stdc++.h> using namespace std; class node { public: int data; node *left; node *right; node(int d) { data=d; left=NULL; right=NULL; } }; multimap<int, int> m; void getLevelOrder(node *root){ int n=0; queue<pair<node *,int>> q; q.push({root,0}); while(!q.empty()){ pair<node *,int> curr=q.front(); q.pop(); m.insert({curr.second,curr.first->data}); if(curr.first->left){ q.push({curr.first->left,curr.second-1}); } if(curr.first->right){ q.push({curr.first->right,curr.second+1}); } } } void bottomView(struct node *root) { if(root) getLevelOrder(root); auto it=m.begin(); it++; for(auto itr=m.begin();itr!=m.end();itr++) { if(it->first != itr->first) cout<<(itr->second)<<" "; it++; } m.clear(); } int main() { node *root=new node(30); root->left=new node(20); root->right=new node(50); root->left->left=new node(10); root->right->left=new node(40); root->right->right=new node(60); root->right->right->right=new node(70); bottomView(root); return 0; }
[ "noreply@github.com" ]
noreply@github.com
743b40b9de993b89b9c37bbcc5473f44ea1b04e3
eecdb1d4ea164abae696ed72a02ee1e6e483ae36
/src/Shader.cpp
ce4816341c8fe5be77266b67c59cbe9837c8c8b7
[]
no_license
pauloalexandreanjos/ogl-screenshooter
3b1e68933fc058ec8b884b510c80352702809fc2
6af9e2e731f86738db1e1e30e7b792caf3bf7e8b
refs/heads/master
2023-03-02T06:39:50.403149
2021-02-06T16:57:25
2021-02-06T16:57:25
324,896,558
0
0
null
null
null
null
UTF-8
C++
false
false
3,117
cpp
#include "Shader.h" #include <iostream> #include <string> Shader::Shader(std::string vertexShaderFile, std::string fragmentShaderFile) { unsigned int vertexShader = this->createShader( vertexShaderFile, GL_VERTEX_SHADER); unsigned int fragmentShader = this->createShader( fragmentShaderFile, GL_FRAGMENT_SHADER); std::cout << "Criou os shaders" << std::endl; this->shaderID = glCreateProgram(); glAttachShader(this->shaderID, vertexShader); glAttachShader(this->shaderID, fragmentShader); glLinkProgram(this->shaderID); int success; GLchar infoLog[512]; glGetProgramiv(this->shaderID, GL_LINK_STATUS, &success); if(!success) { glGetProgramInfoLog(this->shaderID, 512, NULL, infoLog); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); std::cout << "Deletou os shaders " << std::endl; } std::string Shader::loadShader(std::string shaderName) { std::ifstream file; std::cout << "Tentando abrir o arquivo " << shaderName << std::endl; file.open(shaderName, std::fstream::in | std::ifstream::binary); if (!file.is_open()) { std::cout << "Arquivo não abriu" << std::endl; return nullptr; } /*file.seekg(0, file.end); int length = file.tellg(); file.seekg(0, file.beg); fragmentShaderSource = new char[length+1]; file.read(fragmentShaderSource, length); fragmentShaderSource[length] = '\0';*/ std::stringstream source; source << file.rdbuf(); file.close(); std::cout << "Fechou o arquivo" << std::endl; return source.str(); } unsigned int Shader::createShader(std::string shaderSourceFile, GLenum shaderType) { unsigned int shaderId = glCreateShader(shaderType); // GL_VERTEX_SHADER | GL_FRAGMENT_SHADER std::cout << "Compilando o shader >> " << shaderId << " <<" << std::endl; std::string shaderSource = loadShader(shaderSourceFile); const char *shaderSourceCode = shaderSource.c_str(); glShaderSource(shaderId, 1, &shaderSourceCode, NULL); glCompileShader(shaderId); int success; GLchar infoLog[512]; glGetShaderiv(shaderId, GL_COMPILE_STATUS, &success); if(!success) { glGetShaderInfoLog(shaderId, 512, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } else { std::cout << "Shader >> " << shaderId << " << compilado com sucesso!" << std::endl; } return shaderId; } void Shader::use() { glUseProgram(this->shaderID); } void Shader::setBool(const std::string &name, bool value) const { glUniform1i(glGetUniformLocation(this->shaderID, name.c_str()), (int)value); } void Shader::setInt(const std::string &name, int value) const { glUniform1i(glGetUniformLocation(this->shaderID, name.c_str()), value); } void Shader::setFloat(const std::string &name, float value) const { glUniform1f(glGetUniformLocation(this->shaderID, name.c_str()), value); }
[ "paulo.alexandre.anjos@gmail.com" ]
paulo.alexandre.anjos@gmail.com
18105f956e2373c493928a9332f5c4f390da8121
a967db628a6b214f56eeb63a2c5502e6435ea28e
/CPP_3/EWeek4_solution2017/Assignment4Code/BrightnessDecorator.h
85c90bb887551111df7ac4286edd40144e2d0755
[]
no_license
claytonjwong/cpp-UW
09a183412e99ff04a0584c60bd70ba0fc3e47837
da6fdcae4a8d1e53b3b8398ef6c89ceb66b02869
refs/heads/master
2020-05-17T02:28:39.292059
2019-04-26T00:24:40
2019-04-26T00:24:40
183,454,522
1
0
null
null
null
null
UTF-8
C++
false
false
477
h
#pragma once #include "BitmapIteratorDecorator.h" #include "Byte.h" namespace BitmapGraphics { class BrightnessDecorator : public BitmapIteratorDecorator { public: BrightnessDecorator( HBitmapIterator originalIterator, const int& brightnessAdjustment); void setBrightnessAdjustment(int brightnessAdjustment); int getBrightnessAdjustment() const; Color getColor() const override; private: int myBrightnessAdjustment; }; }
[ "claytonjwong@gmail.com" ]
claytonjwong@gmail.com
6cdffea21923925a710d362e91140e4a9ecc9a45
4a4c1dcd29abe87745bb30adfbdf5205eb39f3b5
/havok/Source/Common/Base/Math/Vector/Mx/hkMxVector_AVX.inl
ad032de73fe5143a1500f92e637dcc59bd5f5a4b
[]
no_license
Hengle/ThirdParty
e7c4d794088712ec88bcea28a27f3acb71b6208c
a7ebed87d43e9cc58ec50836a2cc747bc539fd93
refs/heads/master
2023-03-16T04:24:59.905476
2014-01-20T16:54:54
2014-01-20T16:54:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
89,679
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2012 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #if defined(HK_REAL_IS_DOUBLE) || (HK_SSE_VERSION < 0x50) #error This implementation is for 32-Bit float with AVX SIMD instruction set #endif #include <Common/Base/Math/Vector/Mx/hkMxCommon_AVX.inl> #define MXV_NO_OPERANDS(METHOD, OP) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##H(__m256* v) { METHOD##H<I-1>(v); v[I-1] = OP(); } \ template <> HK_FORCE_INLINE void METHOD##H<1>(__m256* v) { v[0] = OP(); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD() { hkMxVector_Implementation::METHOD##H<((M+1)>>1)>(m_vec.v); } #define MXV_OP_MXVECTOR(METHOD, OP) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##MXV_MXV_MXV(__m256* v, const __m256* v0) { METHOD##MXV_MXV_MXV<I-1>(v, v0); v[I-1] = OP(v[I-1],v0[I-1]); } \ template <> HK_FORCE_INLINE void METHOD##MXV_MXV_MXV<1>(__m256* v, const __m256* v0) { v[0] = OP(v[0],v0[0]); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxVectorParameter m) { hkMxVector_Implementation::METHOD##MXV_MXV_MXV<((M+1)>>1)>(m_vec.v, m.m_vec.v); } #define MXV_OP_MXVECTOR_MXVECTOR(METHOD, OP) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##H(__m256* v, const __m256* v0, const __m256* v1) { METHOD##H<I-1>(v, v0, v1); v[I-1] = OP(v0[I-1], v1[I-1]); } \ template <> HK_FORCE_INLINE void METHOD##H<1>(__m256* v, const __m256* v0, const __m256* v1) { v[0] = OP(v0[0], v1[0]); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxVectorParameter v0, hkMxVectorParameter v1) { hkMxVector_Implementation::METHOD##H<((M+1)>>1)>(m_vec.v, v0.m_vec.v, v1.m_vec.v); } #define MXV_OP_MXVECTOR_MXVECTOR_MXVECTOR(METHOD, OP1, OP2) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##H(__m256* v, const __m256* v0, const __m256* v1, const __m256* v2) { METHOD##H<I-1>(v, v0, v1, v2); v[I-1] = OP1(v0[I-1], OP2(v1[I-1], v2[I-1])); } \ template <> HK_FORCE_INLINE void METHOD##H<1>(__m256* v, const __m256* v0, const __m256* v1, const __m256* v2) { v[0] = OP1(v0[0], OP2(v1[0], v2[0])); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxVectorParameter v0, hkMxVectorParameter v1, hkMxVectorParameter v2) { hkMxVector_Implementation::METHOD##H<((M+1)>>1)>(m_vec.v, v0.m_vec.v, v1.m_vec.v, v2.m_vec.v); } #define MXV_OP_MXVECTOR_MXVECTOR_MXSINGLE(METHOD, OP1, OP2) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##S2H(__m256* v, const __m256* v0, const __m256* v1, const __m256& v2) { METHOD##S2H<I-1>(v, v0, v1, v2); v[I-1] = OP1(v0[I-1], OP2(v1[I-1], v2)); } \ template <> HK_FORCE_INLINE void METHOD##S2H<1>(__m256* v, const __m256* v0, const __m256* v1, const __m256& v2) { v[0] = OP1(v0[0], OP2(v1[0], v2)); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxVectorParameter v0, hkMxVectorParameter v1, hkMxSingleParameter v2) { hkMxVector_Implementation::METHOD##S2H<((M+1)>>1)>(m_vec.v, v0.m_vec.v, v1.m_vec.v, v2.m_single.s); } #define MXV_OP_MXVECTOR_MXVECTOR_MXREAL(METHOD, OP1, OP2) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##HVR(__m256* v, const __m256* v0, const __m256* v1, const __m256* v2) { METHOD##HVR<I-1>(v, v0, v1, v2); v[I-1] = OP1(v0[I-1], OP2(v1[I-1], v2[I-1])); } \ template <> HK_FORCE_INLINE void METHOD##HVR<1>(__m256* v, const __m256* v0, const __m256* v1, const __m256* v2) { v[0] = OP1(v0[0], OP2(v1[0], v2[0])); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxVectorParameter v0, hkMxVectorParameter v1, hkMxRealParameter v2) { hkMxVector_Implementation::METHOD##HVR<((M+1)>>1)>(m_vec.v, v0.m_vec.v, v1.m_vec.v, v2.m_real.r); } #define MXV_OP_MXVECTOR_MXVECTOR_SELF(METHOD, OP1, OP2) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##HSE(__m256* v, const __m256* v0, const __m256* v1) { METHOD##HSE<I-1>(v, v0, v1); v[I-1] = OP1(v[I-1], OP2(v0[I-1], v1[I-1])); } \ template <> HK_FORCE_INLINE void METHOD##HSE<1>(__m256* v, const __m256* v0, const __m256* v1) { v[0] = OP1(v[0], OP2(v0[0], v1[0])); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxVectorParameter v0, hkMxVectorParameter v1) { hkMxVector_Implementation::METHOD##HSE<((M+1)>>1)>(m_vec.v, v0.m_vec.v, v1.m_vec.v); } #define MXV_OP_MXVECTOR_MXSINGLE_SELF(METHOD, OP1, OP2) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##HSES(__m256* v, const __m256* v0, const __m256& v1) { METHOD##HSES<I-1>(v, v0, v1); v[I-1] = OP1(v[I-1], OP2(v0[I-1], v1)); } \ template <> HK_FORCE_INLINE void METHOD##HSES<1>(__m256* v, const __m256* v0, const __m256& v1) { v[0] = OP1(v[0], OP2(v0[0], v1)); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxVectorParameter v0, hkMxSingleParameter v1) { hkMxVector_Implementation::METHOD##HSES<((M+1)>>1)>(m_vec.v, v0.m_vec.v, v1.m_single.s); } #define MXV_OP_MXREAL_MXVECTOR_SELF(METHOD, OP1, OP2) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##HSE2(__m256* v, const __m256* v0, const __m256* v1) { METHOD##HSE2<I-1>(v, v0, v1); v[I-1] = OP1(v[I-1], OP2(v0[I-1], v1[I-1])); } \ template <> HK_FORCE_INLINE void METHOD##HSE2<1>(__m256* v, const __m256* v0, const __m256* v1) { v[0] = OP1(v[0], OP2(v0[0], v1[0])); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxRealParameter v0, hkMxVectorParameter v1) { hkMxVector_Implementation::METHOD##HSE2<((M+1)>>1)>(m_vec.v, v0.m_real.r, v1.m_vec.v); } #define MXV_OP_MXVECTOR_MXSINGLE_MXREAL(METHOD, OP1, OP2) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##S2SR(__m256* v, const __m256* v0, const __m256& v1, const __m256* v2) { METHOD##S2SR<I-1>(v, v0, v1, v2); v[I-1] = OP1(v0[I-1], OP2(v1, v2[I-1])); } \ template <> HK_FORCE_INLINE void METHOD##S2SR<1>(__m256* v, const __m256* v0, const __m256& v1, const __m256* v2) { v[0] = OP1(v0[0], OP2(v1, v2[0])); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxVectorParameter v0, hkMxSingleParameter v1, hkMxRealParameter v2) { hkMxVector_Implementation::METHOD##S2SR<((M+1)>>1)>(m_vec.v, v0.m_vec.v, v1.m_single.s, v2.m_real.r); } #define MXV_OP_MXREAL(METHOD, OP) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##SHR(__m256* v, const __m256* v0) { METHOD##SHR<I-1>(v, v0); v[I-1] = OP(v[I-1],v0[I-1]); } \ template <> HK_FORCE_INLINE void METHOD##SHR<1>(__m256* v, const __m256* v0) { v[0] = OP(v[0],v0[0]); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxRealParameter s) { hkMxVector_Implementation::METHOD##SHR<((M+1)>>1)>(m_vec.v, s.m_real.r); } #define MXV_OP_MXSINGLE(METHOD, OP) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##SH(__m256* v, const __m256& v0) {METHOD##SH<I-1>(v, v0); v[I-1] = OP(v[I-1],v0); } \ template <> HK_FORCE_INLINE void METHOD##SH<1>(__m256* v, const __m256& v0) { v[0] = OP(v[0],v0); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxSingleParameter s) { hkMxVector_Implementation::METHOD##SH<((M+1)>>1)>(m_vec.v, s.m_single.s); } #define MXV_OP_MXREAL_MXVECTOR(METHOD, OP) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##RVH(__m256* v, const __m256* v0, const __m256* v1) { METHOD##RVH<I-1>(v, v0, v1); v[I-1] = OP(v0[I-1], v1[I-1]); } \ template <> HK_FORCE_INLINE void METHOD##RVH<1>(__m256* v, const __m256* v0, const __m256* v1) { v[0] = OP(v0[0], v1[0]); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxRealParameter r, hkMxVectorParameter v0 ) { hkMxVector_Implementation::METHOD##RVH<((M+1)>>1)>(m_vec.v, r.m_real.r, v0.m_vec.v ); } #define MXV_OP_MXVECTOR_MXSINGLE(METHOD, OP) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##SH(__m256* v, const __m256* v0, const __m256& v1) { METHOD##SH<I-1>(v, v0, v1); v[I-1] = OP(v0[I-1], v1); } \ template <> HK_FORCE_INLINE void METHOD##SH<1>(__m256* v, const __m256* v0, const __m256& v1) { v[0] = OP(v0[0], v1); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxVectorParameter v, hkMxSingleParameter s) { hkMxVector_Implementation::METHOD##SH<((M+1)>>1)>(m_vec.v, v.m_vec.v, s.m_single.s); } #define MXV_OP_MXSINGLE_MXSINGLE(METHOD, OP1, OP2) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##MX_SS(__m256* v, const __m256& v0) { METHOD##MX_SS<I-1>(v, v0); v[I-1] = OP1(v[I-1], v0); } \ template <> HK_FORCE_INLINE void METHOD##MX_SS<1>( __m256* v, const __m256& v0) { v[0] = OP1(v[0], v0); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxSingleParameter s0, hkMxSingleParameter s1) { const __m256 s = OP2(s0.m_single.s, s1.m_single.s); hkMxVector_Implementation::METHOD##MX_SS<((M+1)>>1)>(m_vec.v, s); } #define MXV_OP_MXSINGLE_MXVECTOR(METHOD, OP) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##RSH(__m256* v, const __m256& v1, const __m256* v0) { METHOD##RSH<I-1>(v, v1, v0); v[I-1] = OP(v1, v0[I-1]); } \ template <> HK_FORCE_INLINE void METHOD##RSH<1>(__m256* v, const __m256& v1, const __m256* v0) { v[0] = OP(v1, v0[0]); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxSingleParameter s, hkMxVectorParameter v) { hkMxVector_Implementation::METHOD##RSH<((M+1)>>1)>(m_vec.v, s.m_single.s, v.m_vec.v); } #define MXV_COMPARE(METHOD, OP) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##OP##CH(const __m256* v0, const __m256* v1, __m256* mask) { \ METHOD##OP##CH<I-1>(v0,v1,mask); \ /*mask[I-1] = _mm256_cmp_ps(v0[I-1],v1[I-1],OP);*/ \ /* workaround VS2010 assembler bug */ \ const __m256 masklow = _mm256_cmp_ps(v0[I-1], v1[I-1], OP); \ const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(v0[I-1],v0[I-1], _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_permute2f128_ps(v1[I-1],v1[I-1], _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), OP); \ mask[I-1] = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); } \ template <> HK_FORCE_INLINE void METHOD##OP##CH<1>(const __m256* v0, const __m256* v1, __m256* mask) { \ /*mask[0] = _mm256_cmp_ps(v0[0],v1[0],OP);*/ \ /* workaround VS2010 assembler bug */ \ const __m256 masklow = _mm256_cmp_ps(v0[0], v1[0], OP); \ const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(v0[0],v0[0], _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_permute2f128_ps(v1[0],v1[0], _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), OP); \ mask[0] = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxVectorParameter v1, hkMxMask<M>& mask) const { hkMxVector_Implementation::METHOD##OP##CH<((M+1)>>1)>(m_vec.v, v1.m_vec.v, mask.m_comp.c); } #define MXV_COMPARE_SINGLE(METHOD, OP) \ namespace hkMxVector_Implementation { \ template <int I> HK_FORCE_INLINE void METHOD##OP##CHS(const __m256* v0, const __m256& v1, __m256* mask) { \ METHOD##OP##CHS<I-1>(v0,v1,mask); \ /*mask[I-1] = _mm256_cmp_ps(v0[I-1],v1,OP);*/ \ /* workaround VS2010 assembler bug */ \ const __m256 masklow = _mm256_cmp_ps(v0[I-1], v1, OP); \ const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(v0[I-1],v0[I-1], _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_permute2f128_ps(v1,v1, _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), OP); \ mask[I-1] = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); } \ template <> HK_FORCE_INLINE void METHOD##OP##CHS<1>(const __m256* v0, const __m256& v1, __m256* mask) { \ /*mask[0] = _mm256_cmp_ps(v0[0],v1,OP);*/ \ /* workaround VS2010 assembler bug */ \ const __m256 masklow = _mm256_cmp_ps(v0[0], v1, OP); \ const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(v0[0],v0[0], _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_permute2f128_ps(v1,v1, _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), OP); \ mask[0] = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); } \ } \ template <int M> HK_FORCE_INLINE void hkMxVector<M>::METHOD(hkMxSingleParameter v1, hkMxMask<M>& mask) const { hkMxVector_Implementation::METHOD##OP##CHS<((M+1)>>1)>(m_vec.v, v1.m_single.s, mask.m_comp.c); } #ifndef HK_DISABLE_MATH_CONSTRUCTORS namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void constructH(__m256* v, const __m256& v0) { constructH<I-1>(v, v0); v[I-1] = v0; } template <> HK_FORCE_INLINE void constructH<1>(__m256* v, const __m256& v0) { v[0] = v0; } } template <int M> HK_FORCE_INLINE hkMxVector<M>::hkMxVector(hkVector4Parameter v) { const __m256 vr = _mm256_broadcast_ps(&v.m_quad); hkMxVector_Implementation::constructH<((M+1)>>1)>(m_vec.v, vr); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void constructRealH(__m256* v, const __m256* v0) { constructRealH<I-1>(v, v0); v[I-1] = v0[I-1]; } template <> HK_FORCE_INLINE void constructRealH<1>(__m256* v, const __m256* v0) { v[0] = v0[0]; } } template <int M> HK_FORCE_INLINE hkMxVector<M>::hkMxVector(hkMxRealParameter v) { hkMxVector_Implementation::constructRealH<((M+1)>>1)>(m_vec.v, v.m_real.r); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void constructSRealH(__m256* v, const __m256& r) { constructSRealH<I-1>(v, r); v[I-1] = r; } template <> HK_FORCE_INLINE void constructSRealH<1>(__m256* v, const __m256& r) { v[0] = r; } } template <int M> HK_FORCE_INLINE hkMxVector<M>::hkMxVector(hkSimdRealParameter r) { const __m256 sr = _mm256_broadcast_ps(&r.m_real); hkMxVector_Implementation::constructSRealH<((M+1)>>1)>(m_vec.v, sr); } #endif namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void setBCH(__m256* v, const __m256* v0) { setBCH<I-1>(v, v0); v[I-1] = v0[I-1]; } template <> HK_FORCE_INLINE void setBCH<1>(__m256* v, const __m256* v0) { v[0] = v0[0]; } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setBroadcast( hkMxRealParameter r ) { hkMxVector_Implementation::setBCH<((M+1)>>1)>(m_vec.v, r.m_real.r); } namespace hkMxVector_Implementation { template <int I, int C> struct setScalarBroadcastH { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { setScalarBroadcastH<I-1,C>::apply(v, v0); v[I-1] = _mm256_permute_ps(v0[I-1], C); } }; template <int C> struct setScalarBroadcastH<1,C> { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { v[0] = _mm256_permute_ps(v0[0], C); } }; } template <int M> template <int I> HK_FORCE_INLINE void hkMxVector<M>::setScalarBroadcast(hkMxVectorParameter v) { HK_MXVECTOR_VECTOR4_SUBINDEX_CHECK; const int control = I | (I<<2) | (I<<4) | (I<<6); hkMxVector_Implementation::setScalarBroadcastH<((M+1)>>1),control>::apply(m_vec.v, v.m_vec.v); } template <int M> template <int I> HK_FORCE_INLINE void hkMxVector<M>::setVector(hkVector4Parameter v) { HK_MXVECTOR_MX_SUBINDEX_CHECK; const int subvector = I>>1; const int subvectorsubindex = ((I+1)>>1) - subvector; m_vec.v[subvector] = _mm256_insertf128_ps(m_vec.v[subvector], v.m_quad, subvectorsubindex); } template <int M> template <int I> HK_FORCE_INLINE const hkVector4& hkMxVector<M>::getVector() const { HK_MXVECTOR_MX_SUBINDEX_CHECK; const int subvector = I>>1; const int subvectorsubindex = ((I+1)>>1) - subvector; hkVector4 v; v.m_quad = _mm256_extractf128_ps(m_vec.v[subvector], subvectorsubindex); return v; } template <int M> template <int I> HK_FORCE_INLINE void hkMxVector<M>::getVector(hkVector4& vOut) const { HK_MXVECTOR_MX_SUBINDEX_CHECK; const int subvector = I>>1; const int subvectorsubindex = ((I+1)>>1) - subvector; vOut.m_quad = _mm256_extractf128_ps(m_vec.v[subvector], subvectorsubindex); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void setConstH(__m256* v, const __m256& vC) { setConstH<I-1>(v,vC); v[I-1] = vC; } template <> HK_FORCE_INLINE void setConstH<1>(__m256* v, const __m256& vC) { v[0] = vC; } } template <int M> template<int vectorConstant> HK_FORCE_INLINE void hkMxVector<M>::setConstant() { const __m256 vC = _mm256_broadcast_ps(g_vectorConstants + vectorConstant); hkMxVector_Implementation::setConstH<((M+1)>>1)>(m_vec.v, vC); } namespace hkMxVector_Implementation { template <int I, int N> struct isOkH { HK_FORCE_INLINE static __m256 apply(const __m256* v) { // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(v[N], _mm256_setzero_ps(), _CMP_UNORD_Q); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(v[N],v[N], _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_UNORD_Q); const __m256 c = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); return _mm256_or_ps(c, isOkH<I-2,N+1>::apply(v)); } }; template <int N> struct isOkH<2,N> { HK_FORCE_INLINE static __m256 apply(const __m256* v) { // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(v[N], _mm256_setzero_ps(), _CMP_UNORD_Q); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(v[N],v[N], _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_UNORD_Q); return _mm256_permute2f128_ps(masklow,maskhigh, 0x20); } }; template <int N> struct isOkH<1,N> { HK_FORCE_INLINE static __m256 apply(const __m256* v) { static HK_ALIGN32( const hkUint32 mask[8] ) = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }; // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(v[N], _mm256_setzero_ps(), _CMP_UNORD_Q); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(v[N],v[N], _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_UNORD_Q); const __m256 c = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); return _mm256_and_ps(c, *(__m256*)&mask); } }; } template <int M> template <int N> HK_FORCE_INLINE hkBool32 hkMxVector<M>::isOk() const { HK_MXVECTOR_VECTOR4_UNSUPPORTED_LENGTH_CHECK; #if !defined(HK_DEBUG) // pragma compiler perf warning #endif const __m256 c = hkMxVector_Implementation::isOkH<M,0>::apply(m_vec.v); switch (N) // compiletime switch { case 2 : return !(_mm256_movemask_ps(c) & 0x33); break; case 3 : return !(_mm256_movemask_ps(c) & 0x77); break; case 4 : return !(_mm256_movemask_ps(c)); break; default: return !(_mm256_movemask_ps(c) & 0x11); break; } } namespace hkMxVector_Implementation { template <int I, int N> struct moveLoadH { HK_FORCE_INLINE static void apply(__m256* HK_RESTRICT v, const __m256* HK_RESTRICT v0) { v[N] = v0[N]; moveLoadH<I-2,N+1>::apply(v, v0); } }; template <int N> struct moveLoadH<2,N> { HK_FORCE_INLINE static void apply(__m256* HK_RESTRICT v, const __m256* HK_RESTRICT v0) { v[N] = v0[N]; } }; template <int N> struct moveLoadH<1,N> { HK_FORCE_INLINE static void apply(__m256* HK_RESTRICT v, const __m256* HK_RESTRICT v0) { v[N] = _mm256_insertf128_ps(_mm256_setzero_ps(), _mm256_castps256_ps128(v0[N]), 0x0); } }; } template <int M> HK_FORCE_INLINE void hkMxVector<M>::moveLoad(const hkVector4* HK_RESTRICT v) { HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)v) & 0x1f ) == 0, "v must be 32-byte aligned."); hkMxVector_Implementation::moveLoadH<M,0>::apply(m_vec.v, (const __m256* HK_RESTRICT)v); } namespace hkMxVector_Implementation { template <int I, int N> struct moveStoreH { HK_FORCE_INLINE static void apply(hkVector4* HK_RESTRICT v, const __m256* HK_RESTRICT v0) { *((__m256*)(v+(2*N))) = v0[N]; moveStoreH<I-2,N+1>::apply(v, v0); } }; template <int N> struct moveStoreH<2,N> { HK_FORCE_INLINE static void apply(hkVector4* HK_RESTRICT v, const __m256* HK_RESTRICT v0) { *((__m256*)(v+(2*N))) = v0[N]; } }; template <int N> struct moveStoreH<1,N> { HK_FORCE_INLINE static void apply(hkVector4* HK_RESTRICT v, const __m256* HK_RESTRICT v0) { *((__m128*)(v+(2*N))) = _mm256_castps256_ps128(v0[N]); } }; } template <int M> HK_FORCE_INLINE void hkMxVector<M>::moveStore(hkVector4* HK_RESTRICT v) const { HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)v) & 0x1f ) == 0, "v must be 32-byte aligned."); hkMxVector_Implementation::moveStoreH<M,0>::apply(v, m_vec.v); } template <int M> HK_FORCE_INLINE void hkMxVector<M>::operator= ( hkMxVectorParameter v ) { hkMxVector_Implementation::moveLoadH<M,0>::apply(m_vec.v, v.m_vec.v); } namespace hkMxVector_Implementation { template <int I, int N> struct loadRH { HK_FORCE_INLINE static void apply(__m256* v, const hkReal* r) { v[N] = _mm256_load_ps(r+(N*8)); loadRH<I-2,N+1>::apply(v, r); } }; template <int N> struct loadRH<2,N> { HK_FORCE_INLINE static void apply(__m256* v, const hkReal* r) { v[N] = _mm256_load_ps(r+(N*8)); } }; template <int N> struct loadRH<1,N> { HK_FORCE_INLINE static void apply(__m256* v, const hkReal* r) { v[N] = _mm256_setr_ps(r[N*8], r[(N*8)+1], r[(N*8)+2], r[(N*8)+3], 0,0,0,0); } }; } template <int M> HK_FORCE_INLINE void hkMxVector<M>::load(const hkReal* r) { HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)r) & 0x1f ) == 0, "r must be 32-byte aligned."); hkMxVector_Implementation::loadRH<M,0>::apply(m_vec.v, r); } namespace hkMxVector_Implementation { template <int I, int N> struct loadNRH { HK_FORCE_INLINE static void apply(__m256* v, const hkReal* r) { v[N] = _mm256_loadu_ps(r+(N*8)); loadNRH<I-2,N+1>::apply(v, r); } }; template <int N> struct loadNRH<2,N> { HK_FORCE_INLINE static void apply(__m256* v, const hkReal* r) { v[N] = _mm256_loadu_ps(r+(N*8)); } }; template <int N> struct loadNRH<1,N> { HK_FORCE_INLINE static void apply(__m256* v, const hkReal* r) { v[N] = _mm256_setr_ps(r[N*8], r[(N*8)+1], r[(N*8)+2], r[(N*8)+3], 0,0,0,0); } }; } template <int M> HK_FORCE_INLINE void hkMxVector<M>::loadNotAligned(const hkReal* r) { hkMxVector_Implementation::loadNRH<M,0>::apply(m_vec.v, r); } template <int M> HK_FORCE_INLINE void hkMxVector<M>::loadNotCached(const hkReal* r) { HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)r) & 0x1f ) == 0, "r must be 32-byte aligned."); hkMxVector_Implementation::loadRH<M,0>::apply(m_vec.v, r); } namespace hkMxVector_Implementation { template <int I, int N> struct storeRH { HK_FORCE_INLINE static void apply(const __m256* v, hkReal* r) { _mm256_store_ps(r+(N*8), v[N]); storeRH<I-2,N+1>::apply(v, r); } }; template <int N> struct storeRH<2,N> { HK_FORCE_INLINE static void apply(const __m256* v, hkReal* r) { _mm256_store_ps(r+(N*8), v[N]); } }; template <int N> struct storeRH<1,N> { HK_FORCE_INLINE static void apply(const __m256* v, hkReal* r) { static HK_ALIGN32( const hkUint32 mask[8] ) = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }; _mm256_maskstore_ps(r+(N*8), *(__m256i*)&mask, v[N]); } }; } template <int M> HK_FORCE_INLINE void hkMxVector<M>::store(hkReal* r) const { HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)r) & 0x1f ) == 0, "r must be 32-byte aligned."); hkMxVector_Implementation::storeRH<M,0>::apply(m_vec.v, r); } namespace hkMxVector_Implementation { template <int I, int N> struct storeNRH { HK_FORCE_INLINE static void apply(const __m256* v, hkReal* r) { _mm256_storeu_ps(r+(N*8), v[N]); storeNRH<I-2,N+1>::apply(v, r); } }; template <int N> struct storeNRH<2,N> { HK_FORCE_INLINE static void apply(const __m256* v, hkReal* r) { _mm256_storeu_ps(r+(N*8), v[N]); } }; template <int N> struct storeNRH<1,N> { HK_FORCE_INLINE static void apply(const __m256* v, hkReal* r) { static HK_ALIGN32( const hkUint32 mask[8] ) = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }; _mm256_maskstore_ps(r+(N*8), *(__m256i*)&mask, v[N]); } }; } template <int M> HK_FORCE_INLINE void hkMxVector<M>::storeNotAligned(hkReal* r) const { hkMxVector_Implementation::storeNRH<M,0>::apply(m_vec.v, r); } namespace hkMxVector_Implementation { template <int I, int N> struct storeCNRH { HK_FORCE_INLINE static void apply(const __m256* v, hkReal* r) { _mm256_stream_ps(r+(N*8), v[N]); storeCNRH<I-2,N+1>::apply(v, r); } }; template <int N> struct storeCNRH<2,N> { HK_FORCE_INLINE static void apply(const __m256* v, hkReal* r) { _mm256_stream_ps(r+(N*8), v[N]); } }; template <int N> struct storeCNRH<1,N> { HK_FORCE_INLINE static void apply(const __m256* v, hkReal* r) { // hm, no nt hint for mask static HK_ALIGN32( const hkUint32 mask[8] ) = { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000 }; _mm256_maskstore_ps(r+(N*8), *(__m256i*)&mask, v[N]); } }; } template <int M> HK_FORCE_INLINE void hkMxVector<M>::storeNotCached(hkReal* r) const { HK_MATH_ASSERT(0x64211c2f, ( ((hkUlong)r) & 0x1f ) == 0, "r must be 32-byte aligned."); hkMxVector_Implementation::storeCNRH<M,0>::apply(m_vec.v, r); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void setDiv12H(__m256* v, const __m256* v0, const __m256* v1) { setDiv12H<I-1>(v,v0,v1); v[I-1] = _mm256_mul_ps(v0[I-1], _mm256_rcp_ps(v1[I-1])); } template <> HK_FORCE_INLINE void setDiv12H<1>(__m256* v, const __m256* v0, const __m256* v1) { v[0] = _mm256_mul_ps(v0[0], _mm256_rcp_ps(v1[0])); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setDiv_12BitAccurate(hkMxVectorParameter v0, hkMxVectorParameter v1) { hkMxVector_Implementation::setDiv12H<((M+1)>>1)>(m_vec.v, v0.m_vec.v, v1.m_vec.v); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void setDiv23H(__m256* v, const __m256* v0, const __m256* v1) { setDiv23H<I-1>(v,v0,v1); v[I-1] = _mm256_mul_ps(v0[I-1], hkMxCommon_Implementation::reciprocalH(v1[I-1])); } template <> HK_FORCE_INLINE void setDiv23H<1>(__m256* v, const __m256* v0, const __m256* v1) { v[0] = _mm256_mul_ps(v0[0], hkMxCommon_Implementation::reciprocalH(v1[0])); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setDiv_23BitAccurate(hkMxVectorParameter v0, hkMxVectorParameter v1) { hkMxVector_Implementation::setDiv23H<((M+1)>>1)>(m_vec.v, v0.m_vec.v, v1.m_vec.v); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void setSqrtInverseH(__m256* v, const __m256* v0, const __m256& one) { setSqrtInverseH<I-1>(v,v0,one); v[I-1] = _mm256_div_ps(one, _mm256_sqrt_ps(v0[I-1])); } template <> HK_FORCE_INLINE void setSqrtInverseH<1>(__m256* v, const __m256* v0, const __m256& one) { v[0] = _mm256_div_ps(one, _mm256_sqrt_ps(v0[0])); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setSqrtInverse(hkMxVectorParameter v) { const __m256 one = _mm256_set1_ps(1.0f); hkMxVector_Implementation::setSqrtInverseH<((M+1)>>1)>(m_vec.v, v.m_vec.v, one); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void setSqrtInverse12H(__m256* v, const __m256* v0) { setSqrtInverse12H<I-1>(v,v0); v[I-1] = _mm256_rsqrt_ps(v0[I-1]); } template <> HK_FORCE_INLINE void setSqrtInverse12H<1>(__m256* v, const __m256* v0) { v[0] = _mm256_rsqrt_ps(v0[0]); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setSqrtInverse_12BitAccurate(hkMxVectorParameter v) { hkMxVector_Implementation::setSqrtInverse12H<((M+1)>>1)>(m_vec.v, v.m_vec.v); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void setSqrtInverse23H(__m256* v, const __m256* v0) { setSqrtInverse23H<I-1>(v,v0); v[I-1] = hkMxCommon_Implementation::reciprocalSquareRootH(v0[I-1]); } template <> HK_FORCE_INLINE void setSqrtInverse23H<1>(__m256* v, const __m256* v0) { v[0] = hkMxCommon_Implementation::reciprocalSquareRootH(v0[0]); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setSqrtInverse_23BitAccurate(hkMxVectorParameter v) { hkMxVector_Implementation::setSqrtInverse23H<((M+1)>>1)>(m_vec.v, v.m_vec.v); } namespace hkMxVector_Implementation { template <int I, int N> struct normalizeH { HK_FORCE_INLINE static void apply(__m256* v, const __m256& one) { normalizeH<I-1,N>::apply(v,one); const __m256 len2 = hkMxCommon_Implementation::dotProdH<N>(v[I-1],v[I-1]); // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(len2, _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(len2,len2, _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 equalsZero = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); const __m256 e = _mm256_div_ps(one, _mm256_sqrt_ps(len2)); // Ensures that we return 0 const __m256 result = _mm256_andnot_ps(equalsZero, e); v[I-1] = _mm256_mul_ps(result, v[I-1]); } }; template <int N> struct normalizeH<1,N> { HK_FORCE_INLINE static void apply(__m256* v, const __m256& one) { const __m256 len2 = hkMxCommon_Implementation::dotProdH<N>(v[0],v[0]); // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(len2, _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(len2,len2, _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 equalsZero = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); const __m256 e = _mm256_div_ps(one, _mm256_sqrt_ps(len2)); // Ensures that we return 0 const __m256 result = _mm256_andnot_ps(equalsZero, e); v[0] = _mm256_mul_ps(result, v[0]); } }; } template <int M> template <int N> HK_FORCE_INLINE void hkMxVector<M>::normalize() { HK_MXVECTOR_VECTOR4_UNSUPPORTED_LENGTH_CHECK; const __m256 oneV = _mm256_set1_ps(1.0f); hkMxVector_Implementation::normalizeH<((M+1)>>1),N>::apply(m_vec.v, oneV); } namespace hkMxVector_Implementation { template <int I, int N> struct normalize12H { HK_FORCE_INLINE static void apply(__m256* v) { normalize12H<I-1,N>::apply(v); const __m256 len2 = hkMxCommon_Implementation::dotProdH<N>(v[I-1],v[I-1]); // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(len2, _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(len2,len2, _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 equalsZero = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); const __m256 e = _mm256_rsqrt_ps(len2); // Ensures that we return 0 const __m256 result = _mm256_andnot_ps(equalsZero, e); v[I-1] = _mm256_mul_ps(result, v[I-1]); } }; template <int N> struct normalize12H<1,N> { HK_FORCE_INLINE static void apply(__m256* v) { const __m256 len2 = hkMxCommon_Implementation::dotProdH<N>(v[0],v[0]); // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(len2, _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(len2,len2, _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 equalsZero = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); const __m256 e = _mm256_rsqrt_ps(len2); // Ensures that we return 0 const __m256 result = _mm256_andnot_ps(equalsZero, e); v[0] = _mm256_mul_ps(result, v[0]); } }; } template <int M> template <int N> HK_FORCE_INLINE void hkMxVector<M>::normalize_12BitAccurate() { HK_MXVECTOR_VECTOR4_UNSUPPORTED_LENGTH_CHECK; hkMxVector_Implementation::normalize12H<((M+1)>>1),N>::apply(m_vec.v); } namespace hkMxVector_Implementation { template <int I, int N> struct normalize23H { HK_FORCE_INLINE static void apply(__m256* v) { normalize23H<I-1,N>::apply(v); const __m256 len2 = hkMxCommon_Implementation::dotProdH<N>(v[I-1],v[I-1]); // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(len2, _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(len2,len2, _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 equalsZero = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); const __m256 e = hkMxCommon_Implementation::reciprocalSquareRootH(len2); // Ensures that we return 0 const __m256 result = _mm256_andnot_ps(equalsZero, e); v[I-1] = _mm256_mul_ps(result, v[I-1]); } }; template <int N> struct normalize23H<1,N> { HK_FORCE_INLINE static void apply(__m256* v) { const __m256 len2 = hkMxCommon_Implementation::dotProdH<N>(v[0],v[0]); // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(len2, _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(len2,len2, _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 equalsZero = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); const __m256 e = hkMxCommon_Implementation::reciprocalSquareRootH(len2); // Ensures that we return 0 const __m256 result = _mm256_andnot_ps(equalsZero, e); v[0] = _mm256_mul_ps(result, v[0]); } }; } template <int M> template <int N> HK_FORCE_INLINE void hkMxVector<M>::normalize_23BitAccurate() { HK_MXVECTOR_VECTOR4_UNSUPPORTED_LENGTH_CHECK; hkMxVector_Implementation::normalize23H<((M+1)>>1),N>::apply(m_vec.v); } namespace hkMxVector_Implementation { template <int N> HK_FORCE_INLINE __m256 getNegMaskH() { static HK_ALIGN32( const hkUint32 mask[8] ) = { 0x80000000, 0x00000000, 0x00000000, 0x00000000, 0x80000000, 0x00000000, 0x00000000, 0x00000000 }; return *(const __m256*)&mask; } template <> HK_FORCE_INLINE __m256 getNegMaskH<2>() { static HK_ALIGN32( const hkUint32 mask[8] ) = { 0x80000000, 0x80000000, 0x00000000, 0x00000000, 0x80000000, 0x80000000, 0x00000000, 0x00000000 }; return *(const __m256*)&mask; } template <> HK_FORCE_INLINE __m256 getNegMaskH<3>() { static HK_ALIGN32( const hkUint32 mask[8] ) = { 0x80000000, 0x80000000, 0x80000000, 0x00000000, 0x80000000, 0x80000000, 0x80000000, 0x00000000 }; return *(const __m256*)&mask; } template <> HK_FORCE_INLINE __m256 getNegMaskH<4>() { static HK_ALIGN32( const hkUint32 mask[8] ) = { 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000, 0x80000000 }; return *(const __m256*)&mask; } template <int I> HK_FORCE_INLINE void setNegH(__m256* v0, const __m256* v1, const __m256& mask) { setNegH<I-1>(v0,v1,mask); v0[I-1] = _mm256_xor_ps(v1[I-1],mask); } template <> HK_FORCE_INLINE void setNegH<1>(__m256* v0, const __m256* v1, const __m256& mask) { v0[0] = _mm256_xor_ps(v1[0],mask); } } template <int M> template <int N> HK_FORCE_INLINE void hkMxVector<M>::setNeg(hkMxVectorParameter v0) { HK_MXVECTOR_VECTOR4_UNSUPPORTED_LENGTH_CHECK; const __m256 maskV = hkMxVector_Implementation::getNegMaskH<N>(); hkMxVector_Implementation::setNegH<((M+1)>>1)>(m_vec.v, v0.m_vec.v, maskV); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void setAbsH(__m256* v0, const __m256* v1, const __m256& mask) { setAbsH<I-1>(v0,v1,mask); v0[I-1] = _mm256_and_ps(v1[I-1],mask); } template <> HK_FORCE_INLINE void setAbsH<1>(__m256* v0, const __m256* v1, const __m256& mask) { v0[0] = _mm256_and_ps(v1[0],mask); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setAbs(hkMxVectorParameter v0) { static HK_ALIGN32( const hkUint32 mask[8] ) = { 0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff }; hkMxVector_Implementation::setAbsH<((M+1)>>1)>(m_vec.v, v0.m_vec.v, *(const __m256*)&mask); } namespace hkMxVector_Implementation { template <int N, int I> struct zeroCompH { HK_FORCE_INLINE static void apply(__m256* v) { zeroCompH<N-1,I>::apply(v); v[N-1] = _mm256_blend_ps(v[N-1], _mm256_setzero_ps(), (0x01 << I) | (0x10 << I)); } }; template <int I> struct zeroCompH<1,I> { HK_FORCE_INLINE static void apply(__m256* v) { v[0] = _mm256_blend_ps(v[0], _mm256_setzero_ps(), (0x01 << I) | (0x10 << I)); } }; } template <int M> template <int I> HK_FORCE_INLINE void hkMxVector<M>::zeroComponent() { HK_MXVECTOR_VECTOR4_SUBINDEX_CHECK; hkMxVector_Implementation::zeroCompH<((M+1)>>1),I>::apply(m_vec.v); } MXV_NO_OPERANDS( setZero, _mm256_setzero_ps ) MXV_OP_MXVECTOR( add, _mm256_add_ps ) MXV_OP_MXVECTOR( sub, _mm256_sub_ps ) MXV_OP_MXVECTOR( mul, _mm256_mul_ps ) MXV_OP_MXREAL( mul, _mm256_mul_ps ) MXV_OP_MXVECTOR_MXVECTOR( setAdd, _mm256_add_ps ) MXV_OP_MXVECTOR_MXVECTOR( setSub, _mm256_sub_ps ) MXV_OP_MXVECTOR_MXVECTOR( setMul, _mm256_mul_ps ) MXV_OP_MXVECTOR_MXVECTOR( setDiv, _mm256_div_ps ) MXV_OP_MXVECTOR_MXVECTOR( setMin, _mm256_min_ps ) MXV_OP_MXVECTOR_MXVECTOR( setMax, _mm256_max_ps ) MXV_OP_MXREAL_MXVECTOR( setMul, _mm256_mul_ps ) MXV_OP_MXVECTOR_MXVECTOR_MXVECTOR( setAddMul, _mm256_add_ps, _mm256_mul_ps ) MXV_OP_MXVECTOR_MXVECTOR_MXVECTOR( setSubMul, _mm256_sub_ps, _mm256_mul_ps ) MXV_OP_MXVECTOR_MXVECTOR_MXSINGLE( setAddMul, _mm256_add_ps, _mm256_mul_ps ) MXV_OP_MXVECTOR_MXVECTOR_MXSINGLE( setSubMul, _mm256_sub_ps, _mm256_mul_ps ) MXV_OP_MXVECTOR_MXVECTOR_MXREAL( setSubMul, _mm256_sub_ps, _mm256_mul_ps ) MXV_OP_MXVECTOR_MXSINGLE_MXREAL( setSubMul, _mm256_sub_ps, _mm256_mul_ps ) MXV_OP_MXSINGLE( add, _mm256_add_ps ) MXV_OP_MXSINGLE( sub, _mm256_sub_ps ) MXV_OP_MXSINGLE( mul, _mm256_mul_ps ) MXV_OP_MXREAL_MXVECTOR_SELF( addMul, _mm256_add_ps, _mm256_mul_ps ) MXV_OP_MXVECTOR_MXVECTOR_SELF( addMul, _mm256_add_ps, _mm256_mul_ps ) MXV_OP_MXVECTOR_MXSINGLE_SELF( addMul, _mm256_add_ps, _mm256_mul_ps ) MXV_OP_MXVECTOR_MXSINGLE( setAdd, _mm256_add_ps ) MXV_OP_MXVECTOR_MXSINGLE( setSub, _mm256_sub_ps ) MXV_OP_MXVECTOR_MXSINGLE( setMul, _mm256_mul_ps ) MXV_OP_MXVECTOR_MXSINGLE( setMin, _mm256_min_ps ) MXV_OP_MXVECTOR_MXSINGLE( setMax, _mm256_max_ps ) MXV_OP_MXSINGLE_MXSINGLE( addMul, _mm256_add_ps, _mm256_mul_ps ) MXV_OP_MXSINGLE_MXVECTOR( setSub, _mm256_sub_ps ) MXV_COMPARE( compareEqual, _CMP_EQ_OQ ) MXV_COMPARE( compareNotEqual, _CMP_NEQ_OQ ) MXV_COMPARE( compareLessThan, _CMP_LT_OQ ) MXV_COMPARE( compareGreaterThan, _CMP_GT_OQ ) MXV_COMPARE( compareLessThanEqual, _CMP_LE_OQ ) MXV_COMPARE( compareGreaterThanEqual, _CMP_GE_OQ ) MXV_COMPARE_SINGLE( compareEqual, _CMP_EQ_OQ ) MXV_COMPARE_SINGLE( compareNotEqual, _CMP_NEQ_OQ ) MXV_COMPARE_SINGLE( compareLessThan, _CMP_LT_OQ ) MXV_COMPARE_SINGLE( compareGreaterThan, _CMP_GT_OQ ) MXV_COMPARE_SINGLE( compareLessThanEqual, _CMP_LE_OQ ) MXV_COMPARE_SINGLE( compareGreaterThanEqual, _CMP_GE_OQ ) namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void setCrossH(__m256* v, const __m256* v0, const __m256* v1) { setCrossH<I-1>(v,v0,v1); v[I-1] = hkMxCommon_Implementation::crossH( v0[I-1], v1[I-1]); } template <> HK_FORCE_INLINE void setCrossH<1>(__m256* v, const __m256* v0, const __m256* v1) { v[0] = hkMxCommon_Implementation::crossH( v0[0], v1[0]); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setCross(hkMxVectorParameter v0, hkMxVectorParameter v1) { hkMxVector_Implementation::setCrossH<((M+1)>>1)>(m_vec.v, v0.m_vec.v, v1.m_vec.v); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void setCrossSH(__m256* v, const __m256& v0, const __m256* v1) { setCrossSH<I-1>(v,v0,v1); v[I-1] = hkMxCommon_Implementation::crossH( v0, v1[I-1]); } template <> HK_FORCE_INLINE void setCrossSH<1>(__m256* v, const __m256& v0, const __m256* v1) { v[0] = hkMxCommon_Implementation::crossH( v0, v1[0]); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setCross(hkMxSingleParameter v0, hkMxVectorParameter v1) { hkMxVector_Implementation::setCrossSH<((M+1)>>1)>(m_vec.v, v0.m_single.s, v1.m_vec.v); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void setCrossHS(__m256* v, const __m256* v0, const __m256& v1) { setCrossHS<I-1>(v,v0,v1); v[I-1] = hkMxCommon_Implementation::crossH( v0[I-1], v1); } template <> HK_FORCE_INLINE void setCrossHS<1>(__m256* v, const __m256* v0, const __m256& v1) { v[0] = hkMxCommon_Implementation::crossH( v0[0], v1); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setCross(hkMxVectorParameter v0, hkMxSingleParameter v1) { hkMxVector_Implementation::setCrossHS<((M+1)>>1)>(m_vec.v, v0.m_vec.v, v1.m_single.s); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void setInterpolateH(__m256* v, const __m256* v0, const __m256* v1, const __m256* t) { setInterpolateH<I-1>(v,v0,v1,t); const __m256 d = _mm256_sub_ps(v1[I-1], v0[I-1]); v[I-1] = _mm256_add_ps( v0[I-1], _mm256_mul_ps(d, t[I-1]) ); } template <> HK_FORCE_INLINE void setInterpolateH<1>(__m256* v, const __m256* v0, const __m256* v1, const __m256* t) { const __m256 d = _mm256_sub_ps(v1[0], v0[0]); v[0] = _mm256_add_ps( v0[0], _mm256_mul_ps(d, t[0]) ); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setInterpolate(hkMxVectorParameter v0, hkMxVectorParameter v1, hkMxRealParameter t) { hkMxVector_Implementation::setInterpolateH<((M+1)>>1)>(m_vec.v, v0.m_vec.v, v1.m_vec.v, t.m_real.r); } namespace hkMxVector_Implementation { template <int M> HK_FORCE_INLINE void setAddMulH(__m256* v, const __m256* v0, const __m256* v1, hkVector4Parameter v2) { HK_MXVECTOR_MX_NOT_IMPLEMENTED; } template <> HK_FORCE_INLINE void setAddMulH<1>(__m256* v, const __m256* v0, const __m256* v1, hkVector4Parameter v2) { const __m128 a = _mm_shuffle_ps(v2.m_quad, v2.m_quad, _MM_SHUFFLE(0,0,0,0)); const __m128 b = _mm_shuffle_ps(v2.m_quad, v2.m_quad, _MM_SHUFFLE(1,1,1,1)); __m256 c = _mm256_insertf128_ps(_mm256_undefined_ps(), a, 0x0); c = _mm256_insertf128_ps(c, b, 0x1); v[0] = _mm256_add_ps(v0[0], _mm256_mul_ps(v1[0], c)); } template <> HK_FORCE_INLINE void setAddMulH<2>(__m256* v, const __m256* v0, const __m256* v1, hkVector4Parameter v2) { const __m128 a = _mm_shuffle_ps(v2.m_quad, v2.m_quad, _MM_SHUFFLE(2,2,2,2)); const __m128 b = _mm_shuffle_ps(v2.m_quad, v2.m_quad, _MM_SHUFFLE(3,3,3,3)); setAddMulH<1>(v,v0,v1,v2); __m256 c = _mm256_insertf128_ps(_mm256_undefined_ps(), a, 0x0); c = _mm256_insertf128_ps(c, b, 0x1); v[1] = _mm256_add_ps(v0[1], _mm256_mul_ps(v1[1], c)); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setAddMul(hkMxVectorParameter v0, hkMxVectorParameter v1, hkVector4Parameter v2) { hkMxVector_Implementation::setAddMulH<((M+1)>>1)>(m_vec.v, v0.m_vec.v, v1.m_vec.v, v2); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void setXYZ_W_H(__m256* v, const __m256* xyz, const __m256* w) { setXYZ_W_H<I-1>(v,xyz,w); v[I-1] = _mm256_blend_ps(xyz[I-1],w[I-1],0x88); } template <> HK_FORCE_INLINE void setXYZ_W_H<1>(__m256* v, const __m256* xyz, const __m256* w) { v[0] = _mm256_blend_ps(xyz[0],w[0],0x88); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setXYZ_W(hkMxVectorParameter v0, hkMxVectorParameter v1) { hkMxVector_Implementation::setXYZ_W_H<((M+1)>>1)>(m_vec.v, v0.m_vec.v, v1.m_vec.v); } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setXYZ_W(hkMxVectorParameter v0, hkMxRealParameter r1) { hkMxVector_Implementation::setXYZ_W_H<((M+1)>>1)>(m_vec.v, v0.m_vec.v, r1.m_real.r); } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setXYZ(hkMxVectorParameter v0) { hkMxVector_Implementation::setXYZ_W_H<((M+1)>>1)>(m_vec.v, v0.m_vec.v, m_vec.v); } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setW(hkMxVectorParameter v0) { hkMxVector_Implementation::setXYZ_W_H<((M+1)>>1)>(m_vec.v, m_vec.v, v0.m_vec.v); } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setW(hkMxRealParameter r0) { hkMxVector_Implementation::setXYZ_W_H<((M+1)>>1)>(m_vec.v, m_vec.v, r0.m_real.r); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void setW_SH(__m256* v, const __m256& w) { setW_SH<I-1>(v,w); v[I-1] = _mm256_blend_ps(v[I-1],w,0x88); } template <> HK_FORCE_INLINE void setW_SH<1>(__m256* v, const __m256& w) { v[0] = _mm256_blend_ps(v[0],w,0x88); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setW(hkMxSingleParameter v0) { hkMxVector_Implementation::setW_SH<((M+1)>>1)>(m_vec.v, v0.m_single.s); } template <int M> HK_FORCE_INLINE void hkMxVector<M>::storeTransposed4(hkMatrix4& matrix4) const { HK_MXVECTOR_MX_NOT_IMPLEMENTED; } template <> HK_FORCE_INLINE void hkMxVector<1>::storeTransposed4(hkMatrix4& matrix4) const { const __m128 s = _mm256_extractf128_ps(m_vec.v[0], 0x0); hkVector4 a; a.m_quad = _mm_shuffle_ps(s,s,_MM_SHUFFLE(0,0,0,0)); hkVector4 b; b.m_quad = _mm_shuffle_ps(s,s,_MM_SHUFFLE(1,1,1,1)); hkVector4 c; c.m_quad = _mm_shuffle_ps(s,s,_MM_SHUFFLE(2,2,2,2)); hkVector4 d; d.m_quad = _mm_shuffle_ps(s,s,_MM_SHUFFLE(3,3,3,3)); matrix4.setCols(a,b,c,d); // todo. for debug: set .yzw to 0x23456789 } template <> HK_FORCE_INLINE void hkMxVector<2>::storeTransposed4(hkMatrix4& matrix4) const { hkVector4 a; a.m_quad = _mm256_extractf128_ps(m_vec.v[0], 0x0); hkVector4 b; b.m_quad = _mm256_extractf128_ps(m_vec.v[0], 0x1); matrix4.setRows(a,b,b,b); } template <> HK_FORCE_INLINE void hkMxVector<3>::storeTransposed4(hkMatrix4& matrix4) const { hkVector4 a; a.m_quad = _mm256_extractf128_ps(m_vec.v[0], 0x0); hkVector4 b; b.m_quad = _mm256_extractf128_ps(m_vec.v[0], 0x1); hkVector4 c; c.m_quad = _mm256_extractf128_ps(m_vec.v[1], 0x0); matrix4.setRows(a,b,c,c); } template <> HK_FORCE_INLINE void hkMxVector<4>::storeTransposed4(hkMatrix4& matrix4) const { hkVector4 a; a.m_quad = _mm256_extractf128_ps(m_vec.v[0], 0x0); hkVector4 b; b.m_quad = _mm256_extractf128_ps(m_vec.v[0], 0x1); hkVector4 c; c.m_quad = _mm256_extractf128_ps(m_vec.v[1], 0x0); hkVector4 d; d.m_quad = _mm256_extractf128_ps(m_vec.v[1], 0x1); matrix4.setRows(a,b,c,d); } namespace hkMxVector_Implementation { template <int M, int N> struct hAddH { HK_FORCE_INLINE static void apply(hkMxVectorParameter v, hkVector4& addsOut) { HK_MXVECTOR_MX_NOT_IMPLEMENTED; } }; template <> struct hAddH<4,4> { HK_FORCE_INLINE static void apply(const hkMxVector<4>& v, hkVector4& addsOut) { const __m256 a = _mm256_hadd_ps(v.m_vec.v[0],v.m_vec.v[0]); const __m256 aa = _mm256_hadd_ps(a,a); const __m256 b = _mm256_hadd_ps(v.m_vec.v[1],v.m_vec.v[1]); const __m256 bb = _mm256_hadd_ps(b,b); hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); hkSimdReal sc; sc.m_real = _mm256_extractf128_ps(bb, 0x0); hkSimdReal sd; sd.m_real = _mm256_extractf128_ps(bb, 0x1); addsOut.set(sa,sb,sc,sd); } }; template <> struct hAddH<2,3> { HK_FORCE_INLINE static void apply(const hkMxVector<2>& v, hkVector4& addsOut) { const __m256 a = _mm256_hadd_ps(v.m_vec.v[0],v.m_vec.v[0]); const __m256 aa = _mm256_add_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(2,2,2,2)), _mm256_shuffle_ps(a,a,_MM256_PERMUTE(0,0,0,0))); hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); addsOut.set(sa,sb,sb,sb); } }; template <> struct hAddH<2,4> { HK_FORCE_INLINE static void apply(const hkMxVector<2>& v, hkVector4& addsOut) { const __m256 a = _mm256_hadd_ps(v.m_vec.v[0],v.m_vec.v[0]); const __m256 aa = _mm256_hadd_ps(a,a); hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); addsOut.set(sa,sb,sb,sb); } }; template <> struct hAddH<4,3> { HK_FORCE_INLINE static void apply(const hkMxVector<4>& v, hkVector4& addsOut) { const __m256 a = _mm256_hadd_ps(v.m_vec.v[0],v.m_vec.v[0]); const __m256 aa = _mm256_add_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(2,2,2,2)), _mm256_shuffle_ps(a,a,_MM256_PERMUTE(0,0,0,0))); const __m256 b = _mm256_hadd_ps(v.m_vec.v[1],v.m_vec.v[1]); const __m256 bb = _mm256_add_ps( _mm256_shuffle_ps(v.m_vec.v[1],v.m_vec.v[1],_MM256_PERMUTE(2,2,2,2)), _mm256_shuffle_ps(b,b,_MM256_PERMUTE(0,0,0,0))); hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); hkSimdReal sc; sc.m_real = _mm256_extractf128_ps(bb, 0x0); hkSimdReal sd; sd.m_real = _mm256_extractf128_ps(bb, 0x1); addsOut.set(sa,sb,sc,sd); } }; template <> struct hAddH<3,4> { HK_FORCE_INLINE static void apply(const hkMxVector<3>& v, hkVector4& addsOut) { const __m256 a = _mm256_hadd_ps(v.m_vec.v[0],v.m_vec.v[0]); const __m256 aa = _mm256_hadd_ps(a,a); const __m256 b = _mm256_hadd_ps(v.m_vec.v[1],v.m_vec.v[1]); const __m256 bb = _mm256_hadd_ps(b,b); hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); hkSimdReal sc; sc.m_real = _mm256_extractf128_ps(bb, 0x0); addsOut.set(sa,sb,sc,sc); } }; template <> struct hAddH<3,3> { HK_FORCE_INLINE static void apply(const hkMxVector<3>& v, hkVector4& addsOut) { const __m256 a = _mm256_hadd_ps(v.m_vec.v[0],v.m_vec.v[0]); const __m256 aa = _mm256_add_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(2,2,2,2)), _mm256_shuffle_ps(a,a,_MM256_PERMUTE(0,0,0,0))); const __m256 b = _mm256_hadd_ps(v.m_vec.v[1],v.m_vec.v[1]); const __m256 bb = _mm256_add_ps( _mm256_shuffle_ps(v.m_vec.v[1],v.m_vec.v[1],_MM256_PERMUTE(2,2,2,2)), _mm256_shuffle_ps(b,b,_MM256_PERMUTE(0,0,0,0))); hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); hkSimdReal sc; sc.m_real = _mm256_extractf128_ps(bb, 0x0); addsOut.set(sa,sb,sc,sc); } }; template <int N> struct hAddH<1,N> { HK_FORCE_INLINE static void apply(const hkMxVector<1>& v, hkVector4& addsOut) { const hkVector4 a = v.getVector<0>(); addsOut.setHorizontalAdd<N>(a); } }; } template <int M> template <int N> HK_FORCE_INLINE void hkMxVector<M>::horizontalAdd( hkVector4& addsOut ) const { hkMxVector_Implementation::hAddH<M,N>::apply(*this, addsOut); } namespace hkMxVector_Implementation { template <int M, int N> struct hMinH { HK_FORCE_INLINE static void apply(hkMxVectorParameter v, hkVector4& minsOut) { HK_MXVECTOR_MX_NOT_IMPLEMENTED; } }; template <> struct hMinH<4,4> { HK_FORCE_INLINE static void apply(const hkMxVector<4>& v, hkVector4& minsOut) { const __m256 a0 = _mm256_min_ps( _mm256_shuffle_ps( v.m_vec.v[0], v.m_vec.v[0],_MM256_PERMUTE(1,0,3,2)), v.m_vec.v[0]); // yxwz+xyzw = xy xy zw zw const __m256 a1 = _mm256_shuffle_ps(a0,a0, _MM256_PERMUTE(2,3,0,1)); // = zw zw xy xy const __m256 aa = _mm256_min_ps( a0, a1 ); // xywz all 4 two times const __m256 b0 = _mm256_min_ps( _mm256_shuffle_ps( v.m_vec.v[1], v.m_vec.v[1],_MM256_PERMUTE(1,0,3,2)), v.m_vec.v[1]); // yxwz+xyzw = xy xy zw zw const __m256 b1 = _mm256_shuffle_ps(b0,b0, _MM256_PERMUTE(2,3,0,1)); // = zw zw xy xy const __m256 bb = _mm256_min_ps( b0, b1 ); // xywz all 4 two times hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); hkSimdReal sc; sc.m_real = _mm256_extractf128_ps(bb, 0x0); hkSimdReal sd; sd.m_real = _mm256_extractf128_ps(bb, 0x1); minsOut.set(sa,sb,sc,sd); } }; template <> struct hMinH<4,3> { HK_FORCE_INLINE static void apply(const hkMxVector<4>& v, hkVector4& minsOut) { const __m256 axy = _mm256_min_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(1,1,1,1)), _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(0,0,0,0))); const __m256 aa = _mm256_min_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(2,2,2,2)), axy); const __m256 bxy = _mm256_min_ps( _mm256_shuffle_ps(v.m_vec.v[1],v.m_vec.v[1],_MM256_PERMUTE(1,1,1,1)), _mm256_shuffle_ps(v.m_vec.v[1],v.m_vec.v[1],_MM256_PERMUTE(0,0,0,0))); const __m256 bb = _mm256_min_ps( _mm256_shuffle_ps(v.m_vec.v[1],v.m_vec.v[1],_MM256_PERMUTE(2,2,2,2)), bxy); hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); hkSimdReal sc; sc.m_real = _mm256_extractf128_ps(bb, 0x0); hkSimdReal sd; sd.m_real = _mm256_extractf128_ps(bb, 0x1); minsOut.set(sa,sb,sc,sd); } }; template <> struct hMinH<3,4> { HK_FORCE_INLINE static void apply(const hkMxVector<3>& v, hkVector4& minsOut) { const __m256 a0 = _mm256_min_ps( _mm256_shuffle_ps( v.m_vec.v[0], v.m_vec.v[0],_MM256_PERMUTE(1,0,3,2)), v.m_vec.v[0]); // yxwz+xyzw = xy xy zw zw const __m256 a1 = _mm256_shuffle_ps(a0,a0, _MM256_PERMUTE(2,3,0,1)); // = zw zw xy xy const __m256 aa = _mm256_min_ps( a0, a1 ); // xywz all 4 two times const __m256 b0 = _mm256_min_ps( _mm256_shuffle_ps( v.m_vec.v[1], v.m_vec.v[1],_MM256_PERMUTE(1,0,3,2)), v.m_vec.v[1]); // yxwz+xyzw = xy xy zw zw const __m256 b1 = _mm256_shuffle_ps(b0,b0, _MM256_PERMUTE(2,3,0,1)); // = zw zw xy xy const __m256 bb = _mm256_min_ps( b0, b1 ); // xywz all 4 two times hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); hkSimdReal sc; sc.m_real = _mm256_extractf128_ps(bb, 0x0); minsOut.set(sa,sb,sc,sc); } }; template <> struct hMinH<3,3> { HK_FORCE_INLINE static void apply(const hkMxVector<3>& v, hkVector4& minsOut) { const __m256 axy = _mm256_min_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(1,1,1,1)), _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(0,0,0,0))); const __m256 aa = _mm256_min_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(2,2,2,2)), axy); const __m256 bxy = _mm256_min_ps( _mm256_shuffle_ps(v.m_vec.v[1],v.m_vec.v[1],_MM256_PERMUTE(1,1,1,1)), _mm256_shuffle_ps(v.m_vec.v[1],v.m_vec.v[1],_MM256_PERMUTE(0,0,0,0))); const __m256 bb = _mm256_min_ps( _mm256_shuffle_ps(v.m_vec.v[1],v.m_vec.v[1],_MM256_PERMUTE(2,2,2,2)), bxy); hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); hkSimdReal sc; sc.m_real = _mm256_extractf128_ps(bb, 0x0); minsOut.set(sa,sb,sc,sc); } }; template <> struct hMinH<2,4> { HK_FORCE_INLINE static void apply(const hkMxVector<2>& v, hkVector4& minsOut) { const __m256 a0 = _mm256_min_ps( _mm256_shuffle_ps( v.m_vec.v[0], v.m_vec.v[0],_MM256_PERMUTE(1,0,3,2)), v.m_vec.v[0]); // yxwz+xyzw = xy xy zw zw const __m256 a1 = _mm256_shuffle_ps(a0,a0, _MM256_PERMUTE(2,3,0,1)); // = zw zw xy xy const __m256 aa = _mm256_min_ps( a0, a1 ); // xywz all 4 two times hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); minsOut.set(sa,sb,sb,sb); } }; template <> struct hMinH<2,3> { HK_FORCE_INLINE static void apply(const hkMxVector<2>& v, hkVector4& minsOut) { const __m256 axy = _mm256_min_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(1,1,1,1)), _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(0,0,0,0))); const __m256 aa = _mm256_min_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(2,2,2,2)), axy); hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); minsOut.set(sa,sb,sb,sb); } }; template <int N> struct hMinH<1,N> { HK_FORCE_INLINE static void apply(const hkMxVector<1>& v, hkVector4& minsOut) { const hkVector4 a = v.getVector<0>(); minsOut.setHorizontalMin<N>(a); } }; } template <int M> template <int N> HK_FORCE_INLINE void hkMxVector<M>::horizontalMin( hkVector4& minsOut ) const { hkMxVector_Implementation::hMinH<M,N>::apply(*this, minsOut); } namespace hkMxVector_Implementation { template <int M, int N> struct hMaxH { HK_FORCE_INLINE static void apply(hkMxVectorParameter v, hkVector4& maxsOut) { HK_MXVECTOR_MX_NOT_IMPLEMENTED; } }; template <> struct hMaxH<4,4> { HK_FORCE_INLINE static void apply(const hkMxVector<4>& v, hkVector4& maxsOut) { const __m256 a0 = _mm256_max_ps( _mm256_shuffle_ps( v.m_vec.v[0], v.m_vec.v[0],_MM256_PERMUTE(1,0,3,2)), v.m_vec.v[0]); // yxwz+xyzw = xy xy zw zw const __m256 a1 = _mm256_shuffle_ps(a0,a0, _MM256_PERMUTE(2,3,0,1)); // = zw zw xy xy const __m256 aa = _mm256_max_ps( a0, a1 ); // xywz all 4 two times const __m256 b0 = _mm256_max_ps( _mm256_shuffle_ps( v.m_vec.v[1], v.m_vec.v[1],_MM256_PERMUTE(1,0,3,2)), v.m_vec.v[1]); // yxwz+xyzw = xy xy zw zw const __m256 b1 = _mm256_shuffle_ps(b0,b0, _MM256_PERMUTE(2,3,0,1)); // = zw zw xy xy const __m256 bb = _mm256_max_ps( b0, b1 ); // xywz all 4 two times hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); hkSimdReal sc; sc.m_real = _mm256_extractf128_ps(bb, 0x0); hkSimdReal sd; sd.m_real = _mm256_extractf128_ps(bb, 0x1); maxsOut.set(sa,sb,sc,sd); } }; template <> struct hMaxH<4,3> { HK_FORCE_INLINE static void apply(const hkMxVector<4>& v, hkVector4& maxsOut) { const __m256 axy = _mm256_max_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(1,1,1,1)), _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(0,0,0,0))); const __m256 aa = _mm256_max_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(2,2,2,2)), axy); const __m256 bxy = _mm256_max_ps( _mm256_shuffle_ps(v.m_vec.v[1],v.m_vec.v[1],_MM256_PERMUTE(1,1,1,1)), _mm256_shuffle_ps(v.m_vec.v[1],v.m_vec.v[1],_MM256_PERMUTE(0,0,0,0))); const __m256 bb = _mm256_max_ps( _mm256_shuffle_ps(v.m_vec.v[1],v.m_vec.v[1],_MM256_PERMUTE(2,2,2,2)), bxy); hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); hkSimdReal sc; sc.m_real = _mm256_extractf128_ps(bb, 0x0); hkSimdReal sd; sd.m_real = _mm256_extractf128_ps(bb, 0x1); maxsOut.set(sa,sb,sc,sd); } }; template <> struct hMaxH<3,4> { HK_FORCE_INLINE static void apply(const hkMxVector<3>& v, hkVector4& maxsOut) { const __m256 a0 = _mm256_max_ps( _mm256_shuffle_ps( v.m_vec.v[0], v.m_vec.v[0],_MM256_PERMUTE(1,0,3,2)), v.m_vec.v[0]); // yxwz+xyzw = xy xy zw zw const __m256 a1 = _mm256_shuffle_ps(a0,a0, _MM256_PERMUTE(2,3,0,1)); // = zw zw xy xy const __m256 aa = _mm256_max_ps( a0, a1 ); // xywz all 4 two times const __m256 b0 = _mm256_max_ps( _mm256_shuffle_ps( v.m_vec.v[1], v.m_vec.v[1],_MM256_PERMUTE(1,0,3,2)), v.m_vec.v[1]); // yxwz+xyzw = xy xy zw zw const __m256 b1 = _mm256_shuffle_ps(b0,b0, _MM256_PERMUTE(2,3,0,1)); // = zw zw xy xy const __m256 bb = _mm256_max_ps( b0, b1 ); // xywz all 4 two times hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); hkSimdReal sc; sc.m_real = _mm256_extractf128_ps(bb, 0x0); maxsOut.set(sa,sb,sc,sc); } }; template <> struct hMaxH<3,3> { HK_FORCE_INLINE static void apply(const hkMxVector<3>& v, hkVector4& maxsOut) { const __m256 axy = _mm256_max_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(1,1,1,1)), _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(0,0,0,0))); const __m256 aa = _mm256_max_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(2,2,2,2)), axy); const __m256 bxy = _mm256_max_ps( _mm256_shuffle_ps(v.m_vec.v[1],v.m_vec.v[1],_MM256_PERMUTE(1,1,1,1)), _mm256_shuffle_ps(v.m_vec.v[1],v.m_vec.v[1],_MM256_PERMUTE(0,0,0,0))); const __m256 bb = _mm256_max_ps( _mm256_shuffle_ps(v.m_vec.v[1],v.m_vec.v[1],_MM256_PERMUTE(2,2,2,2)), bxy); hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); hkSimdReal sc; sc.m_real = _mm256_extractf128_ps(bb, 0x0); maxsOut.set(sa,sb,sc,sc); } }; template <> struct hMaxH<2,4> { HK_FORCE_INLINE static void apply(const hkMxVector<2>& v, hkVector4& maxsOut) { const __m256 a0 = _mm256_max_ps( _mm256_shuffle_ps( v.m_vec.v[0], v.m_vec.v[0],_MM256_PERMUTE(1,0,3,2)), v.m_vec.v[0]); // yxwz+xyzw = xy xy zw zw const __m256 a1 = _mm256_shuffle_ps(a0,a0, _MM256_PERMUTE(2,3,0,1)); // = zw zw xy xy const __m256 aa = _mm256_max_ps( a0, a1 ); // xywz all 4 two times hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); maxsOut.set(sa,sb,sb,sb); } }; template <> struct hMaxH<2,3> { HK_FORCE_INLINE static void apply(const hkMxVector<2>& v, hkVector4& maxsOut) { const __m256 axy = _mm256_max_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(1,1,1,1)), _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(0,0,0,0))); const __m256 aa = _mm256_max_ps( _mm256_shuffle_ps(v.m_vec.v[0],v.m_vec.v[0],_MM256_PERMUTE(2,2,2,2)), axy); hkSimdReal sa; sa.m_real = _mm256_extractf128_ps(aa, 0x0); hkSimdReal sb; sb.m_real = _mm256_extractf128_ps(aa, 0x1); maxsOut.set(sa,sb,sb,sb); } }; template <int N> struct hMaxH<1,N> { HK_FORCE_INLINE static void apply(const hkMxVector<1>& v, hkVector4& maxsOut) { const hkVector4 a = v.getVector<0>(); maxsOut.setHorizontalMax<N>(a); } }; } template <int M> template <int N> HK_FORCE_INLINE void hkMxVector<M>::horizontalMax( hkVector4& maxsOut ) const { hkMxVector_Implementation::hMaxH<M,N>::apply(*this, maxsOut); } namespace hkMxVector_Implementation { template <int I, int N> struct reduceAddH { HK_FORCE_INLINE static __m256 apply(const __m256* v) { const __m256 r = reduceAddH<I-2,N+1>::apply(v); return _mm256_add_ps(r, _mm256_add_ps(v[N], _mm256_permute2f128_ps(v[N], v[N], _MM256_PERMUTE2(_MM256_A_LOW,_MM256_A_HIGH)))); } }; template <int N> struct reduceAddH<2,N> { HK_FORCE_INLINE static __m256 apply(const __m256* v) { return _mm256_add_ps(v[N], _mm256_permute2f128_ps(v[N], v[N], _MM256_PERMUTE2(_MM256_A_LOW,_MM256_A_HIGH))); } }; template <int N> struct reduceAddH<1,N> { HK_FORCE_INLINE static __m256 apply(const __m256* v) { return v[N]; } }; } template <int M> HK_FORCE_INLINE void hkMxVector<M>::reduceAdd(hkVector4& addOut) const { const __m256 r = hkMxVector_Implementation::reduceAddH<M,0>::apply(m_vec.v); addOut.m_quad = _mm256_extractf128_ps(r, 0x0); } namespace hkMxVector_Implementation { template <int I, int N> struct dotH { HK_FORCE_INLINE static void apply(const __m256* v, const __m256* v0, __m256* dotsOut) { dotH<I-1,N>::apply(v, v0, dotsOut); dotsOut[I-1] = hkMxCommon_Implementation::dotProdH<N>(v[I-1], v0[I-1]); } }; template <int N> struct dotH<1,N> { HK_FORCE_INLINE static void apply(const __m256* v, const __m256* v0, __m256* dotsOut) { dotsOut[0] = hkMxCommon_Implementation::dotProdH<N>(v[0], v0[0]); } }; } template <int M> template <int N> HK_FORCE_INLINE void hkMxVector<M>::dot(hkMxVectorParameter v, hkMxReal<M>& dotsOut) const { hkMxVector_Implementation::dotH<((M+1)>>1),N>::apply(m_vec.v, v.m_vec.v, dotsOut.m_real.r); } namespace hkMxVector_Implementation { template <int I, int N> struct dotHSingle { HK_FORCE_INLINE static void apply(const __m256* v, const __m256& v0, __m256* dotsOut) { dotHSingle<I-1,N>::apply(v, v0, dotsOut); dotsOut[I-1] = hkMxCommon_Implementation::dotProdH<N>(v[I-1],v0); } }; template <int N> struct dotHSingle<1,N> { HK_FORCE_INLINE static void apply(const __m256* v, const __m256& v0, __m256* dotsOut) { dotsOut[0] = hkMxCommon_Implementation::dotProdH<N>(v[0],v0); } }; } template <int M> template <int N> HK_FORCE_INLINE void hkMxVector<M>::dot(hkMxSingleParameter v, hkMxReal<M>& dotsOut) const { hkMxVector_Implementation::dotHSingle<((M+1)>>1),N>::apply(m_vec.v, v.m_single.s, dotsOut.m_real.r); } namespace hkMxVector_Implementation { template <int I, int N, hkUint32 byteAddressIncrement> struct gatherH { HK_FORCE_INLINE static void apply(__m256* v, const __m128* HK_RESTRICT base) { v[N] = _mm256_insertf128_ps(_mm256_undefined_ps(), *hkAddByteOffsetConst( base, (N*2)*byteAddressIncrement ), 0x0); v[N] = _mm256_insertf128_ps(v[N], *hkAddByteOffsetConst( base, (N*2+1)*byteAddressIncrement ), 0x1); gatherH<I-2, N+1, byteAddressIncrement>::apply(v, base); } }; template <int N, hkUint32 byteAddressIncrement> struct gatherH<2, N, byteAddressIncrement> { HK_FORCE_INLINE static void apply(__m256* v, const __m128* HK_RESTRICT base) { v[N] = _mm256_insertf128_ps(_mm256_undefined_ps(), *hkAddByteOffsetConst( base, (N*2)*byteAddressIncrement ), 0x0); v[N] = _mm256_insertf128_ps(v[N], *hkAddByteOffsetConst( base, (N*2+1)*byteAddressIncrement ), 0x1); } }; template <int N, hkUint32 byteAddressIncrement> struct gatherH<1, N, byteAddressIncrement> { HK_FORCE_INLINE static void apply(__m256* v, const __m128* HK_RESTRICT base) { v[N] = _mm256_broadcast_ps(hkAddByteOffsetConst( base, (N*2)*byteAddressIncrement )); } }; } template <int M> template <hkUint32 byteAddressIncrement> HK_FORCE_INLINE void hkMxVector<M>::gather(const hkVector4* HK_RESTRICT base) { hkMxVector_Implementation::gatherH<M, 0, byteAddressIncrement>::apply(m_vec.v, &(base->m_quad)); } template <int M> template <hkUint32 byteAddressIncrement, int N> HK_FORCE_INLINE void hkMxVector<M>::gather(const hkVector4* HK_RESTRICT base) { HK_MXVECTOR_MX_NOT_IMPLEMENTED; // TODO.jn } namespace hkMxVector_Implementation { template <int I, int N, hkUint32 byteAddressIncrement> struct gatherUintH { HK_FORCE_INLINE static void apply(__m256* v, const __m128* HK_RESTRICT base, const hkUint16* indices) { v[N] = _mm256_insertf128_ps(_mm256_undefined_ps(), *hkAddByteOffsetConst( base, indices[N*2]*byteAddressIncrement ), 0x0); v[N] = _mm256_insertf128_ps(v[N], *hkAddByteOffsetConst( base, indices[N*2+1]*byteAddressIncrement ), 0x1); gatherUintH<I-2, N+1, byteAddressIncrement>::apply(v, base, indices); } }; template <int N, hkUint32 byteAddressIncrement> struct gatherUintH<2, N, byteAddressIncrement> { HK_FORCE_INLINE static void apply(__m256* v, const __m128* HK_RESTRICT base, const hkUint16* indices) { v[N] = _mm256_insertf128_ps(_mm256_undefined_ps(), *hkAddByteOffsetConst( base, indices[N*2]*byteAddressIncrement ), 0x0); v[N] = _mm256_insertf128_ps(v[N], *hkAddByteOffsetConst( base, indices[N*2+1]*byteAddressIncrement ), 0x1); } }; template <int N, hkUint32 byteAddressIncrement> struct gatherUintH<1, N, byteAddressIncrement> { HK_FORCE_INLINE static void apply(__m256* v, const __m128* HK_RESTRICT base, const hkUint16* indices) { v[N] = _mm256_broadcast_ps(hkAddByteOffsetConst( base, indices[N*2]*byteAddressIncrement )); } }; } template <int M> template <hkUint32 byteAddressIncrement> HK_FORCE_INLINE void hkMxVector<M>::gather(const hkVector4* HK_RESTRICT base, const hkUint16* indices) { hkMxVector_Implementation::gatherUintH<M, 0, byteAddressIncrement>::apply(m_vec.v, &(base->m_quad), indices); } namespace hkMxVector_Implementation { template <int I, int N, hkUint32 byteAddressIncrement> struct gatherIntH { HK_FORCE_INLINE static void apply(__m256* v, const __m128* HK_RESTRICT base, const hkInt32* indices) { v[N] = _mm256_insertf128_ps(_mm256_undefined_ps(), *hkAddByteOffsetConst( base, indices[N*2]*byteAddressIncrement ), 0x0); v[N] = _mm256_insertf128_ps(v[N], *hkAddByteOffsetConst( base, indices[N*2+1]*byteAddressIncrement ), 0x1); gatherIntH<I-2, N+1, byteAddressIncrement>::apply(v, base, indices); } }; template <int N, hkUint32 byteAddressIncrement> struct gatherIntH<2, N, byteAddressIncrement> { HK_FORCE_INLINE static void apply(__m256* v, const __m128* HK_RESTRICT base, const hkInt32* indices) { v[N] = _mm256_insertf128_ps(_mm256_undefined_ps(), *hkAddByteOffsetConst( base, indices[N*2]*byteAddressIncrement ), 0x0); v[N] = _mm256_insertf128_ps(v[N], *hkAddByteOffsetConst( base, indices[N*2+1]*byteAddressIncrement ), 0x1); } }; template <int N, hkUint32 byteAddressIncrement> struct gatherIntH<1, N, byteAddressIncrement> { HK_FORCE_INLINE static void apply(__m256* v, const __m128* HK_RESTRICT base, const hkInt32* indices) { v[N] = _mm256_broadcast_ps(hkAddByteOffsetConst( base, indices[N*2]*byteAddressIncrement )); } }; } template <int M> template <hkUint32 byteAddressIncrement> HK_FORCE_INLINE void hkMxVector<M>::gather(const hkVector4* HK_RESTRICT base, const hkInt32* indices) { hkMxVector_Implementation::gatherIntH<M, 0, byteAddressIncrement>::apply(m_vec.v, &(base->m_quad), indices); } namespace hkMxVector_Implementation { template <int I, int N, hkUint32 byteOffset> struct gatherWithOffsetH { HK_FORCE_INLINE static void apply(__m256* v, const void** base) { const __m128* HK_RESTRICT ptr0 = (const __m128*)hkAddByteOffsetConst(base[N*2], byteOffset); const __m128* HK_RESTRICT ptr1 = (const __m128*)hkAddByteOffsetConst(base[N*2+1], byteOffset); gatherWithOffsetH<I-2, N+1, byteOffset>::apply(v, base); v[N] = _mm256_insertf128_ps(_mm256_undefined_ps(), *ptr0, 0x0); v[N] = _mm256_insertf128_ps(v[N], *ptr1, 0x1); } }; template <int N, hkUint32 byteOffset> struct gatherWithOffsetH<2, N, byteOffset> { HK_FORCE_INLINE static void apply(__m256* v, const void** base) { const __m128* HK_RESTRICT ptr0 = (const __m128*)hkAddByteOffsetConst(base[N*2], byteOffset); const __m128* HK_RESTRICT ptr1 = (const __m128*)hkAddByteOffsetConst(base[N*2+1], byteOffset); v[N] = _mm256_insertf128_ps(_mm256_undefined_ps(), *ptr0, 0x0); v[N] = _mm256_insertf128_ps(v[N], *ptr1, 0x1); } }; template <int N, hkUint32 byteOffset> struct gatherWithOffsetH<1, N, byteOffset> { HK_FORCE_INLINE static void apply(__m256* v, const void** base) { const __m128* HK_RESTRICT ptr = (const __m128*)hkAddByteOffsetConst(base[N*2], byteOffset); v[N] = _mm256_broadcast_ps(ptr); } }; } template <int M> template <hkUint32 byteOffset> HK_FORCE_INLINE void hkMxVector<M>::gatherWithOffset(const void* base[M]) { hkMxVector_Implementation::gatherWithOffsetH<M, 0, byteOffset>::apply(m_vec.v, base); } namespace hkMxVector_Implementation { template <int I, int N, hkUint32 byteAddressIncrement> struct scatterUintH { HK_FORCE_INLINE static void apply(const __m256* v, __m128* base, const hkUint16* indices) { __m128* HK_RESTRICT ptr0 = hkAddByteOffset(base, indices[N*2] * byteAddressIncrement); __m128* HK_RESTRICT ptr1 = hkAddByteOffset(base, indices[N*2+1] * byteAddressIncrement); scatterUintH<I-2, N+1, byteAddressIncrement>::apply(v, base, indices); *ptr0 = _mm256_extractf128_ps(v[N], 0x0); *ptr1 = _mm256_extractf128_ps(v[N], 0x1); } }; template <int N, hkUint32 byteAddressIncrement> struct scatterUintH<2, N, byteAddressIncrement> { HK_FORCE_INLINE static void apply(const __m256* v, __m128* base, const hkUint16* indices) { __m128* HK_RESTRICT ptr0 = hkAddByteOffset(base, indices[N*2] * byteAddressIncrement); __m128* HK_RESTRICT ptr1 = hkAddByteOffset(base, indices[N*2+1] * byteAddressIncrement); *ptr0 = _mm256_extractf128_ps(v[N], 0x0); *ptr1 = _mm256_extractf128_ps(v[N], 0x1); } }; template <int N, hkUint32 byteAddressIncrement> struct scatterUintH<1, N, byteAddressIncrement> { HK_FORCE_INLINE static void apply(const __m256* v, __m128* base, const hkUint16* indices) { __m128* HK_RESTRICT ptr = hkAddByteOffset(base, indices[N*2] * byteAddressIncrement); *ptr = _mm256_extractf128_ps(v[N], 0x0); } }; } template <int M> template <hkUint32 byteAddressIncrement> HK_FORCE_INLINE void hkMxVector<M>::scatter(hkVector4* base, const hkUint16* indices) const { hkMxVector_Implementation::scatterUintH<M, 0, byteAddressIncrement>::apply(m_vec.v, &(base->m_quad), indices); } namespace hkMxVector_Implementation { template <int I, int N, hkUint32 byteAddressIncrement> struct scatterIntH { HK_FORCE_INLINE static void apply(const __m256* v, __m128* base, const hkInt32* indices) { __m128* HK_RESTRICT ptr0 = hkAddByteOffset(base, indices[N*2] * byteAddressIncrement); __m128* HK_RESTRICT ptr1 = hkAddByteOffset(base, indices[N*2+1] * byteAddressIncrement); scatterIntH<I-2, N+1, byteAddressIncrement>::apply(v, base, indices); *ptr0 = _mm256_extractf128_ps(v[N], 0x0); *ptr1 = _mm256_extractf128_ps(v[N], 0x1); } }; template <int N, hkUint32 byteAddressIncrement> struct scatterIntH<2, N, byteAddressIncrement> { HK_FORCE_INLINE static void apply(const __m256* v, __m128* base, const hkInt32* indices) { __m128* HK_RESTRICT ptr0 = hkAddByteOffset(base, indices[N*2] * byteAddressIncrement); __m128* HK_RESTRICT ptr1 = hkAddByteOffset(base, indices[N*2+1] * byteAddressIncrement); *ptr0 = _mm256_extractf128_ps(v[N], 0x0); *ptr1 = _mm256_extractf128_ps(v[N], 0x1); } }; template <int N, hkUint32 byteAddressIncrement> struct scatterIntH<1, N, byteAddressIncrement> { HK_FORCE_INLINE static void apply(const __m256* v, __m128* base, const hkInt32* indices) { __m128* HK_RESTRICT ptr = hkAddByteOffset(base, indices[N*2] * byteAddressIncrement); *ptr = _mm256_extractf128_ps(v[N], 0x0); } }; } template <int M> template <hkUint32 byteAddressIncrement> HK_FORCE_INLINE void hkMxVector<M>::scatter(hkVector4* base, const hkInt32* indices) const { hkMxVector_Implementation::scatterIntH<M, 0, byteAddressIncrement>::apply(m_vec.v, &(base->m_quad), indices); } namespace hkMxVector_Implementation { template <int I, int N, hkUint32 byteAddressIncrement> struct scatterH { HK_FORCE_INLINE static void apply(const __m256* v, __m128* base) { __m128* HK_RESTRICT ptr0 = hkAddByteOffset(base, (N*2) * byteAddressIncrement); __m128* HK_RESTRICT ptr1 = hkAddByteOffset(base, (N*2+1) * byteAddressIncrement); scatterH<I-2, N+1, byteAddressIncrement>::apply(v, base); *ptr0 = _mm256_extractf128_ps(v[N], 0x0); *ptr1 = _mm256_extractf128_ps(v[N], 0x1); } }; template <int N, hkUint32 byteAddressIncrement> struct scatterH<2, N, byteAddressIncrement> { HK_FORCE_INLINE static void apply(const __m256* v, __m128* base) { __m128* HK_RESTRICT ptr0 = hkAddByteOffset(base, (N*2) * byteAddressIncrement); __m128* HK_RESTRICT ptr1 = hkAddByteOffset(base, (N*2+1) * byteAddressIncrement); *ptr0 = _mm256_extractf128_ps(v[N], 0x0); *ptr1 = _mm256_extractf128_ps(v[N], 0x1); } }; template <int N, hkUint32 byteAddressIncrement> struct scatterH<1, N, byteAddressIncrement> { HK_FORCE_INLINE static void apply(const __m256* v, __m128* base) { __m128* HK_RESTRICT ptr = hkAddByteOffset(base, (N*2) * byteAddressIncrement); *ptr = _mm256_extractf128_ps(v[N], 0x0); } }; } template <int M> template <hkUint32 byteAddressIncrement> HK_FORCE_INLINE void hkMxVector<M>::scatter(hkVector4* base) const { hkMxVector_Implementation::scatterH<M, 0, byteAddressIncrement>::apply(m_vec.v, &(base->m_quad)); } namespace hkMxVector_Implementation { template <int I, int N, hkUint32 byteOffset> struct scatterWithOffsetH { HK_FORCE_INLINE static void apply(const __m256* v, void** base) { __m128* HK_RESTRICT ptr0 = (__m128*)hkAddByteOffsetConst(base[N*2], byteOffset); __m128* HK_RESTRICT ptr1 = (__m128*)hkAddByteOffsetConst(base[N*2+1], byteOffset); scatterWithOffsetH<I-2, N+1, byteOffset>::apply(v, base); *ptr0 = _mm256_extractf128_ps(v[N], 0x0); *ptr1 = _mm256_extractf128_ps(v[N], 0x1); } }; template <int N, hkUint32 byteOffset> struct scatterWithOffsetH<2, N, byteOffset> { HK_FORCE_INLINE static void apply(const __m256* v, void** base) { __m128* HK_RESTRICT ptr0 = (__m128*)hkAddByteOffsetConst(base[N*2], byteOffset); __m128* HK_RESTRICT ptr1 = (__m128*)hkAddByteOffsetConst(base[N*2+1], byteOffset); *ptr0 = _mm256_extractf128_ps(v[N], 0x0); *ptr1 = _mm256_extractf128_ps(v[N], 0x1); } }; template <int N, hkUint32 byteOffset> struct scatterWithOffsetH<1, N, byteOffset> { HK_FORCE_INLINE static void apply(const __m256* v, void** base) { __m128* HK_RESTRICT ptr = (__m128*)hkAddByteOffsetConst(base[N*2], byteOffset); *ptr = _mm256_extractf128_ps(v[N], 0x0); } }; } template <int M> template <hkUint32 byteOffset> HK_FORCE_INLINE void hkMxVector<M>::scatterWithOffset(void* base[M]) const { hkMxVector_Implementation::scatterWithOffsetH<M, 0, byteOffset>::apply(m_vec.v, base); } namespace hkMxVector_Implementation { template <int I, int N> struct lengthH { HK_FORCE_INLINE static void apply(const __m256* v, __m256* lensOut) { lengthH<I-1, N>::apply(v, lensOut); lensOut[I-1] = _mm256_sqrt_ps(hkMxCommon_Implementation::dotProdH<N>(v[I-1], v[I-1])); } }; template <int N> struct lengthH<1, N> { HK_FORCE_INLINE static void apply(const __m256* v, __m256* lensOut) { lensOut[0] = _mm256_sqrt_ps(hkMxCommon_Implementation::dotProdH<N>(v[0], v[0])); } }; } template <int M> template <int N> HK_FORCE_INLINE void hkMxVector<M>::length(hkMxReal<M>& lensOut) const { hkMxVector_Implementation::lengthH<((M+1)>>1), N>::apply(m_vec.v, lensOut.m_real.r); } namespace hkMxVector_Implementation { template <int I, int N> struct lengthSqrH { HK_FORCE_INLINE static void apply(const __m256* v, __m256* lensOut) { lengthSqrH<I-1, N>::apply(v, lensOut); lensOut[I-1] = hkMxCommon_Implementation::dotProdH<N>(v[I-1], v[I-1]); } }; template <int N> struct lengthSqrH<1, N> { HK_FORCE_INLINE static void apply(const __m256* v, __m256* lensOut) { lensOut[0] = hkMxCommon_Implementation::dotProdH<N>(v[0], v[0]); } }; } template <int M> template <int N> HK_FORCE_INLINE void hkMxVector<M>::lengthSquared(hkMxReal<M>& lensOut) const { hkMxVector_Implementation::lengthSqrH<((M+1)>>1), N>::apply(m_vec.v, lensOut.m_real.r); } namespace hkMxVector_Implementation { template <int I, int N> struct lengthInvH { HK_FORCE_INLINE static void apply(const __m256* v, __m256* lensOut, const __m256& one) { lengthInvH<I-1, N>::apply(v, lensOut, one); const __m256 len2 = hkMxCommon_Implementation::dotProdH<N>(v[I-1], v[I-1]); // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(len2, _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(len2,len2, _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 equalsZero = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); const __m256 e = _mm256_div_ps(one, _mm256_sqrt_ps(len2)); lensOut[I-1] = _mm256_andnot_ps(equalsZero, e); } }; template <int N> struct lengthInvH<1, N> { HK_FORCE_INLINE static void apply(const __m256* v, __m256* lensOut, const __m256& one) { const __m256 len2 = hkMxCommon_Implementation::dotProdH<N>(v[0], v[0]); // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(len2, _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(len2,len2, _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 equalsZero = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); const __m256 e = _mm256_div_ps(one, _mm256_sqrt_ps(len2)); lensOut[0] = _mm256_andnot_ps(equalsZero, e); } }; } template <int M> template <int N> HK_FORCE_INLINE void hkMxVector<M>::lengthInverse(hkMxReal<M>& lensOut) const { __m256 one = _mm256_set1_ps(1.0f); hkMxVector_Implementation::lengthInvH<((M+1)>>1), N>::apply(m_vec.v, lensOut.m_real.r, one); } namespace hkMxVector_Implementation { template <int I, int N> struct lengthInv12H { HK_FORCE_INLINE static void apply(const __m256* v, __m256* lensOut) { lengthInv12H<I-1, N>::apply(v, lensOut); const __m256 len2 = hkMxCommon_Implementation::dotProdH<N>(v[I-1], v[I-1]); // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(len2, _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(len2,len2, _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 equalsZero = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); const __m256 e = _mm256_rsqrt_ps(len2); lensOut[I-1] = _mm256_andnot_ps(equalsZero, e); } }; template <int N> struct lengthInv12H<1, N> { HK_FORCE_INLINE static void apply(const __m256* v, __m256* lensOut) { const __m256 len2 = hkMxCommon_Implementation::dotProdH<N>(v[0], v[0]); // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(len2, _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(len2,len2, _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 equalsZero = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); const __m256 e = _mm256_rsqrt_ps(len2); lensOut[0] = _mm256_andnot_ps(equalsZero, e); } }; } template <int M> template <int N> HK_FORCE_INLINE void hkMxVector<M>::lengthInverse_12BitAccurate(hkMxReal<M>& lensOut) const { hkMxVector_Implementation::lengthInv12H<((M+1)>>1), N>::apply(m_vec.v, lensOut.m_real.r); } namespace hkMxVector_Implementation { template <int I, int N> struct lengthInv23H { HK_FORCE_INLINE static void apply(const __m256* v, __m256* lensOut) { lengthInv23H<I-1,N>::apply(v, lensOut); const __m256 len2 = hkMxCommon_Implementation::dotProdH<N>(v[I-1], v[I-1]); // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(len2, _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(len2,len2, _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 equalsZero = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); const __m256 e = hkMxCommon_Implementation::reciprocalSquareRootH(len2); lensOut[I-1] = _mm256_andnot_ps(equalsZero, e); } }; template <int N> struct lengthInv23H<1, N> { HK_FORCE_INLINE static void apply(const __m256* v, __m256* lensOut) { const __m256 len2 = hkMxCommon_Implementation::dotProdH<N>(v[0], v[0]); // workaround VS2010 assembler bug const __m256 masklow = _mm256_cmp_ps(len2, _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 maskhigh = _mm256_cmp_ps(_mm256_permute2f128_ps(len2,len2, _MM256_PERMUTE2(_MM256_A_LOW, _MM256_A_HIGH)), _mm256_setzero_ps(), _CMP_EQ_OQ); const __m256 equalsZero = _mm256_permute2f128_ps(masklow,maskhigh, 0x20); const __m256 e = hkMxCommon_Implementation::reciprocalSquareRootH(len2); lensOut[0] = _mm256_andnot_ps(equalsZero, e); } }; } template <int M> template <int N> HK_FORCE_INLINE void hkMxVector<M>::lengthInverse_23BitAccurate(hkMxReal<M>& lensOut) const { hkMxVector_Implementation::lengthInv23H<((M+1)>>1), N>::apply(m_vec.v, lensOut.m_real.r); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void selectH(__m256* v, const __m256* mask, const __m256* tVal, const __m256* fVal) { selectH<I-1>(v, mask, tVal, fVal); v[I-1] = _mm256_blendv_ps(fVal[I-1], tVal[I-1], mask[I-1]); } template <> HK_FORCE_INLINE void selectH<1>(__m256* v, const __m256* mask, const __m256* tVal, const __m256* fVal) { v[0] = _mm256_blendv_ps(fVal[0], tVal[0], mask[0]); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setSelect(hkMxMaskParameter mask, hkMxVectorParameter trueValue, hkMxVectorParameter falseValue ) { hkMxVector_Implementation::selectH<((M+1)>>1)>(m_vec.v, mask.m_comp.c, trueValue.m_vec.v, falseValue.m_vec.v); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void selectSH(__m256* v, const __m256* mask, const __m256& tVal, const __m256* fVal) { selectSH<I-1>(v, mask, tVal, fVal); v[I-1] = _mm256_blendv_ps(fVal[I-1], tVal, mask[I-1]); } template <> HK_FORCE_INLINE void selectSH<1>(__m256* v, const __m256* mask, const __m256& tVal, const __m256* fVal) { v[0] = _mm256_blendv_ps(fVal[0], tVal, mask[0]); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setSelect(hkMxMaskParameter mask, hkMxSingleParameter trueValue, hkMxVectorParameter falseValue ) { hkMxVector_Implementation::selectSH<((M+1)>>1)>(m_vec.v, mask.m_comp.c, trueValue.m_single.s, falseValue.m_vec.v); } namespace hkMxVector_Implementation { template <int I> HK_FORCE_INLINE void selectHS(__m256* v, const __m256* mask, const __m256* tVal, const __m256& fVal) { selectHS<I-1>(v, mask, tVal, fVal); v[I-1] = _mm256_blendv_ps(fVal, tVal[I-1], mask[I-1]); } template <> HK_FORCE_INLINE void selectHS<1>(__m256* v, const __m256* mask, const __m256* tVal, const __m256& fVal) { v[0] = _mm256_blendv_ps(fVal, tVal[0], mask[0]); } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setSelect(hkMxMaskParameter mask, hkMxVectorParameter trueValue, hkMxSingleParameter falseValue ) { hkMxVector_Implementation::selectHS<((M+1)>>1)>(m_vec.v, mask.m_comp.c, trueValue.m_vec.v, falseValue.m_single.s); } namespace hkMxVector_Implementation { template <int I, int N> struct leftCH { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { leftCH<I-1,N>::apply(v,v0); v[I-1] = _mm256_permute2f128_ps(v0[I-1], v0[I%N], _MM256_PERMUTE2(_MM256_B_LOW,_MM256_A_HIGH)); } }; template <int N> struct leftCH<1,N> { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { v[0] = _mm256_permute2f128_ps(v0[0], v0[1%N], _MM256_PERMUTE2(_MM256_B_LOW,_MM256_A_HIGH)); } }; template <int I, int N> struct leftCUH { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { v[N] = _mm256_permute2f128_ps(v0[N], v0[N+1], _MM256_PERMUTE2(_MM256_B_LOW,_MM256_A_HIGH)); leftCUH<I-1,N+1>::apply(v,v0); } }; template <int N> struct leftCUH<0,N> { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { v[N] = v0[0]; } }; template <int I, int N> struct rightCH { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { rightCH<I-1,N>::apply(v,v0); v[I-1] = _mm256_permute2f128_ps(v0[I-1], v0[(I-2)%N], _MM256_PERMUTE2(_MM256_A_LOW,_MM256_B_HIGH)); } }; template <int N> struct rightCH<1,N> { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { v[0] = _mm256_permute2f128_ps(v0[0], v0[(N-1)%N], _MM256_PERMUTE2(_MM256_A_LOW,_MM256_B_HIGH)); } }; template <int I, int N> struct rightCUH { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { v[N] = _mm256_permute2f128_ps(v0[I], v0[N], _MM256_PERMUTE2(_MM256_B_LOW,_MM256_A_LOW)); rightCUH<I-1,N+1>::apply(v,v0); } }; template <int N> struct rightCUH<0,N> { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { v[N] = _mm256_permute2f128_ps(v0[0], _mm256_undefined_ps(), _MM256_PERMUTE2(_MM256_A_LOW,_MM256_A_HIGH)); } }; template <> struct rightCUH<0,0> { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { v[0] = v0[0]; } }; template <int I, int N> struct revertH { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { revertH<I-1,N+1>::apply(v,v0); v[I-1] = _mm256_permute2f128_ps(v0[N], v0[N], _MM256_PERMUTE2(_MM256_A_LOW,_MM256_A_HIGH)); } }; template <int N> struct revertH<1,N> { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { v[0] = _mm256_permute2f128_ps(v0[N], v0[N], _MM256_PERMUTE2(_MM256_A_LOW,_MM256_A_HIGH)); } }; template <int I, int N> struct revertUH { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { v[N] = _mm256_permute2f128_ps(v0[I], v0[I-1], _MM256_PERMUTE2(_MM256_B_HIGH,_MM256_A_LOW)); revertUH<I-1,N+1>::apply(v,v0); } }; template <int N> struct revertUH<0,N> { HK_FORCE_INLINE static void apply(__m256* v, const __m256* v0) { v[N] = v0[0]; } }; } template <int M> template <hkMxVectorPermutation::Permutation P> HK_FORCE_INLINE void hkMxVector<M>::setVectorPermutation(hkMxVectorParameter m) { HK_COMPILE_TIME_ASSERT2((P==hkMxVectorPermutation::SHIFT_LEFT_CYCLIC)||(P==hkMxVectorPermutation::SHIFT_RIGHT_CYCLIC)||(P==hkMxVectorPermutation::REVERSE),MX_UNKNOWN_PERMUTATION); const int N = (M+1)>>1; if ( ((2*N)-M) == 0 ) // compiletime check for uneven number of vectors { if (P == hkMxVectorPermutation::SHIFT_LEFT_CYCLIC ) { hkMxVector_Implementation::leftCH<N,N>::apply(m_vec.v, m.m_vec.v); } else if ( P == hkMxVectorPermutation::SHIFT_RIGHT_CYCLIC ) { hkMxVector_Implementation::rightCH<N,N>::apply(m_vec.v,m.m_vec.v); } else /*if ( P == hkMxVectorPermutation::REVERSE )*/ { hkMxVector_Implementation::revertH<N,0>::apply(m_vec.v, m.m_vec.v); } } else { if (P == hkMxVectorPermutation::SHIFT_LEFT_CYCLIC ) { hkMxVector_Implementation::leftCUH<N-1,0>::apply(m_vec.v, m.m_vec.v); } else if ( P == hkMxVectorPermutation::SHIFT_RIGHT_CYCLIC ) { hkMxVector_Implementation::rightCUH<N-1,0>::apply(m_vec.v,m.m_vec.v); } else /*if ( P == hkMxVectorPermutation::REVERSE )*/ { hkMxVector_Implementation::revertUH<N-1,0>::apply(m_vec.v, m.m_vec.v); } } } template <int M> HK_FORCE_INLINE void hkMxVector<M>::setAsBroadcast(hkVector4Parameter v) { HK_MXVECTOR_MX_NOT_IMPLEMENTED; } template <> HK_FORCE_INLINE void hkMxVector<4>::setAsBroadcast(hkVector4Parameter v) { hkReal x = v(0); hkReal y = v(1); m_vec.v[0] = _mm256_setr_ps(x,x,x,x,y,y,y,y); hkReal z = v(2); hkReal w = v(3); m_vec.v[1] = _mm256_setr_ps(z,z,z,z,w,w,w,w); } template <> HK_FORCE_INLINE void hkMxVector<3>::setAsBroadcast(hkVector4Parameter v) { hkReal x = v(0); hkReal y = v(1); m_vec.v[0] = _mm256_setr_ps(x,x,x,x,y,y,y,y); hkReal z = v(2); m_vec.v[1] = _mm256_broadcast_ss(&z); } template <> HK_FORCE_INLINE void hkMxVector<2>::setAsBroadcast(hkVector4Parameter v) { hkReal x = v(0); hkReal y = v(1); m_vec.v[0] = _mm256_setr_ps(x,x,x,x,y,y,y,y); } template <> HK_FORCE_INLINE void hkMxVector<1>::setAsBroadcast(hkVector4Parameter v) { hkReal x = v(0); m_vec.v[0] = _mm256_broadcast_ss(&x); } #undef MXV_NO_OPERANDS #undef MXV_OP_MXVECTOR #undef MXV_OP_MXVECTOR_MXVECTOR #undef MXV_OP_MXVECTOR_MXVECTOR_MXVECTOR #undef MXV_OP_MXVECTOR_MXVECTOR_MXSINGLE #undef MXV_OP_MXVECTOR_MXVECTOR_MXREAL #undef MXV_OP_MXVECTOR_MXVECTOR_SELF #undef MXV_OP_MXVECTOR_MXSINGLE_SELF #undef MXV_OP_MXREAL_MXVECTOR_SELF #undef MXV_OP_MXVECTOR_MXSINGLE_MXREAL #undef MXV_OP_MXREAL #undef MXV_OP_MXSINGLE #undef MXV_OP_MXREAL_MXVECTOR #undef MXV_OP_MXVECTOR_MXSINGLE #undef MXV_OP_MXSINGLE_MXSINGLE #undef MXV_OP_MXSINGLE_MXVECTOR #undef MXV_COMPARE #undef MXV_COMPARE_SINGLE /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20120831) * * Confidential Information of Havok. (C) Copyright 1999-2012 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ "evg.gamedev@gmail.com" ]
evg.gamedev@gmail.com
8a69bea5259d582f54d5d940f4d4a1a3b36f7268
444e3a601af404664cc5c59624eb91388e49dc88
/RecoUtils/src/classes.h
226f502fc72d51ff7460fd601a09a5942eac16f1
[]
no_license
muell149/CommonTools
d2386e61e66b9178a735c740a356f80226cd8282
c950bff9969efa63e9d4f9ae0737ee902ddcefdf
refs/heads/master
2021-01-23T10:00:37.059864
2014-09-15T00:59:46
2014-09-15T00:59:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
328
h
#include "DataFormats/Common/interface/Wrapper.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/EDProducer.h" namespace { struct dictionary { std::vector<std::pair<unsigned int,float> > am7; std::map<unsigned int,std::vector<std::pair<unsigned int,float> > > am8; }; }
[ "charles.mueller@cern.ch" ]
charles.mueller@cern.ch
a384f21a079c281509045a5b555e301dce8cbf1c
e88f8d973fd9e725d6041670c57b016b95eb5571
/11278 - One-Handed Typist.cpp
9f44b358c41c2f0ed1e884188a479eb7c0efc7d7
[]
no_license
rhasanrakib/UVA-Problem-Solved-
577a49ec041e7ab322e4413bac8b3bd93327f4b6
5bdf5fc284c80979f8018ecd9c5719895a0d2462
refs/heads/master
2023-03-13T04:21:03.762698
2021-02-28T10:03:24
2021-02-28T10:03:24
132,423,088
1
0
null
null
null
null
UTF-8
C++
false
false
642
cpp
#include<bits/stdc++.h> using namespace std; int main() { char dvo[] = "`123qjlmfp/[]456.orsuyb;=\\789aehtdck-0zx,inwvg' ~!@#QJLMFP?{}$%^>ORSUYB:+|&*(AEHTDCK_)ZX<INWVG\""; char keyboard[]="`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./ ~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:\"ZXCVBNM<>?"; char indx[200]; int i,j,k,l; char inp[500]; for(i=0;i<strlen(keyboard);i++) { indx[keyboard[i]]=dvo[i]; } for(i=0;i<strlen(keyboard);i++) printf("i=%d %d %c\n",i,indx[keyboard[i]],dvo[i]); while(gets(inp)) { int len=strlen(inp); int keylen=strlen(dvo); for(i=0;i<len;i++) { printf("%c",indx[inp[i]]); } cout<<endl; } }
[ "rakibulh170@gmail.com" ]
rakibulh170@gmail.com
8c46263094aef5a3f864a3c586239d5a058a5ca7
ca7319fc17b36a9f28bf8eb14d944e70aa787c85
/src/cpp_code/Hockney/Hockney.H
13904b13be28e0c6e41a2f47f695c0639a7f68ec
[]
no_license
hbeams/VortexInCell
a5bb6c90f6da5942ab6adc73d893d8b70ce0f78f
9e08b8192747d8577e4a4aa722b05db517713457
refs/heads/master
2020-06-30T04:53:33.840575
2019-08-05T21:42:10
2019-08-05T21:42:10
200,731,701
5
0
null
null
null
null
UTF-8
C++
false
false
624
h
#ifndef _HOCKNEY_ #define _HOCKNEY_ #include "RectMDArray.H" #include "FFTMD.H" #include "ConvKernel.H" #include <array> #include <memory> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <string> using namespace std; class Hockney { public: Hockney(); Hockney(shared_ptr<ConvKernel>& a_kerPtr,const double& a_h,int a_M); void define(shared_ptr<ConvKernel>& a_kerPtr,const double& a_h,int a_M); void convolve(RectMDArray<double>& a_rhs); ~Hockney(){}; protected: double m_h; int m_M,m_N; FFTMD m_fftmd; shared_ptr<ConvKernel> m_kerPtr; bool m_isDefined; }; #endif
[ "noreply@github.com" ]
noreply@github.com
958a00bee4c5eff7ca217ba40ccd17e9961760ee
412490586f58cd690eea9bb0fdc30bb1fafa79e1
/test/gtl_test_socketclient/gtl_test_socketclient.cpp
ca3fd3613c6d6eb582171bbbe51582f830c3d9b3
[]
no_license
xyfigo/gtl
a93e236557fc3eee73fe8025775cef22977be125
2468d858dec43d664e7aafa252e1d2b79623fba1
refs/heads/master
2020-04-15T15:55:41.025404
2017-03-29T04:09:30
2017-03-29T04:09:30
null
0
0
null
null
null
null
GB18030
C++
false
false
1,915
cpp
// gtl_test_socketclient.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "../../gtl/socket.h" int _tmain(int argc, _TCHAR* argv[]) { gtl::Socket::startup(); gtl::SocketClient sc; gtl::SessionSharedPtr ssp = sc.connect("127.0.0.1", 6666); int ok = -1; int cmd = gtl::Session::BEGINSESSION; ssp->send((const char *)&cmd, sizeof(int),0); ssp->receive((char*)&ok, sizeof(int), 0); if (ok == gtl::Session::OKAY) { std::cout << "开始会话\n"; } //////////////////////////////////////////////////////////// cmd = gtl::Session::RANGEQUERY; ssp->send((const char *)&cmd, sizeof(int), 0); ssp->receive((char*)&ok, sizeof(int), 0); if (ok == gtl::Session::OKAY) { std::cout << "开始范围查询\n"; } //发送参数 char buf[256]; ssp->send(buf, 256, 0); //接收查询结果 int result = ssp->receive(buf, 256, 0); //////////////////////////////////////////////////////////////// cmd = gtl::Session::KNNQUERY; ssp->send((const char *)&cmd, sizeof(int), 0); ssp->receive((char*)&ok, sizeof(int), 0); if (ok == gtl::Session::OKAY) { std::cout << "开始邻近查询\n"; } //发送参数 ssp->send(buf, 256, 0); //接收查询结果 result = ssp->receive(buf, 256, 0); ////////////////////////////////////////////////////////////////// cmd = gtl::Session::KNNQUERY; ssp->send((const char *)&cmd, sizeof(int), 0); ssp->receive((char*)&ok, sizeof(int), 0); if (ok == gtl::Session::OKAY) { std::cout << "开始邻近查询\n"; } //发送参数 ssp->send(buf, 256, 0); //接收查询结果 result = ssp->receive(buf, 256, 0); //////////////////////////////////////////////////////////////////// cmd = gtl::Session::ENDSESSION; ssp->send((const char *)&cmd, sizeof(int), 0); ssp->receive((char*)&ok, sizeof(int), 0); if (ok == gtl::Session::OKAY) { std::cout << "结束会话\n"; } gtl::Socket::cleanup(); return 0; }
[ "zwhe@cug.edu.cn" ]
zwhe@cug.edu.cn
f72e33d1960db91b15d2f0a5d52f03f402d0428c
da1ba0378e1ed8ff8380afb9072efcd3bbead74e
/google/cloud/dialogflow_es/contexts_options.h
991a33690a1cc33d97f47c1642a4bfde5a013357
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Jseph/google-cloud-cpp
76894af7ce744cd44304b48bea32d5116ded7497
fd8e70650ebac0c10bac4b293972e79eef46b128
refs/heads/master
2022-10-18T13:07:01.710328
2022-10-01T18:16:16
2022-10-01T18:16:16
192,397,663
0
0
null
2019-06-17T18:22:36
2019-06-17T18:22:35
null
UTF-8
C++
false
false
2,053
h
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/dialogflow/v2/context.proto #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_DIALOGFLOW_ES_CONTEXTS_OPTIONS_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_DIALOGFLOW_ES_CONTEXTS_OPTIONS_H #include "google/cloud/dialogflow_es/contexts_connection.h" #include "google/cloud/dialogflow_es/contexts_connection_idempotency_policy.h" #include "google/cloud/backoff_policy.h" #include "google/cloud/options.h" #include "google/cloud/version.h" #include <memory> namespace google { namespace cloud { namespace dialogflow_es { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN /// Option to use with `google::cloud::Options`. struct ContextsRetryPolicyOption { using Type = std::shared_ptr<ContextsRetryPolicy>; }; /// Option to use with `google::cloud::Options`. struct ContextsBackoffPolicyOption { using Type = std::shared_ptr<BackoffPolicy>; }; /// Option to use with `google::cloud::Options`. struct ContextsConnectionIdempotencyPolicyOption { using Type = std::shared_ptr<ContextsConnectionIdempotencyPolicy>; }; using ContextsPolicyOptionList = OptionList<ContextsRetryPolicyOption, ContextsBackoffPolicyOption, ContextsConnectionIdempotencyPolicyOption>; GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace dialogflow_es } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_DIALOGFLOW_ES_CONTEXTS_OPTIONS_H
[ "noreply@github.com" ]
noreply@github.com
7e1d08fc7d0a13d2f6247df57ddeed36e6bf1add
050243efb53e78497024af0156c87d416c3afc53
/src/checkpoints.cpp
0ce9515dbd3d942d4daeeb3398392e466966bf17
[ "MIT" ]
permissive
LeinCoin/Ritzcoin
95f358031c1ffe1a714c5ea08f8abe2d6b3ea00d
393bf63f2a7e7e672138f1caec8b7b9862acc060
refs/heads/master
2021-01-15T22:30:01.871282
2016-05-15T13:27:42
2016-05-15T13:27:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,287
cpp
// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/foreach.hpp> #include "checkpoints.h" #include "main.h" #include "uint256.h" namespace Checkpoints { typedef std::map<int, uint256> MapCheckpoints; // How many times we expect transactions after the last checkpoint to // be slower. This number is a compromise, as it can't be accurate for // every system. When reindexing from a fast disk with a slow CPU, it // can be up to 20, while when downloading from a slow network with a // fast multicore CPU, it won't be much higher than 1. static const double fSigcheckVerificationFactor = 5.0; struct CCheckpointData { const MapCheckpoints *mapCheckpoints; int64 nTimeLastCheckpoint; int64 nTransactionsLastCheckpoint; double fTransactionsPerDay; }; // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) static MapCheckpoints mapCheckpoints = boost::assign::map_list_of ( 0, uint256("0xf2a02df42853e11ee406a22cf94873880099bd9e1a76d057e8bcfd34bbab89ec")) ( 1, uint256("0x60e0b685683ce72a961d39dfcd6e3321211039d62b27dd28d06812bb24e1844d")) // ( 2, uint256("0xf2a02df42853e11ee406a22cf94873880099bd9e1a76d057e8bcfd34bbab89ec")) ; static const CCheckpointData data = { &mapCheckpoints, 1388880557, // * UNIX timestamp of last checkpoint block 0, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 8000.0 // * estimated number of transactions per day after checkpoint }; static MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of ( 0, uint256("0x")) ; static const CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1369685559, 37581, 300 }; const CCheckpointData &Checkpoints() { if (fTestNet) return dataTestnet; else return data; } bool CheckBlock(int nHeight, const uint256& hash) { if (fTestNet) return true; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return true; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; MapCheckpoints::const_iterator i = checkpoints.find(nHeight); if (i == checkpoints.end()) return true; return hash == i->second; } // Guess how far we are in the verification process at the given block index double GuessVerificationProgress(CBlockIndex *pindex) { if (pindex==NULL) return 0.0; int64 nNow = time(NULL); double fWorkBefore = 0.0; // Amount of work done before pindex double fWorkAfter = 0.0; // Amount of work left after pindex (estimated) // Work is defined as: 1.0 per transaction before the last checkoint, and // fSigcheckVerificationFactor per transaction after. const CCheckpointData &data = Checkpoints(); if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) { double nCheapBefore = pindex->nChainTx; double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx; double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore; fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor; } else { double nCheapBefore = data.nTransactionsLastCheckpoint; double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint; double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay; fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor; fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor; } return fWorkBefore / (fWorkBefore + fWorkAfter); } int GetTotalBlocksEstimate() { if (fTestNet) return 0; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return 0; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; return checkpoints.rbegin()->first; } CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex) { if (fTestNet) return NULL; // Testnet has no checkpoints if (!GetBoolArg("-checkpoints", true)) return NULL; const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints; BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) { const uint256& hash = i.second; std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash); if (t != mapBlockIndex.end()) return t->second; } return NULL; } }
[ "webmaster@ritzcoin.com" ]
webmaster@ritzcoin.com
062054fd83bf7d2ec911d73e7ff1fe0606a88934
5b4da825e536f570a464ae9f5d7f377fc16e12b7
/externals/wasm-compiler/llvm/lib/Target/AMDGPU/SILowerControlFlow.cpp
7ed18f27e5912ad2ecdf83330723d3a96796aa23
[ "BSD-3-Clause", "Apache-2.0", "MIT", "NCSA" ]
permissive
JaminChan/eos_win
9ecb3fe7d1fbb52340e7b8df42b2d3d6695930a6
c03e57151cfe152d0d3120abb13226f4df74f37e
refs/heads/master
2020-03-24T20:38:49.539494
2018-09-06T10:13:16
2018-09-06T10:13:16
142,989,586
0
0
MIT
2018-09-04T06:49:10
2018-07-31T09:02:44
C++
UTF-8
C++
false
false
14,761
cpp
//===-- SILowerControlFlow.cpp - Use predicates for control flow ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file /// \brief This pass lowers the pseudo control flow instructions to real /// machine instructions. /// /// All control flow is handled using predicated instructions and /// a predicate stack. Each Scalar ALU controls the operations of 64 Vector /// ALUs. The Scalar ALU can update the predicate for any of the Vector ALUs /// by writting to the 64-bit EXEC register (each bit corresponds to a /// single vector ALU). Typically, for predicates, a vector ALU will write /// to its bit of the VCC register (like EXEC VCC is 64-bits, one for each /// Vector ALU) and then the ScalarALU will AND the VCC register with the /// EXEC to update the predicates. /// /// For example: /// %VCC = V_CMP_GT_F32 %VGPR1, %VGPR2 /// %SGPR0 = SI_IF %VCC /// %VGPR0 = V_ADD_F32 %VGPR0, %VGPR0 /// %SGPR0 = SI_ELSE %SGPR0 /// %VGPR0 = V_SUB_F32 %VGPR0, %VGPR0 /// SI_END_CF %SGPR0 /// /// becomes: /// /// %SGPR0 = S_AND_SAVEEXEC_B64 %VCC // Save and update the exec mask /// %SGPR0 = S_XOR_B64 %SGPR0, %EXEC // Clear live bits from saved exec mask /// S_CBRANCH_EXECZ label0 // This instruction is an optional /// // optimization which allows us to /// // branch if all the bits of /// // EXEC are zero. /// %VGPR0 = V_ADD_F32 %VGPR0, %VGPR0 // Do the IF block of the branch /// /// label0: /// %SGPR0 = S_OR_SAVEEXEC_B64 %EXEC // Restore the exec mask for the Then block /// %EXEC = S_XOR_B64 %SGPR0, %EXEC // Clear live bits from saved exec mask /// S_BRANCH_EXECZ label1 // Use our branch optimization /// // instruction again. /// %VGPR0 = V_SUB_F32 %VGPR0, %VGPR // Do the THEN block /// label1: /// %EXEC = S_OR_B64 %EXEC, %SGPR0 // Re-enable saved exec mask bits //===----------------------------------------------------------------------===// #include "AMDGPU.h" #include "AMDGPUSubtarget.h" #include "SIInstrInfo.h" #include "SIMachineFunctionInfo.h" #include "llvm/CodeGen/LivePhysRegs.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" using namespace llvm; #define DEBUG_TYPE "si-lower-control-flow" namespace { class SILowerControlFlow : public MachineFunctionPass { private: const SIRegisterInfo *TRI; const SIInstrInfo *TII; LiveIntervals *LIS; MachineRegisterInfo *MRI; void emitIf(MachineInstr &MI); void emitElse(MachineInstr &MI); void emitBreak(MachineInstr &MI); void emitIfBreak(MachineInstr &MI); void emitElseBreak(MachineInstr &MI); void emitLoop(MachineInstr &MI); void emitEndCf(MachineInstr &MI); void findMaskOperands(MachineInstr &MI, unsigned OpNo, SmallVectorImpl<MachineOperand> &Src) const; void combineMasks(MachineInstr &MI); public: static char ID; SILowerControlFlow() : MachineFunctionPass(ID), TRI(nullptr), TII(nullptr), LIS(nullptr), MRI(nullptr) {} bool runOnMachineFunction(MachineFunction &MF) override; StringRef getPassName() const override { return "SI Lower control flow pseudo instructions"; } void getAnalysisUsage(AnalysisUsage &AU) const override { // Should preserve the same set that TwoAddressInstructions does. AU.addPreserved<SlotIndexes>(); AU.addPreserved<LiveIntervals>(); AU.addPreservedID(LiveVariablesID); AU.addPreservedID(MachineLoopInfoID); AU.addPreservedID(MachineDominatorsID); AU.setPreservesCFG(); MachineFunctionPass::getAnalysisUsage(AU); } }; } // End anonymous namespace char SILowerControlFlow::ID = 0; INITIALIZE_PASS(SILowerControlFlow, DEBUG_TYPE, "SI lower control flow", false, false) static void setImpSCCDefDead(MachineInstr &MI, bool IsDead) { MachineOperand &ImpDefSCC = MI.getOperand(3); assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef()); ImpDefSCC.setIsDead(IsDead); } char &llvm::SILowerControlFlowID = SILowerControlFlow::ID; void SILowerControlFlow::emitIf(MachineInstr &MI) { MachineBasicBlock &MBB = *MI.getParent(); const DebugLoc &DL = MI.getDebugLoc(); MachineBasicBlock::iterator I(&MI); MachineOperand &SaveExec = MI.getOperand(0); MachineOperand &Cond = MI.getOperand(1); assert(SaveExec.getSubReg() == AMDGPU::NoSubRegister && Cond.getSubReg() == AMDGPU::NoSubRegister); unsigned SaveExecReg = SaveExec.getReg(); MachineOperand &ImpDefSCC = MI.getOperand(4); assert(ImpDefSCC.getReg() == AMDGPU::SCC && ImpDefSCC.isDef()); // Add an implicit def of exec to discourage scheduling VALU after this which // will interfere with trying to form s_and_saveexec_b64 later. unsigned CopyReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass); MachineInstr *CopyExec = BuildMI(MBB, I, DL, TII->get(AMDGPU::COPY), CopyReg) .addReg(AMDGPU::EXEC) .addReg(AMDGPU::EXEC, RegState::ImplicitDefine); unsigned Tmp = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass); MachineInstr *And = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_AND_B64), Tmp) .addReg(CopyReg) //.addReg(AMDGPU::EXEC) .addReg(Cond.getReg()); setImpSCCDefDead(*And, true); MachineInstr *Xor = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_XOR_B64), SaveExecReg) .addReg(Tmp) .addReg(CopyReg); setImpSCCDefDead(*Xor, ImpDefSCC.isDead()); // Use a copy that is a terminator to get correct spill code placement it with // fast regalloc. MachineInstr *SetExec = BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64_term), AMDGPU::EXEC) .addReg(Tmp, RegState::Kill); // Insert a pseudo terminator to help keep the verifier happy. This will also // be used later when inserting skips. MachineInstr *NewBr = BuildMI(MBB, I, DL, TII->get(AMDGPU::SI_MASK_BRANCH)) .addOperand(MI.getOperand(2)); if (!LIS) { MI.eraseFromParent(); return; } LIS->InsertMachineInstrInMaps(*CopyExec); // Replace with and so we don't need to fix the live interval for condition // register. LIS->ReplaceMachineInstrInMaps(MI, *And); LIS->InsertMachineInstrInMaps(*Xor); LIS->InsertMachineInstrInMaps(*SetExec); LIS->InsertMachineInstrInMaps(*NewBr); LIS->removeRegUnit(*MCRegUnitIterator(AMDGPU::EXEC, TRI)); MI.eraseFromParent(); // FIXME: Is there a better way of adjusting the liveness? It shouldn't be // hard to add another def here but I'm not sure how to correctly update the // valno. LIS->removeInterval(SaveExecReg); LIS->createAndComputeVirtRegInterval(SaveExecReg); LIS->createAndComputeVirtRegInterval(Tmp); LIS->createAndComputeVirtRegInterval(CopyReg); } void SILowerControlFlow::emitElse(MachineInstr &MI) { MachineBasicBlock &MBB = *MI.getParent(); const DebugLoc &DL = MI.getDebugLoc(); unsigned DstReg = MI.getOperand(0).getReg(); assert(MI.getOperand(0).getSubReg() == AMDGPU::NoSubRegister); bool ExecModified = MI.getOperand(3).getImm() != 0; MachineBasicBlock::iterator Start = MBB.begin(); // We are running before TwoAddressInstructions, and si_else's operands are // tied. In order to correctly tie the registers, split this into a copy of // the src like it does. unsigned CopyReg = MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass); BuildMI(MBB, Start, DL, TII->get(AMDGPU::COPY), CopyReg) .addOperand(MI.getOperand(1)); // Saved EXEC // This must be inserted before phis and any spill code inserted before the // else. unsigned SaveReg = ExecModified ? MRI->createVirtualRegister(&AMDGPU::SReg_64RegClass) : DstReg; MachineInstr *OrSaveExec = BuildMI(MBB, Start, DL, TII->get(AMDGPU::S_OR_SAVEEXEC_B64), SaveReg) .addReg(CopyReg); MachineBasicBlock *DestBB = MI.getOperand(2).getMBB(); MachineBasicBlock::iterator ElsePt(MI); if (ExecModified) { MachineInstr *And = BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_AND_B64), DstReg) .addReg(AMDGPU::EXEC) .addReg(SaveReg); if (LIS) LIS->InsertMachineInstrInMaps(*And); } MachineInstr *Xor = BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::S_XOR_B64_term), AMDGPU::EXEC) .addReg(AMDGPU::EXEC) .addReg(DstReg); MachineInstr *Branch = BuildMI(MBB, ElsePt, DL, TII->get(AMDGPU::SI_MASK_BRANCH)) .addMBB(DestBB); if (!LIS) { MI.eraseFromParent(); return; } LIS->RemoveMachineInstrFromMaps(MI); MI.eraseFromParent(); LIS->InsertMachineInstrInMaps(*OrSaveExec); LIS->InsertMachineInstrInMaps(*Xor); LIS->InsertMachineInstrInMaps(*Branch); // src reg is tied to dst reg. LIS->removeInterval(DstReg); LIS->createAndComputeVirtRegInterval(DstReg); LIS->createAndComputeVirtRegInterval(CopyReg); if (ExecModified) LIS->createAndComputeVirtRegInterval(SaveReg); // Let this be recomputed. LIS->removeRegUnit(*MCRegUnitIterator(AMDGPU::EXEC, TRI)); } void SILowerControlFlow::emitBreak(MachineInstr &MI) { MachineBasicBlock &MBB = *MI.getParent(); const DebugLoc &DL = MI.getDebugLoc(); unsigned Dst = MI.getOperand(0).getReg(); MachineInstr *Or = BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_OR_B64), Dst) .addReg(AMDGPU::EXEC) .addOperand(MI.getOperand(1)); if (LIS) LIS->ReplaceMachineInstrInMaps(MI, *Or); MI.eraseFromParent(); } void SILowerControlFlow::emitIfBreak(MachineInstr &MI) { MI.setDesc(TII->get(AMDGPU::S_OR_B64)); } void SILowerControlFlow::emitElseBreak(MachineInstr &MI) { MI.setDesc(TII->get(AMDGPU::S_OR_B64)); } void SILowerControlFlow::emitLoop(MachineInstr &MI) { MachineBasicBlock &MBB = *MI.getParent(); const DebugLoc &DL = MI.getDebugLoc(); MachineInstr *AndN2 = BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_ANDN2_B64_term), AMDGPU::EXEC) .addReg(AMDGPU::EXEC) .addOperand(MI.getOperand(0)); MachineInstr *Branch = BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) .addOperand(MI.getOperand(1)); if (LIS) { LIS->ReplaceMachineInstrInMaps(MI, *AndN2); LIS->InsertMachineInstrInMaps(*Branch); } MI.eraseFromParent(); } void SILowerControlFlow::emitEndCf(MachineInstr &MI) { MachineBasicBlock &MBB = *MI.getParent(); const DebugLoc &DL = MI.getDebugLoc(); MachineBasicBlock::iterator InsPt = MBB.begin(); MachineInstr *NewMI = BuildMI(MBB, InsPt, DL, TII->get(AMDGPU::S_OR_B64), AMDGPU::EXEC) .addReg(AMDGPU::EXEC) .addOperand(MI.getOperand(0)); if (LIS) LIS->ReplaceMachineInstrInMaps(MI, *NewMI); MI.eraseFromParent(); if (LIS) LIS->handleMove(*NewMI); } // Returns replace operands for a logical operation, either single result // for exec or two operands if source was another equivalent operation. void SILowerControlFlow::findMaskOperands(MachineInstr &MI, unsigned OpNo, SmallVectorImpl<MachineOperand> &Src) const { MachineOperand &Op = MI.getOperand(OpNo); if (!Op.isReg() || !TargetRegisterInfo::isVirtualRegister(Op.getReg())) { Src.push_back(Op); return; } MachineInstr *Def = MRI->getUniqueVRegDef(Op.getReg()); if (!Def || Def->getParent() != MI.getParent() || !(Def->isFullCopy() || (Def->getOpcode() == MI.getOpcode()))) return; // Make sure we do not modify exec between def and use. // A copy with implcitly defined exec inserted earlier is an exclusion, it // does not really modify exec. for (auto I = Def->getIterator(); I != MI.getIterator(); ++I) if (I->modifiesRegister(AMDGPU::EXEC, TRI) && !(I->isCopy() && I->getOperand(0).getReg() != AMDGPU::EXEC)) return; for (const auto &SrcOp : Def->explicit_operands()) if (SrcOp.isUse() && (!SrcOp.isReg() || TargetRegisterInfo::isVirtualRegister(SrcOp.getReg()) || SrcOp.getReg() == AMDGPU::EXEC)) Src.push_back(SrcOp); } // Search and combine pairs of equivalent instructions, like // S_AND_B64 x, (S_AND_B64 x, y) => S_AND_B64 x, y // S_OR_B64 x, (S_OR_B64 x, y) => S_OR_B64 x, y // One of the operands is exec mask. void SILowerControlFlow::combineMasks(MachineInstr &MI) { assert(MI.getNumExplicitOperands() == 3); SmallVector<MachineOperand, 4> Ops; unsigned OpToReplace = 1; findMaskOperands(MI, 1, Ops); if (Ops.size() == 1) OpToReplace = 2; // First operand can be exec or its copy findMaskOperands(MI, 2, Ops); if (Ops.size() != 3) return; unsigned UniqueOpndIdx; if (Ops[0].isIdenticalTo(Ops[1])) UniqueOpndIdx = 2; else if (Ops[0].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1; else if (Ops[1].isIdenticalTo(Ops[2])) UniqueOpndIdx = 1; else return; unsigned Reg = MI.getOperand(OpToReplace).getReg(); MI.RemoveOperand(OpToReplace); MI.addOperand(Ops[UniqueOpndIdx]); if (MRI->use_empty(Reg)) MRI->getUniqueVRegDef(Reg)->eraseFromParent(); } bool SILowerControlFlow::runOnMachineFunction(MachineFunction &MF) { const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); TII = ST.getInstrInfo(); TRI = &TII->getRegisterInfo(); // This doesn't actually need LiveIntervals, but we can preserve them. LIS = getAnalysisIfAvailable<LiveIntervals>(); MRI = &MF.getRegInfo(); MachineFunction::iterator NextBB; for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE; BI = NextBB) { NextBB = std::next(BI); MachineBasicBlock &MBB = *BI; MachineBasicBlock::iterator I, Next, Last; for (I = MBB.begin(), Last = MBB.end(); I != MBB.end(); I = Next) { Next = std::next(I); MachineInstr &MI = *I; switch (MI.getOpcode()) { case AMDGPU::SI_IF: emitIf(MI); break; case AMDGPU::SI_ELSE: emitElse(MI); break; case AMDGPU::SI_BREAK: emitBreak(MI); break; case AMDGPU::SI_IF_BREAK: emitIfBreak(MI); break; case AMDGPU::SI_ELSE_BREAK: emitElseBreak(MI); break; case AMDGPU::SI_LOOP: emitLoop(MI); break; case AMDGPU::SI_END_CF: emitEndCf(MI); break; case AMDGPU::S_AND_B64: case AMDGPU::S_OR_B64: // Cleanup bit manipulations on exec mask combineMasks(MI); Last = I; continue; default: Last = I; continue; } // Replay newly inserted code to combine masks Next = (Last == MBB.end()) ? MBB.begin() : Last; } } return true; }
[ "349683504@qq.com" ]
349683504@qq.com
f62031bf9fcc660a5c613019ccc0dc933dd6a945
2bbb3cb94e8340aa60e0f17a16ff100e32b9ba0b
/proj/src/proj_multihreading.cpp
9aebef74694a2af0e7a27ba04af9f15d0db38a44
[]
no_license
monalisakalla/Assignments
8346d13b9aa73f914b7dbbc6f103f2c2a4b33bc4
f7e239e329d01949f7d31da8b2385682ef788a26
refs/heads/master
2020-03-21T22:43:22.880792
2018-10-31T06:40:05
2018-10-31T06:40:05
139,143,223
0
0
null
null
null
null
UTF-8
C++
false
false
2,669
cpp
#include "../inc/proj_multihreading.h" static bool threadCreation = false; static bool keepAlive = true; bool WorkerThread::wthKeepAlive = true; PrimaryThread::PrimaryThread() { dataregion.resize(MAXSIZE); } void PrimaryThread::gracefullExitCallBackFunc(int signum) { cout<<endl<<"gracefull exit called"<<endl; WorkerThread::wthKeepAlive = false; keepAlive = false; } void PrimaryThread::Start() { wObj1 = new WorkerThread(); wObj2 = new WorkerThread(); wObj3 = new WorkerThread(); wObj4 = new WorkerThread(); wt1 = new thread(&WorkerThread::Write, wObj1,TH1STARTPOS, TH1ENDPOS,THI1STARTVALUE, this,wObj2); wt1->detach(); wt2 = new thread(&WorkerThread::Write, wObj2,TH2STARTPOS, TH2ENDPOS,TH2STARTVALUE,this,wObj3); wt2->detach(); wt3 = new thread(&WorkerThread::Write, wObj3,TH3STARTPOS, TH3ENDPOS,TH3STARTVALUE,this,wObj4); wt3->detach(); wt4 = new thread(&WorkerThread::Write, wObj4,TH4STARTPOS, TH4ENDPOS,TH4STARTVALUE,this,wObj1); wt4->detach(); } WorkerThread::WorkerThread() { cout<< endl << "Worker thread boject created" << endl; } void WorkerThread::Write(int startpos, int endpos, int startvalue, PrimaryThread *pthis, WorkerThread *nextWorkerThread) { while(wthKeepAlive) { int initvalue = startvalue; cout<<endl<<"startpos :"<<startpos << " " <<"endpos :"<<endpos<<" "<<"startvalue :" <<startvalue; for(int count = startpos ; count<= endpos; count++) { //cout<<endl<<count<<endl; pthis->dataregion[count] = initvalue; initvalue++; } nextWorkerThread->Verify(startpos,endpos,startvalue,pthis); } cout << endl << "Worker thread exited successfully!!!!" << endl; } void WorkerThread::Verify(int startpos, int endpos, int startvalue, PrimaryThread *pthis) { int initvalue = startvalue; int misscount = 0; cout<<endl<<"startpos verify :"<<startpos << " " <<"endpos :"<<endpos<<" "<<"startvalue :" <<startvalue; for(int count = startpos ; count<= endpos; count++) { if(pthis->dataregion.at(count) != initvalue) { cout <<endl <<"Value not matched at pos: " << count <<"current value is:" << pthis->dataregion.at(count) << endl; misscount++; } initvalue ++ ; } cout<<endl << "Count of values missed to write in this data region is :" << misscount <<endl; } int main() { while (keepAlive) { if(!threadCreation) { threadCreation = true; PrimaryThread *pth = new PrimaryThread(); thread primaryThread( &PrimaryThread::Start,pth); signal(SIGINT, PrimaryThread::gracefullExitCallBackFunc); primaryThread.join(); } } cout << endl << "Main thread exited successfully" << endl; return 1; }
[ "monalisa.kalla@einfochips.com" ]
monalisa.kalla@einfochips.com
a5a0e6cd9c471aa19c56deac9c2bc4d627d86677
b1f1316be90ffbdf2bf81bf9521f309763b92233
/Doom/src/Doom/OpenGl/Texture.cpp
7fbdb711c1f5f45ab0783c34373b28acf5845cc0
[ "MIT" ]
permissive
anggawasita/OpenGL_Engine
f8cde189521f6b717d75db82991943eff85999af
16393609755e171dd5430cdd7586771d859d5113
refs/heads/master
2023-02-27T14:34:00.550646
2021-01-29T13:46:19
2021-01-29T13:46:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,123
cpp
#include "../pch.h" #include "Texture.h" #include "stb_image.h" #include <filesystem> namespace fs = std::filesystem; using namespace Doom; Texture::Texture(const std::string& path, int flip,bool repeat) :m_RendererID(0), m_FilePath(path), m_LocalBuffer(nullptr), m_height(0), m_width(0), m_BPP(0) { auto iter = s_Textures.find(path); if(iter == s_Textures.end()) s_Textures.insert(std::make_pair(path, this)); else { #ifdef _DEBUG std::cout << NAMECOLOR << "Texture" << BOLDYELLOW << ": <" << NAMECOLOR << path << BOLDYELLOW << "> has already existed\n" << RESET; #endif return; } stbi_set_flip_vertically_on_load(flip); m_LocalBuffer = stbi_load(path.c_str(), &m_width, &m_height, &m_BPP, 4); glGenTextures(1, &m_RendererID); glBindTexture(GL_TEXTURE_2D, m_RendererID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if (repeat) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_REPEAT); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); } glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_LocalBuffer); glBindTexture(GL_TEXTURE_2D, 0); if (m_LocalBuffer) UnloadFromRAM(m_FilePath); s_IsTextureAdded = true; } Texture::Texture() { } std::vector<Texture*> Texture::GetLoadedTexturesFromFolder(std::string filePath) { std::vector<Texture*> ts; for (const auto& entry : fs::directory_iterator(filePath)) { std::string pathToTexture = entry.path().string(); if (pathToTexture.find(".png") <= pathToTexture.length() || pathToTexture.find(".jpeg") <= pathToTexture.length()) { size_t index = 0; index = pathToTexture.find("\\", index); pathToTexture.replace(index, 1, "/"); Texture* t = Texture::Get(pathToTexture); if (t != nullptr) { ts.push_back(t); } } } return ts; } void Doom::Texture::DispatchLoadedTextures() { std::lock_guard<std::mutex> lock(s_LockTextureLoadingMtx); for (uint32_t i = 0; i < s_LoadedTextures.size(); i++) { LoadTextureInVRAM(s_LoadedTextures[i]->m_FilePath,true); } s_LoadedTextures.clear(); if (s_IsTextureAdded) { s_IsTextureAdded = false; for (auto i = s_WaitingForTextures.begin(); i != s_WaitingForTextures.end();) { std::function<Texture*()> f = i->second; Texture* t = f(); if (t != nullptr) { s_WaitingForTextures.erase(i++); } else { ++i; } } } } Texture::~Texture() { auto it = s_Textures.find(m_FilePath); if (it != s_Textures.end()) { s_Textures.erase(it); UnloadFromRAM(m_FilePath); UnloadFromVRAM(m_FilePath); } } void Texture::Bind(unsigned int slot) const { glActiveTexture(GL_TEXTURE0 + slot); glBindTexture(GL_TEXTURE_2D, m_RendererID); } void Texture::UnBind() const{ glBindTexture(GL_TEXTURE_2D, 0); } void Doom::Texture::ShutDown() { std::vector<Texture*> ts; for (auto i = s_Textures.begin(); i != s_Textures.end(); i++) { ts.push_back(i->second); } s_Textures.clear(); for (uint32_t i = 0; i < ts.size(); i) { delete ts[i]; ts.erase(ts.begin() + i); } } void Doom::Texture::Delete(Texture* texture) { auto iter = s_Textures.find(texture->m_FilePath); if (iter != s_Textures.end()) { delete iter->second; s_Textures.erase(iter); } } void Doom::Texture::AsyncLoadTexture(const std::string & filePath) { ThreadPool::GetInstance().Enqueue([=] { LoadTextureInRAM(filePath, true); { std::lock_guard<std::mutex> lock(s_LockTextureLoadingMtx); s_LoadedTextures.push_back(Texture::Get(filePath)); } }); } Texture* Doom::Texture::Get(std::string filePath,bool showErrors) { auto iter = s_Textures.find(filePath); if (iter != s_Textures.end()) { return iter->second; } else { if(showErrors) std::cout << NAMECOLOR << "Texture" << BOLDYELLOW << ": <" << NAMECOLOR << filePath << BOLDYELLOW << "> doesn't exist\n" << RESET; return nullptr; } } void Texture::GetAsync(void* ptr, std::function<Texture*()> f) { s_WaitingForTextures.insert(std::make_pair(ptr, f)); } void Doom::Texture::RemoveFromGetAsync(void * ptr) { auto iter = s_WaitingForTextures.find(ptr); if (iter != s_WaitingForTextures.end()) s_WaitingForTextures.erase(iter); } bool Doom::Texture::UnloadFromRAM(const std::string& filePath) { Texture* t = Get(filePath,false); if (t != nullptr && t->m_LocalBuffer) { stbi_image_free(t->m_LocalBuffer); t->m_LocalBuffer = nullptr; return true; } return false; } bool Doom::Texture::UnloadFromVRAM(const std::string& filePath) { Texture* t = Get(filePath,false); if (t != nullptr || t != NULL) { glDeleteTextures(1, &t->m_RendererID); t->m_RendererID = -1; return true; } return false; } Texture * Doom::Texture::ColoredTexture(const std::string& name, uint32_t color) { auto iter = s_Textures.find(name); if (iter != s_Textures.end()) { #ifdef _DEBUG std::cout << NAMECOLOR << "Texture" << BOLDYELLOW << ": <" << NAMECOLOR << name << BOLDYELLOW << "> has already existed\n" << RESET; #endif return iter->second; } Texture* t = new Texture(); s_IsTextureAdded = true; t->m_FilePath = name; glGenTextures(1, &t->m_RendererID); glBindTexture(GL_TEXTURE_2D, t->m_RendererID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &color); glBindTexture(GL_TEXTURE_2D, 0); s_Textures.insert(std::make_pair(t->m_FilePath, t)); return t; } Texture * Doom::Texture::Create(const std::string& filePath,bool flip,bool repeat) { Texture* t = Get(filePath,false); if (t == nullptr || t == NULL) return new Texture(filePath, flip, repeat); else return t; } bool Doom::Texture::LoadTextureInRAM(const std::string& filePath, bool flip) { Texture* t = nullptr; auto iter = s_Textures.find(filePath); if (iter == s_Textures.end()) { t = new Texture(); s_IsTextureAdded = true; t->m_FilePath = filePath; std::lock_guard<std::mutex> lock(Texture::s_LockTextureLoadingMtx); s_Textures.insert(std::make_pair(t->m_FilePath, t)); } else { t = iter->second; } if (t->m_LocalBuffer == nullptr) { stbi_set_flip_vertically_on_load(flip); t->m_LocalBuffer = stbi_load(t->m_FilePath.c_str(), &t->m_width, &t->m_height, &t->m_BPP, 4); return true; } else { #ifdef _DEBUG std::cout << NAMECOLOR << "Texture" << BOLDYELLOW << ": <" << NAMECOLOR << filePath << BOLDYELLOW << "> m_localBuffer is not empty\n" << RESET; #endif return false; } } bool Doom::Texture::LoadTextureInVRAM(const std::string& filePath, bool unloadFromRam) { Texture* t = Get(filePath); if (t == nullptr) return false; if (t->m_RendererID != -1) { #ifdef _DEBUG std::cout << NAMECOLOR << "Texture" << BOLDYELLOW << ": <" << NAMECOLOR << filePath << BOLDYELLOW << "> has been already in VRAM\n" << RESET; #endif //UnloadFromVRAM(filePath); return true; } if(t->m_LocalBuffer == nullptr){ #ifdef _DEBUG std::cout << NAMECOLOR << "Texture" << RED ": <"<< NAMECOLOR << filePath << RED << "> Can't be loaded in VRAM, m_LocalBuffer is unloaded from RAM!\n" << RESET; #endif return false; } glGenTextures(1, &t->m_RendererID); glBindTexture(GL_TEXTURE_2D, t->m_RendererID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, t->m_width, t->m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, t->m_LocalBuffer); glBindTexture(GL_TEXTURE_2D, 0); if (unloadFromRam) { UnloadFromRAM(t->m_FilePath); } return true; } unsigned int Doom::Texture::LoadCubeMap(std::vector<std::string> faces) { unsigned int m_RendererID; glGenTextures(1, &m_RendererID); glBindTexture(GL_TEXTURE_CUBE_MAP, m_RendererID); int width, height, nChannles; for (size_t i = 0; i < faces.size(); i++) { stbi_set_flip_vertically_on_load(false); unsigned char* data = stbi_load(faces[i].c_str(), &width, &height, &nChannles, 0); if (data) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); stbi_image_free(data); } else { std::cout << RED << "Cube map texture failed to load at path: " + faces[i] << RESET << std::endl; stbi_image_free(data); } } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); return m_RendererID; }
[ "turlak01@mail.ru" ]
turlak01@mail.ru
4bce27aafd8d54074f819d7b9e14604d7bf33147
394fd2a44126ae5607c30a58fe5593db1c6e5a02
/src/SCmodParPortPPdev.hpp
2932d24c47162cc85a7c15e4ad20094cd2464a63
[]
no_license
thx8411/qastrocam-g2
653b98463609737ab328f63929690f27d7f100eb
c1453cc8bc2e7719db21bae5bffe3340c66b42e0
refs/heads/master
2021-01-17T11:35:54.403879
2016-04-01T20:33:07
2016-04-01T20:33:07
40,839,897
2
0
null
null
null
null
UTF-8
C++
false
false
1,591
hpp
/****************************************************************** Qastrocam-g2 Copyright (C) 2009 Blaise-Florentin Collin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License v2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *******************************************************************/ #ifndef _SCmodParPortPPdev_hpp_ #define _SCmodParPortPPdev_hpp_ #include "SCmod.hpp" #include "PPort.hpp" #include <string> using namespace std; // driving lxmode using part port class SCmodParPortPPdev : public SCmod { public: SCmodParPortPPdev(); virtual ~SCmodParPortPPdev(); void enterLongPoseMode(); void leaveLongPoseMode(); void stopAccumulation(); void startAccumulation(); private: // lists used par port bits enum pportBit {evenLinesTransfer=0, oddLinesTransfer=1, preamp=2, shutter=3}; // entry i PPdev table int portEntry; // PPdev object PPort* paralPort; // are logical level on the port inverted ? bool inverted; // port device name string device; }; #endif
[ "thx8411@c1ec87e9-771e-51c6-fe90-2aeb2be771a7" ]
thx8411@c1ec87e9-771e-51c6-fe90-2aeb2be771a7
f76defdfe76b231af0d04704b095c42d5d55ba93
5b483e4aae2404a538d9d4a31d0f6ed7b1f346be
/BumperStrip.cpp
2e1eb3314dbf7bc132d6a407b0bd72b4e2247a8d
[]
no_license
SilasYoome/Bumper_Strip_Interrupt_in_Arduino
cc4733f44ae22212815cc90c4611eb5328f784d9
2d9a24fb0e15ace12d0f10b98247d7109ce1ebf2
refs/heads/main
2023-03-22T04:01:03.089020
2021-03-08T06:22:33
2021-03-08T06:22:33
345,551,315
0
0
null
null
null
null
UTF-8
C++
false
false
419
cpp
#include "BumperStrip.h" #include <Arduino.h> int Debug_Flag = 0; BumperStrip::BumperStrip(int BumperStrip_Pin){ BumpterStrip_Pin_ = BumperStrip_Pin; } void BumperStrip::init(){ pinMode(BumpterStrip_Pin_,INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(BumpterStrip_Pin_),&BumperStrip::BumperStrip_ISR,CHANGE); } void BumperStrip::BumperStrip_ISR(){ Serial.println(Debug_Flag); Debug_Flag++; }
[ "71079352+SilasYoome@users.noreply.github.com" ]
71079352+SilasYoome@users.noreply.github.com
6a10c210c2a5685bfbf9ae401b66c0b9d6214635
1d395f31bd8fc6485a333618d6f523a1bc9a8489
/Src/BlackCat.Game/Game/System/Network/bcNetworkManager.h
957b0d0b77e31b862bc2c6a6e7bed51a8442b52c
[]
no_license
MohammadRB/BlackCat-Engine
f44f8ced87dee8fd6840fce2917beba74ab8865e
e0490ee54f124ec20e57a3ea1960a07957866a9c
refs/heads/master
2023-08-23T12:25:10.703995
2023-07-19T22:11:48
2023-07-19T22:11:48
19,066,510
3
1
null
2023-09-10T14:20:59
2014-04-23T10:59:49
C++
UTF-8
C++
false
false
1,259
h
// [27/05/2021 MRB] #pragma once #include "CorePlatformImp/Utility/bcClock.h" #include "Game/System/Network/Message/bcNetworkMessage.h" #include "Game/System/Network/bcNetworkDefinitions.h" namespace black_cat::game { class bc_scene; class bc_actor; struct bc_network_manager_update_context { const platform::bc_clock::update_param& m_clock; const bool m_send_rtt_message; }; class bci_network_manager { public: virtual ~bci_network_manager() = default; virtual bc_network_type get_network_type() const noexcept = 0; virtual bc_network_state get_network_state() const noexcept = 0; virtual void add_actor_to_sync(bc_actor& p_actor) = 0; virtual void remove_actor_from_sync(bc_actor& p_actor) = 0; virtual void actor_removed(bc_actor& p_actor) = 0; virtual void send_message(bc_network_message_ptr p_message) = 0; virtual void update(const bc_network_manager_update_context& p_context) = 0; template<class TMessage, typename = std::enable_if_t<!std::is_same_v<TMessage, bc_network_message_ptr>>> void send_message(TMessage p_message); }; template<class TMessage, typename> void bci_network_manager::send_message(TMessage p_message) { send_message(bc_make_network_message(std::move(p_message))); } }
[ "mohammad.r.barzegar@gmail.com" ]
mohammad.r.barzegar@gmail.com
aa2a43facf9124a212ede5bbaf5758e7633a3eed
30052f149920c6a235759e9c573990a5ec00b976
/A/mountain_scenery.cpp
c53c694e29fca2ec5e0f7976598b489c6081f2b7
[]
no_license
Ajay35/spoj
63f29fda94aeed4a581d265dfabbd6ef600ddd69
34d59f8b1c435b98cc1a171d57cdcff7b50e6f78
refs/heads/master
2020-03-18T16:32:59.068268
2019-07-30T11:54:29
2019-07-30T11:54:29
134,972,271
0
0
null
null
null
null
UTF-8
C++
false
false
366
cpp
#include <bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { int n,k,i,p; cin>>n>>k; p=2*n+1; int a[p]; for(i=0;i<p;i++) cin>>a[i]; for(i=1;i<p;i+=2){ if(k>0 and a[i-1]+1<a[i] and a[i]>a[i+1]+1){ a[i]=a[i]-1; k--; } if(k==0) break; } for(i=0;i<p;i++){ printf("%d ",a[i]); } return 0; }
[ "ajayjadhav35@live.com" ]
ajayjadhav35@live.com
f5c21bc5a301c22a6b2e2e9bc8963dd0fd23047b
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/ocr/include/tencentcloud/ocr/v20181119/model/MotorVehicleSaleInvoice.h
667ce3c1c0549a204449b24dcccdaafdb1de55c2
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
39,959
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_OCR_V20181119_MODEL_MOTORVEHICLESALEINVOICE_H_ #define TENCENTCLOUD_OCR_V20181119_MODEL_MOTORVEHICLESALEINVOICE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Ocr { namespace V20181119 { namespace Model { /** * 机动车销售统一发票 */ class MotorVehicleSaleInvoice : public AbstractModel { public: MotorVehicleSaleInvoice(); ~MotorVehicleSaleInvoice() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取发票名称 * @return Title 发票名称 * */ std::string GetTitle() const; /** * 设置发票名称 * @param _title 发票名称 * */ void SetTitle(const std::string& _title); /** * 判断参数 Title 是否已赋值 * @return Title 是否已赋值 * */ bool TitleHasBeenSet() const; /** * 获取发票代码 * @return Code 发票代码 * */ std::string GetCode() const; /** * 设置发票代码 * @param _code 发票代码 * */ void SetCode(const std::string& _code); /** * 判断参数 Code 是否已赋值 * @return Code 是否已赋值 * */ bool CodeHasBeenSet() const; /** * 获取发票号码 * @return Number 发票号码 * */ std::string GetNumber() const; /** * 设置发票号码 * @param _number 发票号码 * */ void SetNumber(const std::string& _number); /** * 判断参数 Number 是否已赋值 * @return Number 是否已赋值 * */ bool NumberHasBeenSet() const; /** * 获取开票日期 * @return Date 开票日期 * */ std::string GetDate() const; /** * 设置开票日期 * @param _date 开票日期 * */ void SetDate(const std::string& _date); /** * 判断参数 Date 是否已赋值 * @return Date 是否已赋值 * */ bool DateHasBeenSet() const; /** * 获取税前金额 * @return PretaxAmount 税前金额 * */ std::string GetPretaxAmount() const; /** * 设置税前金额 * @param _pretaxAmount 税前金额 * */ void SetPretaxAmount(const std::string& _pretaxAmount); /** * 判断参数 PretaxAmount 是否已赋值 * @return PretaxAmount 是否已赋值 * */ bool PretaxAmountHasBeenSet() const; /** * 获取价税合计(小写) * @return Total 价税合计(小写) * */ std::string GetTotal() const; /** * 设置价税合计(小写) * @param _total 价税合计(小写) * */ void SetTotal(const std::string& _total); /** * 判断参数 Total 是否已赋值 * @return Total 是否已赋值 * */ bool TotalHasBeenSet() const; /** * 获取价税合计(大写) * @return TotalCn 价税合计(大写) * */ std::string GetTotalCn() const; /** * 设置价税合计(大写) * @param _totalCn 价税合计(大写) * */ void SetTotalCn(const std::string& _totalCn); /** * 判断参数 TotalCn 是否已赋值 * @return TotalCn 是否已赋值 * */ bool TotalCnHasBeenSet() const; /** * 获取销售方名称 * @return Seller 销售方名称 * */ std::string GetSeller() const; /** * 设置销售方名称 * @param _seller 销售方名称 * */ void SetSeller(const std::string& _seller); /** * 判断参数 Seller 是否已赋值 * @return Seller 是否已赋值 * */ bool SellerHasBeenSet() const; /** * 获取销售方单位代码 * @return SellerTaxID 销售方单位代码 * */ std::string GetSellerTaxID() const; /** * 设置销售方单位代码 * @param _sellerTaxID 销售方单位代码 * */ void SetSellerTaxID(const std::string& _sellerTaxID); /** * 判断参数 SellerTaxID 是否已赋值 * @return SellerTaxID 是否已赋值 * */ bool SellerTaxIDHasBeenSet() const; /** * 获取销售方电话 * @return SellerTel 销售方电话 * */ std::string GetSellerTel() const; /** * 设置销售方电话 * @param _sellerTel 销售方电话 * */ void SetSellerTel(const std::string& _sellerTel); /** * 判断参数 SellerTel 是否已赋值 * @return SellerTel 是否已赋值 * */ bool SellerTelHasBeenSet() const; /** * 获取销售方地址 * @return SellerAddress 销售方地址 * */ std::string GetSellerAddress() const; /** * 设置销售方地址 * @param _sellerAddress 销售方地址 * */ void SetSellerAddress(const std::string& _sellerAddress); /** * 判断参数 SellerAddress 是否已赋值 * @return SellerAddress 是否已赋值 * */ bool SellerAddressHasBeenSet() const; /** * 获取销售方开户行 * @return SellerBank 销售方开户行 * */ std::string GetSellerBank() const; /** * 设置销售方开户行 * @param _sellerBank 销售方开户行 * */ void SetSellerBank(const std::string& _sellerBank); /** * 判断参数 SellerBank 是否已赋值 * @return SellerBank 是否已赋值 * */ bool SellerBankHasBeenSet() const; /** * 获取销售方银行账号 * @return SellerBankAccount 销售方银行账号 * */ std::string GetSellerBankAccount() const; /** * 设置销售方银行账号 * @param _sellerBankAccount 销售方银行账号 * */ void SetSellerBankAccount(const std::string& _sellerBankAccount); /** * 判断参数 SellerBankAccount 是否已赋值 * @return SellerBankAccount 是否已赋值 * */ bool SellerBankAccountHasBeenSet() const; /** * 获取购买方名称 * @return Buyer 购买方名称 * */ std::string GetBuyer() const; /** * 设置购买方名称 * @param _buyer 购买方名称 * */ void SetBuyer(const std::string& _buyer); /** * 判断参数 Buyer 是否已赋值 * @return Buyer 是否已赋值 * */ bool BuyerHasBeenSet() const; /** * 获取购买方纳税人识别号 * @return BuyerTaxID 购买方纳税人识别号 * */ std::string GetBuyerTaxID() const; /** * 设置购买方纳税人识别号 * @param _buyerTaxID 购买方纳税人识别号 * */ void SetBuyerTaxID(const std::string& _buyerTaxID); /** * 判断参数 BuyerTaxID 是否已赋值 * @return BuyerTaxID 是否已赋值 * */ bool BuyerTaxIDHasBeenSet() const; /** * 获取购买方身份证号码/组织机构代码 * @return BuyerID 购买方身份证号码/组织机构代码 * */ std::string GetBuyerID() const; /** * 设置购买方身份证号码/组织机构代码 * @param _buyerID 购买方身份证号码/组织机构代码 * */ void SetBuyerID(const std::string& _buyerID); /** * 判断参数 BuyerID 是否已赋值 * @return BuyerID 是否已赋值 * */ bool BuyerIDHasBeenSet() const; /** * 获取主管税务机关 * @return TaxAuthorities 主管税务机关 * */ std::string GetTaxAuthorities() const; /** * 设置主管税务机关 * @param _taxAuthorities 主管税务机关 * */ void SetTaxAuthorities(const std::string& _taxAuthorities); /** * 判断参数 TaxAuthorities 是否已赋值 * @return TaxAuthorities 是否已赋值 * */ bool TaxAuthoritiesHasBeenSet() const; /** * 获取主管税务机关代码 * @return TaxAuthoritiesCode 主管税务机关代码 * */ std::string GetTaxAuthoritiesCode() const; /** * 设置主管税务机关代码 * @param _taxAuthoritiesCode 主管税务机关代码 * */ void SetTaxAuthoritiesCode(const std::string& _taxAuthoritiesCode); /** * 判断参数 TaxAuthoritiesCode 是否已赋值 * @return TaxAuthoritiesCode 是否已赋值 * */ bool TaxAuthoritiesCodeHasBeenSet() const; /** * 获取车辆识别代码 * @return VIN 车辆识别代码 * */ std::string GetVIN() const; /** * 设置车辆识别代码 * @param _vIN 车辆识别代码 * */ void SetVIN(const std::string& _vIN); /** * 判断参数 VIN 是否已赋值 * @return VIN 是否已赋值 * */ bool VINHasBeenSet() const; /** * 获取厂牌型号 * @return VehicleModel 厂牌型号 * */ std::string GetVehicleModel() const; /** * 设置厂牌型号 * @param _vehicleModel 厂牌型号 * */ void SetVehicleModel(const std::string& _vehicleModel); /** * 判断参数 VehicleModel 是否已赋值 * @return VehicleModel 是否已赋值 * */ bool VehicleModelHasBeenSet() const; /** * 获取发动机号码 * @return VehicleEngineCode 发动机号码 * */ std::string GetVehicleEngineCode() const; /** * 设置发动机号码 * @param _vehicleEngineCode 发动机号码 * */ void SetVehicleEngineCode(const std::string& _vehicleEngineCode); /** * 判断参数 VehicleEngineCode 是否已赋值 * @return VehicleEngineCode 是否已赋值 * */ bool VehicleEngineCodeHasBeenSet() const; /** * 获取合格证号 * @return CertificateNumber 合格证号 * */ std::string GetCertificateNumber() const; /** * 设置合格证号 * @param _certificateNumber 合格证号 * */ void SetCertificateNumber(const std::string& _certificateNumber); /** * 判断参数 CertificateNumber 是否已赋值 * @return CertificateNumber 是否已赋值 * */ bool CertificateNumberHasBeenSet() const; /** * 获取商检单号 * @return InspectionNumber 商检单号 * */ std::string GetInspectionNumber() const; /** * 设置商检单号 * @param _inspectionNumber 商检单号 * */ void SetInspectionNumber(const std::string& _inspectionNumber); /** * 判断参数 InspectionNumber 是否已赋值 * @return InspectionNumber 是否已赋值 * */ bool InspectionNumberHasBeenSet() const; /** * 获取机器编号 * @return MachineID 机器编号 * */ std::string GetMachineID() const; /** * 设置机器编号 * @param _machineID 机器编号 * */ void SetMachineID(const std::string& _machineID); /** * 判断参数 MachineID 是否已赋值 * @return MachineID 是否已赋值 * */ bool MachineIDHasBeenSet() const; /** * 获取车辆类型 * @return VehicleType 车辆类型 * */ std::string GetVehicleType() const; /** * 设置车辆类型 * @param _vehicleType 车辆类型 * */ void SetVehicleType(const std::string& _vehicleType); /** * 判断参数 VehicleType 是否已赋值 * @return VehicleType 是否已赋值 * */ bool VehicleTypeHasBeenSet() const; /** * 获取发票消费类型 * @return Kind 发票消费类型 * */ std::string GetKind() const; /** * 设置发票消费类型 * @param _kind 发票消费类型 * */ void SetKind(const std::string& _kind); /** * 判断参数 Kind 是否已赋值 * @return Kind 是否已赋值 * */ bool KindHasBeenSet() const; /** * 获取省 * @return Province 省 * */ std::string GetProvince() const; /** * 设置省 * @param _province 省 * */ void SetProvince(const std::string& _province); /** * 判断参数 Province 是否已赋值 * @return Province 是否已赋值 * */ bool ProvinceHasBeenSet() const; /** * 获取市 * @return City 市 * */ std::string GetCity() const; /** * 设置市 * @param _city 市 * */ void SetCity(const std::string& _city); /** * 判断参数 City 是否已赋值 * @return City 是否已赋值 * */ bool CityHasBeenSet() const; /** * 获取合计税额 * @return Tax 合计税额 * */ std::string GetTax() const; /** * 设置合计税额 * @param _tax 合计税额 * */ void SetTax(const std::string& _tax); /** * 判断参数 Tax 是否已赋值 * @return Tax 是否已赋值 * */ bool TaxHasBeenSet() const; /** * 获取税率 * @return TaxRate 税率 * */ std::string GetTaxRate() const; /** * 设置税率 * @param _taxRate 税率 * */ void SetTaxRate(const std::string& _taxRate); /** * 判断参数 TaxRate 是否已赋值 * @return TaxRate 是否已赋值 * */ bool TaxRateHasBeenSet() const; /** * 获取是否有公司印章(0:没有,1:有) * @return CompanySealMark 是否有公司印章(0:没有,1:有) * */ int64_t GetCompanySealMark() const; /** * 设置是否有公司印章(0:没有,1:有) * @param _companySealMark 是否有公司印章(0:没有,1:有) * */ void SetCompanySealMark(const int64_t& _companySealMark); /** * 判断参数 CompanySealMark 是否已赋值 * @return CompanySealMark 是否已赋值 * */ bool CompanySealMarkHasBeenSet() const; /** * 获取吨位 * @return Tonnage 吨位 * */ std::string GetTonnage() const; /** * 设置吨位 * @param _tonnage 吨位 * */ void SetTonnage(const std::string& _tonnage); /** * 判断参数 Tonnage 是否已赋值 * @return Tonnage 是否已赋值 * */ bool TonnageHasBeenSet() const; /** * 获取备注 * @return Remark 备注 * */ std::string GetRemark() const; /** * 设置备注 * @param _remark 备注 * */ void SetRemark(const std::string& _remark); /** * 判断参数 Remark 是否已赋值 * @return Remark 是否已赋值 * */ bool RemarkHasBeenSet() const; /** * 获取发票联次 * @return FormType 发票联次 * */ std::string GetFormType() const; /** * 设置发票联次 * @param _formType 发票联次 * */ void SetFormType(const std::string& _formType); /** * 判断参数 FormType 是否已赋值 * @return FormType 是否已赋值 * */ bool FormTypeHasBeenSet() const; /** * 获取发票联名 * @return FormName 发票联名 * */ std::string GetFormName() const; /** * 设置发票联名 * @param _formName 发票联名 * */ void SetFormName(const std::string& _formName); /** * 判断参数 FormName 是否已赋值 * @return FormName 是否已赋值 * */ bool FormNameHasBeenSet() const; /** * 获取开票人 * @return Issuer 开票人 * */ std::string GetIssuer() const; /** * 设置开票人 * @param _issuer 开票人 * */ void SetIssuer(const std::string& _issuer); /** * 判断参数 Issuer 是否已赋值 * @return Issuer 是否已赋值 * */ bool IssuerHasBeenSet() const; /** * 获取完税凭证号码 * @return TaxNum 完税凭证号码 * */ std::string GetTaxNum() const; /** * 设置完税凭证号码 * @param _taxNum 完税凭证号码 * */ void SetTaxNum(const std::string& _taxNum); /** * 判断参数 TaxNum 是否已赋值 * @return TaxNum 是否已赋值 * */ bool TaxNumHasBeenSet() const; /** * 获取限乘人数 * @return MaxPeopleNum 限乘人数 * */ std::string GetMaxPeopleNum() const; /** * 设置限乘人数 * @param _maxPeopleNum 限乘人数 * */ void SetMaxPeopleNum(const std::string& _maxPeopleNum); /** * 判断参数 MaxPeopleNum 是否已赋值 * @return MaxPeopleNum 是否已赋值 * */ bool MaxPeopleNumHasBeenSet() const; /** * 获取产地 * @return Origin 产地 * */ std::string GetOrigin() const; /** * 设置产地 * @param _origin 产地 * */ void SetOrigin(const std::string& _origin); /** * 判断参数 Origin 是否已赋值 * @return Origin 是否已赋值 * */ bool OriginHasBeenSet() const; /** * 获取机打发票代码 * @return MachineCode 机打发票代码 * */ std::string GetMachineCode() const; /** * 设置机打发票代码 * @param _machineCode 机打发票代码 * */ void SetMachineCode(const std::string& _machineCode); /** * 判断参数 MachineCode 是否已赋值 * @return MachineCode 是否已赋值 * */ bool MachineCodeHasBeenSet() const; /** * 获取机打发票号码 * @return MachineNumber 机打发票号码 * */ std::string GetMachineNumber() const; /** * 设置机打发票号码 * @param _machineNumber 机打发票号码 * */ void SetMachineNumber(const std::string& _machineNumber); /** * 判断参数 MachineNumber 是否已赋值 * @return MachineNumber 是否已赋值 * */ bool MachineNumberHasBeenSet() const; /** * 获取是否存在二维码(1:有,0:无) * @return QRCodeMark 是否存在二维码(1:有,0:无) * */ int64_t GetQRCodeMark() const; /** * 设置是否存在二维码(1:有,0:无) * @param _qRCodeMark 是否存在二维码(1:有,0:无) * */ void SetQRCodeMark(const int64_t& _qRCodeMark); /** * 判断参数 QRCodeMark 是否已赋值 * @return QRCodeMark 是否已赋值 * */ bool QRCodeMarkHasBeenSet() const; private: /** * 发票名称 */ std::string m_title; bool m_titleHasBeenSet; /** * 发票代码 */ std::string m_code; bool m_codeHasBeenSet; /** * 发票号码 */ std::string m_number; bool m_numberHasBeenSet; /** * 开票日期 */ std::string m_date; bool m_dateHasBeenSet; /** * 税前金额 */ std::string m_pretaxAmount; bool m_pretaxAmountHasBeenSet; /** * 价税合计(小写) */ std::string m_total; bool m_totalHasBeenSet; /** * 价税合计(大写) */ std::string m_totalCn; bool m_totalCnHasBeenSet; /** * 销售方名称 */ std::string m_seller; bool m_sellerHasBeenSet; /** * 销售方单位代码 */ std::string m_sellerTaxID; bool m_sellerTaxIDHasBeenSet; /** * 销售方电话 */ std::string m_sellerTel; bool m_sellerTelHasBeenSet; /** * 销售方地址 */ std::string m_sellerAddress; bool m_sellerAddressHasBeenSet; /** * 销售方开户行 */ std::string m_sellerBank; bool m_sellerBankHasBeenSet; /** * 销售方银行账号 */ std::string m_sellerBankAccount; bool m_sellerBankAccountHasBeenSet; /** * 购买方名称 */ std::string m_buyer; bool m_buyerHasBeenSet; /** * 购买方纳税人识别号 */ std::string m_buyerTaxID; bool m_buyerTaxIDHasBeenSet; /** * 购买方身份证号码/组织机构代码 */ std::string m_buyerID; bool m_buyerIDHasBeenSet; /** * 主管税务机关 */ std::string m_taxAuthorities; bool m_taxAuthoritiesHasBeenSet; /** * 主管税务机关代码 */ std::string m_taxAuthoritiesCode; bool m_taxAuthoritiesCodeHasBeenSet; /** * 车辆识别代码 */ std::string m_vIN; bool m_vINHasBeenSet; /** * 厂牌型号 */ std::string m_vehicleModel; bool m_vehicleModelHasBeenSet; /** * 发动机号码 */ std::string m_vehicleEngineCode; bool m_vehicleEngineCodeHasBeenSet; /** * 合格证号 */ std::string m_certificateNumber; bool m_certificateNumberHasBeenSet; /** * 商检单号 */ std::string m_inspectionNumber; bool m_inspectionNumberHasBeenSet; /** * 机器编号 */ std::string m_machineID; bool m_machineIDHasBeenSet; /** * 车辆类型 */ std::string m_vehicleType; bool m_vehicleTypeHasBeenSet; /** * 发票消费类型 */ std::string m_kind; bool m_kindHasBeenSet; /** * 省 */ std::string m_province; bool m_provinceHasBeenSet; /** * 市 */ std::string m_city; bool m_cityHasBeenSet; /** * 合计税额 */ std::string m_tax; bool m_taxHasBeenSet; /** * 税率 */ std::string m_taxRate; bool m_taxRateHasBeenSet; /** * 是否有公司印章(0:没有,1:有) */ int64_t m_companySealMark; bool m_companySealMarkHasBeenSet; /** * 吨位 */ std::string m_tonnage; bool m_tonnageHasBeenSet; /** * 备注 */ std::string m_remark; bool m_remarkHasBeenSet; /** * 发票联次 */ std::string m_formType; bool m_formTypeHasBeenSet; /** * 发票联名 */ std::string m_formName; bool m_formNameHasBeenSet; /** * 开票人 */ std::string m_issuer; bool m_issuerHasBeenSet; /** * 完税凭证号码 */ std::string m_taxNum; bool m_taxNumHasBeenSet; /** * 限乘人数 */ std::string m_maxPeopleNum; bool m_maxPeopleNumHasBeenSet; /** * 产地 */ std::string m_origin; bool m_originHasBeenSet; /** * 机打发票代码 */ std::string m_machineCode; bool m_machineCodeHasBeenSet; /** * 机打发票号码 */ std::string m_machineNumber; bool m_machineNumberHasBeenSet; /** * 是否存在二维码(1:有,0:无) */ int64_t m_qRCodeMark; bool m_qRCodeMarkHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_OCR_V20181119_MODEL_MOTORVEHICLESALEINVOICE_H_
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
4eded410d1b22ffd34135df09be735aa360a0116
a7764174fb0351ea666faa9f3b5dfe304390a011
/inc/CDM_PresentationDirectory.hxx
cb81c92bb0f8a763ba30bccc51be8c9db10eaaa0
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
2,998
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _CDM_PresentationDirectory_HeaderFile #define _CDM_PresentationDirectory_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_Macro_HeaderFile #include <Standard_Macro.hxx> #endif #ifndef _TCollection_BasicMap_HeaderFile #include <TCollection_BasicMap.hxx> #endif #ifndef _Handle_CDM_Document_HeaderFile #include <Handle_CDM_Document.hxx> #endif #ifndef _Handle_CDM_DataMapNodeOfPresentationDirectory_HeaderFile #include <Handle_CDM_DataMapNodeOfPresentationDirectory.hxx> #endif #ifndef _Standard_Integer_HeaderFile #include <Standard_Integer.hxx> #endif #ifndef _Standard_Boolean_HeaderFile #include <Standard_Boolean.hxx> #endif class Standard_DomainError; class Standard_NoSuchObject; class TCollection_ExtendedString; class CDM_Document; class CDM_DataMapNodeOfPresentationDirectory; class CDM_DataMapIteratorOfPresentationDirectory; class CDM_PresentationDirectory : public TCollection_BasicMap { public: void* operator new(size_t,void* anAddress) { return anAddress; } void* operator new(size_t size) { return Standard::Allocate(size); } void operator delete(void *anAddress) { if (anAddress) Standard::Free((Standard_Address&)anAddress); } Standard_EXPORT CDM_PresentationDirectory(const Standard_Integer NbBuckets = 1); Standard_EXPORT CDM_PresentationDirectory& Assign(const CDM_PresentationDirectory& Other) ; CDM_PresentationDirectory& operator =(const CDM_PresentationDirectory& Other) { return Assign(Other); } Standard_EXPORT void ReSize(const Standard_Integer NbBuckets) ; Standard_EXPORT void Clear() ; ~CDM_PresentationDirectory() { Clear(); } Standard_EXPORT Standard_Boolean Bind(const TCollection_ExtendedString& K,const Handle(CDM_Document)& I) ; Standard_EXPORT Standard_Boolean IsBound(const TCollection_ExtendedString& K) const; Standard_EXPORT Standard_Boolean UnBind(const TCollection_ExtendedString& K) ; Standard_EXPORT const Handle_CDM_Document& Find(const TCollection_ExtendedString& K) const; const Handle_CDM_Document& operator()(const TCollection_ExtendedString& K) const { return Find(K); } Standard_EXPORT Handle_CDM_Document& ChangeFind(const TCollection_ExtendedString& K) ; Handle_CDM_Document& operator()(const TCollection_ExtendedString& K) { return ChangeFind(K); } protected: private: Standard_EXPORT CDM_PresentationDirectory(const CDM_PresentationDirectory& Other); }; // other Inline functions and methods (like "C++: function call" methods) #endif
[ "shoka.sho2@excel.co.jp" ]
shoka.sho2@excel.co.jp
ab1ed5aa0ebde0b6afe38c6ecd618f0487f02240
046b675cb8529d1585a688f21563eb0209c94f19
/src/Control2012/libreoffice/com/sun/star/sheet/XCellAddressable.hpp
ed0b89106cdf230556f16151de9f31ed50c8a27c
[]
no_license
yoshi5534/schorsch-the-robot
a2a4bd35668600451e53bd8d7f879df90dcb9994
77eb8dcabaad5da3908d6b4b78a05985323f9ba4
refs/heads/master
2021-03-12T19:41:35.524173
2013-04-17T20:00:29
2013-04-17T20:00:29
32,867,962
0
0
null
null
null
null
UTF-8
C++
false
false
1,511
hpp
#ifndef INCLUDED_COM_SUN_STAR_SHEET_XCELLADDRESSABLE_HPP #define INCLUDED_COM_SUN_STAR_SHEET_XCELLADDRESSABLE_HPP #include "sal/config.h" #include "com/sun/star/sheet/XCellAddressable.hdl" #include "com/sun/star/uno/XInterface.hpp" #include "com/sun/star/table/CellAddress.hpp" #include "com/sun/star/uno/RuntimeException.hpp" #include "com/sun/star/uno/Reference.hxx" #include "com/sun/star/uno/Type.hxx" #include "cppu/unotype.hxx" #include "osl/mutex.hxx" namespace com { namespace sun { namespace star { namespace sheet { inline ::com::sun::star::uno::Type const & cppu_detail_getUnoType(::com::sun::star::sheet::XCellAddressable const *) { static typelib_TypeDescriptionReference * the_type = 0; if ( !the_type ) { typelib_static_mi_interface_type_init( &the_type, "com.sun.star.sheet.XCellAddressable", 0, 0 ); } return * reinterpret_cast< ::com::sun::star::uno::Type * >( &the_type ); } } } } } inline ::com::sun::star::uno::Type const & SAL_CALL getCppuType(::com::sun::star::uno::Reference< ::com::sun::star::sheet::XCellAddressable > const *) SAL_THROW(()) { return ::cppu::UnoType< ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XCellAddressable > >::get(); } ::com::sun::star::uno::Type const & ::com::sun::star::sheet::XCellAddressable::static_type(void *) { return ::getCppuType(static_cast< ::com::sun::star::uno::Reference< ::com::sun::star::sheet::XCellAddressable > * >(0)); } #endif // INCLUDED_COM_SUN_STAR_SHEET_XCELLADDRESSABLE_HPP
[ "schorsch@localhost" ]
schorsch@localhost
b146aa34d96764e4c0cf1101de4467b40a9d6bb6
2a88b58673d0314ed00e37ab7329ab0bbddd3bdc
/blazetest/src/mathtest/dmatdmatmult/DDbDDb.cpp
f10f883ba27781a2026efe14887ba2e4fc038946
[ "BSD-3-Clause" ]
permissive
shiver/blaze-lib
3083de9600a66a586e73166e105585a954e324ea
824925ed21faf82bb6edc48da89d3c84b8246cbf
refs/heads/master
2020-09-05T23:00:34.583144
2016-08-24T03:55:17
2016-08-24T03:55:17
66,765,250
2
1
NOASSERTION
2020-04-06T05:02:41
2016-08-28T11:43:51
C++
UTF-8
C++
false
false
4,127
cpp
//================================================================================================= /*! // \file src/mathtest/dmatdmatmult/DDbDDb.cpp // \brief Source file for the DDbDDb dense matrix/dense matrix multiplication math test // // Copyright (C) 2013 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/DiagonalMatrix.h> #include <blaze/math/DynamicMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dmatdmatmult/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'DDbDDb'..." << std::endl; using blazetest::mathtest::TypeB; try { // Matrix type definitions typedef blaze::DiagonalMatrix< blaze::DynamicMatrix<TypeB> > DDb; // Creator type definitions typedef blazetest::Creator<DDb> CDDb; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { RUN_DMATDMATMULT_OPERATION_TEST( CDDb( i ), CDDb( i ) ); } // Running tests with large matrices RUN_DMATDMATMULT_OPERATION_TEST( CDDb( 15UL ), CDDb( 15UL ) ); RUN_DMATDMATMULT_OPERATION_TEST( CDDb( 37UL ), CDDb( 37UL ) ); RUN_DMATDMATMULT_OPERATION_TEST( CDDb( 63UL ), CDDb( 63UL ) ); RUN_DMATDMATMULT_OPERATION_TEST( CDDb( 16UL ), CDDb( 16UL ) ); RUN_DMATDMATMULT_OPERATION_TEST( CDDb( 32UL ), CDDb( 32UL ) ); RUN_DMATDMATMULT_OPERATION_TEST( CDDb( 64UL ), CDDb( 64UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix multiplication:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
96d4675ef05c01842533d14e8a3896f6646180e8
f8a6635b8375c605b0ce0ada67c998020ec6e944
/src/typing_machine.hpp
4ae62a323b0c99e26b6260a08449abbdac956c2d
[]
no_license
marekesz/rbgParser
94fa3f01e3241c01ac8923792e58a770d4f1daa6
58c40a0a6a5493c12063e5cdf8e8d8cc5154ff86
refs/heads/master
2020-03-18T04:55:48.385785
2018-05-21T14:30:52
2018-05-21T14:30:52
134,314,322
1
0
null
2018-05-21T19:16:49
2018-05-21T19:16:48
null
UTF-8
C++
false
false
1,748
hpp
#ifndef TYPING_MACHINE #define TYPING_MACHINE #include<map> #include"tree_utils.hpp" namespace rbg_parser{ class declarations; class typing_machine{ std::map<operator_type, std::vector<possible_operator_interpretation>> operator_meanings; std::map<bracket_type, std::vector<possible_bracket_interpretation>> bracket_meanings; const declarations& decls; bool operator_types_match(const std::vector<expression_type>& elements, const possible_operator_interpretation& op_int)const; bool bracket_types_match(expression_type element, suffix_type s, const possible_bracket_interpretation& br_int)const; public: typing_machine(const declarations& decls); typing_machine(const typing_machine&)=default; typing_machine& operator=(const typing_machine&)=default; typing_machine(typing_machine&&)=default; typing_machine& operator=(typing_machine&&)=default; ~typing_machine(void)=default; expression_type evaluate_identifier(const token& t)const; void add_operator_interpretation( operator_type t, bool arity_matters, std::vector<expression_type>&& types_to_match, expression_type result); void add_bracket_interpretation( bracket_type t, expression_type type_to_match, std::set<suffix_type>&& suffixes_to_match, expression_type result); expression_type evaluate_operator_sequence(operator_type t, const std::vector<expression_type>& elements)const; expression_type evaluate_brackets(bracket_type t, expression_type element, suffix_type s)const; }; typing_machine prepare_types_for_rbg(const declarations& decls); } #endif
[ "jakubsutowicz@gmail.com" ]
jakubsutowicz@gmail.com
3d2e798efd7c56653dc1af4f34962a744d78f219
66d8ea74e6ec6effebb3649782a61c28eaf58ddd
/arduino/sketchbook/libraries/RichUNOKitC/RichUNOKitC_LCD1602.h
9d656064bbb0af4bcde219ae2a508a7452e17039
[]
no_license
philipp68/IOT-Experiments
ca35273bc45e0e0e18e2d9ac4b030721c8a136f7
bcaf76f559be84012d5244374b7d32401dab8dbc
refs/heads/master
2021-06-29T13:45:08.037205
2019-04-16T19:55:09
2019-04-16T19:55:09
134,470,403
0
0
null
null
null
null
UTF-8
C++
false
false
3,642
h
/********************************************** LiquidCrystal_I2C last updated on 21/12/2011 Tim Starling Fix the reset bug (Thanks Tim) www.yfrobot.com **********************************************/ #ifndef LiquidCrystal_I2C_h #define LiquidCrystal_I2C_h #include <inttypes.h> #include "Print.h" #include <Wire.h> // commands #define LCD_CLEARDISPLAY 0x01 #define LCD_RETURNHOME 0x02 #define LCD_ENTRYMODESET 0x04 #define LCD_DISPLAYCONTROL 0x08 #define LCD_CURSORSHIFT 0x10 #define LCD_FUNCTIONSET 0x20 #define LCD_SETCGRAMADDR 0x40 #define LCD_SETDDRAMADDR 0x80 // flags for display entry mode #define LCD_ENTRYRIGHT 0x00 #define LCD_ENTRYLEFT 0x02 #define LCD_ENTRYSHIFTINCREMENT 0x01 #define LCD_ENTRYSHIFTDECREMENT 0x00 // flags for display on/off control #define LCD_DISPLAYON 0x04 #define LCD_DISPLAYOFF 0x00 #define LCD_CURSORON 0x02 #define LCD_CURSOROFF 0x00 #define LCD_BLINKON 0x01 #define LCD_BLINKOFF 0x00 // flags for display/cursor shift #define LCD_DISPLAYMOVE 0x08 #define LCD_CURSORMOVE 0x00 #define LCD_MOVERIGHT 0x04 #define LCD_MOVELEFT 0x00 // flags for function set #define LCD_8BITMODE 0x10 #define LCD_4BITMODE 0x00 #define LCD_2LINE 0x08 #define LCD_1LINE 0x00 #define LCD_5x10DOTS 0x04 #define LCD_5x8DOTS 0x00 // flags for backlight control #define LCD_BACKLIGHT 0x08 #define LCD_NOBACKLIGHT 0x00 #define En B00000100 // Enable bit #define Rw B00000010 // Read/Write bit #define Rs B00000001 // Register select bit class LiquidCrystal_I2C : public Print { public: LiquidCrystal_I2C(uint8_t lcd_Addr = 0x3f,uint8_t lcd_cols = 16,uint8_t lcd_rows = 2); void begin(uint8_t cols, uint8_t rows, uint8_t charsize = LCD_5x8DOTS ); void clear(); void home(); void noDisplay(); void display(); void noBlink(); void blink(); void noCursor(); void cursor(); void scrollDisplayLeft(); void scrollDisplayRight(); void printLeft(); void printRight(); void leftToRight(); void rightToLeft(); void shiftIncrement(); void shiftDecrement(); void noBacklight(); void backlight(); void autoscroll(); void noAutoscroll(); void createChar(uint8_t, uint8_t[]); void setCursor(uint8_t, uint8_t); #if defined(ARDUINO) && ARDUINO >= 100 virtual size_t write(uint8_t); #else virtual void write(uint8_t); #endif void command(uint8_t); void init(); ////compatibility API function aliases void blink_on(); // alias for blink() void blink_off(); // alias for noBlink() void cursor_on(); // alias for cursor() void cursor_off(); // alias for noCursor() void setBacklight(uint8_t new_val); // alias for backlight() and nobacklight() void load_custom_character(uint8_t char_num, uint8_t *rows); // alias for createChar() void printstr(const char[]); ////Unsupported API functions (not implemented in this library) uint8_t status(); void setContrast(uint8_t new_val); uint8_t keypad(); void setDelay(int,int); void on(); void off(); uint8_t init_bargraph(uint8_t graphtype); void draw_horizontal_graph(uint8_t row, uint8_t column, uint8_t len, uint8_t pixel_col_end); void draw_vertical_graph(uint8_t row, uint8_t column, uint8_t len, uint8_t pixel_col_end); private: void init_priv(); void send(uint8_t, uint8_t); void write4bits(uint8_t); void expanderWrite(uint8_t); void pulseEnable(uint8_t); uint8_t _Addr; uint8_t _displayfunction; uint8_t _displaycontrol; uint8_t _displaymode; uint8_t _numlines; uint8_t _cols; uint8_t _rows; uint8_t _backlightval; }; #endif
[ "philipp.schneider@phonak.com" ]
philipp.schneider@phonak.com
8dc2b829268efabd4470b54c92d130308117f3b4
610e522e2e42330d8438bc940b310317e564b2bb
/GPRMB.ino
c721b69a6ebad5d888abd57048d435abc2e32df7
[]
no_license
Hammershoj/BoatPilot
932b71c4f1b450562bf606a0875b590827ad5cd8
efaf5c8346def2f7502178a44544e71f8b64e8b3
refs/heads/master
2022-10-03T09:17:47.763112
2022-09-14T18:49:37
2022-09-14T18:49:37
195,001,793
4
1
null
2022-09-14T18:39:42
2019-07-03T07:26:24
C
UTF-8
C++
false
false
5,624
ino
#if GPS_Used ==1 void Get_GPRMB() { //Serial.println("GPRMB"); j_MAX = 15; // number of Words in NEMA Sentence Parse_Sentence(); for(int j = 0; j<j_MAX; j++) { data_RMB[j] = data_IN[j]; //see void Parse Sentence if(print_RMB)Serial.println(data_IN[j]); } // data_RMB[0] Header // data_RMB[1] Data Status // data_RMB[2] Cross track error // data_RMB[3] Cross track error L/R // data_RMB[4] Waypoint Origin Origin_Waypoint = data_RMB[4]; if(Origin_Waypoint == "") { Origin_Waypoint = "NO Origin"; } // Origin_Waypoint.toCharArray(ETdata.SD_Origin_Waypoint,11); // data_RMB[5] Destination Waypoint Waypoint_next = data_RMB[5]; if(Waypoint_next == "") { Active_waypoint = "NO WPT"; } //Waypoint_next.toCharArray(ETdata.SD_Active_waypoint,11); Waypoint_Age = millis(); if(Anticipate_Turns == 0 && Number_of_waypoints == 0) // When anticipate turns is 1 and number of waypoints > 0 the destination // lat and lon are taken from RTE and WPL in ANTICIPATE TURNS. Recalculating them here screws up anticipate turns { // data_RMB[6] Destination Latitude To_Degrees(data_RMB[6]); Lat_destination = Lat_Lon_Deg; // value returned from function if(data_RMB[7] == "S") Lat_Waypoint = - Lat_Waypoint; //data_RMB[7]; // Lat N/S // data_RMB[8] Destination Logitude To_Degrees(data_RMB[8]); Lon_destination = Lat_Lon_Deg; // value returned from function if(data_RMB[9] == "W")Lon_destination = -Lon_destination; //data_RMB[9]; // Lon E/W; } // data_RMB[10] Destination Range string1 = data_RMB[10]; NEMA_TO_FLOAT(3); //string1 is the input, 2 is the number of decimal positions, returns float3 Range_Destination = float3; // ETdata.SD_Range_Destination = Range_Destination; // Changed this to facilitate Anticipated Turns which range gets sent to ET data will be set in void Loop() // data_RMB[11] Destination Bearing string1 = data_RMB[11]; NEMA_TO_FLOAT(1); //string1 is the input, 2 is the number of decimal positions, returns float3 Bearing_to_destination = float3; // ETdata.SD_Bearing_to_destination = Bearing_to_destination; //Changed this to facilitate Anticipated Turns which range gets sent to ET data will be set in void Loop( // data_RMB[12] Velocity towards Destination // string1 = data_RMB[12]; // NEMA_TO_FLOAT(1); //string1 is the input, 2 is the number of decimal positions, returns float3 // Velocity_towards_destination = float3; // ETdata.SD_Velocity_towards_destination = Velocity_towards_destination;; // data_RMB[13] Arrival Alarm // data_RMB[14] Fix Status /* Serial.println(); Serial.print("Lat Destination = "); Serial.println(Lat_destination,4); Serial.print("Lon Destination = "); Serial.println(Lon_destination,4); */ if(print_RMB) {PRINT_RMB();} } //end of void GPRMB() case /********************* PRINT RMB **************************************************/ void PRINT_RMB() { Serial.println(); Serial.println("---------------"); Serial.print("Header: "); Serial.println(data_RMB[0]); Serial.print("Data Status: "); Serial.println(data_RMB[1]); Serial.print("Cross Track Error: "); // Serial.println(XTE); Serial.println(data_RMB[2]); Serial.print("Error L or R: "); // Serial.println(XTE_LR); Serial.println(data_RMB[3]); Serial.print("Origin Waypoint: "); // Serial.println(Origin_Waypoint); Serial.println(Origin_Waypoint); Serial.print("Destination Waypoint: "); // Serial.println(Waypoint_next); Serial.println(Waypoint_next); Serial.print("Destination Latitude: "); Serial.println(Lat_destination,4); Serial.print("Latitude N/S: "); Serial.println(data_RMB[7]); Serial.print("Destination Logitude: "); Serial.println(Lon_destination,4); Serial.print("Longitude E/W: "); Serial.println(data_RMB[9]); Serial.print("Range to Destination: "); Serial.println(Range_Destination,3); Serial.print("True Bearing to Destination: "); // Serial.println(Bearing_to_destination); Serial.println(Bearing_to_destination); Serial.print("Velocity towards Destination: "); Serial.println(Velocity_towards_destination); Serial.print("Arrival Alarm, A = Arrived, V= Not Arrived: "); Serial.println(data_RMB[13]); Serial.print("Fix Status A, D or V: "); Serial.println(data_RMB[14]); Serial.println("---------------"); } // end void PRINT_RMB #endif
[ "carsten@hammershoj.com" ]
carsten@hammershoj.com
e62fce9d293a971ee03a0032921922f448bb07a7
504afac34ed4aa421b66fec21c92e10c525ebc57
/code/estudio4/gui/linkopdlg.hpp
6296be8cd8641214fcf5d170dffb744af4a2ed55
[ "CC0-1.0" ]
permissive
grimtraveller/Enigma-Studio-4
1c63ed0f1d04f8c9685cbe299025f9a2f1051bf8
5b82e1e2b05e95b409f372b323e4c0fdeedab6fa
refs/heads/master
2021-01-20T05:57:38.984513
2016-04-19T14:58:37
2016-04-19T14:58:37
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,671
hpp
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This file is part of * ______ _ __ __ * / ____/____ (_)____ _ ____ ___ ____ _ / // / * / __/ / __ \ / // __ `// __ `__ \ / __ `/ / // /_ * / /___ / / / // // /_/ // / / / / // /_/ / /__ __/ * /_____//_/ /_//_/ \__, //_/ /_/ /_/ \__,_/ /_/. * /____/ * * Copyright © 2003-2012 Brain Control, all rights reserved. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef LINK_OP_DLG_HPP #define LINK_OP_DLG_HPP #include <QtWidgets/QDialog> #include "ui_linkopdlg.hpp" #include "../../eshared/eshared.hpp" class eLinkOpDlg : public QDialog, protected Ui::LinkOpDlg { Q_OBJECT public: eLinkOpDlg(eInt allowedLinks, QWidget *parent=nullptr); eInt getAllowedLinks() const; eID getSelectedOpId() const; private: void _initPageTree(); void _makeConnections(); void _addAllStored(); void _addByAlpha(eChar alpha); void _addByPage(const eOperatorPage *page, eChar prefix=' '); void _addFound(const QString &name); void _addToOpTree(const eIOperator *op); private Q_SLOTS: void _onPageTreeSelChanged(); void _onOpTreeSelChanged(); void _onOpTreeDoubleClick(QTreeWidgetItem *item); void _onFindClicked(); private: const eInt m_allowedLinks; }; #endif // LINK_OP_DLG_HPP
[ "hunta@braincontrol.com" ]
hunta@braincontrol.com
27bec98a25faba3166b1ce0fb5cdc2a94bc3445d
82f5957f2b20f7d62c94950f6ff4f4b5e9ad05e0
/src/init.cpp
ff2494f1b54e40f9232330c2fcfe9d8755224b28
[ "MIT" ]
permissive
VChainX/vCredit
8c8033701e119450e72602b992af57dbf86df387
d0031ee9e445dc18313be760a5f9fd0c24d6a328
refs/heads/master
2021-07-08T08:45:15.970901
2019-01-02T11:52:02
2019-01-02T11:52:02
134,194,116
3
1
MIT
2018-06-02T23:43:48
2018-05-20T23:08:38
C++
UTF-8
C++
false
false
36,038
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "txdb.h" #include "walletdb.h" #include "bitcoinrpc.h" #include "net.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "checkpoints.h" #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <boost/algorithm/string/predicate.hpp> #include <openssl/crypto.h> #ifndef WIN32 #include <signal.h> #endif using namespace std; using namespace boost; CWallet* pwalletMain; CClientUIInterface uiInterface; std::string strWalletFileName; bool fConfChange; bool fEnforceCanonical; unsigned int nNodeLifespan; unsigned int nDerivationMethodIndex; unsigned int nMinerSleep; bool fStakeLowPriority; bool fUseFastIndex; enum Checkpoints::CPMode CheckpointsMode; ////////////////////////////////////////////////////////////////////////////// // // Shutdown // void ExitTimeout(void* parg) { #ifdef WIN32 MilliSleep(5000); ExitProcess(0); #endif } void StartShutdown() { #ifdef QT_GUI // ensure we leave the Qt main loop for a clean GUI exit (Shutdown() is called in bitcoin.cpp afterwards) uiInterface.QueueShutdown(); #else // Without UI, Shutdown() can simply be started in a new thread NewThread(Shutdown, NULL); #endif } void Shutdown(void* parg) { static CCriticalSection cs_Shutdown; static bool fTaken; // Make this thread recognisable as the shutdown thread RenameThread("vcredit-shutoff"); bool fFirstThread = false; { TRY_LOCK(cs_Shutdown, lockShutdown); if (lockShutdown) { fFirstThread = !fTaken; fTaken = true; } } static bool fExit; if (fFirstThread) { fShutdown = true; nTransactionsUpdated++; // CTxDB().Close(); bitdb.Flush(false); StopNode(); bitdb.Flush(true); boost::filesystem::remove(GetPidFile()); UnregisterWallet(pwalletMain); delete pwalletMain; NewThread(ExitTimeout, NULL); MilliSleep(50); printf("vcredit exited\n\n"); fExit = true; #ifndef QT_GUI // ensure non-UI client gets exited here, but let Bitcoin-Qt reach 'return 0;' in bitcoin.cpp exit(0); #endif } else { while (!fExit) MilliSleep(500); MilliSleep(100); ExitThread(0); } } void HandleSIGTERM(int) { fRequestShutdown = true; } void HandleSIGHUP(int) { fReopenDebugLog = true; } ////////////////////////////////////////////////////////////////////////////// // // Start // #if !defined(QT_GUI) bool AppInit(int argc, char* argv[]) { bool fRet = false; try { // // Parameters // // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main() ParseParameters(argc, argv); if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified directory does not exist\n"); Shutdown(NULL); } ReadConfigFile(mapArgs, mapMultiArgs); if (mapArgs.count("-?") || mapArgs.count("--help")) { // First part of help message is specific to bitcoind / RPC client std::string strUsage = _("vcredit version") + " " + FormatFullVersion() + "\n\n" + _("Usage:") + "\n" + " vcreditd [options] " + "\n" + " vcreditd [options] <command> [params] " + _("Send command to -server or xonecoind") + "\n" + " vcreditd [options] help " + _("List commands") + "\n" + " vcreditd [options] help <command> " + _("Get help for a command") + "\n"; strUsage += "\n" + HelpMessage(); fprintf(stdout, "%s", strUsage.c_str()); return false; } // Command-line RPC for (int i = 1; i < argc; i++) if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "vcredit:")) fCommandLine = true; if (fCommandLine) { int ret = CommandLineRPC(argc, argv); exit(ret); } fRet = AppInit2(); } catch (std::exception& e) { PrintException(&e, "AppInit()"); } catch (...) { PrintException(NULL, "AppInit()"); } if (!fRet) Shutdown(NULL); return fRet; } extern void noui_connect(); int main(int argc, char* argv[]) { bool fRet = false; // Connect bitcoind signal handlers noui_connect(); fRet = AppInit(argc, argv); if (fRet && fDaemon) return 0; return 1; } #endif bool static InitError(const std::string &str) { uiInterface.ThreadSafeMessageBox(str, _("vcredit"), CClientUIInterface::OK | CClientUIInterface::MODAL); return false; } bool static InitWarning(const std::string &str) { uiInterface.ThreadSafeMessageBox(str, _("vcredit"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL); return true; } bool static Bind(const CService &addr, bool fError = true) { if (IsLimited(addr)) return false; std::string strError; if (!BindListenPort(addr, strError)) { if (fError) return InitError(strError); return false; } return true; } // Core-specific options shared between UI and daemon std::string HelpMessage() { string strUsage = _("Options:") + "\n" + " -? " + _("This help message") + "\n" + " -conf=<file> " + _("Specify configuration file (default: vcredit.conf)") + "\n" + " -pid=<file> " + _("Specify pid file (default: vcreditd.pid)") + "\n" + " -datadir=<dir> " + _("Specify data directory") + "\n" + " -wallet=<dir> " + _("Specify wallet file (within data directory)") + "\n" + " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" + " -dblogsize=<n> " + _("Set database disk log size in megabytes (default: 100)") + "\n" + " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" + " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" + " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" + " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n" " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" + " -port=<port> " + _("Listen for connections on <port> (default: 36522 or testnet: 36523)") + "\n" + " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" + " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" + " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" + " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" + " -externalip=<ip> " + _("Specify your own public address") + "\n" + " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" + " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" + " -irc " + _("Find peers using internet relay chat (default: 0)") + "\n" + " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" + " -bind=<addr> " + _("Bind to given address. Use [host]:port notation for IPv6") + "\n" + " -dnsseed " + _("Find peers using DNS lookup (default: 1)") + "\n" + " -staking " + _("Stake your coins to support network and gain reward (default: 1)") + "\n" + " -synctime " + _("Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)") + "\n" + " -cppolicy " + _("Sync checkpoints policy (default: strict)") + "\n" + " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" + " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" + " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" + " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" + " -stakelowpriority " + _("Lower staking thread priority. Possible performance/CPU usage trade-off. (default: 0)") + "\n" + #ifdef USE_UPNP #if USE_UPNP " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" + #else " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" + #endif #endif " -detachdb " + _("Detach block and address databases. Increases shutdown time (default: 0)") + "\n" + " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" + " -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.01)") + "\n" + #ifdef QT_GUI " -server " + _("Accept command line and JSON-RPC commands") + "\n" + #endif #if !defined(WIN32) && !defined(QT_GUI) " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" + #endif " -testnet " + _("Use the test network") + "\n" + " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" + " -debugnet " + _("Output extra network debugging information") + "\n" + " -logtimestamps " + _("Prepend debug output with timestamp") + "\n" + " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" + " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" + #ifdef WIN32 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" + #endif " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" + " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" + " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 36520 or testnet: 36521)") + "\n" + " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" + " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" + " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" + " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" + " -confchange " + _("Require a confirmations for change (default: 0)") + "\n" + " -enforcecanonical " + _("Enforce transaction scripts to use canonical PUSH operators (default: 1)") + "\n" + " -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" + " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" + " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" + " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" + " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" + " -checkblocks=<n> " + _("How many blocks to check at startup (default: 2500, 0 = all)") + "\n" + " -checklevel=<n> " + _("How thorough the block verification is (0-6, default: 1)") + "\n" + " -loadblock=<file> " + _("Imports blocks from external blk000?.dat file") + "\n" + "\n" + _("Block creation options:") + "\n" + " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" + " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" + " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" + "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" + " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" + " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" + " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" + " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n"; return strUsage; } /** Initialize bitcoin. * @pre Parameters should be parsed and config file should be read. */ bool AppInit2() { // ********************************************************* Step 1: setup #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif #if _MSC_VER >= 1400 // Disable confusing "helpful" text message on abort, Ctrl-C _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifdef WIN32 // Enable Data Execution Prevention (DEP) // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008 // A failure is non-critical and needs no further attention! #ifndef PROCESS_DEP_ENABLE // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), // which is not correct. Can be removed, when GCCs winbase.h is fixed! #define PROCESS_DEP_ENABLE 0x00000001 #endif typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE); #endif #ifndef WIN32 umask(077); // Clean shutdown on SIGTERM struct sigaction sa; sa.sa_handler = HandleSIGTERM; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); // Reopen debug.log on SIGHUP struct sigaction sa_hup; sa_hup.sa_handler = HandleSIGHUP; sigemptyset(&sa_hup.sa_mask); sa_hup.sa_flags = 0; sigaction(SIGHUP, &sa_hup, NULL); #endif // ********************************************************* Step 2: parameter interactions nNodeLifespan = GetArg("-addrlifespan", 7); fUseFastIndex = GetBoolArg("-fastindex", true); fStakeLowPriority = GetBoolArg("-stakelowpriority", false); nMinerSleep = GetArg("-minersleep", 500); CheckpointsMode = Checkpoints::STRICT; std::string strCpMode = GetArg("-cppolicy", "strict"); if(strCpMode == "strict") CheckpointsMode = Checkpoints::STRICT; if(strCpMode == "advisory") CheckpointsMode = Checkpoints::ADVISORY; if(strCpMode == "permissive") CheckpointsMode = Checkpoints::PERMISSIVE; nDerivationMethodIndex = 0; fTestNet = GetBoolArg("-testnet"); //fTestNet = true; if (fTestNet) { SoftSetBoolArg("-irc", true); } if (mapArgs.count("-bind")) { // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified SoftSetBoolArg("-listen", true); } if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { // when only connecting to trusted nodes, do not seed via DNS, or listen by default SoftSetBoolArg("-dnsseed", false); SoftSetBoolArg("-listen", false); } if (mapArgs.count("-proxy")) { // to protect privacy, do not listen by default if a proxy server is specified SoftSetBoolArg("-listen", false); } if (!GetBoolArg("-listen", true)) { // do not map ports or try to retrieve public IP when not listening (pointless) SoftSetBoolArg("-upnp", false); SoftSetBoolArg("-discover", false); } if (mapArgs.count("-externalip")) { // if an explicit public IP is specified, do not try to find others SoftSetBoolArg("-discover", false); } if (GetBoolArg("-salvagewallet")) { // Rewrite just private keys: rescan to find transactions SoftSetBoolArg("-rescan", true); } // ********************************************************* Step 3: parameter-to-internal-flags fDebug = GetBoolArg("-debug"); // -debug implies fDebug* if (fDebug) fDebugNet = true; else fDebugNet = GetBoolArg("-debugnet"); bitdb.SetDetach(GetBoolArg("-detachdb", false)); #if !defined(WIN32) && !defined(QT_GUI) fDaemon = GetBoolArg("-daemon"); #else fDaemon = false; #endif if (fDaemon) fServer = true; else fServer = GetBoolArg("-server"); /* force fServer when running without GUI */ #if !defined(QT_GUI) fServer = true; #endif fPrintToConsole = GetBoolArg("-printtoconsole"); fPrintToDebugger = GetBoolArg("-printtodebugger"); fLogTimestamps = GetBoolArg("-logtimestamps"); if (mapArgs.count("-timeout")) { int nNewTimeout = GetArg("-timeout", 5000); if (nNewTimeout > 0 && nNewTimeout < 600000) nConnectTimeout = nNewTimeout; } if (mapArgs.count("-paytxfee")) { if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee)) return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str())); if (nTransactionFee > 0.25 * COIN) InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.")); } fConfChange = GetBoolArg("-confchange", false); fEnforceCanonical = GetBoolArg("-enforcecanonical", true); if (mapArgs.count("-mininput")) { if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue)) return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str())); } // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log std::string strDataDir = GetDataDir().string(); std::string strWalletFileName = GetArg("-wallet", "wallet.dat"); // strWalletFileName must be a plain filename without a directory if (strWalletFileName != boost::filesystem::basename(strWalletFileName) + boost::filesystem::extension(strWalletFileName)) return InitError(strprintf(_("Wallet %s resides outside data directory %s."), strWalletFileName.c_str(), strDataDir.c_str())); // Make sure only a single Bitcoin process is using the data directory. boost::filesystem::path pathLockFile = GetDataDir() / ".lock"; FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. if (file) fclose(file); static boost::interprocess::file_lock lock(pathLockFile.string().c_str()); if (!lock.try_lock()) return InitError(strprintf(_("Cannot obtain a lock on data directory %s. vcredit is probably already running."), strDataDir.c_str())); #if !defined(WIN32) && !defined(QT_GUI) if (fDaemon) { // Daemonize pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno); return false; } if (pid > 0) { CreatePidFile(GetPidFile(), pid); return true; } pid_t sid = setsid(); if (sid < 0) fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno); } #endif if (GetBoolArg("-shrinkdebugfile", !fDebug)) ShrinkDebugFile(); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); printf("vcredit version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str()); printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION)); if (!fLogTimestamps) printf("Startup time: %s\n", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str()); printf("Default data directory %s\n", GetDefaultDataDir().string().c_str()); printf("Used data directory %s\n", strDataDir.c_str()); std::ostringstream strErrors; if (fDaemon) fprintf(stdout, "vcredit server starting\n"); int64_t nStart; // ********************************************************* Step 5: verify database integrity uiInterface.InitMessage(_("Verifying database integrity...")); if (!bitdb.Open(GetDataDir())) { string msg = strprintf(_("Error initializing database environment %s!" " To recover, BACKUP THAT DIRECTORY, then remove" " everything from it except for wallet.dat."), strDataDir.c_str()); return InitError(msg); } if (GetBoolArg("-salvagewallet")) { // Recover readable keypairs: if (!CWalletDB::Recover(bitdb, strWalletFileName, true)) return false; } if (filesystem::exists(GetDataDir() / strWalletFileName)) { CDBEnv::VerifyResult r = bitdb.Verify(strWalletFileName, CWalletDB::Recover); if (r == CDBEnv::RECOVER_OK) { string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!" " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if" " your balance or transactions are incorrect you should" " restore from a backup."), strDataDir.c_str()); uiInterface.ThreadSafeMessageBox(msg, _("vcredit"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL); } if (r == CDBEnv::RECOVER_FAIL) return InitError(_("wallet.dat corrupt, salvage failed")); } // ********************************************************* Step 6: network initialization int nSocksVersion = GetArg("-socks", 5); if (nSocksVersion != 4 && nSocksVersion != 5) return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion)); if (mapArgs.count("-onlynet")) { std::set<enum Network> nets; BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) { enum Network net = ParseNetwork(snet); if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str())); nets.insert(net); } for (int n = 0; n < NET_MAX; n++) { enum Network net = (enum Network)n; if (!nets.count(net)) SetLimited(net); } } #if defined(USE_IPV6) #if ! USE_IPV6 else SetLimited(NET_IPV6); #endif #endif CService addrProxy; bool fProxy = false; if (mapArgs.count("-proxy")) { addrProxy = CService(mapArgs["-proxy"], 9050); if (!addrProxy.IsValid()) return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str())); if (!IsLimited(NET_IPV4)) SetProxy(NET_IPV4, addrProxy, nSocksVersion); if (nSocksVersion > 4) { #ifdef USE_IPV6 if (!IsLimited(NET_IPV6)) SetProxy(NET_IPV6, addrProxy, nSocksVersion); #endif SetNameProxy(addrProxy, nSocksVersion); } fProxy = true; } // -tor can override normal proxy, -notor disables tor entirely if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) { CService addrOnion; if (!mapArgs.count("-tor")) addrOnion = addrProxy; else addrOnion = CService(mapArgs["-tor"], 9050); if (!addrOnion.IsValid()) return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str())); SetProxy(NET_TOR, addrOnion, 5); SetReachable(NET_TOR); } // see Step 2: parameter interactions for more information about these fNoListen = !GetBoolArg("-listen", true); fDiscover = GetBoolArg("-discover", true); fNameLookup = GetBoolArg("-dns", true); #ifdef USE_UPNP fUseUPnP = GetBoolArg("-upnp", USE_UPNP); #endif bool fBound = false; if (!fNoListen) { std::string strError; if (mapArgs.count("-bind")) { BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) { CService addrBind; if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str())); fBound |= Bind(addrBind); } } else { struct in_addr inaddr_any; inaddr_any.s_addr = INADDR_ANY; #ifdef USE_IPV6 if (!IsLimited(NET_IPV6)) fBound |= Bind(CService(in6addr_any, GetListenPort()), false); #endif if (!IsLimited(NET_IPV4)) fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound); } if (!fBound) return InitError(_("Failed to listen on any port. Use -listen=0 if you want this.")); } if (mapArgs.count("-externalip")) { BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) { CService addrLocal(strAddr, GetListenPort(), fNameLookup); if (!addrLocal.IsValid()) return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str())); AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL); } } if (mapArgs.count("-reservebalance")) // ppcoin: reserve balance amount { if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) { InitError(_("Invalid amount for -reservebalance=<amount>")); return false; } } if (mapArgs.count("-checkpointkey")) // ppcoin: checkpoint master priv key { if (!Checkpoints::SetCheckpointPrivKey(GetArg("-checkpointkey", ""))) InitError(_("Unable to sign checkpoint, wrong checkpointkey?\n")); } BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"]) AddOneShot(strDest); // ********************************************************* Step 7: load blockchain if (!bitdb.Open(GetDataDir())) { string msg = strprintf(_("Error initializing database environment %s!" " To recover, BACKUP THAT DIRECTORY, then remove" " everything from it except for wallet.dat."), strDataDir.c_str()); return InitError(msg); } if (GetBoolArg("-loadblockindextest")) { CTxDB txdb("r"); txdb.LoadBlockIndex(); PrintBlockTree(); return false; } uiInterface.InitMessage(_("Loading block index...")); printf("Loading block index...\n"); nStart = GetTimeMillis(); if (!LoadBlockIndex()) return InitError(_("Error loading blkindex.dat")); // as LoadBlockIndex can take several minutes, it's possible the user // requested to kill bitcoin-qt during the last operation. If so, exit. // As the program has not fully started yet, Shutdown() is possibly overkill. if (fRequestShutdown) { printf("Shutdown requested. Exiting.\n"); return false; } printf(" block index %15"PRId64"ms\n", GetTimeMillis() - nStart); if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree")) { PrintBlockTree(); return false; } if (mapArgs.count("-printblock")) { string strMatch = mapArgs["-printblock"]; int nFound = 0; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { uint256 hash = (*mi).first; if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0) { CBlockIndex* pindex = (*mi).second; CBlock block; block.ReadFromDisk(pindex); block.BuildMerkleTree(); block.print(); printf("\n"); nFound++; } } if (nFound == 0) printf("No blocks matching %s were found\n", strMatch.c_str()); return false; } // // ********************************************************* Testing Zerocoin // // // if (GetBoolArg("-zerotest", false)) // { // printf("\n=== ZeroCoin tests start ===\n"); // printf("=== ZeroCoin tests end ===\n\n"); // } // ********************************************************* Step 8: load wallet uiInterface.InitMessage(_("Loading wallet...")); printf("Loading wallet...\n"); nStart = GetTimeMillis(); bool fFirstRun = true; pwalletMain = new CWallet(strWalletFileName); DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun); if (nLoadWalletRet != DB_LOAD_OK) { if (nLoadWalletRet == DB_CORRUPT) strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n"; else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) { string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data" " or address book entries might be missing or incorrect.")); uiInterface.ThreadSafeMessageBox(msg, _("vcredit"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL); } else if (nLoadWalletRet == DB_TOO_NEW) strErrors << _("Error loading wallet.dat: Wallet requires newer version of vcredit") << "\n"; else if (nLoadWalletRet == DB_NEED_REWRITE) { strErrors << _("Wallet needed to be rewritten: restart vcredit to complete") << "\n"; printf("%s", strErrors.str().c_str()); return InitError(strErrors.str()); } else strErrors << _("Error loading wallet.dat") << "\n"; } if (GetBoolArg("-upgradewallet", fFirstRun)) { int nMaxVersion = GetArg("-upgradewallet", 0); if (nMaxVersion == 0) // the -upgradewallet without argument case { printf("Performing wallet upgrade to %i\n", FEATURE_LATEST); nMaxVersion = CLIENT_VERSION; pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately } else printf("Allowing wallet upgrade up to %i\n", nMaxVersion); if (nMaxVersion < pwalletMain->GetVersion()) strErrors << _("Cannot downgrade wallet") << "\n"; pwalletMain->SetMaxVersion(nMaxVersion); } if (fFirstRun) { // Create new keyUser and set as default key RandAddSeedPerfmon(); CPubKey newDefaultKey; if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) { pwalletMain->SetDefaultKey(newDefaultKey); if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), "")) strErrors << _("Cannot write default address") << "\n"; } } printf("%s", strErrors.str().c_str()); printf(" wallet %15"PRId64"ms\n", GetTimeMillis() - nStart); RegisterWallet(pwalletMain); CBlockIndex *pindexRescan = pindexBest; if (GetBoolArg("-rescan")) pindexRescan = pindexGenesisBlock; else { CWalletDB walletdb(strWalletFileName); CBlockLocator locator; if (walletdb.ReadBestBlock(locator)) pindexRescan = locator.GetBlockIndex(); } if (pindexBest != pindexRescan && pindexBest && pindexRescan && pindexBest->nHeight > pindexRescan->nHeight) { uiInterface.InitMessage(_("Rescanning...")); printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight); nStart = GetTimeMillis(); pwalletMain->ScanForWalletTransactions(pindexRescan, true); printf(" rescan %15"PRId64"ms\n", GetTimeMillis() - nStart); } // ********************************************************* Step 9: import blocks if (mapArgs.count("-loadblock")) { uiInterface.InitMessage(_("Importing blockchain data file.")); BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"]) { FILE *file = fopen(strFile.c_str(), "rb"); if (file) LoadExternalBlockFile(file); } exit(0); } filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat"; if (filesystem::exists(pathBootstrap)) { uiInterface.InitMessage(_("Importing bootstrap blockchain data file.")); FILE *file = fopen(pathBootstrap.string().c_str(), "rb"); if (file) { filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old"; LoadExternalBlockFile(file); RenameOver(pathBootstrap, pathBootstrapOld); } } // ********************************************************* Step 10: load peers uiInterface.InitMessage(_("Loading addresses...")); printf("Loading addresses...\n"); nStart = GetTimeMillis(); { CAddrDB adb; if (!adb.Read(addrman)) printf("Invalid or missing peers.dat; recreating\n"); } printf("Loaded %i addresses from peers.dat %"PRId64"ms\n", addrman.size(), GetTimeMillis() - nStart); // ********************************************************* Step 11: start node if (!CheckDiskSpace()) return false; RandAddSeedPerfmon(); //// debug print printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size()); printf("nBestHeight = %d\n", nBestHeight); printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size()); printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size()); printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size()); if (!NewThread(StartNode, NULL)) InitError(_("Error: could not start node")); if (fServer) NewThread(ThreadRPCServer, NULL); // ********************************************************* Step 12: finished uiInterface.InitMessage(_("Done loading")); printf("Done loading\n"); if (!strErrors.str().empty()) return InitError(strErrors.str()); // Add wallet transactions that aren't already in a block to mapTransactions pwalletMain->ReacceptWalletTransactions(); #if !defined(QT_GUI) // Loop until process is exit()ed from shutdown() function, // called from ThreadRPCServer thread when a "stop" command is received. while (1) MilliSleep(5000); #endif return true; }
[ "noreply@github.com" ]
noreply@github.com
f10129b22df8431bef05407237bfd65163026219
74ef11065048fcf08ee5b9ef1c11c0ce10079301
/expansion_js/src/duktaper/standalone_run.h
b2decf701bfd49e28824bb3d7a6102773cb22549
[ "MIT" ]
permissive
kliment-olechnovic/voronota
fa2548c9ccc3dd6f5a10a054300aca8b6d31ecf4
52c2b0d55f2979d0eef478ed0be20376cb3d561a
refs/heads/master
2023-09-04T05:09:11.275304
2023-08-30T07:59:07
2023-08-30T07:59:07
203,789,299
19
6
MIT
2023-07-04T06:25:54
2019-08-22T12:20:48
C++
UTF-8
C++
false
false
3,980
h
#ifndef DUKTAPER_STANDALONE_RUN_H_ #define DUKTAPER_STANDALONE_RUN_H_ #include <unistd.h> #include <stdio.h> #include "../dependencies/linenoise/linenoise.h" #include "binding_javascript.h" #include "duktape_manager.h" #include "stocked_data_resources.h" namespace voronota { namespace duktaper { class StandaloneRun { public: static void run(const bool no_setup_defaults, const std::vector<std::string>& command_args) { if(command_args.empty()) { throw std::runtime_error(std::string("No command arguments")); } if(!no_setup_defaults) { operators::SetupDefaults().run(0); } ScriptExecutionManager execution_manager; DuktapeManager::set_script_execution_manager(execution_manager); DuktapeManager::eval(BindingJavascript::generate_setup_script(execution_manager.collection_of_command_documentations(), false)); DuktapeManager::eval(generate_command_args_init_script(command_args)); const std::string file_name=command_args[0]; if(file_name=="-") { if(is_stdin_from_terminal()) { DuktapeManager::flag_to_print_result_on_eval()=true; bool readline_failed=false; while(!readline_failed && !execution_manager.exit_requested()) { DuktapeManager::eval(LineReading::read_line_from_stdin(readline_failed)); } } else { DuktapeManager::eval(read_script(std::cin)); } } else if(file_name.rfind(inline_script_prefix())==0) { DuktapeManager::eval(file_name.substr(inline_script_prefix().size())+"\n"); } else { std::ifstream input(file_name.c_str(), std::ios::in); if(!input.good()) { throw std::runtime_error(std::string("Invalid file '")+file_name+"'\n"); } DuktapeManager::eval(read_script(input)); } } private: #if USE_LINENOISE > 0 class LineReading { public: static std::string read_line_from_stdin(bool& failed) { ManagedLineBuffer mlb(linenoise("> ")); failed=(mlb.line==0); if(!failed) { std::string result; if(*mlb.line) { linenoiseHistoryAdd(mlb.line); result=mlb.line; } return result; } return std::string(); } private: struct ManagedLineBuffer { char* line; ManagedLineBuffer(char* line) : line(line) { } ~ManagedLineBuffer() { if(line!=0) { free(static_cast<void*>(line)); } } }; }; #else class LineReading { public: static std::string read_line_from_stdin(bool& failed) { std::string result; std::getline(std::cin, result); failed=std::cin.fail(); if(failed) { return std::string(); } return result; } }; #endif static const std::string& inline_script_prefix() { static const std::string prefix="js:"; return prefix; } static std::string generate_command_args_init_script(const std::vector<std::string>& command_args) { std::ostringstream output; output << "CommandArgs=[];\n"; for(std::size_t i=0;i<command_args.size();i++) { if(i==0 && command_args[i].rfind(inline_script_prefix())==0) { output << "CommandArgs.push('inline_script');\n"; } else if(command_args[i].find('\'')!=std::string::npos) { std::string fixed_str; for(std::size_t j=0;j<command_args[i].size();j++) { if(command_args[i][j]=='\'') { fixed_str.push_back('\\'); } fixed_str.push_back(command_args[i][j]); } output << "CommandArgs.push('" << fixed_str << "');\n"; } else { output << "CommandArgs.push('" << command_args[i] << "');\n"; } } return output.str(); } static std::string read_script(std::istream& input) { std::ostringstream output; int number_of_lines=0; while(input.good()) { std::string line; std::getline(input, line); if(!line.empty() && (number_of_lines>0 || line[0]!='#')) { output << line << "\n"; } number_of_lines++; } return output.str(); } static bool is_stdin_from_terminal() { return (isatty(fileno(stdin))==1); } }; } } #endif /* DUKTAPER_STANDALONE_RUN_H_ */
[ "kliment.olechnovic@gmail.com" ]
kliment.olechnovic@gmail.com
107da19ef6fd9a0c11da1f1397d3690c403e5b6d
cc335dee59a178db2d02e843749682db4cf71441
/Speed&Traction Control/Traction_Control/Traction_Control.ino
b44ec626d2ff83151ee0c626d64829f6c8558014
[]
no_license
Tyler-Montcalm/Mech471
b8f70919ca014ae79d76f4085898ad70256bca8d
482da9117907273bf1bd4ad42d81091991c549bb
refs/heads/master
2020-12-10T21:13:06.172924
2020-04-30T00:35:41
2020-04-30T00:35:41
233,707,217
0
0
null
null
null
null
UTF-8
C++
false
false
1,000
ino
//Code written by: Tyler Montcalm #include "PID_traction.h" #include "definitions.h" float U_traction=0; float percent_speed=50; float my_motor_speed_traction=0; float t0_traction=0; void launch_control(); void setup() { t0_traction=micros()*11.0e-6; } void loop() { // Idea is to adjust the speed of the rear so that the front and back wheels are reading an equivalent speed i.e no slip my_motor_speed_traction=(10*percent_speed)+U_traction; // my_motor(my_motor_speed_traction); U_traction=pid_traction_calculate(percent_speed,t0_traction); // this will return a U } void launch_control() { // for launch control we ramp up voltage until there is slip and then stay there so essentially //its a contrinuous PID where we are accellerating as fast as possible same thing as traction control my_motor_speed_traction=(10*percent_speed)+U_traction; // my_motor(my_motor_speed_traction); U_traction=pid_traction_calculate(percent_speed,t0_traction); // this will return a U }
[ "montcalm-tyler@outlook.com" ]
montcalm-tyler@outlook.com
aaf61e9a68749c5c7e02edd1d211a2916f5bcb02
b367fe5f0c2c50846b002b59472c50453e1629bc
/xbox_leak_may_2020/xbox trunk/xbox/private/vc6addon/ide/pkgs/dbg/miscdlgs.cpp
6d0d1a5521af2229c5d1215bd19788c2494b6fb8
[]
no_license
sgzwiz/xbox_leak_may_2020
11b441502a659c8da8a1aa199f89f6236dd59325
fd00b4b3b2abb1ea6ef9ac64b755419741a3af00
refs/heads/master
2022-12-23T16:14:54.706755
2020-09-27T18:24:48
2020-09-27T18:24:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,563
cpp
#include "stdafx.h" #pragma hdrstop #include "plist.h" #include "fbrdbg.h" #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif /////////////////////////////////////////////////////////////////////////////// // CMapRemoteDllDlg implementation /////////////////////////////////////////////////////////////////////////////// CMapRemoteDllDlg::CMapRemoteDllDlg(LPCTSTR szRemote, CWnd * pParent /* = NULL */) : C3dDialog(CMapRemoteDllDlg::IDD, pParent) { m_strRemote = szRemote; } BEGIN_MESSAGE_MAP(CMapRemoteDllDlg, C3dDialog) //{{AFX_MSG_MAP(CMapRemoteDllDlg) ON_EN_CHANGE(IDC_REMOTE_MAP_LOCAL_NAME, OnNameChange) ON_BN_CLICKED(ID_BROWSE, OnBrowse) ON_BN_CLICKED(IDC_PROMPT_DLLS, OnPromptDLLs) //}}AFX_MSG_MAP END_MESSAGE_MAP() /////////////////////////////////////////////////////////////////////////////// // BOOL CMapRemoteDllDlg::OnInitDialog() /////////////////////////////////////////////////////////////////////////////// BOOL CMapRemoteDllDlg::OnInitDialog() { // Set the text for the remote file we are trying to map ((CStatic *)GetDlgItem(IDC_REMOTE_FILE_TXT))->SetWindowText(m_strRemote); ((CEdit *)GetDlgItem(IDC_REMOTE_MAP_LOCAL_NAME))->SetWindowText(m_strRemote); // Init the state of the "try to locate any more" box in proj m_fPrompt = TRUE; ((CButton *)GetDlgItem(IDC_PROMPT_DLLS))->SetCheck(1); // Enable the OK button UpdateOKState(); return TRUE; } /////////////////////////////////////////////////////////////////////////////// // void CMapRemoteDllDlg::UpdateOKState() /////////////////////////////////////////////////////////////////////////////// void CMapRemoteDllDlg::UpdateOKState() { // Enable OK if there is a local name entered BOOL bOK = ((CEdit *)GetDlgItem(IDC_REMOTE_MAP_LOCAL_NAME))->LineLength() > 0; // Enable OK if the "Try to local other DLLs" checkbox is checked // (and we're not trying to locate the JIT exe) if ( !(theApp.m_jit.GetActive() && !theApp.m_jit.FPathIsReal()) ) { bOK |= ( ((CButton *)GetDlgItem(IDC_PROMPT_DLLS))->GetCheck() == 0); } ((CButton *)GetDlgItem(IDOK))->EnableWindow(bOK); } /////////////////////////////////////////////////////////////////////////////// // void CMapRemoteDllDlg::OnNameChange() /////////////////////////////////////////////////////////////////////////////// void CMapRemoteDllDlg::OnNameChange() { UpdateOKState(); } /////////////////////////////////////////////////////////////////////////////// // void CMapRemoteDllDlg::OnOK() /////////////////////////////////////////////////////////////////////////////// void CMapRemoteDllDlg::OnOK() { CString strLocalName; CString strDLLPath; ((CEdit *)GetDlgItem(IDC_REMOTE_MAP_LOCAL_NAME))->GetWindowText(strLocalName); // str can be empty if one of the checkboxes is checked. if (!strLocalName.IsEmpty()) { if (FFindDLL(strLocalName, strDLLPath) && CheckEXEForDebug(strDLLPath, TRUE, FALSE)) { m_strLocal = strDLLPath; m_fPrompt = ( ((CButton *)GetDlgItem(IDC_PROMPT_DLLS))->GetCheck() == 1 ); CDialog::OnOK(); } return; } m_strLocal.Empty(); m_fPrompt = ( ((CButton *)GetDlgItem(IDC_PROMPT_DLLS))->GetCheck() == 1 ); CDialog::OnOK(); } void CMapRemoteDllDlg::OnCancel( ) { // If the user doesn't ever want to be prompted for *this* // DLL again, save the remote name in DLLInfo and exit. if (!theApp.m_jit.GetActive() || theApp.m_jit.FPathIsReal()) { HBLDTARGET hTarget; gpIBldSys->GetActiveTarget(ACTIVE_BUILDER, &hTarget); UpdateDLLInfoRec (_T(""), m_strRemote, TRUE, (ULONG) hTarget, FALSE); // AddRecToDLLInfo("", m_strRemote, TRUE, (UINT)hTarget); } m_fPrompt = ( ((CButton *)GetDlgItem (IDC_PROMPT_DLLS))->GetCheck() == 1 ); CDialog::OnCancel(); } void CMapRemoteDllDlg::OnBrowse( ) { CString strTitle; CString str; CString strFilter; CFileDialog dlg(TRUE); strTitle.LoadString(IDS_FIND_LOCAL_MODULE); dlg.m_ofn.lpstrTitle = strTitle; dlg.m_ofn.Flags |= OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_NONETWORKBUTTON; if (theApp.m_jit.GetActive() && !theApp.m_jit.FPathIsReal()) { VERIFY(str.LoadString(IDS_FILTER_EXES)); } else { VERIFY(str.LoadString(IDS_FILTER_DLLS)); } AppendFilterSuffix(strFilter, dlg.m_ofn, str); dlg.m_ofn.lpstrFilter = strFilter; dlg.m_ofn.nFilterIndex = 1; for ( ; ; ) { if (dlg.DoModal() == IDCANCEL) { return; } str = dlg.GetPathName(); if (CheckEXEForDebug(str, TRUE, FALSE)) { ((CEdit *)GetDlgItem(IDC_REMOTE_MAP_LOCAL_NAME))->SetWindowText(str); return; } } } /////////////////////////////////////////////////////////////////////////////// // void CMapRemoteDllDlg::OnPromptDLLs() /////////////////////////////////////////////////////////////////////////////// void CMapRemoteDllDlg::OnPromptDLLs() { UpdateOKState(); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // CAssertFailedDlg dialog CAssertFailedDlg::CAssertFailedDlg(CWnd* pParent /*=NULL*/) : C3dDialog(CAssertFailedDlg::IDD, pParent) { //{{AFX_DATA_INIT(CAssertFailedDlg) m_strAssertText = _T(""); //}}AFX_DATA_INIT } void CAssertFailedDlg::DoDataExchange(CDataExchange* pDX) { C3dDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAssertFailedDlg) DDX_Text(pDX, IDC_ASSERT_TEXT, m_strAssertText); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAssertFailedDlg, C3dDialog) //{{AFX_MSG_MAP(CAssertFailedDlg) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP END_MESSAGE_MAP() // // Attach to Active Dialog // // // CAttachToActive Message Map BEGIN_MESSAGE_MAP(CAttachToActive, C3dDialog) ON_BN_CLICKED (IDC_SYSTEM_PROCESSES,OnChangeSystemProcess) END_MESSAGE_MAP() CAttachToActive::CAttachToActive( CWnd* pParent // = NULL ) : C3dDialog (CAttachToActive::IDD, pParent) { m_ProcessId = 0; m_TaskList = NULL; } CAttachToActive::~CAttachToActive( ) { delete [] m_TaskList; m_TaskList = NULL; } void CAttachToActive::DoDataExchange( CDataExchange* pDX ) { C3dDialog::DoDataExchange (pDX); } #define PL_INDEX_NAME 0 #define PL_INDEX_PID 1 #define PL_INDEX_TITLE 2 int CALLBACK PLCompareFunction( LPARAM lParam1, LPARAM lParam2, LPARAM nSortField ) { TASK_LIST* Task1 = (TASK_LIST*)lParam1; TASK_LIST* Task2 = (TASK_LIST*)lParam2; switch (nSortField) { case PL_INDEX_NAME: return lstrcmpi (Task1->ProcessName, Task2->ProcessName); case PL_INDEX_PID: return ((int)Task1->dwProcessId - (int)Task2->dwProcessId); case PL_INDEX_TITLE: { if (!Task1->hwnd && !Task2->hwnd) return 0; if (!Task1->hwnd) return 1; if (!Task2->hwnd) return -1; return lstrcmpi (Task1->WindowTitle, Task2->WindowTitle); } default: ASSERT (FALSE); } return 0; } BOOL CAttachToActive::OnNotify( WPARAM wParam, LPARAM lParam, LRESULT* lResult ) { switch ( ((LPNMHDR)lParam)->code ) { case LVN_COLUMNCLICK: return OnLvnColumnClick ((NM_LISTVIEW*) lParam, lResult); case NM_DBLCLK: return OnNmDblClk((NMHDR*) lParam, lResult); } return 0; } BOOL CAttachToActive::OnLvnColumnClick( NM_LISTVIEW* ListData, LRESULT* lResult ) { CListCtrl* ProcessList = (CListCtrl*) GetDlgItem (IDC_PROCESS_LIST); ULONG nSortField; ASSERT (ProcessList); // // this is a sort request ProcessList->SortItems (PLCompareFunction, ListData->iSubItem); return TRUE; } BOOL CAttachToActive::OnNmDblClk( NMHDR* Data, LRESULT* lResult ) { OnOK(); return TRUE; } BOOL CAttachToActive::OnInitDialog( ) /*++ Routine Description: Initialize dialog with list of processes. Return Value: Returns TRUE to denote success. --*/ { C3dDialog::OnInitDialog (); CButton* SysProc = (CButton*) GetDlgItem (IDC_SYSTEM_PROCESSES); SysProc->SetCheck (FALSE); m_TaskList = new TASK_LIST [512]; m_nTasks = 512; CListCtrl* ProcessList = (CListCtrl*)GetDlgItem (IDC_PROCESS_LIST); CString str; str.LoadString(IDS_PROCESS); ProcessList->InsertColumn (PL_INDEX_NAME, str, LVCFMT_LEFT, 110); str.LoadString(IDS_PROCESSID); ProcessList->InsertColumn (PL_INDEX_PID, str, LVCFMT_LEFT, 75); str.LoadString(IDS_TITLE); ProcessList->InsertColumn (PL_INDEX_TITLE, str, LVCFMT_LEFT, 200); FillProcessList (FALSE); return TRUE; } void CAttachToActive::EmptyProcessList( ) { CListCtrl* ProcessList = (CListCtrl*) GetDlgItem (IDC_PROCESS_LIST); ProcessList->DeleteAllItems (); } void CAttachToActive::FillProcessList( BOOL fSystemProcesses ) { TASK_LIST_ENUM TaskListEnum; int nTasks; TCHAR Buffer [15]; int nItem; ULONG CurrentProcessId = GetCurrentProcessId (); CListCtrl* ProcessList = (CListCtrl*)GetDlgItem (IDC_PROCESS_LIST); CWaitCursor boy_oh_boy_is_c_plus_plus_a_neato_language; bool fWinNT = (GetOsVersion() == VER_PLATFORM_WIN32_NT); if (!InitPlistApi ()) { return; } SetDebugPrivilege (fSystemProcesses); do { nTasks = GetTaskList (m_TaskList, m_nTasks); if (m_nTasks < nTasks && fWinNT) { // // compensate for new PSAPI code - NT alone) // m_nTasks = nTasks; m_TaskList = new TASK_LIST [nTasks]; if (!m_TaskList) { return; } } else { break; } } while (1); TaskListEnum.tlist = m_TaskList; TaskListEnum.numtasks = nTasks; GetWindowTitles (&TaskListEnum); /* for (int i = 0; i < nTasks; i++) { if (m_TaskList [i].dwProcessId == CurrentProcessId) { // do not list our own process m_TaskList [i].BinaryType = IMAGE_BAD_EXECUTABLE; continue; } // // get imageinfo is already done by GetTaskList on NT // if (!GetTaskImageInfo (&m_TaskList [i])) { m_TaskList [i].BinaryType = IMAGE_BAD_EXECUTABLE; } } */ FreePlistApi (); for (int i = 0; i < nTasks; i++) { if (m_TaskList [i].dwProcessId == CurrentProcessId) { continue; } if (fWinNT) { if (!fSystemProcesses && (m_TaskList[i].flags & TASK_SYSTEM_PROCESS)) { continue; } _ultoa (m_TaskList[i].dwProcessId, Buffer, 10); } else { // // if image is anything but a 32 bit GUI or CUI App, ignore if (!GetTaskImageInfo(&m_TaskList[i])) { continue; } if (m_TaskList [i].BinaryType != IMAGE_SUBSYSTEM_WINDOWS_CUI && m_TaskList [i].BinaryType != IMAGE_SUBSYSTEM_WINDOWS_GUI) { continue; } _ultoa (m_TaskList[i].dwProcessId, Buffer, 16); } nItem = ProcessList->InsertItem (0, m_TaskList[i].ProcessName); ProcessList->SetItemText (nItem, 1, Buffer); ProcessList->SetItemText (nItem, 2, (m_TaskList[i].hwnd ? m_TaskList [i].WindowTitle : " ")); ProcessList->SetItemData (nItem, (LPARAM)&m_TaskList [i]); } ProcessList->SetItemState (0, LVNI_SELECTED, LVNI_SELECTED); } void CAttachToActive::OnChangeSystemProcess( ) { CButton* SysProc = (CButton*) GetDlgItem (IDC_SYSTEM_PROCESSES); EmptyProcessList (); if (SysProc->GetCheck ()) { FillProcessList (TRUE); } else { FillProcessList (FALSE); } } void CAttachToActive::OnOK( ) { int nItem; CListCtrl* ProcessList = (CListCtrl*) GetDlgItem (IDC_PROCESS_LIST); CString str; PTASK_LIST Task; ASSERT (ProcessList); nItem = ProcessList->GetNextItem (-1, LVNI_SELECTED); if (nItem != -1) { Task = (PTASK_LIST) ProcessList->GetItemData (nItem); ASSERT (Task); m_ProcessId = Task->dwProcessId; m_ProcessName = Task->ProcessName; m_ImageName = Task->ImageName ; C3dDialog::OnOK (); return; } C3dDialog::OnCancel (); } // // List Module Dialog // static const char *GetBaseName( const char *pFullPath ) { const char *pSlash = _tcsrchr( pFullPath, '\\' ); return pSlash ? pSlash+1 : pFullPath; } // // CModuleDialog Message Map BEGIN_MESSAGE_MAP(CModuleDialog, C3dDialog) ON_BN_CLICKED (IDC_SYSTEM_PROCESSES,OnChangeModule) END_MESSAGE_MAP() CModuleDialog::CModuleDialog( CWnd* pParent // = NULL ) : C3dDialog (CModuleDialog::IDD, pParent) { m_pModuleList = NULL; } CModuleDialog::~CModuleDialog( ) { if (m_pModuleList) BMFree( m_pModuleList ); m_pModuleList = NULL; } void CModuleDialog::DoDataExchange( CDataExchange* pDX ) { C3dDialog::DoDataExchange (pDX); } #define PL_BASENAME 0 #define PL_ADDR 1 #define PL_FULLPATH 2 #define PL_ORDER 3 int CALLBACK PLCompareFunctionModule( LPARAM lParam1, LPARAM lParam2, LPARAM nSortField ) { LPMODULE_ENTRY Mod1 = (LPMODULE_ENTRY)lParam1; LPMODULE_ENTRY Mod2 = (LPMODULE_ENTRY)lParam2; ASSERT( Mod1 && Mod2 ); switch (nSortField) { case PL_BASENAME: return _tcsicmp (GetBaseName(ModuleEntryName(Mod1)), GetBaseName(ModuleEntryName(Mod2)) ); case PL_ADDR: if (ModuleEntryBase(Mod1) > ModuleEntryBase(Mod2)) return 1; else if (ModuleEntryBase(Mod1) != ModuleEntryBase(Mod2)) return -1; else return 0; case PL_FULLPATH: return _tcsicmp (ModuleEntryName(Mod1), ModuleEntryName(Mod2) ); case PL_ORDER: return (Mod1-Mod2); default: ASSERT (FALSE); } return 0; } BOOL CModuleDialog::OnNotify( WPARAM wParam, LPARAM lParam, LRESULT* lResult ) { switch ( ((LPNMHDR)lParam)->code ) { case LVN_COLUMNCLICK: return OnLvnColumnClick ((NM_LISTVIEW*) lParam, lResult); case NM_DBLCLK: return OnNmDblClk((NMHDR*) lParam, lResult); } return 0; } BOOL CModuleDialog::OnLvnColumnClick( NM_LISTVIEW* ListData, LRESULT* lResult ) { CListCtrl* ProcessList = (CListCtrl*) GetDlgItem (IDC_MODULE_LIST); ULONG nSortField; ASSERT (ProcessList); // // this is a sort request ProcessList->SortItems (PLCompareFunctionModule, ListData->iSubItem); return TRUE; } BOOL CModuleDialog::OnNmDblClk( NMHDR* Data, LRESULT* lResult ) { // OnOK(); return TRUE; } BOOL CModuleDialog::OnInitDialog( ) /*++ Routine Description: Initialize dialog with list of modules Return Value: Returns TRUE to denote success. --*/ { C3dDialog::OnInitDialog (); CListCtrl* ProcessList = (CListCtrl*)GetDlgItem (IDC_MODULE_LIST); DWORD dwStyle = ProcessList->GetExtendedStyle(); ProcessList->SetExtendedStyle( dwStyle | LVS_EX_FULLROWSELECT ); CString str; str.LoadString(IDS_MODULENAME); ProcessList->InsertColumn (PL_BASENAME, str, LVCFMT_LEFT, 100 ); str.LoadString(IDS_ADDRESS); ProcessList->InsertColumn (PL_ADDR, str, LVCFMT_LEFT, 200 ); str.LoadString(IDS_FULLPATH); ProcessList->InsertColumn (PL_FULLPATH, str, LVCFMT_LEFT, 300 ); str = "Order"; ProcessList->InsertColumn (PL_ORDER, str, LVCFMT_LEFT, 40 ); FillModuleList (); return TRUE; } void CModuleDialog::EmptyModuleList( ) { if (m_pModuleList) BMFree( m_pModuleList ); m_pModuleList = NULL; CListCtrl* ProcessList = (CListCtrl*) GetDlgItem (IDC_MODULE_LIST); ProcessList->DeleteAllItems (); } void CModuleDialog::FillModuleList( ) { int nTasks; int nItem; CListCtrl* ProcessList = (CListCtrl*)GetDlgItem (IDC_MODULE_LIST); CWaitCursor boy_oh_boy_is_c_plus_plus_a_neato_language; XOSD xosd = OSDGetModuleList( hpidCurr, htidCurr, NULL, &m_pModuleList ); if (xosd!=xosdNone) return; LPMODULE_ENTRY pMod = FirstModuleEntry( m_pModuleList ); for (int i=0; i<ModuleListCount(m_pModuleList); i++) { // code used for Win95 testing only // if (ModuleEntryBase(pMod) > 0x70000000) // ModuleEntryBase(pMod) += 0x80000000; nItem = ProcessList->InsertItem( i, GetBaseName( ModuleEntryName(pMod) ) ); TCHAR szAddr[ MAX_PATH ]; wsprintf( szAddr, "0x%08lX - 0x%08lX", ModuleEntryBase(pMod), ModuleEntryBase(pMod)+ModuleEntryLimit(pMod)-1 ); ProcessList->SetItemText( nItem, PL_ADDR, szAddr ); ProcessList->SetItemText( nItem, PL_FULLPATH, ModuleEntryName(pMod) ); wsprintf( szAddr, "%d", pMod-FirstModuleEntry(m_pModuleList)+1 ); ProcessList->SetItemText( nItem, PL_ORDER, szAddr ); ProcessList->SetItemData( nItem, (LPARAM)pMod ); pMod = NextModuleEntry( pMod ); } } void CModuleDialog::OnChangeModule( ) { EmptyModuleList (); FillModuleList (); } void CModuleDialog::OnOK( ) { C3dDialog::OnOK (); } // // No symbolic information dialog // BEGIN_MESSAGE_MAP(CNoSymbolInfoDlg, C3dDialog) END_MESSAGE_MAP() CNoSymbolInfoDlg::CNoSymbolInfoDlg( CWnd* pParent // = NULL ) : C3dDialog (CNoSymbolInfoDlg::IDD, pParent) { m_fNoPrompt = FALSE; m_strCaption = ""; m_strPrompt = ""; } void CNoSymbolInfoDlg::DoDataExchange( CDataExchange* pDX ) { C3dDialog::DoDataExchange (pDX); DDX_Check (pDX, IDC_NO_PROMPT, m_fNoPrompt); } BOOL CNoSymbolInfoDlg::OnInitDialog( ) { CString str; TCHAR buffer [512]; CStatic* st = (CStatic*) GetDlgItem (IDC_PROMPT); if (m_strCaption != "") { SetWindowText (m_strCaption); } str.LoadString (ERR_No_Debug_Info); sprintf (buffer, str, (LPCTSTR) m_strPrompt); m_strPrompt = buffer; st->SetWindowText (m_strPrompt); return TRUE; } // // CFibers Message Map BEGIN_MESSAGE_MAP(CFibers, C3dDialog) END_MESSAGE_MAP() CFibers::CFibers( CWnd* pParent // = NULL ) : C3dDialog (CFibers::IDD, pParent) { } #define FL_INDEX_NAME 0 #define FL_INDEX_PID 1 #define FL_INDEX_TITLE 2 CFibers::~CFibers( ) { delete [] m_FbrLst; m_FbrCntx = NULL; } void CFibers::DoDataExchange( CDataExchange* pDX ) { C3dDialog::DoDataExchange (pDX); } int CALLBACK FLCompareFunction( LPARAM lParam1, LPARAM lParam2, LPARAM nSortField ) { PFBRLST fbrl1 = (PFBRLST) lParam1; PFBRLST fbrl2 = (PFBRLST) lParam2; switch (nSortField) { case FL_INDEX_NAME: return lstrcmpi (fbrl1->strFbr, fbrl2->strFbr); break; case FL_INDEX_PID: return ((int)fbrl1->FbrCntx - (int)fbrl2->FbrCntx); break; case FL_INDEX_TITLE: { return 0; } default: ASSERT (FALSE); } return 0; } extern BOOL GetSymbolFromAddr(PADDR, CString&); BOOL CFibers::OnNotify( WPARAM wParam, LPARAM lParam, LRESULT* lResult ) { switch ( ((LPNMHDR)lParam)->code ) { case LVN_COLUMNCLICK: return OnLvnColumnClick ((NM_LISTVIEW*) lParam, lResult); } return 0; } BOOL CFibers::OnLvnColumnClick( NM_LISTVIEW* ListData, LRESULT* lResult ) { CListCtrl* FiberList = (CListCtrl*) GetDlgItem (IDC_FIBERS_LIST); ULONG nSortField; ASSERT (FiberList); // // this is a sort request FiberList->SortItems (FLCompareFunction, ListData->iSubItem); return TRUE; } BOOL CFibers::OnInitDialog( ) /*++ Routine Description: Initialize dialog with list of processes. Return Value: Returns TRUE to denote success. --*/ { TASK_LIST_ENUM TaskListEnum; TCHAR Buffer [15]; TCHAR Location[256]; DWORD nFbrs=0; DWORD nItem; OFBRS ofbrs; DWORD sizebuf[16]; DWORD *dwFbrLst; C3dDialog::OnInitDialog (); CListCtrl* FiberList = (CListCtrl*)GetDlgItem (IDC_FIBERS_LIST); FiberList->InsertColumn (FL_INDEX_NAME, "Fiber", LVCFMT_LEFT, 110); FiberList->InsertColumn (FL_INDEX_PID, "Fiber Id", LVCFMT_LEFT, 75); //FiberList->InsertColumn (FL_INDEX_TITLE, "Title", LVCFMT_LEFT, 150); ofbrs.op = OFBR_QUERY_LIST_SIZE; // Sytem services return values in the same buffer as the command // so copy the command to the return buffer. memcpy(sizebuf,&ofbrs,sizeof(OFBRS)); OSDSystemService (hpidCurr, htidCurr, ssvcFiberDebug, (LPVOID) sizebuf, sizeof(OFBRS),//should use two calls &nFbrs ); int lstsize = *((int *)sizebuf); // must have enough room for OFBRS lstsize = (lstsize < sizeof(OFBRS)) ? sizeof(OFBRS) : lstsize; dwFbrLst = new DWORD [lstsize]; m_FbrLst = new FBRLST [lstsize]; ofbrs.op = OFBR_GET_LIST; // Sytem services return values in the same buffer as the command // so copy the command to the return buffer. memcpy(dwFbrLst,&ofbrs,sizeof(OFBRS)); OSDSystemService (hpidCurr, htidCurr, ssvcFiberDebug, (LPVOID) dwFbrLst, lstsize,//should use two calls &nFbrs ); nFbrs = nFbrs>>2;//number of fibers rather than bytes for (int i = 0; i < nFbrs; i++) { CString strLocation; ADDR Addr = {0}; _snprintf(Buffer,16,"0x%08x",dwFbrLst[i]); m_FbrLst[i].FbrCntx = (LPVOID) dwFbrLst[i]; ofbrs.op = OFBR_SET_FBRCNTX; ofbrs.FbrCntx = (LPVOID) dwFbrLst[i]; OSDSystemService (hpidCurr, htidCurr, ssvcFiberDebug, (LPVOID) &ofbrs, sizeof(OFBRS), NULL ); HTID htid = htidCurr; OSDGetFrame(hpidCurr,htid,1,&htid); OSDGetAddr(hpidCurr,htid,adrPC,(PADDR)&Addr); // Get the thread location. First, see if we can determine a function // name for the current CS:EIP. If we can't, then look up the stack // for the first address for which we DO have symbols. if (!GetSymbolFromAddr(&Addr,strLocation)) { // If the address that the top of stack doesn't have a symbol, // then look up the stack, and if we find something we recognize, // put its function name in brackets int i; HFME hfme; LPFME lpfme; for (i = 0; (hfme = CLHfmeGetNth(i)) != NULL; ++i) { lpfme = (LPFME)LLLpvFromHlle(hfme); if (lpfme->clt == cltProc) { // found a function: format as "[func_name]" if (GetSymbolFromAddr(&lpfme->addrProc, strLocation)) { _snprintf(Location,256, "[%s]", (const char*)strLocation); break; } } UnlockHlle(hfme); } if (hfme) { UnlockHlle(hfme); } } else { _tcsncpy(Location, (LPCTSTR)strLocation, 256); Location[255-1] = '\0'; } m_FbrLst[i].strFbr = Location; nItem = FiberList->InsertItem (0, Location); FiberList->SetItemText (nItem, 1, Buffer); //FiberList->SetItemText (nItem, 2, " "); FiberList->SetItemData (nItem, (LPARAM)&(m_FbrLst[i])); } FiberList->SetItemState (0, LVNI_SELECTED, LVNI_SELECTED); // Put the old thread back ofbrs.op = OFBR_SET_FBRCNTX; ofbrs.FbrCntx = NULL; OSDSystemService (hpidCurr, htidCurr, ssvcFiberDebug, (LPVOID) &ofbrs, sizeof(OFBRS), NULL ); HTID htid = htidCurr; OSDGetFrame(hpidCurr,htid,1,&htid); delete [] dwFbrLst; return TRUE; } void CFibers::OnOK( ) { int nItem; CListCtrl* FiberList = (CListCtrl*) GetDlgItem (IDC_FIBERS_LIST); CString str; PFBRLST fbrl; ASSERT (FiberList); nItem = FiberList->GetNextItem (-1, LVNI_SELECTED); if (nItem != -1) { fbrl = (PFBRLST) FiberList->GetItemData (nItem); ASSERT (fbrl); m_FbrCntx = fbrl->FbrCntx; C3dDialog::OnOK (); return; } C3dDialog::OnCancel (); }
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
378946db06522b2a4ebfd2f223abd564c680f2a9
7eddcf61699205e0af7d4421fe76fe67cb232ec9
/C++/CodeChef/NUMGAME.cpp
2e2f0c71156bfd84a61f4e5fe38763e10c5c8af4
[]
no_license
cuongdangn/CompetitivePrograming
389761a140d9351abaa411f8ca53f07c70c0b6ba
86ab92e313cb5c15b429fb0fb4d36534ae89eb4e
refs/heads/master
2022-11-28T22:43:21.392720
2020-08-14T17:24:02
2020-08-14T17:24:02
287,583,980
0
0
null
null
null
null
UTF-8
C++
false
false
261
cpp
#include<iostream> #include<cmath> #include<cstdio> using namespace std; int t; int main() { scanf("%d",&t); for(int i=1;i<=t;i++) { int x; scanf("%d",&x); if(x%2==0)printf("ALICE\n"); else printf("BOB\n"); } }
[ "cuongdangngoc97@gmail.com" ]
cuongdangngoc97@gmail.com
b7521953480e71971dbec0683ac7362882aadcc8
96cfecabf42dab5deee1855b3bb8a81ff5ee896b
/dnde3/archive.ixx
01b996bb7accfaa321c8dbb6899a1ea3d9ea3c1e
[]
no_license
Pavelius/dnde3
7ba54fec0b5ddf2e7c1dc32376e1a5cdf0c1e475
9fb515f1c0b0c6d17648fd9d5659e183d1820bf2
refs/heads/master
2021-12-14T22:50:37.013939
2021-12-10T06:27:38
2021-12-10T06:27:38
226,627,371
2
0
null
null
null
null
UTF-8
C++
false
false
3,453
ixx
export module archive; import collections; import stream; import stringbuilder; export struct archive { struct dataset { void* data; template<class T, unsigned N> constexpr dataset(T(&data)[N]) : data(&data), size(sizeof(T)), count(current_count), current_count(N), maximum_count(N) {} template<class T, unsigned N> constexpr dataset(adat<T, N>& data) : data(&data.data), size(sizeof(T)), count(data.count), current_count(0), maximum_count(N) {} void* get(int index) const { return (char*)data + index * size; } int indexof(void* p) const { if(((char*)p) >= ((char*)data) && ((char*)p) < ((char*)data + size * count)) return ((char*)p - (char*)data) / size; return -1; } private: unsigned size; unsigned maximum_count; unsigned current_count; unsigned& count; }; io::stream& source; bool writemode; aref<dataset> pointers; archive(io::stream& source, bool writemode) : source(source), writemode(writemode), pointers() {} archive(io::stream& source, bool writemode, const aref<dataset>& pointers) : source(source), writemode(writemode), pointers(pointers) {} void setpointer(void** value) { unsigned pid; if(writemode) { pid = -1; auto j = 0; for(auto& e : pointers) { auto i = e.indexof(*value); if(i != -1) { pid = (j << 24) | i; break; } j++; } source.write(&pid, sizeof(pid)); } else { *value = 0; source.read(&pid, sizeof(pid)); if(pid != -1) { auto bi = pid >> 24; auto ii = pid & 0xFFFFFF; *value = pointers[bi].get(ii); } } } bool signature(const char* id) { char temp[4] = {}; if(writemode) { stringbuilder sb(temp); sb.add(id); source.write(temp, sizeof(temp)); } else { source.read(temp, sizeof(temp)); if(szcmpi(temp, id) != 0) return false; } return true; } // Check if file have at least this version bool version(short major, short minor) { short major_reader = major; short minor_reader = minor; set(major_reader); set(minor_reader); if(!writemode) { if(major_reader < major) return false; else if(major_reader == major && minor_reader < minor) return false; } return true; } // Any pointer class template<class T> void set(T*& value) { setpointer((void**)&value); } // Full specialization for strings template<> void set<const char>(const char*& e) { if(writemode) { unsigned len = zlen(e); source.write(&len, sizeof(len)); if(len) source.write(e, len); } else { unsigned len; char temp[128 * 128]; source.read(&len, sizeof(len)); e = 0; if(len) { source.read(temp, len); temp[len] = 0; //e = szdup(temp); } } } // Array with fixed count template<typename T, unsigned N> void set(T(&value)[N]) { for(int i = 0; i < N; i++) set(value[i]); }; // Fixed data collection template<typename T, unsigned N> void set(adat<T, N>& value) { set(value.count); for(auto& e : value) set(e); } // Custom aref collection template<typename T> void set(aref<T>& value) { set(value.count); set(value.data); } // All simple types and requisites template<class T> void set(T& value) { if(writemode) source.write(&value, sizeof(value)); else source.read(&value, sizeof(value)); } // Full specialization for arrays void set(array& e) { set(e.count); if(e.count > 0) { if(writemode) source.write(e.data, e.size * e.count); else source.read(e.data, e.size * e.count); } } };
[ "p000000000001@gmail.com" ]
p000000000001@gmail.com
86f1d0c0c8ab8462bd20c1e07d4e054983fd4fc2
ecb4b5e25557ca4edf4f28300510d47fea2edcbe
/Classes/HelloWorldScene.cpp
ada389f84a76b4613a7802de296961e464592a3d
[]
no_license
haidragon/chess
42690dcac02e6cb2507b2ce4de25d41df7a3a472
f99ca5ad41ac234348a180b204cf4b33d3c335e6
refs/heads/master
2020-03-22T20:53:34.587731
2018-07-15T08:37:37
2018-07-15T08:37:37
140,639,698
0
0
null
null
null
null
UTF-8
C++
false
false
4,826
cpp
/**************************************************************************** Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "HelloWorldScene.h" #include "SimpleAudioEngine.h" USING_NS_CC; Scene* HelloWorld::createScene() { return HelloWorld::create(); } // Print useful error message instead of segfaulting when files are not there. static void problemLoading(const char* filename) { printf("Error while loading: %s\n", filename); printf("Depending on how you compiled you might have to add 'Resources/' in front of filenames in HelloWorldScene.cpp\n"); } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Scene::init() ) { return false; } auto visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); if (closeItem == nullptr || closeItem->getContentSize().width <= 0 || closeItem->getContentSize().height <= 0) { problemLoading("'CloseNormal.png' and 'CloseSelected.png'"); } else { float x = origin.x + visibleSize.width - closeItem->getContentSize().width/2; float y = origin.y + closeItem->getContentSize().height/2; closeItem->setPosition(Vec2(x,y)); } // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24); if (label == nullptr) { problemLoading("'fonts/Marker Felt.ttf'"); } else { // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, 1); } // add "HelloWorld" splash screen" auto sprite = Sprite::create("background.png"); if (sprite == nullptr) { problemLoading("'background.png'"); } else { // position the sprite on the center of the screen sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); } return true; } void HelloWorld::menuCloseCallback(Ref* pSender) { //Close the cocos2d-x game scene and quit the application Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif /*To navigate back to native iOS screen(if present) without quitting the application ,do not use Director::getInstance()->end() and exit(0) as given above,instead trigger a custom event created in RootViewController.mm as below*/ //EventCustom customEndEvent("game_scene_close_event"); //_eventDispatcher->dispatchEvent(&customEndEvent); }
[ "noreply@github.com" ]
noreply@github.com
cd434d6e8d3cc111e1b2916f44a0ad609f43c781
38f7189795c68b451b49b57821414e9588e0c755
/zad5/main.cpp
1703fe3002d34d25d3147a333d7d8beb35c3de02
[]
no_license
Jyang772/przykladowe_zad_egzamin
cb6e9f50a942678d9f030af5731d2482712ae352
7dc4a8bf1397dd8168d089c7a833cd1bc7a8f1bb
refs/heads/master
2020-12-31T01:23:54.903466
2013-12-20T23:33:33
2013-12-20T23:33:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
694
cpp
#include <iostream> #include <fstream> #include <cstring> using namespace std; void wiersze(string nazwa,char zn) { ifstream plik(nazwa.c_str()); if(!plik.good()) { cout << "Blad pliku"; } string wiersz; int n = 0; while(!plik.eof()) { getline(plik,wiersz); bool is = true; for(int i = 0; i < wiersz.size(); i++) if(wiersz[i] == zn) { is = false; break; } if(is) n++; } plik.close(); cout << " Liczba wierszy nie zawierajych znaku " << zn << " jest rowna: " << n << endl; } int main() { wiersze("dane.txt", 'k'); return 0; }
[ "karina.szewczyk@poczta.onet.pl" ]
karina.szewczyk@poczta.onet.pl
b4f8b8cd48631408cec002981b006a1815a74971
f536aefa791d6c3783547998a04386a15346a0a6
/src/Tortoise_Object.h
202b7fd9b324e9490c7970ddd5a5ee106761b9cc
[]
no_license
Hanslen/CPP_mario_Wrestle
afd83e7c109e841a45632f6945becc2c9b80edbf
2afc11e029e1b97fc6637edf0666716cadfd1871
refs/heads/master
2021-07-07T10:52:39.953410
2017-09-28T17:38:28
2017-09-28T17:38:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
750
h
#pragma once #include "DisplayableObject.h" #include "JPGImage.h" class Tortoise_Object : public DisplayableObject { public: Tortoise_Object(BaseEngine* pEngine); ~Tortoise_Object(); void Draw(); ImageData tortoise, tortoise2; ImageData subTortoise1, subTortoise; int left; bool up; bool fly; bool direction; //0 for left, 1 for right static int hasSub; static int subX; static int canJump; int subY; static int subOver; static int wantJump; void DoUpdate(int iCurrentTime); private: int action; int randAction; int size; int rotate_val; void moveLeft(); void moveRight(); void moveUp(); void moveShake(); void moveFly(); void moveBig(); void moveSmall(); void moveRocket(); };
[ "psyjc3@exmail.nottingham.ac.uk" ]
psyjc3@exmail.nottingham.ac.uk
519fac5c84ec674801bebee9c129b2d98660c932
18b71afb22f6c65d0916e8b2457a525dd53205cc
/functional.h
c46334379a388306ce6c6d29c62bf19409ebc984
[ "MIT" ]
permissive
keithalewis/fmsum
d0fd9c87c4578a00321cf81bd1323c8987339d9a
d2da4021115d429799d734b66e8b47bd6e72d990
refs/heads/master
2020-04-16T09:02:13.523028
2019-02-25T21:40:50
2019-02-25T21:40:50
165,448,170
0
0
null
null
null
null
UTF-8
C++
false
false
1,071
h
// functional.h - Extend <functional> #pragma once #include <functional> namespace { template<class X, class Y, class Binop> inline auto operator_binop(const Binop& binop, const std::function<Y(X)>& f, const std::function<Y(X)>& g) { return [&binop,&f,&g](const X& x) { return binop(f(x), g(x)); }; } } template<class X, class Y> inline std::function<Y(const X&)> K(const Y& y) { return [y](const X&) { return y; }; } template<class X, class Y> inline auto operator+(const std::function<Y(X)>& f,const std::function<Y(X)>& g) { return operator_binop(std::plus<Y>{},f,g); } template<class X,class Y> inline auto operator-(const std::function<Y(X)>& f,const std::function<Y(X)>& g) { return operator_binop(std::minus<Y>{},f,g); } template<class X,class Y> inline auto operator*(const std::function<Y(X)>& f,const std::function<Y(X)>& g) { return operator_binop(std::multiplies<Y>{},f,g); } template<class X,class Y> inline auto operator/(const std::function<Y(X)>& f,const std::function<Y(X)>& g) { return operator_binop(std::divides<Y>{},f,g); }
[ "keithalewis@live.com" ]
keithalewis@live.com
ded60d2da6aaeeee91a774d1cb8987484df5340b
c5f925c1e63239f92942d3c3c306f77facbdbc44
/clang/test/SemaSYCL/sampler_t-member-init.cpp
9fff3c5cf83c93169758eb0aff06596daf80918f
[ "Apache-2.0", "LLVM-exception", "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
hanzhan1/llvm
e4f71c99e09744e749295716a5641d23e74311e5
efe40bb5c797b102088e3cd2579a0f57ccf93310
refs/heads/private/hanzhan1/fix-sync-main
2023-05-08T09:10:40.750734
2020-12-22T02:31:13
2020-12-22T02:31:13
311,268,275
0
0
null
2021-05-26T08:28:04
2020-11-09T08:16:43
null
UTF-8
C++
false
false
1,516
cpp
// RUN: %clang_cc1 %s -fsycl -fsycl-is-device -ast-dump 2>&1 | FileCheck %s const __ocl_sampler_t Global = 0; class Foo { int i; __ocl_sampler_t Member; __ocl_sampler_t Member2; __ocl_sampler_t Member3; __ocl_sampler_t Member4; Foo(__ocl_sampler_t Param) : // CHECK: CXXConstructorDecl // CHECK-SAME: Foo 'void (__ocl_sampler_t)' Member(Param), // CHECK: CXXCtorInitializer Field // CHECK-SAME: 'Member' '__ocl_sampler_t':'sampler_t' // CHECK-NEXT: ImplicitCastExpr // CHECK-SAME: '__ocl_sampler_t':'sampler_t' <LValueToRValue> // CHECK-NEXT: DeclRefExpr // CHECK-SAME: lvalue ParmVar // CHECK-SAME: 'Param' '__ocl_sampler_t':'sampler_t' Member2(4), // CHECK: CXXCtorInitializer Field // CHECK-SAME: 'Member2' '__ocl_sampler_t':'sampler_t' // CHECK-NEXT: ImplicitCastExpr // CHECK-SAME: 'sampler_t' <IntToOCLSampler> // CHECK-NEXT: IntegerLiteral // CHECK-SAME: 'int' 4 Member3(), // CHECK: CXXCtorInitializer Field // CHECK-SAME: 'Member3' '__ocl_sampler_t':'sampler_t' // CHECK-NEXT: ImplicitValueInitExpr // CHECK-SAME: '__ocl_sampler_t':'sampler_t' Member4(Global) // CHECK: CXXCtorInitializer Field // CHECK-SAME: 'Member4' '__ocl_sampler_t':'sampler_t' // CHECK-NEXT: ImplicitCastExpr // CHECK-SAME: '__ocl_sampler_t':'sampler_t' <LValueToRValue> // CHECK-NEXT: DeclRefExpr // CHECK-SAME: lvalue Var // CHECK-SAME: 'Global' 'const __ocl_sampler_t':'const sampler_t' {} };
[ "alexey.bader@intel.com" ]
alexey.bader@intel.com
2ac40cfc78698eb054cd30a72a899533d1aced0d
70681b44e800d9994bc7e128a537eca932f8eec9
/zillow/trinary_tree/Trinary.cpp
39e4d23134362c65e47599dd47433da2892f6957
[]
no_license
shercoder/practice_problems
3e12b3aa4238dccb5b9f0f1be8294cfb2815a54d
7d92656df49bb750f7cd601e97b336305efddbc9
refs/heads/master
2020-04-18T02:39:02.815559
2015-05-18T01:05:05
2015-05-18T01:05:05
8,229,006
0
0
null
null
null
null
UTF-8
C++
false
false
1,151
cpp
#include <iostream> #include <fstream> using namespace std; #include "NodeTree.h" int main(int argc, const char* argv[]) { if (argc != 2) { cout << "Usage: " << argv[0] << " <input_file>" << endl; return 1; } ifstream ifs(argv[1]); if (!ifs.is_open()) { cout << "Could not open " << argv[1] << " successfully." << endl; return 1; } NodeTree *tree = new NodeTree(); int next = 0; char mode; string buffer; while(!ifs.eof()) { getline(ifs, buffer); sscanf(buffer.c_str(), "%c %d", &mode, &next); switch(mode) { case 'A': tree->insert(next); break; case 'R': if (tree->remove(next)) { cout << "Successfully deleted " << next << endl; } else { cout << "Did not find " << next << endl; } break; case 'P': tree->print(); cout << endl; break; default: break; } } delete tree; ifs.close(); return 0; }
[ "singh.pardeep6605@gmail.com" ]
singh.pardeep6605@gmail.com
7b7936f6dd12f5668f5686b89dcf71b14578bcf7
4b36f779b3aba48287616bcef32d781aa6aecd1f
/doc_template/src/sources/table/xml/xmltablesourcedialog.cpp
1a05b81490aa7dc1f1232d6b379b114774e8db73
[]
no_license
dicentra13/doctpl
00333772454aafe2e5e94355fddaaf12634f1618
4f917eda1c724ecda856b73b340d1b4c82c45cbf
refs/heads/master
2020-12-24T09:38:15.663662
2018-06-19T19:01:56
2018-06-19T19:01:56
73,277,205
0
0
null
null
null
null
UTF-8
C++
false
false
5,461
cpp
#include "xmltablesourcedialog.h" #include "xmltablesource.h" #include <QListWidget> #include <QListWidgetItem> #include <QVBoxLayout> #include <QHBoxLayout> #include <QLabel> #include <QLineEdit> #include <QDialogButtonBox> #include <QMessageBox> #include <QPushButton> XMLTableSourceDialog::XMLTableSourceDialog(SourceNameValidator validator, QWidget *parent) : TableSourceDialog(validator, parent) , edited_(0) { createWidgets(); addQuery(); removeQueryButton_->setEnabled(false); } XMLTableSourceDialog::XMLTableSourceDialog(SourceNameValidator validator, XMLTableSource *source, QWidget *parent) : TableSourceDialog(validator, source, parent) , edited_(source) { createWidgets(); fileName_->setText(source->fileName()); QStringList queries = source->queryList(); QStringList::const_iterator i = queries.begin(); for (; i != queries.end(); i++) { QListWidgetItem *item = new QListWidgetItem(queryWidget_, QListWidgetItem::Type); item->setFlags(item->flags() | Qt::ItemIsEditable); item->setText(*i); queryWidget_->addItem(item); } removeQueryButton_->setEnabled(queries.size() > 1); } void XMLTableSourceDialog::createWidgets() { QVBoxLayout *layout = new QVBoxLayout(this); setLayout(layout); layout->addWidget(nameWidget()); QHBoxLayout *filenameLayout = new QHBoxLayout; filenameLayout->addWidget(new QLabel(tr("DLG_XML_FILE"), this)); fileName_ = new QLineEdit(this); filenameLayout->addWidget(fileName_); layout->addLayout(filenameLayout); addQueryButton_ = new QPushButton(tr("DLG_XML_TABLE_ADD_QUERY"), this); removeQueryButton_ = new QPushButton( tr("DLG_XML_TABLE_REMOVE_QUERY"), this); connect(addQueryButton_, SIGNAL(clicked()), this, SLOT(addQuery())); connect(removeQueryButton_, SIGNAL(clicked()), this, SLOT(removeQueries())); QHBoxLayout *queryLayout = new QHBoxLayout; queryLayout->addWidget(new QLabel(tr("DLG_XML_TABLE_QUERIES"), this)); queryLayout->addWidget(addQueryButton_); queryLayout->addWidget(removeQueryButton_); layout->addLayout(queryLayout); queryWidget_ = new QListWidget(this); queryWidget_->setDragDropMode(QAbstractItemView::InternalMove); connect(queryWidget_, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(editItem(QListWidgetItem*))); layout->addWidget(queryWidget_); layout->addWidget(buttons()); } std::unique_ptr<TableSource> XMLTableSourceDialog::createdSource() const { std::unique_ptr<TableSource> source; if (result() == QDialog::Accepted) { XMLTableSource *newXMLTable = new XMLTableSource(name(), fileName_->text()); QStringList queries; for (int i = 0; i < queryWidget_->count(); i++) { QListWidgetItem *item = queryWidget_->item(i); queries.push_back(item->text()); } newXMLTable->setQueryList(queries); source.reset(newXMLTable); } return source; } void XMLTableSourceDialog::accept() { if (checkNonEmptyInput() && checkData()) { if (edited_) { edited_->setName(name_->text()); edited_->setFileName(fileName_->text()); QStringList queries; for (int i = 0; i < queryWidget_->count(); i++) { QListWidgetItem *item = queryWidget_->item(i); queries.push_back(item->text()); } edited_->setQueryList(queries); } QDialog::accept(); } } Source *XMLTableSourceDialog::source() { return edited_; } bool XMLTableSourceDialog::checkNonEmptyInput() { bool res = TableSourceDialog::checkNonEmptyInput(); if (res) { if (fileName_->text().isEmpty()) { fileName_->setFocus(); QMessageBox::warning(this, tr("SOURCE_DATA_VALIDATION"), tr("DLG_XML_SOURCE_EMPTY_FILE_NAME"), QMessageBox::Ok); res = false; } else { int row = 0; while (res && row < queryWidget_->count()) { res = !queryWidget_->item(row)->text().isEmpty(); if (res) row++; } if (!res) { QString s; s.setNum(row + 1); QMessageBox::warning(this, tr("SOURCE_DATA_VALIDATION"), tr("DLG_XML_SOURCE_EMPTY_XPASS") + " " + s, QMessageBox::Ok); queryWidget_->setCurrentRow(row); queryWidget_->editItem(queryWidget_->item(row)); } } } return res; } bool XMLTableSourceDialog::checkData() { return TableSourceDialog::checkData(); } void XMLTableSourceDialog::addQuery() { QListWidgetItem *newItem = new QListWidgetItem; int row = queryWidget_->currentRow(); if (0 <= row && row < queryWidget_->count() - 1) { queryWidget_->insertItem(row + 1, newItem); } else { queryWidget_->addItem(newItem); } row++; newItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDragEnabled | Qt::ItemIsSelectable); queryWidget_->setCurrentRow(row); queryWidget_->editItem(newItem); removeQueryButton_->setEnabled(true); } void XMLTableSourceDialog::removeQueries() { } void XMLTableSourceDialog::editItem(QListWidgetItem *activatedItem) { queryWidget_->editItem(activatedItem); }
[ "anastasia.petrushkina@gmail.com" ]
anastasia.petrushkina@gmail.com
84c8e078430d28e2c68d0d5572fbabba815e37d9
c3eb514bddbb3d0b5a54498af7583cef5e5f1117
/Project/Project/input_interface.h
5f68fb05babbf7a3f1293e889b5cb104438f13ea
[]
no_license
alen6248/Our_Project
f292e70a867c63ca16ffe6b548192cf058c04708
e131377c0854ab4cb9f5207a5a18285c3db235fd
refs/heads/master
2021-01-10T14:24:15.364135
2016-01-02T05:14:43
2016-01-02T05:14:43
48,281,479
0
0
null
null
null
null
BIG5
C++
false
false
1,520
h
#pragma once //==========================設計=================================== //================================================================= /**************************問題***********************************/ //使用tile? /*****************************************************************/ #include "SDL.h" #include "SDL_image.h" #include "SDL_ttf.h" #include "SDL_mixer.h" #include <cstring> #include <vector> #include "Map.h" using namespace std; class Abstract_Interface { public: void interface(); //主要函數 Abstract_Interface(); ~Abstract_Interface(); virtual void clockTick(); virtual void draw(SDL_Surface *surface); virtual void deyPressed(SDLKey key); //?? //Check if mouse hit a specific area. bool mouseHit(const int mouseX, const int mouseY, const int x, const int y, const int w, const int h); virtual void mouseMoved(const int button, const int mouseX, const int mouseY); virtual void mousePressed(const int button, const int mouseX, const int mouseY); static const std::string intToString(const int number); //Convert Int to String. static const std::vector< std::string > getFilesInDir(const std::string dir); //Get a list of files in a directory. Abstract_Interface * state; SDL_Event event; Map * map; string mapLoaded; int myScore; unsigned int round; bool done; }; class Edit_State :public Abstract_Interface { }; class GameOver_State :public Abstract_Interface { }; class Show_Result_State :public Abstract_Interface { };
[ "alen6248@gmail.com" ]
alen6248@gmail.com
40635aebbbbda2dbb5bb549c4c53e0e71ed6b593
051c898be81003a5c90f5a1ce77a252252774973
/preliminary/C/33907693.cpp
657f441d11bad2ac0bcca7bf7400a651d4bede15
[]
no_license
mmatrosov/FKN2020
29caffa241882e672df654b4857b5674d5f96f6e
38bfa7811d4af175415f7cc4da81df44b5b4a74c
refs/heads/master
2022-12-27T19:15:05.849915
2020-10-16T07:12:27
2020-10-16T07:12:27
298,350,636
0
0
null
null
null
null
UTF-8
C++
false
false
755
cpp
#include <bits/stdc++.h> typedef long long ll; typedef long double ld; using namespace std; int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int n; cin >> n; map<int, bool> used; vector<int> a; for (int i = 0; i < n; ++i) { int b; cin >> b; if (!used[b]) { used[b] = 1; a.push_back(b); } } sort(a.begin(), a.end()); int m; cin >> m; for (int i = 0; i < m; ++i) { int p; cin >> p; int j = lower_bound(a.begin(), a.end(), p) - a.begin(); if (j == a.size()) { cout << j << "\n"; continue; } if (a[j] >= p) --j; cout << j + 1 << "\n"; } return 0; }
[ "mikhail.matrosov@gmail.com" ]
mikhail.matrosov@gmail.com
639b578600be71eb65cb48950e9816314f2eb7cc
346b34e4359c4230373a74a5cb785483d4885784
/examples/example_parse_response_header.cpp
b7e026ea6384805fb0a1aa36d7660a971e81434c
[ "MIT" ]
permissive
cmejj/cxxurl
ef851f15beac8844ad49e9436bd7b8a55f256299
516218a740912dc649d3fda297e920f2aad45846
refs/heads/master
2021-09-04T14:21:12.416761
2018-01-19T13:04:21
2018-01-19T13:04:21
118,410,579
0
0
null
2018-01-22T05:27:35
2018-01-22T05:27:35
null
UTF-8
C++
false
false
1,721
cpp
/** * @author : xiaozhuai * @date : 17/1/4 */ #include <iostream> #include <cxxurl/cxxurl_all.h> #include <cxxurl/HeaderParserStream.h> using namespace std; using namespace CXXUrl; void example1(); void example2(); int main(int argc, char** argv){ // these two sample do the same thing example1(); example2(); } void example1(){ HeaderParserStream headerParserStream; Request request = RequestBuilder() .url("http://localhost:3000/get") .followLocation(true) .headerOutput(&headerParserStream) .build(); CURLcode res = request.get(); headerParserStream.parse(); ResponseHeader header = headerParserStream.header; cout << "------------ Code ------------" << endl << res << endl << "---------- HTTP Code ---------" << endl << header.code << endl << "------------ Host ------------" << endl << header["Host"][0] << endl << "-------- Header Parsed -------" << endl << header.dump() << endl << flush; } void example2(){ stringstream ss; ResponseHeader header; Request request = RequestBuilder() .url("http://localhost:3000/get") .followLocation(true) .headerOutput(&ss) .build(); CURLcode res = request.get(); ss >> header; cout << "------------ Code ------------" << endl << res << endl << "---------- HTTP Code ---------" << endl << header.code << endl << "------------ Host ------------" << endl << header["Host"][0] << endl << "-------- Header Parsed -------" << endl << header.dump() << endl << flush; }
[ "798047000@qq.com" ]
798047000@qq.com
503b56e0784de693b5becb4651021e5388510095
536656cd89e4fa3a92b5dcab28657d60d1d244bd
/content/browser/accessibility/browser_accessibility_state_impl.cc
a248bc92a95ce8f33a7ffae00f463443453ed4f5
[ "BSD-3-Clause" ]
permissive
ECS-251-W2020/chromium
79caebf50443f297557d9510620bf8d44a68399a
ac814e85cb870a6b569e184c7a60a70ff3cb19f9
refs/heads/master
2022-08-19T17:42:46.887573
2020-03-18T06:08:44
2020-03-18T06:08:44
248,141,336
7
8
BSD-3-Clause
2022-07-06T20:32:48
2020-03-18T04:52:18
null
UTF-8
C++
false
false
9,576
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/accessibility/browser_accessibility_state_impl.h" #include <stddef.h> #include "base/bind.h" #include "base/command_line.h" #include "base/debug/crash_logging.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "base/task/post_task.h" #include "build/build_config.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/content_switches.h" #include "ui/accessibility/platform/ax_platform_node.h" #include "ui/gfx/color_utils.h" namespace content { // IMPORTANT! // These values are written to logs. Do not renumber or delete // existing items; add new entries to the end of the list. enum ModeFlagHistogramValue { UMA_AX_MODE_NATIVE_APIS = 0, UMA_AX_MODE_WEB_CONTENTS = 1, UMA_AX_MODE_INLINE_TEXT_BOXES = 2, UMA_AX_MODE_SCREEN_READER = 3, UMA_AX_MODE_HTML = 4, // This must always be the last enum. It's okay for its value to // increase, but none of the other enum values may change. UMA_AX_MODE_MAX }; // Record a histograms for an accessibility mode when it's enabled. void RecordNewAccessibilityModeFlags(ModeFlagHistogramValue mode_flag) { UMA_HISTOGRAM_ENUMERATION("Accessibility.ModeFlag", mode_flag, UMA_AX_MODE_MAX); } // Update the accessibility histogram 45 seconds after initialization. static const int ACCESSIBILITY_HISTOGRAM_DELAY_SECS = 45; // static BrowserAccessibilityState* BrowserAccessibilityState::GetInstance() { return BrowserAccessibilityStateImpl::GetInstance(); } // static BrowserAccessibilityStateImpl* BrowserAccessibilityStateImpl::GetInstance() { return base::Singleton< BrowserAccessibilityStateImpl, base::LeakySingletonTraits<BrowserAccessibilityStateImpl>>::get(); } BrowserAccessibilityStateImpl::BrowserAccessibilityStateImpl() : BrowserAccessibilityState(), disable_hot_tracking_(false) { ResetAccessibilityModeValue(); // We need to AddRef() the leaky singleton so that Bind doesn't // delete it prematurely. AddRef(); // Hook ourselves up to observe ax mode changes. ui::AXPlatformNode::AddAXModeObserver(this); // Let each platform do its own initialization. PlatformInitialize(); // Schedule calls to update histograms after a delay. // // The delay is necessary because assistive technology sometimes isn't // detected until after the user interacts in some way, so a reasonable delay // gives us better numbers. // Some things can be done on another thread safely. base::PostDelayedTask( FROM_HERE, {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce( &BrowserAccessibilityStateImpl::UpdateHistogramsOnOtherThread, this), base::TimeDelta::FromSeconds(ACCESSIBILITY_HISTOGRAM_DELAY_SECS)); // Other things must be done on the UI thread (e.g. to access PrefService). base::PostDelayedTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&BrowserAccessibilityStateImpl::UpdateHistogramsOnUIThread, this), base::TimeDelta::FromSeconds(ACCESSIBILITY_HISTOGRAM_DELAY_SECS)); } BrowserAccessibilityStateImpl::~BrowserAccessibilityStateImpl() { // Remove ourselves from the AXMode global observer list. ui::AXPlatformNode::RemoveAXModeObserver(this); } void BrowserAccessibilityStateImpl::OnScreenReaderDetected() { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableRendererAccessibility)) { return; } EnableAccessibility(); } void BrowserAccessibilityStateImpl::EnableAccessibility() { AddAccessibilityModeFlags(ui::kAXModeComplete); } void BrowserAccessibilityStateImpl::DisableAccessibility() { ResetAccessibilityMode(); } bool BrowserAccessibilityStateImpl::IsRendererAccessibilityEnabled() { return !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableRendererAccessibility); } void BrowserAccessibilityStateImpl::ResetAccessibilityModeValue() { accessibility_mode_ = ui::AXMode(); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kForceRendererAccessibility)) { accessibility_mode_ = ui::kAXModeComplete; } } void BrowserAccessibilityStateImpl::ResetAccessibilityMode() { ResetAccessibilityModeValue(); std::vector<WebContentsImpl*> web_contents_vector = WebContentsImpl::GetAllWebContents(); for (size_t i = 0; i < web_contents_vector.size(); ++i) web_contents_vector[i]->SetAccessibilityMode(accessibility_mode_); } bool BrowserAccessibilityStateImpl::IsAccessibleBrowser() { return accessibility_mode_ == ui::kAXModeComplete; } void BrowserAccessibilityStateImpl::AddUIThreadHistogramCallback( base::OnceClosure callback) { ui_thread_histogram_callbacks_.push_back(std::move(callback)); } void BrowserAccessibilityStateImpl::AddOtherThreadHistogramCallback( base::OnceClosure callback) { other_thread_histogram_callbacks_.push_back(std::move(callback)); } void BrowserAccessibilityStateImpl::UpdateHistogramsForTesting() { UpdateHistogramsOnUIThread(); UpdateHistogramsOnOtherThread(); } bool BrowserAccessibilityStateImpl::IsCaretBrowsingEnabled() const { // TODO(crbug.com/1018947): Refine this check once UX provided to toggle caret // browsing mode. return base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableCaretBrowsing); } void BrowserAccessibilityStateImpl::UpdateHistogramsOnUIThread() { UpdatePlatformSpecificHistogramsOnUIThread(); for (auto& callback : ui_thread_histogram_callbacks_) std::move(callback).Run(); ui_thread_histogram_callbacks_.clear(); UMA_HISTOGRAM_BOOLEAN("Accessibility.InvertedColors", color_utils::IsInvertedColorScheme()); UMA_HISTOGRAM_BOOLEAN("Accessibility.ManuallyEnabled", base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kForceRendererAccessibility)); } void BrowserAccessibilityStateImpl::UpdateHistogramsOnOtherThread() { UpdatePlatformSpecificHistogramsOnOtherThread(); for (auto& callback : other_thread_histogram_callbacks_) std::move(callback).Run(); other_thread_histogram_callbacks_.clear(); } void BrowserAccessibilityStateImpl::OnAXModeAdded(ui::AXMode mode) { AddAccessibilityModeFlags(mode); } ui::AXMode BrowserAccessibilityStateImpl::GetAccessibilityMode() { return accessibility_mode_; } #if !defined(OS_ANDROID) && !defined(OS_WIN) && !defined(OS_MACOSX) void BrowserAccessibilityStateImpl::PlatformInitialize() {} void BrowserAccessibilityStateImpl:: UpdatePlatformSpecificHistogramsOnUIThread() {} void BrowserAccessibilityStateImpl:: UpdatePlatformSpecificHistogramsOnOtherThread() {} void BrowserAccessibilityStateImpl::UpdateUniqueUserHistograms() {} #endif void BrowserAccessibilityStateImpl::AddAccessibilityModeFlags(ui::AXMode mode) { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableRendererAccessibility)) { return; } ui::AXMode previous_mode = accessibility_mode_; accessibility_mode_ |= mode; if (accessibility_mode_ == previous_mode) return; // Retrieve only newly added modes for the purposes of logging. int new_mode_flags = mode.mode() & (~previous_mode.mode()); if (new_mode_flags & ui::AXMode::kNativeAPIs) RecordNewAccessibilityModeFlags(UMA_AX_MODE_NATIVE_APIS); if (new_mode_flags & ui::AXMode::kWebContents) RecordNewAccessibilityModeFlags(UMA_AX_MODE_WEB_CONTENTS); if (new_mode_flags & ui::AXMode::kInlineTextBoxes) RecordNewAccessibilityModeFlags(UMA_AX_MODE_INLINE_TEXT_BOXES); if (new_mode_flags & ui::AXMode::kScreenReader) RecordNewAccessibilityModeFlags(UMA_AX_MODE_SCREEN_READER); if (new_mode_flags & ui::AXMode::kHTML) RecordNewAccessibilityModeFlags(UMA_AX_MODE_HTML); std::vector<WebContentsImpl*> web_contents_vector = WebContentsImpl::GetAllWebContents(); for (size_t i = 0; i < web_contents_vector.size(); ++i) web_contents_vector[i]->AddAccessibilityMode(accessibility_mode_); // Add a crash key with the ax_mode, to enable searching for top crashes that // occur when accessibility is turned on. This adds it for the browser // process, and elsewhere the same key is added to renderer processes. static auto* ax_mode_crash_key = base::debug::AllocateCrashKeyString( "ax_mode", base::debug::CrashKeySize::Size64); if (ax_mode_crash_key) { base::debug::SetCrashKeyString(ax_mode_crash_key, accessibility_mode_.ToString()); } } void BrowserAccessibilityStateImpl::RemoveAccessibilityModeFlags( ui::AXMode mode) { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kForceRendererAccessibility) && mode == ui::kAXModeComplete) { return; } int raw_flags = accessibility_mode_.mode() ^ (mode.mode() & accessibility_mode_.mode()); accessibility_mode_ = raw_flags; std::vector<WebContentsImpl*> web_contents_vector = WebContentsImpl::GetAllWebContents(); for (size_t i = 0; i < web_contents_vector.size(); ++i) web_contents_vector[i]->SetAccessibilityMode(accessibility_mode_); } } // namespace content
[ "pcding@ucdavis.edu" ]
pcding@ucdavis.edu
35f43a890909e8bf1b36536c0b77d3c2386cdfb2
2496a1ae2ac0d0ace6a70ce8d2ada38a63a33401
/tensorflow/dtensor/cc/dtensor_device_util.cc
c64c8e7da09ed6d80bdebbb6a4123c5711ed50cd
[ "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause" ]
permissive
plaidml/tensorflow
d78ba08f8fac6455b467e9001f17ad975d7580a2
607ae43f43426421642f26a6abaf350a20b5ffbe
refs/heads/master
2022-09-20T22:33:39.225897
2022-08-11T13:31:22
2022-08-11T13:35:05
215,591,809
1
1
Apache-2.0
2022-04-22T18:49:14
2019-10-16T16:15:50
C++
UTF-8
C++
false
false
47,132
cc
/* Copyright 2022 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/dtensor/cc/dtensor_device_util.h" #include <cstddef> #include <string> #include <utility> #include "absl/container/flat_hash_map.h" #include "absl/strings/str_cat.h" #include "tensorflow/c/eager/c_api_internal.h" #include "tensorflow/c/eager/tfe_tensorhandle_internal.h" #include "tensorflow/c/tf_status.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/core/common_runtime/graph_constructor.h" #include "tensorflow/core/common_runtime/shape_refiner.h" #include "tensorflow/core/framework/attr_value.pb.h" #include "tensorflow/core/framework/function.h" #include "tensorflow/core/framework/node_def.pb.h" #include "tensorflow/core/framework/node_def_util.h" #include "tensorflow/core/framework/tensor.pb.h" #include "tensorflow/core/framework/types.pb.h" #include "tensorflow/core/graph/graph.h" #include "tensorflow/core/lib/strings/proto_serialization.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/fingerprint.h" #include "tensorflow/core/public/version.h" #include "tensorflow/dtensor/cc/constants.h" #include "tensorflow/dtensor/cc/dstatus.h" #include "tensorflow/dtensor/cc/small_constant_optimization.h" namespace tensorflow { namespace dtensor { namespace { // Represents an input node during graph construction. // When executing a Function, `output` is used to align graph inputs // with the inputs to the function call. struct FunctionArgument { Node* node; NodeDefBuilder::NodeOut output; }; std::unique_ptr<parallel_device::ParallelTensor> BroadcastTensorHandleToParallelTensor(TFE_Context* context, TFE_TensorHandle* tensor, const MeshWithParallelDevice& mesh, TF_Status* status) { // Broadcast tensor value to local devices. const Mesh& target_mesh = mesh.mesh_config(); absl::Span<const std::string> local_devices = target_mesh.local_devices(); const int num_local_devices = local_devices.size(); std::vector<parallel_device::TensorHandlePtr> components; components.reserve(num_local_devices); for (int i = 0; i < num_local_devices; ++i) { // Create tensor copies to each local devices specifie by `target_mesh`. components.emplace_back(TFE_TensorHandleCopyToDevice( tensor, context, local_devices[i].c_str(), status)); if (TF_GetCode(status) != TF_OK) { TF_SetStatus( status, TF_INTERNAL, absl::StrCat( "Unable to copy tensor value for broadcast. Original message: ", TF_Message(status)) .c_str()); return nullptr; } } std::unique_ptr<parallel_device::ParallelTensor> parallel_tensor = parallel_device::ParallelTensor::FromTensorHandles( mesh.parallel_device(), std::move(components), status); if (TF_GetCode(status) != TF_OK) return nullptr; return parallel_tensor; } // Broadcast a single non-parallel resource tensor onto `mesh` with a fully // replicated sharding spec. Does not take ownership of `tensor`. std::unique_ptr<TensorWithLayout> BroadcastResourceTensor( TFE_Context* context, TFE_TensorHandle* tensor, const MeshWithParallelDevice& mesh, const std::string& dtensor_device_name, TF_Status* status) { // Only broadcast resource tensors that point to scalars since they are // always replicated. We also still want to catch honest user errors so // error out on non-scalars. // Resolve the Tensor as resource handle and get the shape and dtype // of the tensor it points to. std::unique_ptr<TF_Tensor, decltype(&TF_DeleteTensor)> tf_tensor( TFE_TensorHandleResolve(tensor, status), TF_DeleteTensor); Tensor t; Status convert_status = TF_TensorToTensor(tf_tensor.get(), &t); if (!convert_status.ok() || t.dtype() != DataType::DT_RESOURCE) { TF_SetStatus(status, TF_INTERNAL, convert_status.error_message().c_str()); return nullptr; } // Replicate this resource handle to all devices without changing the // associated device of the resource itself. ResourceHandle r = t.flat<ResourceHandle>()(0); if (r.dtypes_and_shapes().empty()) { TF_SetStatus(status, TF_INTERNAL, "Expected resource handle to have at least one underlying " "dtype and shape during broadcasting."); return nullptr; } PartialTensorShape partial_shape = r.dtypes_and_shapes().begin()->shape; int64_t num_elements = partial_shape.num_elements(); // Only broadcast scalar resource tensors onto a CPU mesh. Copying // resource tensors to non CPU device is not supported. if (num_elements != 1 || !mesh.mesh_config().is_cpu_mesh()) { std::string error_message = "Using a non-DTensor variable with DTensor is only supported for " "scalar variables copying to a CPU mesh. If you are using a scope " "based API, create " "variables inside the DTensor scope.\n"; // Get the stack_trace and Summaries from the resource tensor. absl::StrAppend( &error_message, "Offending variable summary: ", r.SummarizeValue(), "\nStack trace: ", DefinitionLocationMsg(r.definition_stack_trace())); TF_SetStatus(status, TF_INVALID_ARGUMENT, error_message.c_str()); return nullptr; } LOG(INFO) << "Broadcasting resource tensor to a dtensor resource tensor."; if (mesh.mesh_config().is_remote()) { TF_DataType dtype = TFE_TensorHandleDataType(tensor); std::vector<int64_t> shape(TensorShapeAsVector(tensor, status)); if (TF_GetCode(status) != TF_OK) return nullptr; auto layout = Layout::ReplicatedOnMesh(mesh.mesh_config(), shape.size()); auto ret = TensorWithLayout::Dummy(shape, dtype, mesh, layout); return ret; } std::unique_ptr<parallel_device::ParallelTensor> parallel_tensor = BroadcastTensorHandleToParallelTensor(context, tensor, mesh, status); if (TF_GetCode(status) != TF_OK) return nullptr; StatusOr<std::unique_ptr<TensorWithLayout>> result = TensorWithLayout::Wrap( std::move(parallel_tensor), mesh, Layout::ReplicatedOnMesh(mesh.mesh_config(), partial_shape.dims())); if (!result.ok()) { TF_SetStatus( status, TF_INTERNAL, absl::StrCat("Error creating a TensorWithLayout from a resource tensor " "during broadcasting with original error message:", result.status().error_message()) .c_str()); return nullptr; } // Set the shape/type of the tensor that the resource points to // so that the graph has correct shape/type information that we can use. (*result)->UpdateShapeAndDType(partial_shape.AsProto(), r.dtypes_and_shapes().begin()->dtype, status); if (TF_GetCode(status) != TF_OK) { TF_SetStatus(status, TF_INTERNAL, "Error updating shape and dtype for resource tensor during " "broadcasting."); return nullptr; } return std::move(*result); } bool LayoutsAreCompatible(absl::optional<Layout> first_layout, absl::optional<Layout> second_layout) { if (!first_layout.has_value() && !second_layout.has_value()) { return true; } if (!first_layout.has_value() || !second_layout.has_value()) { return false; } return first_layout.value() == second_layout.value(); } // Parse a pair of attribute of (indices, layouts) into a map. Status ParseAttrMap(const Node& node, absl::string_view indices_attr, absl::string_view layout_attr, std::map<int, Layout>* indices_layout_map) { std::vector<std::string> layouts; if (!TryGetNodeAttr(node.attrs(), layout_attr, &layouts)) { return OkStatus(); } const TensorProto* indices; if (!TryGetNodeAttr(node.attrs(), indices_attr, &indices)) { return errors::Internal( "Arg indices must be set when setting inferred resource layouts."); } if (indices->int_val_size() != layouts.size()) { return errors::Internal( "Arg indices for inferred resource argument must match the " "size of inferred resource layout."); } for (int i = 0; i < indices->int_val_size(); ++i) { const auto arg_index = indices->int_val(i); const auto& arg_layout = layouts[i]; indices_layout_map->emplace( arg_index, tensorflow::dtensor::Layout::FromString(arg_layout).ValueOrDie()); } return OkStatus(); } Status ParseResourceArgumentLayouts( const Node& node, std::map<int, Layout>* inferred_resource_input_layouts) { return ParseAttrMap(node, kNewResourceLayoutIndices, kNewResourceArgLayouts, inferred_resource_input_layouts); } Status ParseShapeInputLayouts(const Node& node, std::map<int, Layout>* shape_output_metadata) { return ParseAttrMap(node, kShapeOpInputLayoutIndices, kShapeOpInputLayout, shape_output_metadata); } // Gets the layout attached to a specific node at a given index, ignoring any // Identity ops. StatusOr<Layout> GetLayoutThroughIdentityOps(Node* op, int output_index) { while (op->op_def().name() == "Identity" || op->op_def().name() == "IdentityN") { const Edge* edge; TF_RETURN_IF_ERROR(op->input_edge(output_index, &edge)); op = edge->src(); output_index = edge->src_output(); } const auto serialized_layouts = op->attrs().Find(kLayoutAttr); if (!serialized_layouts) { return errors::InvalidArgument( op->op_def().name(), " doesn't contain attribute : ", kLayoutAttr); } // We assume that there is one layout for each output. if (serialized_layouts->list().s_size() != op->num_outputs()) { return errors::InvalidArgument( "Number of outputs to ", op->op_def().name(), " does not match number of layouts attached"); } return Layout::FromString(serialized_layouts->list().s(output_index)); } } // namespace tensorflow::Fprint128 TensorWithLayout::CacheKey() const { tensorflow::Fprint128 f = tensorflow::Fingerprint128(layout_.ToString()); // Use exact shape to compute the key. for (const int64_t dim : local_shape()) { f = FingerprintCat128(f, dim); } if (const_value_.has_value()) { std::string serialized; SerializeToStringDeterministic(const_value_.value(), &serialized); f = FingerprintCat128(f, tensorflow::Fingerprint128(serialized)); } return f; } std::unique_ptr<TensorWithLayout> TensorWithLayout::Broadcast( TFE_Context* context, TFE_TensorHandle* tensor, const MeshWithParallelDevice& mesh, const std::string& dtensor_device_name, TF_Status* status) { const char* input_device = TFE_TensorHandleDeviceName(tensor, status); if (TF_GetCode(status) != TF_OK) return nullptr; if (dtensor_device_name == input_device) { TF_SetStatus(status, TF_INVALID_ARGUMENT, "Input to Broadcast must be eager tensor."); return nullptr; } // Handle resource tensor broadcasting to the mesh. if (TFE_TensorHandleDataType(tensor) == TF_RESOURCE) { return BroadcastResourceTensor(context, tensor, mesh, dtensor_device_name, status); } if (mesh.mesh_config().is_remote()) { TF_DataType dtype = TFE_TensorHandleDataType(tensor); std::vector<int64_t> shape(TensorShapeAsVector(tensor, status)); if (TF_GetCode(status) != TF_OK) return nullptr; auto layout = Layout::ReplicatedOnMesh(mesh.mesh_config(), shape.size()); auto ret = TensorWithLayout::Dummy(shape, dtype, mesh, layout); absl::optional<NodeDef> const_value = ExtractSmallTensorValue(context, tensor, layout, status); if (TF_GetCode(status) != TF_OK) return nullptr; if (const_value) { ret->set_const_value(const_value.value()); } return ret; } std::unique_ptr<parallel_device::ParallelTensor> parallel_tensor = BroadcastTensorHandleToParallelTensor(context, tensor, mesh, status); if (TF_GetCode(status) != TF_OK) return nullptr; const std::vector<int64_t>* shape; Status s = parallel_tensor->Shape(&shape); if (!s.ok()) { TF_SetStatus(status, static_cast<TF_Code>(s.code()), s.error_message().c_str()); return nullptr; } size_t num_dims = shape->size(); const Layout layout = Layout::ReplicatedOnMesh(mesh.mesh_config(), num_dims); absl::optional<NodeDef> const_value = ExtractSmallTensorValue(context, tensor, layout, status); if (TF_GetCode(status) != TF_OK) return nullptr; std::unique_ptr<TensorWithLayout> result(new TensorWithLayout( std::move(parallel_tensor), mesh, std::move(layout), *shape, /*dtype=*/absl::nullopt, std::move(const_value))); return result; } StatusOr<std::unique_ptr<TensorWithLayout>> TensorWithLayout::Wrap( std::unique_ptr<parallel_device::ParallelTensor> tensor, const MeshWithParallelDevice& mesh, const Layout& layout) { const std::vector<int64_t>* shape; TF_RETURN_IF_ERROR(tensor->Shape(&shape)); if (tensor->dtype() != TF_RESOURCE) { return std::unique_ptr<TensorWithLayout>( new TensorWithLayout(std::move(tensor), mesh, layout, *shape)); } else { return std::unique_ptr<TensorWithLayout>( new ResourceHandleWithLayout(std::move(tensor), mesh, layout, *shape)); } } std::unique_ptr<TensorWithLayout> TensorWithLayout::Dummy( const std::vector<int64_t>& local_shape, const TF_DataType dtype, const MeshWithParallelDevice& mesh, const Layout& layout) { if (dtype != TF_RESOURCE) { return std::unique_ptr<TensorWithLayout>(new TensorWithLayout( /*tensor=*/nullptr, mesh, layout, local_shape, dtype)); } else { return std::unique_ptr<TensorWithLayout>(new ResourceHandleWithLayout( /*tensor=*/nullptr, mesh, layout, local_shape)); } } std::string TensorWithLayout::SummarizeValue() const { std::string value_summary; Status status; if (layout().IsFullyReplicated()) { status = tensorflow::unwrap(tensor()->tensor(0))->SummarizeValue(value_summary); } else { // Note that this just prints the local values for sharded tensors. We could // instead run a collective here to relayout to replicated. status = tensor()->SummarizeValue(value_summary); } if (!status.ok()) { value_summary = "<error computing value>"; } return absl::StrCat(value_summary, ", layout=\"", layout().ToString(), "\""); } std::string TensorWithLayout::DebugString() const { auto dtype = static_cast<DataType>(tensor()->dtype()); const auto& shape_vector = global_shape(); return absl::StrCat("DTensor(", SummarizeValue(), ", shape=", ShapeToDebugString(shape_vector), ", type=", DataTypeString(dtype), ")"); } void ResourceHandleWithLayout::EncodeAttributes( tensorflow::NodeDefBuilder& builder) const { // If set, attach shape and dtype to the given node def. if (dereferenced_shape().has_value()) { builder.Attr("_handle_shapes", {*dereferenced_shape()}); } if (dereferenced_dtype().has_value()) { builder.Attr("_handle_dtypes", {*dereferenced_dtype()}); } } tensorflow::Fprint128 ResourceHandleWithLayout::CacheKey() const { tensorflow::Fprint128 f = tensorflow::Fingerprint128(layout().ToString()); if (dereferenced_shape().has_value()) { std::string serialized; SerializeToStringDeterministic(dereferenced_shape().value(), &serialized); f = FingerprintCat128(f, tensorflow::Fingerprint128(serialized)); } if (dereferenced_dtype().has_value()) { f = FingerprintCat128(f, dereferenced_dtype().value()); } return f; } void ResourceHandleWithLayout::UpdateLayout(const Layout& new_layout, TF_Status* status) { // Only set the value for deferenced layout if the incoming layout is not // empty. This is still hacky as we use empty layout as placeholder for // eagerly placed VarHandleOp. if (!dereferenced_layout_.has_value() && new_layout.IsEmpty()) return; if (dereferenced_layout_.has_value() && !LayoutsAreCompatible(dereferenced_layout_, new_layout)) { // TODO(xiejw, allenl): Consider allowing variables to switch layouts. RETURN_STATUS(status, TF_INVALID_ARGUMENT, "Attempted to overwrite an existing Layout."); } dereferenced_layout_.emplace(new_layout); } void ResourceHandleWithLayout::UpdateAttrs(const EmbeddingResourceAttrs& attrs, TF_Status* status) { if (attrs_.has_value()) { RETURN_STATUS(status, TF_INVALID_ARGUMENT, "Attepted to overwrite an existing embedding resource " "attribute."); } attrs_.emplace(attrs); } StatusOr<std::unique_ptr<TensorWithLayout>> SparseTensorWithLayout::Wrap( std::unique_ptr<parallel_device::ParallelTensor> indices_tensor, std::unique_ptr<parallel_device::ParallelTensor> values_tensor, std::unique_ptr<parallel_device::ParallelTensor> shapes_tensor, const MeshWithParallelDevice& mesh, const Layout& layout, std::vector<int64_t> local_shape) { return std::unique_ptr<TensorWithLayout>(new SparseTensorWithLayout( std::move(indices_tensor), std::move(values_tensor), std::move(shapes_tensor), mesh, layout, local_shape)); } std::string SparseTensorWithLayout::SummarizeValue() const { std::string indices_summary; std::string values_summary; std::string dense_shapes_summary; Status indices_status; Status values_status; Status dense_shapes_status; if (layout().IsFullyReplicated()) { indices_status = tensorflow::unwrap(indices_->tensor(0)) ->SummarizeValue(indices_summary); values_status = tensorflow::unwrap(values_->tensor(0))->SummarizeValue(values_summary); dense_shapes_status = tensorflow::unwrap(dense_shapes_->tensor(0)) ->SummarizeValue(dense_shapes_summary); } else { indices_status = indices_->SummarizeValue(indices_summary); values_status = values_->SummarizeValue(values_summary); dense_shapes_status = dense_shapes_->SummarizeValue(dense_shapes_summary); } if (!indices_status.ok()) values_summary = "<error computing summary for indices>"; if (!values_status.ok()) indices_summary = "<error computing summary for values>"; if (!dense_shapes_status.ok()) indices_summary = "<error computing summary for dense_shapes>"; return absl::StrCat("indices: ", indices_summary, ", ", "values: ", values_summary, ", ", "dense_shapes: ", dense_shapes_summary, ", layout=\"", layout().ToString(), "\""); } std::string SparseTensorWithLayout::DebugString() const { auto dtype = static_cast<DataType>(values_->dtype()); const auto& shape_vector = global_shape(); return absl::StrCat("DTensor(", SummarizeValue(), ", shape=", ShapeToDebugString(shape_vector), ", type=", DataTypeString(dtype), ")"); } TF_DataType SparseTensorWithLayout::dtype() const { if (dtype_.has_value()) { return dtype_.value(); } else { return values_->dtype(); } } TFE_TensorHandle* SparseTensorWithLayout::get_tensor(size_t index) const { int num_sparse_tensors = num_tensors() / 3; if (index < num_sparse_tensors) { return indices()->tensor(index); } else if (index < 2 * num_sparse_tensors) { return values()->tensor(index % num_sparse_tensors); } else { return dense_shapes()->tensor(index % num_sparse_tensors); } } absl::flat_hash_map<int, NodeDef> GetConstantFoldableTensors( const std::vector<TensorWithLayout*>& inputs) { absl::flat_hash_map<int, NodeDef> small_tensors; for (auto index = 0; index < inputs.size(); ++index) { if (inputs[index]->const_value().has_value()) { small_tensors.insert({index, inputs[index]->const_value().value()}); } } return small_tensors; } // Thread unsafe method. go/thread-unsafe // Cache key computation should consider all features of an op that affects // the SPMD lowering. The cache keys of two ops must be different if the // translated functions are different. // - op name and attr // - input shapes and layouts // - default layout of outputs. // - values of constant foldable inputs. tensorflow::Fprint128 FunctionManager::CacheKeyForGraph( const DTensorOperation& doperation, const NameAttrList& attributes, const std::vector<TensorWithLayout*>& inputs, const std::vector<const Layout*>& output_layouts) { tensorflow::Fprint128 cache_key = tensorflow::Fingerprint128(doperation.name); std::string serialized; SerializeToStringDeterministic(attributes, &serialized); cache_key = FingerprintCat128(cache_key, tensorflow::Fingerprint128(serialized)); // Higher level cache based on operation name and input shapes. for (auto i = 0; i < inputs.size(); ++i) { if (!IsConstantFoldable(doperation, i)) { inputs[i]->reset_const_value(); } cache_key = FingerprintCat128(cache_key, inputs[i]->CacheKey()); } for (int output_index = 0; output_index < output_layouts.size(); ++output_index) { if (output_layouts[output_index]) { cache_key = FingerprintCat128(cache_key, output_index); cache_key = FingerprintCat128( cache_key, tensorflow::Fingerprint128(output_layouts[output_index]->ToString())); } } return cache_key; } // Thread-unsafe method go/thread-unsafe. std::pair<tensorflow::Fprint128, const ExecutionFunctions*> FunctionManager::GetCachedFunction( const DTensorOperation& doperation, const NameAttrList& attributes, const std::vector<TensorWithLayout*>& inputs, const std::vector<const Layout*>& output_layouts) { tensorflow::Fprint128 cache_key = CacheKeyForGraph(doperation, attributes, inputs, output_layouts); auto iter = function_cache_.find(cache_key); // Early return if we have a cache hit. if (iter != function_cache_.end()) { return std::pair<Fprint128, ExecutionFunctions*>(cache_key, &iter->second); } // For eager ops we early return the cache miss and do not make further // optimizations. if (!doperation.is_func()) { return std::pair<Fprint128, std::nullptr_t>(cache_key, nullptr); } const tensorflow::Fprint128 doperation_hash = CacheKeyForDTensorOperation(doperation); // Save the constant folded inputs to this doperation if we have not seen this // before. This is needed so that in the next call to this operation, we // can compare these inputs to confirm which one is indeed a constant. auto doperation_iter = dtensor_op_and_small_inputs_.find(doperation_hash); if (doperation_iter == dtensor_op_and_small_inputs_.end()) { dtensor_op_and_small_inputs_.insert( {doperation_hash, GetConstantFoldableTensors(inputs)}); return std::pair<Fprint128, std::nullptr_t>(cache_key, nullptr); } // If we are here, then we have ran this function before but constant folded // some input(s) when it was not a constant input i.e. one of the small value // to this function input changed. So mark those changed values as // non-constant. absl::flat_hash_map<int, NodeDef>& previous_small_inputs = doperation_iter->second; std::vector<int> non_constant_indices; for (auto const& [index, previous_small_input] : previous_small_inputs) { if (inputs[index]->const_value().has_value()) { if (NodeDefsHaveDifferentTensorProto( previous_small_input, inputs[index]->const_value().value())) { inputs[index]->reset_const_value(); non_constant_indices.push_back(index); } } } for (int non_constant_index : non_constant_indices) { previous_small_inputs.erase(non_constant_index); } // Generate a new cache key since we updated small const inputs which change // the cache key. cache_key = CacheKeyForGraph(doperation, attributes, inputs, output_layouts); return std::pair<Fprint128, std::nullptr_t>(cache_key, nullptr); } const ExecutionFunctions* FunctionManager::AddCachedFunction( const DTensorOperation& op, tensorflow::Fprint128 cache_key, ExecutionFunctions function) { return &function_cache_.insert({cache_key, std::move(function)}) .first->second; } bool FunctionManager::IsConstantFoldable(const DTensorOperation& doperation, const int input_index) const { // For eager ops, assume the inputs are constant foldable. if (!doperation.is_func()) return true; const tensorflow::Fprint128 doperation_hash = CacheKeyForDTensorOperation(doperation); // If we didn't see this doperation before then optimisticly assume this is // foldable. The input at `input_index` is foldable only if it is one of the // indices we have saved as the small inputs. auto doperation_iter = dtensor_op_and_small_inputs_.find(doperation_hash); return doperation_iter == dtensor_op_and_small_inputs_.end() || doperation_iter->second.contains(input_index); } const tensorflow::Fprint128 FunctionManager::CacheKeyForDTensorOperation( const DTensorOperation& doperation) const { return tensorflow::Fingerprint128(doperation.name); } std::vector<int64_t> TensorShapeAsVector(TFE_TensorHandle* tensor, TF_Status* status) { std::vector<int64_t> shape(TFE_TensorHandleNumDims(tensor, status)); if (TF_GetCode(status) != TF_OK) return {}; for (int i = 0; i < shape.size(); ++i) { shape[i] = TFE_TensorHandleDim(tensor, i, status); if (TF_GetCode(status) != TF_OK) return {}; } return shape; } Status PrepareGraphForMlir( const FunctionManager& function_manager, const std::vector<TensorWithLayout*>& inputs, const DTensorOperation& doperation, const tensorflow::FunctionLibraryDefinition& flib_def, const NameAttrList& attributes, const absl::optional<Layout>& default_layout, tensorflow::Graph* graph, std::vector<PartialTensorShape>* global_output_shapes, std::vector<const Layout*>* output_layouts) { // We run shape inference on the graph to find output shapes, which may // determine default layouts. ShapeRefiner shape_refiner(TF_GRAPH_DEF_VERSION, &flib_def); shape_refiner.set_function_library_for_shape_inference(&flib_def); tensorflow::Status status; { // We include an _Arg node for the device ID, but this isn't used by the // initial function. It will be provided a value, though, so it's available // for use in rewrites. tensorflow::NodeDefBuilder builder("device_id", "_Arg"); tensorflow::PartialTensorShape partial_shape; TF_RETURN_IF_ERROR(tensorflow::PartialTensorShape::MakePartialShape( static_cast<int*>(nullptr), 0, &partial_shape)); tensorflow::NodeDef arg_node_def; TF_RETURN_IF_ERROR(builder.Attr("shape", partial_shape) .Attr("T", tensorflow::DT_INT32) .Attr("index", 0) .Finalize(&arg_node_def, /*consume=*/true)); tensorflow::Node* arg_node = graph->AddNode(arg_node_def, &status); TF_RETURN_IF_ERROR(status); graph->AddControlEdge(graph->source_node(), arg_node); TF_RETURN_IF_ERROR(shape_refiner.AddNode(arg_node)); } std::vector<FunctionArgument> graph_op_inputs; graph_op_inputs.reserve(inputs.size()); for (int i = 0; i < inputs.size(); ++i) { const TensorWithLayout* input = inputs[i]; // TODO(allenl): This will block until async execution is complete, which // will be slow. We should find a non-blocking way of fetching the shape, // at least pre-cache. // The shape passed into MLIR transformation represents the global shape of // the tensor. Ideally, the local shape on each parallel device should not // be consulted at all and we should use the shape on our input tensor // directly. const auto& shape = input->global_shape(); std::vector<tensorflow::int64> cast_shape(shape.begin(), shape.end()); tensorflow::PartialTensorShape partial_shape; // For resource tensors, `shape` attribute should not be specified as shape // of resource tensors is specified by resource shape subtype -- not the // shape attribute. auto* resource = dynamic_cast<const ResourceHandleWithLayout*>(input); if (!resource) { TF_RETURN_IF_ERROR(tensorflow::PartialTensorShape::MakePartialShape( cast_shape.data(), cast_shape.size(), &partial_shape)); } tensorflow::NodeDef arg_node_def; auto dtype = static_cast<tensorflow::DataType>(input->dtype()); tensorflow::NodeDefBuilder builder(absl::StrCat("op_input_", i), "_Arg"); // Delegate TensorWithLayout to encode attributes if applicable. input->EncodeAttributes(builder); // Here we set each arg node's `index` attribute to the position of // the dtensor inputs. This is important for later use when we create // a mapping from the graph argument node to the corresponding argument // index of the list of dtensor inputs. Thus, even if the argument node // orderings change within the graph, we can always correctly // find the dtensor input corresponding to that arg node. // // This assumes that the dtensor inputs stay unchanged in ordering, // and if there is an ordering change of dtensor inputs, then special // care must be taken. TF_RETURN_IF_ERROR( builder.Attr("shape", partial_shape) .Attr("T", dtype) .Attr("index", i + 1) // Indices are offset by 1 for device_id .Attr(kLayoutAttr, input->layout().ToString()) .Attr(kMeshAttr, input->mesh().mesh_config().ToString()) .Finalize(&arg_node_def, /*consume=*/true)); Node* arg_node = graph->AddNode(arg_node_def, &status); TF_RETURN_IF_ERROR(status); TF_RETURN_IF_ERROR(shape_refiner.AddNode(arg_node)); shape_inference::InferenceContext* inference_context = shape_refiner.GetContext(arg_node); shape_inference::ShapeHandle shape_handle; TF_RETURN_IF_ERROR(inference_context->MakeShapeFromPartialTensorShape( partial_shape, &shape_handle)); TF_RETURN_IF_ERROR(shape_refiner.SetShape(arg_node, 0, shape_handle)); // Small constants are converted into constant graph nodes, instead of being // passed in as input arguments. This provides more information to the SPMD // and layout propagation passes. if (!input->const_value().has_value() || !function_manager.IsConstantFoldable(doperation, i)) { graph_op_inputs.push_back(FunctionArgument{ arg_node, NodeDefBuilder::NodeOut{arg_node->name(), i, dtype}}); graph->AddControlEdge(graph->source_node(), arg_node); } else { // TODO(xiejw): Refactor the TensorWithLayout representation to avoid // special code here. NodeDef const_node = input->const_value().value(); const_node.set_name(absl::StrCat("input_", i, "_const_value")); Node* const_value_n = graph->AddNode(const_node, &status); TF_RETURN_IF_ERROR(status); TF_RETURN_IF_ERROR(shape_refiner.AddNode(const_value_n)); graph_op_inputs.push_back(FunctionArgument{ const_value_n, tensorflow::NodeDefBuilder::NodeOut{ const_value_n->name(), i, dtype}}); } } tensorflow::NodeDef op_node_def; const FunctionDef* function_def = doperation.function_def; if (function_def) { AttrValue func_attr; func_attr.mutable_func()->set_name(doperation.name); std::vector<tensorflow::NodeDefBuilder::NodeOut> func_inputs; std::vector<tensorflow::DataType> inputs_types; for (const auto& in : graph_op_inputs) { func_inputs.emplace_back(in.output); inputs_types.emplace_back(in.output.data_type); } std::vector<tensorflow::DataType> output_types; for (const auto& out : function_def->signature().output_arg()) output_types.emplace_back(out.type()); TF_RETURN_IF_ERROR( NodeDefBuilder("eager_operation", "StatefulPartitionedCall") .Attr("Tin", inputs_types) .Attr("Tout", output_types) .Attr("f", func_attr) .Input(func_inputs) .Finalize(&op_node_def, true)); } else { op_node_def.set_op(doperation.name); op_node_def.set_name("eager_operation"); } op_node_def.mutable_attr()->insert(attributes.attr().begin(), attributes.attr().end()); tensorflow::Node* op_node = graph->AddNode(op_node_def, &status); TF_RETURN_IF_ERROR(status); for (int i = 0; i < graph_op_inputs.size(); ++i) { graph->AddEdge(graph_op_inputs[i].node, 0, op_node, i); } TF_RETURN_IF_ERROR(shape_refiner.AddNode(op_node)); output_layouts->clear(); output_layouts->reserve(op_node->num_outputs()); global_output_shapes->reserve(op_node->num_outputs()); for (int output_index = 0; output_index < op_node->num_outputs(); ++output_index) { tensorflow::NodeDefBuilder builder(absl::StrCat("op_output_", output_index), "_Retval"); tensorflow::NodeDef ret_node_def; tensorflow::DataType output_type = op_node->output_type(output_index); TF_RETURN_IF_ERROR(builder.Attr("T", output_type) .Attr("index", output_index) .Input("eager_operation", output_index, output_type) .Finalize(&ret_node_def, /*consume=*/true)); tensorflow::Node* ret_node = graph->AddNode(ret_node_def, &status); TF_RETURN_IF_ERROR(status); graph->AddEdge(op_node, output_index, ret_node, 0); graph->AddControlEdge(ret_node, graph->sink_node()); shape_inference::InferenceContext* inference_context = shape_refiner.GetContext(op_node); shape_inference::ShapeHandle output_shape_handle = inference_context->output(output_index); TensorShapeProto output_shape_proto; inference_context->ShapeHandleToProto(output_shape_handle, &output_shape_proto); PartialTensorShape global_output_shape(output_shape_proto); VLOG(3) << "Inferred shape for operation '" << doperation.name << "':" << global_output_shape.DebugString(); global_output_shapes->push_back(global_output_shape); const Layout* layout = nullptr; if (default_layout.has_value() && output_index == 0) { // Record the user's requested output layout. The scope currently only // covers the first output of an op. layout = &default_layout.value(); ret_node->AddAttr(kDefaultLayoutAttr, layout->ToString()); } output_layouts->push_back(layout); } return OkStatus(); } // Returns set of functions to run to execute DTensor computation. StatusOr<ExecutionFunctions> IdentifyAllFunctionsToExecute( const tensorflow::Graph& graph, const std::vector<PartialTensorShape>& global_output_shapes) { ExecutionFunctions execution_functions; execution_functions.function_list = std::vector<TranslatedFunction>(); for (Node* node : graph.nodes()) { if (node->op_def().name() != "StatefulPartitionedCall") continue; // Extract mesh to execute the function. std::string serialized_mesh; TF_RETURN_IF_ERROR(GetNodeAttr(node->attrs(), kMeshAttr, &serialized_mesh)); Mesh mesh; TF_ASSIGN_OR_RETURN(mesh, Mesh::FromString(serialized_mesh)); TranslatedFunction function; function.function_mesh = std::move(mesh); function.node_to_execute = node; // Identify input arg information. TF_RETURN_IF_ERROR( ParseResourceArgumentLayouts(*node, &function.resource_input_layouts)); TF_RETURN_IF_ERROR( ParseShapeInputLayouts(*node, &function.shape_output_metadata)); function.input_index_map.resize(node->num_inputs()); // Identity mapping between local mesh function input index and global // input index. for (int in_index = 0; in_index < node->num_inputs(); ++in_index) { Node* input_node; TF_RETURN_IF_ERROR(node->input_node(in_index, &input_node)); if (!input_node->IsArg()) return errors::InvalidArgument( "Input node to mesh computation must be arg node."); int global_index; TF_RETURN_IF_ERROR( GetNodeAttr(input_node->attrs(), "index", &global_index)); function.input_index_map[in_index] = global_index; } // Identify output mappings and layouts for each outputs. std::map<int, const Edge*> output_edges; for (const Edge* out_edge : node->out_edges()) { if (out_edge->IsControlEdge()) continue; const Node* retval_or_identity_node = out_edge->dst(); while (retval_or_identity_node->IsIdentity()) { retval_or_identity_node = *(retval_or_identity_node->out_nodes().begin()); } TF_RET_CHECK(retval_or_identity_node->IsRetval()); int global_index; TF_RETURN_IF_ERROR(GetNodeAttr(retval_or_identity_node->attrs(), "index", &global_index)); output_edges[global_index] = out_edge; } for (auto it = output_edges.begin(); it != output_edges.end(); it++) { const int global_index = it->first; function.output_index_map.emplace_back(global_index); const Edge* retval_edge = it->second; const int output_index = retval_edge->src_output(); // Add output layout and shape information. TF_ASSIGN_OR_RETURN( const Layout output_layout, GetLayoutThroughIdentityOps(retval_edge->src(), output_index)); function.output_layouts.emplace_back(output_layout); function.local_output_shapes.emplace_back( output_layout.LocalShapeFromGlobalShape( global_output_shapes[global_index])); } execution_functions.function_list.emplace_back(std::move(function)); } if (execution_functions.function_list.empty()) { return errors::InvalidArgument( "MLIR transformed graph does not have any functions to execute for " "mesh."); } return execution_functions; } // For functions with control outputs, add identity nodes between // StatefulPartitionedCall and _Retvals, in order to preserve control output // dependencies after StatefulPartitionedCall is inlined at runtime. // Consider calling this in PrepareGraphForMlir, once the identity nodes won't // be dropped during MLIR lowering. // TODO(b/171265131): fix the underlying issue to avoid inserting identity // nodes. Status MaybeInsertIdentityNodes(const FunctionDef* function_def, Graph* graph) { if (function_def == nullptr || function_def->control_ret().empty()) { return OkStatus(); } tensorflow::Status status; for (Node* n : graph->nodes()) { if (!n->IsRetval()) { continue; } const Edge* edge; TF_RETURN_IF_ERROR(n->input_edge(0, &edge)); int ret_index; TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "index", &ret_index)); tensorflow::NodeDefBuilder identity_builder( absl::StrCat("op_output_identity_", ret_index), "Identity"); tensorflow::NodeDef ret_identity_node_def; tensorflow::DataType output_type = n->input_type(0); TF_RETURN_IF_ERROR( identity_builder.Attr("T", output_type) .Input(edge->src()->name(), edge->src_output(), output_type) .Finalize(&ret_identity_node_def, /*consume=*/true)); Node* ret_identity_node = graph->AddNode(ret_identity_node_def, &status); TF_RETURN_IF_ERROR(status); // Delete the edge between StatefulPartitionedCall and _Retval. graph->RemoveEdge(edge); // Add an edge between StatefulPartitionedCall and Identity. graph->AddEdge(edge->src(), edge->src_output(), ret_identity_node, 0); graph->AddControlEdge(edge->src(), ret_identity_node); // Add an edge between Identity and _Retval. graph->AddEdge(ret_identity_node, 0, n, 0); } return OkStatus(); } void AddDTensorFunctionAttr(FunctionDef& function_def) { // Do not xla compile function returned by DTensor MLIR graph transformation // as it already returns compiled graph. AttrValue xla_must_compile_val; xla_must_compile_val.set_b(false); function_def.mutable_attr()->insert( {"_XlaMustCompile", xla_must_compile_val}); // Explicitly place function outputs on the default function device to avoid // redundant host <-> device copies (Placer may place outputs on the host // CPU). AttrValue outputs_on_op_device; outputs_on_op_device.set_b(true); function_def.mutable_attr()->insert( {"_OutputsOnOpDevice", outputs_on_op_device}); } StatusOr<std::vector<parallel_device::ParallelTensor*>> PrepareEmbeddingInputs( const std::vector<TensorWithLayout*>& inputs) { absl::flat_hash_map<int64_t, std::vector<int64_t>> table_vars_input_index; for (int64_t i = 0; i < inputs.size(); ++i) { if (inputs[i]->tensor_type() != kResource) continue; const absl::optional<EmbeddingResourceAttrs>& resource_attrs = inputs[i]->attrs(); if (resource_attrs.has_value()) { table_vars_input_index[resource_attrs->table_id].push_back(i); } } // Check if there is no embedding resource input found. if (table_vars_input_index.empty()) { return errors::Internal("There are no TPU embedding resource input found."); } std::vector<parallel_device::ParallelTensor*> parallel_inputs; // Assure parallel inputs has numeric order as table ids. for (const auto& [table_id, table_vars_indices] : table_vars_input_index) { for (const int64_t input_index : table_vars_indices) { parallel_inputs.push_back(inputs[input_index]->tensor()); } } return parallel_inputs; } StatusOr<std::map<int64_t, std::vector<Node*>>> GetTPUEmbeddingInputNodes( TF_Status* s, const Graph& graph, const std::vector<TensorWithLayout*>& inputs) { // After the graph is lowered, the sparse tensors live at the end of the // argument list, so process the dtensor dense inputs only so that // we index correctly. std::vector<TensorWithLayout*> non_sparse_inputs; non_sparse_inputs.reserve(inputs.size()); for (TensorWithLayout* input : inputs) { if (input->tensor_type() != TensorType::kSparse) { non_sparse_inputs.push_back(input); } } std::map<int64_t, std::vector<Node*>> table_id_node_map; for (Node* node : graph.nodes()) { if (!node->IsArg()) continue; const int64_t& arg_id = node->attrs().Find("index")->i(); const AttrValue* embedding_attr = node->attrs().Find("_tpu_embedding_table_id"); if (embedding_attr == nullptr) continue; EmbeddingResourceAttrs embedding_input_attrs; // Add embedding table id. const int64_t table_id = embedding_attr->i(); embedding_input_attrs.table_id = table_id; // Add embedding slot id if there is one. const AttrValue* embedding_slot_attr = node->attrs().Find("_tpu_embedding_slot_id"); if (embedding_slot_attr != nullptr) { const int64_t slot_id = embedding_slot_attr->i(); embedding_input_attrs.slot_id = slot_id; } table_id_node_map[table_id].push_back(node); // Arg input offset due to device id. if (non_sparse_inputs[arg_id - 1]->attrs().has_value()) continue; non_sparse_inputs[arg_id - 1]->UpdateAttrs(embedding_input_attrs, s); if (!s->status.ok()) { return errors::Internal( "Failed to set embedding resource attrs. \n Got error: ", s->status.error_message()); } } return table_id_node_map; } StatusOr<std::string> ValidateResourceMeshConsistency( const std::vector<TensorWithLayout*>& inputs) { std::string mesh_str; for (TensorWithLayout* inp : inputs) { if ((inp->tensor_type() != kResource) || !inp->attrs().has_value()) continue; const std::string& input_mesh_str = inp->layout().mesh().ToString(); if (mesh_str.empty()) { mesh_str = input_mesh_str; } else if (mesh_str != input_mesh_str) { return errors::Internal(absl::StrCat( "All inputs of embedding resource must be on same mesh. but get : ", mesh_str, " != ", input_mesh_str)); } } VLOG(1) << "Resource input mesh is : " << mesh_str; return mesh_str; } Status InsertFunctionForTPUEmbeddingCheckpoint( TF_Status* status, Graph* graph, const std::vector<TensorWithLayout*>& inputs, const std::string& checkpoint_fn_name) { if (checkpoint_fn_name != kLoadEmbeddingFn && checkpoint_fn_name != kRetrieveEmbeddingFn) { return errors::InvalidArgument(absl::StrCat( "Found wrong function name: ", checkpoint_fn_name, " \n expects : ", kLoadEmbeddingFn, " or ", kRetrieveEmbeddingFn)); } StatusOr<std::map<int64_t, std::vector<Node*>>> table_id_node_map = GetTPUEmbeddingInputNodes(status, *graph, inputs); if (!table_id_node_map.ok()) { return errors::Internal(table_id_node_map.status().error_message()); } StatusOr<std::string> mesh_str = ValidateResourceMeshConsistency(inputs); const int64_t& num_tables = table_id_node_map->size(); NodeDef func_node_def; std::vector<NodeDefBuilder::NodeOut> func_inputs; std::vector<DataType> input_types, output_types; func_inputs.reserve(num_tables); input_types.reserve(num_tables); for (int i = 0; i < num_tables; ++i) { auto node_vec_ptr = table_id_node_map->find(i); if (node_vec_ptr == table_id_node_map->end()) { return errors::Internal( absl::StrCat("Embedding table id ", i, " is not found.")); } for (const Node* n : node_vec_ptr->second) { const std::string& node_name = n->name(); func_inputs.push_back({node_name, i, DT_RESOURCE}); input_types.push_back(DT_RESOURCE); } } AttrValue mesh_attr; *mesh_attr.mutable_s() = *mesh_str; NameAttrList func_attr; func_attr.set_name(checkpoint_fn_name); TF_RETURN_IF_ERROR( NodeDefBuilder(checkpoint_fn_name, "StatefulPartitionedCall") .Attr("Tin", input_types) .Attr("Tout", output_types) .Attr("f", func_attr) .Attr(kMeshAttr, mesh_attr) .Attr("config", mesh_attr) .Input(func_inputs) .Finalize(&func_node_def, true)); TF_ASSIGN_OR_RETURN(Node * func_node, graph->AddNode(func_node_def)); for (int i = 0; i < num_tables; ++i) { const std::vector<Node*>& node_vec = table_id_node_map->find(i)->second; for (int j = 0; j < node_vec.size(); ++j) { graph->AddEdge(node_vec[j], 0, func_node, j + i); } } return OkStatus(); } } // namespace dtensor } // namespace tensorflow
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
69c4c15b5bdbf77687038a7077c6d0461ccfb785
6b5bddc107b800f7fd658413cf626ed6f801ed36
/data/portal.cpp
ec8e285ccb029b0674eb2c8e45b0367275c31916
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
ashr/notes
6c5cc00c1b0a2e30e87755b6f5ee32d463f28ed5
c449d10374b0bded8177e318892fdd58bcce3524
refs/heads/master
2021-05-11T04:39:22.877171
2018-01-17T15:01:05
2018-01-17T15:01:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
359
cpp
// address: 0x4A1ABC // // portal_town_y_from_player_num maps from player number to Y-coordinate of the // town portal position in Tristram. int portal_town_y_from_player_num[4]; // address: 0x4A1ACC // // portal_town_x_from_player_num maps from player number to X-coordinate of the // town portal position in Tristram. int portal_town_x_from_player_num[4];
[ "rnd0x00@gmail.com" ]
rnd0x00@gmail.com
9fc86e67d7f4871a1f124604c96c91f21d705797
7f69e98afe43db75c3d33f7e99dbba702a37a0a7
/src/misc/cliapplication.cpp
2fef1e0674958a2b8ab82da24af4a3505fa1b4cf
[ "Apache-2.0" ]
permissive
hsorby/opencor
ce1125ba6a6cd86a811d13d4b54fb12a53a3cc7c
4ce3332fed67069bd093a6215aeaf81be81c9933
refs/heads/master
2021-01-19T07:23:07.743445
2015-11-08T13:17:29
2015-11-08T13:17:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,154
cpp
/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // CLI application //============================================================================== #include "cliapplication.h" #include "cliinterface.h" #include "cliutils.h" #include "pluginmanager.h" //============================================================================== #include <iostream> //============================================================================== #include <Qt> //============================================================================== #include <QCoreApplication> #include <QSettings> //============================================================================== namespace OpenCOR { //============================================================================== CliApplication::CliApplication() : mPluginManager(0), mLoadedCliPlugins(Plugins()) { } //============================================================================== CliApplication::~CliApplication() { // Delete some internal objects delete mPluginManager; } //============================================================================== void CliApplication::loadPlugins() { // Load all the plugins by creating our plugin manager mPluginManager = new PluginManager(false); // Keep track of our loaded CLI plugins foreach (Plugin *plugin, mPluginManager->loadedPlugins()) if (qobject_cast<CliInterface *>(plugin->instance())) mLoadedCliPlugins << plugin; } //============================================================================== QString CliApplication::pluginDescription(Plugin *pPlugin) const { // Retrieve and return the plugin's default description, stripped out of all // its HTML (should it have some) return plainString(pPlugin->info()->description()); } //============================================================================== void CliApplication::about() const { // Output some information about OpenCOR version(); std::cout << QSysInfo::prettyProductName().toStdString() << std::endl; std::cout << copyright().toStdString() << std::endl; std::cout << std::endl; std::cout << applicationDescription(false).toStdString() << std::endl; std::cout << std::endl; std::cout << applicationBuildInformation(false).toStdString() << std::endl; } //============================================================================== bool CliApplication::command(const QStringList &pArguments, int *pRes) const { // Make sure that we have at least one argument if (!pArguments.count()) return false; // Determine whether the command is to be executed by all the CLI plugins or // only a given CLI plugin static const QString CommandSeparator = "::"; QString commandName = pArguments.first(); QString commandPlugin = commandName; int commandSeparatorPosition = commandName.indexOf(CommandSeparator); if (commandSeparatorPosition != -1) { commandPlugin = commandPlugin.remove(commandSeparatorPosition, commandName.length()-commandSeparatorPosition); commandName = commandName.remove(0, commandPlugin.length()+CommandSeparator.length()); // Make sure that the plugin to which the command is to be sent exists if (!commandPlugin.isEmpty()) { bool pluginFound = false; bool pluginHasCliSupport = false; foreach (Plugin *plugin, mPluginManager->loadedPlugins()) if (!commandPlugin.compare(plugin->name())) { pluginFound = true; pluginHasCliSupport = qobject_cast<CliInterface *>(plugin->instance()); break; } if (!pluginFound) { std::cout << "The " << commandPlugin.toStdString() << " plugin could not be found." << std::endl; return true; } else if (!pluginHasCliSupport) { std::cout << "The " << commandPlugin.toStdString() << " plugin does not support the execution of commands." << std::endl; return true; } } } else { commandPlugin = QString(); } // Make sure that we have a command name if (commandName.isEmpty()) return false; // Make sure that we have at least one CLI-enabled plugin if (mLoadedCliPlugins.isEmpty()) { std::cout << "No plugins could be found to run the command." << std::endl; return true; } // Send the command to the plugin(s) foreach (Plugin *plugin, mLoadedCliPlugins) { if ( commandPlugin.isEmpty() || !commandPlugin.compare(plugin->name())) { QStringList arguments = pArguments; arguments.removeFirst(); // Note: since the first argument corresponds to the command // itself... if (qobject_cast<CliInterface *>(plugin->instance())->executeCommand(commandName, arguments)) *pRes = -1; } } return true; } //============================================================================== void CliApplication::help() const { // Output some help std::cout << "Usage: " << qAppName().toStdString() << " [-a|--about] [-c|--command [<plugin>::]<command> <options>] [-h|--help] [-p|--plugins] [-r|--reset] [-s|--status] [-v|--version] [<files>]" << std::endl; std::cout << " -a, --about Display some information about OpenCOR" << std::endl; std::cout << " -c, --command Send a command to one or all the CLI plugins" << std::endl; std::cout << " -h, --help Display this help information" << std::endl; std::cout << " -p, --plugins Display all the CLI plugins" << std::endl; std::cout << " -r, --reset Reset all your settings" << std::endl; std::cout << " -s, --status Display the status of all the plugins" << std::endl; std::cout << " -v, --version Display the version of OpenCOR" << std::endl; } //============================================================================== void CliApplication::plugins() const { // Output some information about our CLI plugins, so first make sure that we // have at least one of them if (mLoadedCliPlugins.isEmpty()) { std::cout << "No CLI plugins could be found." << std::endl; return; } // First, we retrieve all the CLI plugins information QStringList pluginsInfo = QStringList(); foreach (Plugin *plugin, mLoadedCliPlugins) { // Retrieve the CLI plugin and its default description QString pluginInfo = plugin->name(); QString pluginDesc = pluginDescription(plugin); if (!pluginDesc.isEmpty()) pluginInfo += ": "+pluginDesc; // Add the plugin information to our list pluginsInfo << pluginInfo; } // Now, we can output the plugin information in alphabetical order pluginsInfo.sort(Qt::CaseInsensitive); if (pluginsInfo.count() == 1) std::cout << "The following CLI plugin is available:" << std::endl; else std::cout << "The following CLI plugins are available:" << std::endl; foreach (const QString &pluginInfo, pluginsInfo) std::cout << " - " << pluginInfo.toStdString() << std::endl; } //============================================================================== void CliApplication::reset() const { QSettings settings; settings.clear(); std::cout << "All your settings have been reset." << std::endl; } //============================================================================== void CliApplication::status() const { // Output the status of all the plugins that should (have) normally be(en) // loaded, so first make sure that we have at least one of them if (mPluginManager->loadedPlugins().isEmpty()) { std::cout << "No plugins could be found." << std::endl; return; } // First, we retrieve all the plugins information QStringList pluginsInfo = QStringList(); foreach (Plugin *plugin, mPluginManager->plugins()) { // Retrieve the plugin and its status QString pluginInfo = plugin->name()+": "; // Retrieve the plugin's status switch (plugin->status()) { case Plugin::NotWanted: pluginInfo += "the plugin is not wanted."; break; case Plugin::NotNeeded: pluginInfo += "the plugin is not needed."; break; case Plugin::NotLoaded: pluginInfo += QString("the plugin could not be loaded due to the following problem: %1.").arg(formatMessage(plugin->statusErrors())); break; case Plugin::NotPlugin: pluginInfo += "this is not a plugin."; break; case Plugin::NotCorePlugin: pluginInfo += "the plugin claims to be the core plugin, but it is not."; break; case Plugin::InvalidCorePlugin: pluginInfo += "the plugin should be the core plugin, but it does not support the core interface."; break; case Plugin::NotCliPluginNoCliSupport: pluginInfo += "the plugin supports the CLI interface, but it does not claim to be CLI-capable."; break; case Plugin::NotCliPluginNoCliInterface: pluginInfo += "the plugin claims to be CLI-capable, but it does not support the CLI interface."; break; case Plugin::MissingOrInvalidDependencies: if (plugin->statusErrorsCount() == 1) pluginInfo += QString("the plugin could not be loaded due to the %1 plugin being missing or invalid.").arg(plugin->statusErrors()); else pluginInfo += QString("the plugin could not be loaded due to missing or invalid plugins:\n%1").arg(plugin->statusErrors()); break; default: // Plugin::Loaded pluginInfo += "the plugin is loaded and fully functional."; } // Add the plugin information to our list pluginsInfo << pluginInfo; } // Now, we can output the plugin information in alphabetical order pluginsInfo.sort(Qt::CaseInsensitive); if (pluginsInfo.count() == 1) std::cout << "The following plugin is available:" << std::endl; else std::cout << "The following plugins are available:" << std::endl; foreach (const QString &pluginInfo, pluginsInfo) std::cout << " - " << pluginInfo.toStdString() << std::endl; } //============================================================================== void CliApplication::version() const { // Output the version of OpenCOR std::cout << OpenCOR::version().toStdString() << std::endl; } //============================================================================== bool CliApplication::run(int *pRes) { // See what needs doing with the CLI options, if anything *pRes = 0; // By default, everything is fine enum Option { NoOption, AboutOption, CommandOption, HelpOption, PluginsOption, ResetOption, StatusOption, VersionOption }; Option option = NoOption; QStringList appArguments = qApp->arguments(); QStringList commandArguments = QStringList(); appArguments.removeFirst(); // Note: we remove the first argument since it corresponds to the full path // to our executable, which we are not interested in... foreach (const QString &appArgument, appArguments) { if (!appArgument.compare("-a") || !appArgument.compare("--about")) { if (option == NoOption) { option = AboutOption; } else { *pRes = -1; } } else if (!appArgument.compare("-c") || !appArgument.compare("--command")) { if (option == NoOption) { option = CommandOption; } else { *pRes = -1; } } else if (!appArgument.compare("-h") || !appArgument.compare("--help")) { if (option == NoOption) { option = HelpOption; } else { *pRes = -1; } } else if (!appArgument.compare("-p") || !appArgument.compare("--plugins")) { if (option == NoOption) { option = PluginsOption; } else { *pRes = -1; } } else if (!appArgument.compare("-r") || !appArgument.compare("--reset")) { if (option == NoOption) { option = ResetOption; } else { *pRes = -1; } } else if (!appArgument.compare("-s") || !appArgument.compare("--status")) { if (option == NoOption) { option = StatusOption; } else { *pRes = -1; } } else if (!appArgument.compare("-v") || !appArgument.compare("--version")) { if (option == NoOption) { option = VersionOption; } else { *pRes = -1; } } else if (appArgument.startsWith("-")) { // The user provided at least one unknown option *pRes = -1; break; } else if (option == CommandOption) { // Not an option, so we consider it to be part of a command commandArguments << appArgument; } } // Handle the option the user requested, if any if (!*pRes) { switch (option) { case AboutOption: about(); break; case CommandOption: // Make sure that we have at least one argument (which would be the // command itself) before loading the plugins and then sending the // command to the plugin(s) if (commandArguments.isEmpty()) { *pRes = -1; help(); } else { loadPlugins(); if (!command(commandArguments, pRes)) { *pRes = -1; help(); } } break; case HelpOption: help(); break; case PluginsOption: loadPlugins(); plugins(); break; case ResetOption: reset(); break; case StatusOption: loadPlugins(); status(); break; case VersionOption: version(); break; default: // The user didn't provide any option that requires running OpenCOR // as a CLI application return false; } } else { help(); } return true; } //============================================================================== } // namespace OpenCOR //============================================================================== // End of file //==============================================================================
[ "agarny@hellix.com" ]
agarny@hellix.com
c38bbbc642580124887fdee60239a3b773f5891d
e763b855be527d69fb2e824dfb693d09e59cdacb
/aws-cpp-sdk-cognito-idp/source/model/AdminUpdateUserAttributesRequest.cpp
023464695b68d5e81e4d46b1d7c154bbbf4c0e82
[ "MIT", "Apache-2.0", "JSON" ]
permissive
34234344543255455465/aws-sdk-cpp
47de2d7bde504273a43c99188b544e497f743850
1d04ff6389a0ca24361523c58671ad0b2cde56f5
refs/heads/master
2023-06-10T16:15:54.618966
2018-05-07T23:32:08
2018-05-07T23:32:08
132,632,360
1
0
Apache-2.0
2023-06-01T23:20:47
2018-05-08T15:56:35
C++
UTF-8
C++
false
false
2,042
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/cognito-idp/model/AdminUpdateUserAttributesRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::CognitoIdentityProvider::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; AdminUpdateUserAttributesRequest::AdminUpdateUserAttributesRequest() : m_userPoolIdHasBeenSet(false), m_usernameHasBeenSet(false), m_userAttributesHasBeenSet(false) { } Aws::String AdminUpdateUserAttributesRequest::SerializePayload() const { JsonValue payload; if(m_userPoolIdHasBeenSet) { payload.WithString("UserPoolId", m_userPoolId); } if(m_usernameHasBeenSet) { payload.WithString("Username", m_username); } if(m_userAttributesHasBeenSet) { Array<JsonValue> userAttributesJsonList(m_userAttributes.size()); for(unsigned userAttributesIndex = 0; userAttributesIndex < userAttributesJsonList.GetLength(); ++userAttributesIndex) { userAttributesJsonList[userAttributesIndex].AsObject(m_userAttributes[userAttributesIndex].Jsonize()); } payload.WithArray("UserAttributes", std::move(userAttributesJsonList)); } return payload.WriteReadable(); } Aws::Http::HeaderValueCollection AdminUpdateUserAttributesRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AWSCognitoIdentityProviderService.AdminUpdateUserAttributes")); return headers; }
[ "henso@amazon.com" ]
henso@amazon.com
3ffff48cf19fd43edac3715125e626a0aa0244c2
8559edef3b57407ac5d11cb23df68b50b07b7911
/Best_Online Judge solution/Code force online judge/Wrong Subtraction.cpp
265d0664de2c0bf68fb4c8e8b5372e0e7f470f9b
[]
no_license
mijanur-rahman-40/C-C-plus-plus-Online-Judge-Algorithms-Practise-Programming
2a031b0743356ba4c8670623aaa87b57f0b43f27
254924e4bd890e2f6d434abcc9ef52ef3e209211
refs/heads/master
2023-02-13T06:26:20.422678
2021-01-13T14:20:21
2021-01-13T14:20:21
329,330,528
1
0
null
null
null
null
UTF-8
C++
false
false
260
cpp
#include<bits/stdc++.h> using namespace std; int main() { int num,len; scanf("%d%d",&num,&len); for(int i=0; i<len; i++){ if(num%10==0){ num = num/10; } else num = num-1; } cout<<num<<endl; }
[ "mijanurrahman31416@gmail.com" ]
mijanurrahman31416@gmail.com
052e1239c0a2c889f5eb4ac50b9303a8c64d5a1e
3051050dc3dee97dc60ef78d31ff500b6e93d0fb
/chrome/browser/ash/login/oobe_quick_start/connectivity/target_device_connection_broker_impl_unittest.cc
956dcfcf8dd529295405de5d87361f010ae29d08
[ "BSD-3-Clause" ]
permissive
weblifeio/chromium
cd249e1c9418dcf0792bd68bbdcd2a6e56af0e2e
74ac962b3a95c88614f734066ab2cc48b572359c
refs/heads/main
2023-06-09T19:45:03.535378
2023-05-26T19:16:31
2023-05-26T19:16:31
177,631,387
0
0
null
2019-03-25T17:15:48
2019-03-25T17:15:47
null
UTF-8
C++
false
false
21,898
cc
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/login/oobe_quick_start/connectivity/target_device_connection_broker_impl.h" #include <array> #include "base/base64.h" #include "base/command_line.h" #include "base/functional/bind.h" #include "base/test/task_environment.h" #include "chrome/browser/ash/login/oobe_quick_start/connectivity/fast_pair_advertiser.h" #include "chrome/browser/ash/login/oobe_quick_start/connectivity/random_session_id.h" #include "chrome/browser/ash/login/oobe_quick_start/connectivity/target_device_connection_broker_factory.h" #include "chrome/browser/ash/nearby/quick_start_connectivity_service.h" #include "chrome/browser/ash/nearby/quick_start_connectivity_service_factory.h" #include "chrome/browser/nearby_sharing/fake_nearby_connections_manager.h" #include "chrome/browser/nearby_sharing/public/cpp/nearby_connections_manager.h" #include "chromeos/constants/devicetype.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/test/mock_bluetooth_adapter.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace ash::quick_start { namespace { constexpr size_t kMaxEndpointInfoDisplayNameLength = 18; constexpr uint8_t kEndpointInfoVerificationStyle = 6u; constexpr uint8_t kEndpointInfoDeviceType = 8u; constexpr size_t kEndpointInfoRandomSessionIdLength = 10; // 10 random bytes to use as the RandomSessionId. The corresponding display name // code is (0x135e % 1000) = 958. constexpr std::array<uint8_t, 6> kRandomSessionId = {0x13, 0x5e, 0xfb, 0x0f, 0x3a, 0x20}; // Perform base64 decoding with the kForgiving option to allow for missing // padding. std::vector<uint8_t> Base64DecodeForgiving(base::span<uint8_t> input) { std::string input_str(input.begin(), input.end()); std::string output; base::Base64Decode(input_str, &output, base::Base64DecodePolicy::kForgiving); return std::vector<uint8_t>(output.begin(), output.end()); } struct EndpointInfoTestCase { chromeos::DeviceType device_type; std::string expected_display_name; }; const EndpointInfoTestCase kEndpointInfoTestCases[] = { {chromeos::DeviceType::kChromebook, "Chromebook (958)"}, {chromeos::DeviceType::kChromebox, "Chromebox (958)"}, {chromeos::DeviceType::kChromebit, "Chromebit (958)"}, {chromeos::DeviceType::kChromebase, "Chromebase (958)"}, {chromeos::DeviceType::kUnknown, "Chrome devic (958)"}, }; using testing::NiceMock; // Ensures that the device name retrieved for the EndpointInfo display name will // include the specified device type, e.g. kChromebook will result in a device // name like "Chromebook (958)". void SetDeviceType(chromeos::DeviceType device_type) { switch (device_type) { case chromeos::DeviceType::kChromebook: base::CommandLine::ForCurrentProcess()->InitFromArgv( {"", "--form-factor=CHROMEBOOK"}); break; case chromeos::DeviceType::kChromebox: base::CommandLine::ForCurrentProcess()->InitFromArgv( {"", "--form-factor=CHROMEBOX"}); break; case chromeos::DeviceType::kChromebit: base::CommandLine::ForCurrentProcess()->InitFromArgv( {"", "--form-factor=CHROMEBIT"}); break; case chromeos::DeviceType::kChromebase: base::CommandLine::ForCurrentProcess()->InitFromArgv( {"", "--form-factor=CHROMEBASE"}); break; case chromeos::DeviceType::kUnknown: base::CommandLine::ForCurrentProcess()->InitFromArgv({"", ""}); break; } } // Allows us to delay returning a Bluetooth adapter until after ReturnAdapter() // is called. Used for testing how the connection broker behaves before the // Bluetooth adapter is finished initializing class DeferredBluetoothAdapterFactoryWrapper : public TargetDeviceConnectionBrokerImpl::BluetoothAdapterFactoryWrapper { public: void ReturnAdapter() { if (!adapter_callback_) { return; } device::BluetoothAdapterFactory::Get()->GetAdapter( std::move(adapter_callback_)); } private: void GetAdapterImpl( device::BluetoothAdapterFactory::AdapterCallback callback) override { adapter_callback_ = std::move(callback); } device::BluetoothAdapterFactory::AdapterCallback adapter_callback_; }; class FakeFastPairAdvertiser : public FastPairAdvertiser { public: explicit FakeFastPairAdvertiser( scoped_refptr<device::BluetoothAdapter> adapter, bool should_succeed_on_start, base::OnceCallback<void()> on_stop_advertising_callback, base::OnceCallback<void()> on_destroy_callback) : FastPairAdvertiser(adapter), should_succeed_on_start_(should_succeed_on_start), on_stop_advertising_callback_(std::move(on_stop_advertising_callback)), on_destroy_callback_(std::move(on_destroy_callback)) {} ~FakeFastPairAdvertiser() override { StopAdvertising(base::DoNothing()); std::move(on_destroy_callback_).Run(); } void StartAdvertising(base::OnceCallback<void()> callback, base::OnceCallback<void()> error_callback, const RandomSessionId& random_session_id) override { ++start_advertising_call_count_; if (should_succeed_on_start_) { std::move(callback).Run(); } else { std::move(error_callback).Run(); } } void StopAdvertising(base::OnceCallback<void()> callback) override { if (!has_called_on_stop_advertising_callback_) { std::move(on_stop_advertising_callback_).Run(); has_called_on_stop_advertising_callback_ = true; } std::move(callback).Run(); } size_t start_advertising_call_count() { return start_advertising_call_count_; } private: bool should_succeed_on_start_; bool has_called_on_stop_advertising_callback_ = false; size_t start_advertising_call_count_ = 0u; base::OnceCallback<void()> on_stop_advertising_callback_; base::OnceCallback<void()> on_destroy_callback_; }; class FakeFastPairAdvertiserFactory : public FastPairAdvertiser::Factory { public: explicit FakeFastPairAdvertiserFactory(bool should_succeed_on_start) : should_succeed_on_start_(should_succeed_on_start) {} std::unique_ptr<FastPairAdvertiser> CreateInstance( scoped_refptr<device::BluetoothAdapter> adapter) override { auto fake_fast_pair_advertiser = std::make_unique<FakeFastPairAdvertiser>( adapter, should_succeed_on_start_, base::BindOnce(&FakeFastPairAdvertiserFactory::OnStopAdvertising, weak_ptr_factory_.GetWeakPtr()), base::BindOnce( &FakeFastPairAdvertiserFactory::OnFastPairAdvertiserDestroyed, weak_ptr_factory_.GetWeakPtr())); last_fake_fast_pair_advertiser_ = fake_fast_pair_advertiser.get(); return std::move(fake_fast_pair_advertiser); } void OnFastPairAdvertiserDestroyed() { fast_pair_advertiser_destroyed_ = true; last_fake_fast_pair_advertiser_ = nullptr; } void OnStopAdvertising() { stop_advertising_called_ = true; } size_t StartAdvertisingCount() { return last_fake_fast_pair_advertiser_ ? last_fake_fast_pair_advertiser_->start_advertising_call_count() : 0; } bool AdvertiserDestroyed() { return fast_pair_advertiser_destroyed_; } bool StopAdvertisingCalled() { return stop_advertising_called_; } private: FakeFastPairAdvertiser* last_fake_fast_pair_advertiser_ = nullptr; bool should_succeed_on_start_ = false; bool stop_advertising_called_ = false; bool fast_pair_advertiser_destroyed_ = false; base::WeakPtrFactory<FakeFastPairAdvertiserFactory> weak_ptr_factory_{this}; }; } // namespace class TargetDeviceConnectionBrokerImplTest : public testing::Test { public: TargetDeviceConnectionBrokerImplTest() = default; TargetDeviceConnectionBrokerImplTest(TargetDeviceConnectionBrokerImplTest&) = delete; TargetDeviceConnectionBrokerImplTest& operator=( TargetDeviceConnectionBrokerImplTest&) = delete; ~TargetDeviceConnectionBrokerImplTest() override = default; void SetUp() override { mock_bluetooth_adapter_ = base::MakeRefCounted<NiceMock<device::MockBluetoothAdapter>>(); ON_CALL(*mock_bluetooth_adapter_, IsPresent()) .WillByDefault(Invoke( this, &TargetDeviceConnectionBrokerImplTest::IsBluetoothPresent)); ON_CALL(*mock_bluetooth_adapter_, IsPowered()) .WillByDefault(Invoke( this, &TargetDeviceConnectionBrokerImplTest::IsBluetoothPowered)); device::BluetoothAdapterFactory::SetAdapterForTesting( mock_bluetooth_adapter_); TargetDeviceConnectionBrokerImpl::BluetoothAdapterFactoryWrapper:: set_bluetooth_adapter_factory_wrapper_for_testing( &bluetooth_adapter_factory_wrapper_); CreateConnectionBroker(); SetFakeFastPairAdvertiserFactory(/*should_succeed_on_start=*/true); } void CreateConnectionBroker() { RandomSessionId session_id(kRandomSessionId); connection_broker_ = ash::quick_start::TargetDeviceConnectionBrokerFactory::Create( fake_nearby_connections_manager_.GetWeakPtr(), session_id); } void FinishFetchingBluetoothAdapter() { base::RunLoop().RunUntilIdle(); bluetooth_adapter_factory_wrapper_.ReturnAdapter(); } bool IsBluetoothPowered() { return is_bluetooth_powered_; } bool IsBluetoothPresent() { return is_bluetooth_present_; } void SetBluetoothIsPowered(bool powered) { is_bluetooth_powered_ = powered; } void SetBluetoothIsPresent(bool present) { is_bluetooth_present_ = present; } void SetFakeFastPairAdvertiserFactory(bool should_succeed_on_start) { fast_pair_advertiser_factory_ = std::make_unique<FakeFastPairAdvertiserFactory>( should_succeed_on_start); FastPairAdvertiser::Factory::SetFactoryForTesting( fast_pair_advertiser_factory_.get()); } void StartAdvertisingResultCallback(bool success) { start_advertising_callback_called_ = true; start_advertising_callback_success_ = success; } void StopAdvertisingCallback() { stop_advertising_callback_called_ = true; } std::vector<uint8_t> GenerateEndpointInfo() { return static_cast<TargetDeviceConnectionBrokerImpl*>( connection_broker_.get()) ->GenerateEndpointInfo(); } const RandomSessionId& GetRandomSessionId() { return static_cast<TargetDeviceConnectionBrokerImpl*>( connection_broker_.get()) ->random_session_id_; } protected: bool is_bluetooth_powered_ = true; bool is_bluetooth_present_ = true; bool start_advertising_callback_called_ = false; bool start_advertising_callback_success_ = false; bool stop_advertising_callback_called_ = false; scoped_refptr<NiceMock<device::MockBluetoothAdapter>> mock_bluetooth_adapter_; FakeNearbyConnectionsManager fake_nearby_connections_manager_; std::unique_ptr<TargetDeviceConnectionBroker> connection_broker_; std::unique_ptr<FakeFastPairAdvertiserFactory> fast_pair_advertiser_factory_; DeferredBluetoothAdapterFactoryWrapper bluetooth_adapter_factory_wrapper_; base::test::SingleThreadTaskEnvironment task_environment_; base::WeakPtrFactory<TargetDeviceConnectionBrokerImplTest> weak_ptr_factory_{ this}; }; class TargetDeviceConnectionBrokerImplEndpointInfoTest : public TargetDeviceConnectionBrokerImplTest, public testing::WithParamInterface<EndpointInfoTestCase> { public: void SetUp() override { SetDeviceType(GetParam().device_type); TargetDeviceConnectionBrokerImplTest::SetUp(); } }; TEST_F(TargetDeviceConnectionBrokerImplTest, GetFeatureSupportStatus) { EXPECT_EQ( TargetDeviceConnectionBrokerImpl::FeatureSupportStatus::kUndetermined, connection_broker_->GetFeatureSupportStatus()); FinishFetchingBluetoothAdapter(); SetBluetoothIsPresent(false); EXPECT_EQ( TargetDeviceConnectionBrokerImpl::FeatureSupportStatus::kNotSupported, connection_broker_->GetFeatureSupportStatus()); SetBluetoothIsPresent(true); EXPECT_EQ(TargetDeviceConnectionBrokerImpl::FeatureSupportStatus::kSupported, connection_broker_->GetFeatureSupportStatus()); } TEST_F(TargetDeviceConnectionBrokerImplTest, StartFastPairAdvertising) { FinishFetchingBluetoothAdapter(); EXPECT_EQ(0u, fast_pair_advertiser_factory_->StartAdvertisingCount()); connection_broker_->StartAdvertising( nullptr, base::BindOnce( &TargetDeviceConnectionBrokerImplTest::StartAdvertisingResultCallback, weak_ptr_factory_.GetWeakPtr())); EXPECT_EQ(1u, fast_pair_advertiser_factory_->StartAdvertisingCount()); EXPECT_TRUE(start_advertising_callback_called_); EXPECT_TRUE(start_advertising_callback_success_); } TEST_F(TargetDeviceConnectionBrokerImplTest, StartFastPairAdvertising_BeforeBTAdapterInitialized) { EXPECT_EQ(0u, fast_pair_advertiser_factory_->StartAdvertisingCount()); connection_broker_->StartAdvertising( nullptr, base::BindOnce( &TargetDeviceConnectionBrokerImplTest::StartAdvertisingResultCallback, weak_ptr_factory_.GetWeakPtr())); EXPECT_EQ(0u, fast_pair_advertiser_factory_->StartAdvertisingCount()); FinishFetchingBluetoothAdapter(); EXPECT_EQ(1u, fast_pair_advertiser_factory_->StartAdvertisingCount()); EXPECT_TRUE(start_advertising_callback_called_); EXPECT_TRUE(start_advertising_callback_success_); } TEST_F(TargetDeviceConnectionBrokerImplTest, StartFastPairAdvertisingError_BluetoothNotPresent) { FinishFetchingBluetoothAdapter(); SetBluetoothIsPresent(false); EXPECT_EQ(0u, fast_pair_advertiser_factory_->StartAdvertisingCount()); connection_broker_->StartAdvertising( nullptr, base::BindOnce( &TargetDeviceConnectionBrokerImplTest::StartAdvertisingResultCallback, weak_ptr_factory_.GetWeakPtr())); EXPECT_EQ(0u, fast_pair_advertiser_factory_->StartAdvertisingCount()); EXPECT_TRUE(start_advertising_callback_called_); EXPECT_FALSE(start_advertising_callback_success_); } TEST_F(TargetDeviceConnectionBrokerImplTest, StartFastPairAdvertisingError_BluetoothNotPowered) { FinishFetchingBluetoothAdapter(); SetBluetoothIsPowered(false); EXPECT_EQ(0u, fast_pair_advertiser_factory_->StartAdvertisingCount()); connection_broker_->StartAdvertising( nullptr, base::BindOnce( &TargetDeviceConnectionBrokerImplTest::StartAdvertisingResultCallback, weak_ptr_factory_.GetWeakPtr())); EXPECT_EQ(0u, fast_pair_advertiser_factory_->StartAdvertisingCount()); EXPECT_TRUE(start_advertising_callback_called_); EXPECT_FALSE(start_advertising_callback_success_); } TEST_F(TargetDeviceConnectionBrokerImplTest, StartFastPairAdvertisingError_Unsuccessful) { FinishFetchingBluetoothAdapter(); SetFakeFastPairAdvertiserFactory(/*should_succeed_on_start=*/false); EXPECT_EQ(0u, fast_pair_advertiser_factory_->StartAdvertisingCount()); connection_broker_->StartAdvertising( nullptr, base::BindOnce( &TargetDeviceConnectionBrokerImplTest::StartAdvertisingResultCallback, weak_ptr_factory_.GetWeakPtr())); EXPECT_TRUE(start_advertising_callback_called_); EXPECT_FALSE(start_advertising_callback_success_); EXPECT_TRUE(fast_pair_advertiser_factory_->AdvertiserDestroyed()); } TEST_F(TargetDeviceConnectionBrokerImplTest, StopFastPairAdvertising_NeverStarted) { FinishFetchingBluetoothAdapter(); // If StartAdvertising is never called, StopAdvertising should not propagate // to the fast pair advertiser. connection_broker_->StopAdvertising(base::BindOnce( &TargetDeviceConnectionBrokerImplTest::StopAdvertisingCallback, weak_ptr_factory_.GetWeakPtr())); EXPECT_TRUE(stop_advertising_callback_called_); EXPECT_FALSE(fast_pair_advertiser_factory_->StopAdvertisingCalled()); } TEST_F(TargetDeviceConnectionBrokerImplTest, StopFastPairAdvertising_BeforeBTAdapterInitialized) { connection_broker_->StartAdvertising( nullptr, base::BindOnce( &TargetDeviceConnectionBrokerImplTest::StartAdvertisingResultCallback, weak_ptr_factory_.GetWeakPtr())); // If the Bluetooth adapter hasn't finished initializing, then // StartAdvertisings never completed, and StopAdvertising should not propagate // to the fast pair advertiser. connection_broker_->StopAdvertising(base::BindOnce( &TargetDeviceConnectionBrokerImplTest::StopAdvertisingCallback, weak_ptr_factory_.GetWeakPtr())); EXPECT_TRUE(stop_advertising_callback_called_); EXPECT_FALSE(fast_pair_advertiser_factory_->StopAdvertisingCalled()); } TEST_F(TargetDeviceConnectionBrokerImplTest, StopFastPairAdvertising) { FinishFetchingBluetoothAdapter(); connection_broker_->StartAdvertising( nullptr, base::BindOnce( &TargetDeviceConnectionBrokerImplTest::StartAdvertisingResultCallback, weak_ptr_factory_.GetWeakPtr())); EXPECT_EQ(1u, fast_pair_advertiser_factory_->StartAdvertisingCount()); EXPECT_TRUE(start_advertising_callback_called_); EXPECT_TRUE(start_advertising_callback_success_); EXPECT_FALSE(fast_pair_advertiser_factory_->StopAdvertisingCalled()); connection_broker_->StopAdvertising(base::BindOnce( &TargetDeviceConnectionBrokerImplTest::StopAdvertisingCallback, weak_ptr_factory_.GetWeakPtr())); EXPECT_TRUE(fast_pair_advertiser_factory_->StopAdvertisingCalled()); EXPECT_TRUE(fast_pair_advertiser_factory_->AdvertiserDestroyed()); EXPECT_TRUE(stop_advertising_callback_called_); } TEST_P(TargetDeviceConnectionBrokerImplEndpointInfoTest, GenerateEndpointInfo) { std::vector<uint8_t> endpoint_info = GenerateEndpointInfo(); // Points to the field being parsed. size_t i = 0; ASSERT_GT(endpoint_info.size(), i); uint8_t version = endpoint_info[i]; EXPECT_EQ(1u, version); i++; // Parse the display name. The field is variable-length, so we have to look // out for either a null byte or for the display name to reach the maximum // length. ASSERT_GT(endpoint_info.size(), i); size_t j = 0; std::vector<uint8_t> display_name_bytes; while (i + j < endpoint_info.size() && endpoint_info[i + j] != 0u && j < kMaxEndpointInfoDisplayNameLength) { display_name_bytes.push_back(endpoint_info[i + j]); j++; } // Assert that we didn't break out of the while loop because we ran out of // bytes. ASSERT_LT(i + j, endpoint_info.size()); if (j < kMaxEndpointInfoDisplayNameLength) { // Move past the null-terminator if the display name length is less than the // max. ASSERT_EQ(0u, endpoint_info[i + j]); j++; } std::string display_name = std::string(display_name_bytes.begin(), display_name_bytes.end()); EXPECT_EQ(GetParam().expected_display_name, display_name); i += j; // The remaining advertising info fields are base64-encoded. Decode them // before proceeding. std::vector<uint8_t> advertising_info = Base64DecodeForgiving( base::span<uint8_t>(endpoint_info.begin() + i, endpoint_info.end())); ASSERT_EQ(advertising_info.size(), 60u); i = 0; uint8_t verification_style = advertising_info[i]; EXPECT_EQ(kEndpointInfoVerificationStyle, verification_style); i++; uint8_t device_type = advertising_info[i]; EXPECT_EQ(kEndpointInfoDeviceType, device_type); i++; // Parse the RandomSessionId. The field is fixed-width, but contains a string // that may not occupy the full length, in which case there will be a null // terminator. std::string session_id = GetRandomSessionId().ToString(); for (size_t k = i; k < i + kEndpointInfoRandomSessionIdLength; k++) { if (advertising_info[k] == 0) { break; } EXPECT_EQ(session_id[k - i], advertising_info[k]); } i += kEndpointInfoRandomSessionIdLength; uint8_t is_quick_start = advertising_info[i]; EXPECT_EQ(1u, is_quick_start); i++; uint8_t prefer_target_user_verification = advertising_info[i]; EXPECT_EQ(0u, prefer_target_user_verification); } INSTANTIATE_TEST_SUITE_P(TargetDeviceConnectionBrokerImplTest, TargetDeviceConnectionBrokerImplEndpointInfoTest, testing::ValuesIn(kEndpointInfoTestCases)); TEST_F(TargetDeviceConnectionBrokerImplTest, StartNearbyConnectionsAdvertising) { FinishFetchingBluetoothAdapter(); EXPECT_FALSE(fake_nearby_connections_manager_.IsAdvertising()); connection_broker_->StartAdvertising( nullptr, base::BindOnce( &TargetDeviceConnectionBrokerImplTest::StartAdvertisingResultCallback, weak_ptr_factory_.GetWeakPtr())); EXPECT_TRUE(fake_nearby_connections_manager_.IsAdvertising()); EXPECT_EQ(PowerLevel::kHighPower, fake_nearby_connections_manager_.advertising_power_level()); EXPECT_TRUE(start_advertising_callback_called_); EXPECT_TRUE(start_advertising_callback_success_); } TEST_F(TargetDeviceConnectionBrokerImplTest, StartNearbyConnectionsAdvertisingError) { FinishFetchingBluetoothAdapter(); FakeNearbyConnectionsManager::ConnectionsCallback callback = fake_nearby_connections_manager_.GetStartAdvertisingCallback(); EXPECT_FALSE(fake_nearby_connections_manager_.IsAdvertising()); connection_broker_->StartAdvertising( nullptr, base::BindOnce( &TargetDeviceConnectionBrokerImplTest::StartAdvertisingResultCallback, weak_ptr_factory_.GetWeakPtr())); EXPECT_TRUE(fake_nearby_connections_manager_.IsAdvertising()); EXPECT_FALSE(start_advertising_callback_called_); std::move(callback).Run(NearbyConnectionsManager::ConnectionsStatus::kError); EXPECT_TRUE(start_advertising_callback_called_); EXPECT_FALSE(start_advertising_callback_success_); } } // namespace ash::quick_start
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
347e100a2e3d3d2eb2886c38de5a878658220a8c
24f26275ffcd9324998d7570ea9fda82578eeb9e
/ui/views/examples/message_box_example.cc
67ff6dc0c78b7c4d680f38a51a2c533c55164356
[ "BSD-3-Clause" ]
permissive
Vizionnation/chromenohistory
70a51193c8538d7b995000a1b2a654e70603040f
146feeb85985a6835f4b8826ad67be9195455402
refs/heads/master
2022-12-15T07:02:54.461083
2019-10-25T15:07:06
2019-10-25T15:07:06
217,557,501
2
1
BSD-3-Clause
2022-11-19T06:53:07
2019-10-25T14:58:54
null
UTF-8
C++
false
false
2,483
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/examples/message_box_example.h" #include <memory> #include <utility> #include "base/strings/utf_string_conversions.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/message_box_view.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/view.h" using base::ASCIIToUTF16; namespace views { namespace examples { MessageBoxExample::MessageBoxExample() : ExampleBase("Message Box View") { } MessageBoxExample::~MessageBoxExample() = default; void MessageBoxExample::CreateExampleView(View* container) { GridLayout* layout = container->SetLayoutManager(std::make_unique<views::GridLayout>()); auto message_box_view = std::make_unique<MessageBoxView>( MessageBoxView::InitParams(ASCIIToUTF16("Hello, world!"))); message_box_view->SetCheckBoxLabel(ASCIIToUTF16("Check Box")); const int message_box_column = 0; ColumnSet* column_set = layout->AddColumnSet(message_box_column); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(1 /* expand */, message_box_column); message_box_view_ = layout->AddView(std::move(message_box_view)); const int button_column = 1; column_set = layout->AddColumnSet(button_column); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0.5f, GridLayout::USE_PREF, 0, 0); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0.5f, GridLayout::USE_PREF, 0, 0); layout->StartRow(0 /* no expand */, button_column); status_ = layout->AddView( std::make_unique<LabelButton>(this, ASCIIToUTF16("Show Status"))); toggle_ = layout->AddView( std::make_unique<LabelButton>(this, ASCIIToUTF16("Toggle Checkbox"))); } void MessageBoxExample::ButtonPressed(Button* sender, const ui::Event& event) { if (sender == status_) { message_box_view_->SetCheckBoxLabel( ASCIIToUTF16(message_box_view_->IsCheckBoxSelected() ? "on" : "off")); PrintStatus(message_box_view_->IsCheckBoxSelected() ? "Check Box Selected" : "Check Box Not Selected"); } else if (sender == toggle_) { message_box_view_->SetCheckBoxSelected( !message_box_view_->IsCheckBoxSelected()); } } } // namespace examples } // namespace views
[ "rjkroege@chromium.org" ]
rjkroege@chromium.org
847a18a74124ad3125f90c7a841932f378c4b2ec
24428e18296300212ca28250208dc7f946542e3b
/Array/kadane algo.cpp
3ed2e4890e069af1b47747edf77bd40470290ef1
[]
no_license
Kunal1701/My-Codes
134b21fde6a45816d37a55743ea37a674a5c2ca8
27a81ebdc5c6c79ee9f3f43865803c9195c9d0e7
refs/heads/main
2023-08-29T17:29:26.503621
2021-11-11T15:54:35
2021-11-11T15:54:35
388,391,672
0
0
null
null
null
null
UTF-8
C++
false
false
460
cpp
#include <iostream> #include <climits> using namespace std; int main() { int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } int sum = 0; int largest = INT_MIN; for (int i = 0; i < n; i++) { sum += a[i]; if (sum < 0) { sum = 0; } largest = max(largest, sum); } cout << largest << endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
0e2889d53a127dfef30a2b6d03ea868b5067575c
b57193090bbfa5838f1e673f37ac82ad26286b54
/src/istream/ToBucketIstream.hxx
7598619717b77b97ce1eca8459298cd7095f8842
[]
no_license
luckydonald-backup/beng-proxy
8021e4fe7bb06e24b6f7d2a5464fc6051a8df25f
34ef0a94c7005bde20390c3b60a6439cc6770573
refs/heads/master
2020-05-24T20:56:31.428664
2019-05-16T08:40:44
2019-05-16T09:14:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,634
hxx
/* * Copyright 2007-2019 Content Management AG * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "FacadeIstream.hxx" #include "event/DeferEvent.hxx" #include "SliceFifoBuffer.hxx" /** * This class is an adapter for an existing #Istream implementation * which guarantees that FillBucketList() is available. If the * underlying #Istream doesn't support it, it will copy incoming data * into its own buffer and make it available in a bucket. */ class ToBucketIstream final : public FacadeIstream { SliceFifoBuffer buffer; DeferEvent defer_read; public: ToBucketIstream(struct pool &_pool, EventLoop &_event_loop, UnusedIstreamPtr &&_input) noexcept; private: void DeferredRead() noexcept { input.Read(); } protected: /* virtual methods from class Istream */ void _Read() noexcept override; void _FillBucketList(IstreamBucketList &list) override; size_t _ConsumeBucketList(size_t nbytes) noexcept override; void _Close() noexcept override; /* virtual methods from class IstreamHandler */ bool OnIstreamReady() noexcept override; size_t OnData(const void *data, size_t length) noexcept override; void OnEof() noexcept override; void OnError(std::exception_ptr ep) noexcept override; };
[ "mk@cm4all.com" ]
mk@cm4all.com
a5263bd4531085a259660bfcf5aa6e29b050b9ec
6086e218fd8d3d86849e712373698b0de3e22f9e
/src/maxnode/maxnode-payments.cpp
29cb50b3e55c612921a3285902f6e34c8572c2e3
[ "MIT" ]
permissive
LytixChain/peermaxcoin
4d6530b8d3722feb7b05d97cf3a60da99daccc07
13c2c5e4a8e2ea145cdf965bf5238bf469fe4a24
refs/heads/master
2020-04-01T14:41:28.960879
2018-10-19T18:33:21
2018-10-19T18:33:21
153,304,228
0
0
null
null
null
null
UTF-8
C++
false
false
30,734
cpp
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "maxnode-payments.h" #include "addrman.h" #include "maxnode-budget.h" #include "maxnode-sync.h" #include "maxnodeman.h" #include "obfuscation.h" #include "spork.h" #include "sync.h" #include "util.h" #include "utilmoneystr.h" #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> /** Object for who's going to get paid on which blocks */ CMasternodePayments maxnodePayments; CCriticalSection cs_vecPayments; CCriticalSection cs_mapMasternodeBlocks; CCriticalSection cs_mapMasternodePayeeVotes; // // CMasternodePaymentDB // CMasternodePaymentDB::CMasternodePaymentDB() { pathDB = GetDataDir() / "mnpayments.dat"; strMagicMessage = "MasternodePayments"; } bool CMasternodePaymentDB::Write(const CMasternodePayments& objToSave) { int64_t nStart = GetTimeMillis(); // serialize, checksum data up to that point, then append checksum CDataStream ssObj(SER_DISK, CLIENT_VERSION); ssObj << strMagicMessage; // maxnode cache file specific magic message ssObj << FLATDATA(Params().MessageStart()); // network specific magic number ssObj << objToSave; uint256 hash = Hash(ssObj.begin(), ssObj.end()); ssObj << hash; // open output file, and associate with CAutoFile FILE* file = fopen(pathDB.string().c_str(), "wb"); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error("%s : Failed to open file %s", __func__, pathDB.string()); // Write and commit header, data try { fileout << ssObj; } catch (std::exception& e) { return error("%s : Serialize or I/O error - %s", __func__, e.what()); } fileout.fclose(); LogPrint("maxnode","Written info to mnpayments.dat %dms\n", GetTimeMillis() - nStart); return true; } CMasternodePaymentDB::ReadResult CMasternodePaymentDB::Read(CMasternodePayments& objToLoad, bool fDryRun) { int64_t nStart = GetTimeMillis(); // open input file, and associate with CAutoFile FILE* file = fopen(pathDB.string().c_str(), "rb"); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) { error("%s : Failed to open file %s", __func__, pathDB.string()); return FileError; } // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathDB); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char*)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception& e) { error("%s : Deserialize or I/O error - %s", __func__, e.what()); return HashReadError; } filein.fclose(); CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssObj.begin(), ssObj.end()); if (hashIn != hashTmp) { error("%s : Checksum mismatch, data corrupted", __func__); return IncorrectHash; } unsigned char pchMsgTmp[4]; std::string strMagicMessageTmp; try { // de-serialize file header (maxnode cache file specific magic message) and .. ssObj >> strMagicMessageTmp; // ... verify the message matches predefined one if (strMagicMessage != strMagicMessageTmp) { error("%s : Invalid maxnode payement cache magic message", __func__); return IncorrectMagicMessage; } // de-serialize file header (network specific magic number) and .. ssObj >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) { error("%s : Invalid network magic number", __func__); return IncorrectMagicNumber; } // de-serialize data into CMasternodePayments object ssObj >> objToLoad; } catch (std::exception& e) { objToLoad.Clear(); error("%s : Deserialize or I/O error - %s", __func__, e.what()); return IncorrectFormat; } LogPrint("maxnode","Loaded info from mnpayments.dat %dms\n", GetTimeMillis() - nStart); LogPrint("maxnode"," %s\n", objToLoad.ToString()); if (!fDryRun) { LogPrint("maxnode","Masternode payments manager - cleaning....\n"); objToLoad.CleanPaymentList(); LogPrint("maxnode","Masternode payments manager - result:\n"); LogPrint("maxnode"," %s\n", objToLoad.ToString()); } return Ok; } void DumpMasternodePayments() { int64_t nStart = GetTimeMillis(); CMasternodePaymentDB paymentdb; CMasternodePayments tempPayments; LogPrint("maxnode","Verifying mnpayments.dat format...\n"); CMasternodePaymentDB::ReadResult readResult = paymentdb.Read(tempPayments, true); // there was an error and it was not an error on file opening => do not proceed if (readResult == CMasternodePaymentDB::FileError) LogPrint("maxnode","Missing budgets file - mnpayments.dat, will try to recreate\n"); else if (readResult != CMasternodePaymentDB::Ok) { LogPrint("maxnode","Error reading mnpayments.dat: "); if (readResult == CMasternodePaymentDB::IncorrectFormat) LogPrint("maxnode","magic is ok but data has invalid format, will try to recreate\n"); else { LogPrint("maxnode","file format is unknown or invalid, please fix it manually\n"); return; } } LogPrint("maxnode","Writting info to mnpayments.dat...\n"); paymentdb.Write(maxnodePayments); LogPrint("maxnode","Budget dump finished %dms\n", GetTimeMillis() - nStart); } bool IsBlockValueValid(const CBlock& block, CAmount nExpectedValue, CAmount nMinted) { CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return true; int nHeight = 0; if (pindexPrev->GetBlockHash() == block.hashPrevBlock) { nHeight = pindexPrev->nHeight + 1; } else { //out of order BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock); if (mi != mapBlockIndex.end() && (*mi).second) nHeight = (*mi).second->nHeight + 1; } if (nHeight == 0) { LogPrint("maxnode","IsBlockValueValid() : WARNING: Couldn't find previous block\n"); } //LogPrintf("XX69----------> IsBlockValueValid(): nMinted: %d, nExpectedValue: %d\n", FormatMoney(nMinted), FormatMoney(nExpectedValue)); if (!maxnodeSync.IsSynced()) { //there is no budget data to use to check anything //super blocks will always be on these blocks, max 100 per budgeting if (nHeight % GetBudgetPaymentCycleBlocks() < 100) { return true; } else { if (nMinted > nExpectedValue) { return false; } } } else { // we're synced and have data so check the budget schedule //are these blocks even enabled if (!IsSporkActive(SPORK_13_ENABLE_SUPERBLOCKS)) { return nMinted <= nExpectedValue; } if (budget.IsBudgetPaymentBlock(nHeight)) { //the value of the block is evaluated in CheckBlock return true; } else { if (nMinted > nExpectedValue) { return false; } } } return true; } bool IsBlockPayeeValid(const CBlock& block, int nBlockHeight) { TrxValidationStatus transactionStatus = TrxValidationStatus::InValid; if (!maxnodeSync.IsSynced()) { //there is no budget data to use to check anything -- find the longest chain LogPrint("mnpayments", "Client not synced, skipping block payee checks\n"); return true; } const CTransaction& txNew = (nBlockHeight > Params().LAST_POW_BLOCK() ? block.vtx[1] : block.vtx[0]); //check if it's a budget block if (IsSporkActive(SPORK_13_ENABLE_SUPERBLOCKS)) { if (budget.IsBudgetPaymentBlock(nBlockHeight)) { transactionStatus = budget.IsTransactionValid(txNew, nBlockHeight); if (transactionStatus == TrxValidationStatus::Valid) { return true; } if (transactionStatus == TrxValidationStatus::InValid) { LogPrint("maxnode","Invalid budget payment detected %s\n", txNew.ToString().c_str()); if (IsSporkActive(SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT)) return false; LogPrint("maxnode","Budget enforcement is disabled, accepting block\n"); } } } // If we end here the transaction was either TrxValidationStatus::InValid and Budget enforcement is disabled, or // a double budget payment (status = TrxValidationStatus::DoublePayment) was detected, or no/not enough maxnode // votes (status = TrxValidationStatus::VoteThreshold) for a finalized budget were found // In all cases a maxnode will get the payment for this block //check for maxnode payee if (maxnodePayments.IsTransactionValid(txNew, nBlockHeight)) return true; LogPrint("maxnode","Invalid mn payment detected %s\n", txNew.ToString().c_str()); if (IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) return false; LogPrint("maxnode","Masternode payment enforcement is disabled, accepting block\n"); return true; } void FillBlockPayee(CMutableTransaction& txNew, CAmount nFees, bool fProofOfStake, bool fZPIVStake) { CBlockIndex* pindexPrev = chainActive.Tip(); if (!pindexPrev) return; if (IsSporkActive(SPORK_13_ENABLE_SUPERBLOCKS) && budget.IsBudgetPaymentBlock(pindexPrev->nHeight + 1)) { budget.FillBlockPayee(txNew, nFees, fProofOfStake); } else { maxnodePayments.FillBlockPayee(txNew, nFees, fProofOfStake, fZPIVStake); } } std::string GetRequiredPaymentsString(int nBlockHeight) { if (IsSporkActive(SPORK_13_ENABLE_SUPERBLOCKS) && budget.IsBudgetPaymentBlock(nBlockHeight)) { return budget.GetRequiredPaymentsString(nBlockHeight); } else { return maxnodePayments.GetRequiredPaymentsString(nBlockHeight); } } void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, int64_t nFees, bool fProofOfStake, bool fZPIVStake) { //int lastPoW = Params().LAST_POW_BLOCK(); CBlockIndex* pindexPrev = chainActive.Tip(); if (!pindexPrev) return; bool hasPayment = true; CScript payee; //spork if (!maxnodePayments.GetBlockPayee(pindexPrev->nHeight + 1, payee)) { //no maxnode detected CMasternode* winningNode = mnodeman.GetCurrentMasterNode(1); if (winningNode) { payee = GetScriptForDestination(winningNode->pubKeyCollateralAddress.GetID()); } else { LogPrint("maxnode","CreateNewBlock: Failed to detect maxnode to pay\n"); hasPayment = false; } } CAmount blockValue = GetBlockValue(pindexPrev->nHeight); CAmount maxnodePayment = GetMasternodePayment(pindexPrev->nHeight, blockValue, 0, fZPIVStake); if (hasPayment) { if (fProofOfStake) { /**For Proof Of Stake vout[0] must be null * Stake reward can be split into many different outputs, so we must * use vout.size() to align with several different cases. * An additional output is appended as the maxnode payment */ unsigned int i = txNew.vout.size(); txNew.vout.resize(i + 1); txNew.vout[i].scriptPubKey = payee; txNew.vout[i].nValue = maxnodePayment; //subtract mn payment from the stake reward if (!txNew.vout[1].IsZerocoinMint()) txNew.vout[i - 1].nValue -= maxnodePayment; } else { txNew.vout.resize(2); txNew.vout[1].scriptPubKey = payee; txNew.vout[1].nValue = maxnodePayment; txNew.vout[0].nValue = blockValue - maxnodePayment; } CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrint("maxnode","Masternode payment of %s to %s\n", FormatMoney(maxnodePayment).c_str(), address2.ToString().c_str()); } } int CMasternodePayments::GetMinMasternodePaymentsProto() { if (IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES)) return ActiveProtocol(); // Allow only updated peers else return MIN_PEER_PROTO_VERSION_BEFORE_ENFORCEMENT; // Also allow old peers as long as they are allowed to run } void CMasternodePayments::ProcessMessageMasternodePayments(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { if (!maxnodeSync.IsBlockchainSynced()) return; if (fLiteMode) return; //disable all Obfuscation/Masternode related functionality if (strCommand == "mnget") { //Masternode Payments Request Sync if (fLiteMode) return; //disable all Obfuscation/Masternode related functionality int nCountNeeded; vRecv >> nCountNeeded; if (Params().NetworkID() == CBaseChainParams::MAIN) { if (pfrom->HasFulfilledRequest("mnget")) { LogPrintf("CMasternodePayments::ProcessMessageMasternodePayments() : mnget - peer already asked me for the list\n"); Misbehaving(pfrom->GetId(), 20); return; } } pfrom->FulfilledRequest("mnget"); maxnodePayments.Sync(pfrom, nCountNeeded); LogPrint("mnpayments", "mnget - Sent Masternode winners to peer %i\n", pfrom->GetId()); } else if (strCommand == "mnw") { //Masternode Payments Declare Winner //this is required in litemodef CMasternodePaymentWinner winner; vRecv >> winner; if (pfrom->nVersion < ActiveProtocol()) return; int nHeight; { TRY_LOCK(cs_main, locked); if (!locked || chainActive.Tip() == NULL) return; nHeight = chainActive.Tip()->nHeight; } if (maxnodePayments.mapMasternodePayeeVotes.count(winner.GetHash())) { LogPrint("mnpayments", "mnw - Already seen - %s bestHeight %d\n", winner.GetHash().ToString().c_str(), nHeight); maxnodeSync.AddedMasternodeWinner(winner.GetHash()); return; } int nFirstBlock = nHeight - (mnodeman.CountEnabled() * 1.25); if (winner.nBlockHeight < nFirstBlock || winner.nBlockHeight > nHeight + 20) { LogPrint("mnpayments", "mnw - winner out of range - FirstBlock %d Height %d bestHeight %d\n", nFirstBlock, winner.nBlockHeight, nHeight); return; } std::string strError = ""; if (!winner.IsValid(pfrom, strError)) { // if(strError != "") LogPrint("maxnode","mnw - invalid message - %s\n", strError); return; } if (!maxnodePayments.CanVote(winner.vinMasternode.prevout, winner.nBlockHeight)) { // LogPrint("maxnode","mnw - maxnode already voted - %s\n", winner.vinMasternode.prevout.ToStringShort()); return; } if (!winner.SignatureValid()) { if (maxnodeSync.IsSynced()) { LogPrintf("CMasternodePayments::ProcessMessageMasternodePayments() : mnw - invalid signature\n"); Misbehaving(pfrom->GetId(), 20); } // it could just be a non-synced maxnode mnodeman.AskForMN(pfrom, winner.vinMasternode); return; } CTxDestination address1; ExtractDestination(winner.payee, address1); CBitcoinAddress address2(address1); // LogPrint("mnpayments", "mnw - winning vote - Addr %s Height %d bestHeight %d - %s\n", address2.ToString().c_str(), winner.nBlockHeight, nHeight, winner.vinMasternode.prevout.ToStringShort()); if (maxnodePayments.AddWinningMasternode(winner)) { winner.Relay(); maxnodeSync.AddedMasternodeWinner(winner.GetHash()); } } } bool CMasternodePaymentWinner::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode) { std::string errorMessage; std::string strMasterNodeSignMessage; std::string strMessage = vinMasternode.prevout.ToStringShort() + boost::lexical_cast<std::string>(nBlockHeight) + payee.ToString(); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) { LogPrint("maxnode","CMasternodePing::Sign() - Error: %s\n", errorMessage.c_str()); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) { LogPrint("maxnode","CMasternodePing::Sign() - Error: %s\n", errorMessage.c_str()); return false; } return true; } bool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payee) { if (mapMasternodeBlocks.count(nBlockHeight)) { return mapMasternodeBlocks[nBlockHeight].GetPayee(payee); } return false; } // Is this maxnode scheduled to get paid soon? // -- Only look ahead up to 8 blocks to allow for propagation of the latest 2 winners bool CMasternodePayments::IsScheduled(CMasternode& mn, int nNotBlockHeight) { LOCK(cs_mapMasternodeBlocks); int nHeight; { TRY_LOCK(cs_main, locked); if (!locked || chainActive.Tip() == NULL) return false; nHeight = chainActive.Tip()->nHeight; } CScript mnpayee; mnpayee = GetScriptForDestination(mn.pubKeyCollateralAddress.GetID()); CScript payee; for (int64_t h = nHeight; h <= nHeight + 8; h++) { if (h == nNotBlockHeight) continue; if (mapMasternodeBlocks.count(h)) { if (mapMasternodeBlocks[h].GetPayee(payee)) { if (mnpayee == payee) { return true; } } } } return false; } bool CMasternodePayments::AddWinningMasternode(CMasternodePaymentWinner& winnerIn) { uint256 blockHash = 0; if (!GetBlockHash(blockHash, winnerIn.nBlockHeight - 100)) { return false; } { LOCK2(cs_mapMasternodePayeeVotes, cs_mapMasternodeBlocks); if (mapMasternodePayeeVotes.count(winnerIn.GetHash())) { return false; } mapMasternodePayeeVotes[winnerIn.GetHash()] = winnerIn; if (!mapMasternodeBlocks.count(winnerIn.nBlockHeight)) { CMasternodeBlockPayees blockPayees(winnerIn.nBlockHeight); mapMasternodeBlocks[winnerIn.nBlockHeight] = blockPayees; } } mapMasternodeBlocks[winnerIn.nBlockHeight].AddPayee(winnerIn.payee, 1); return true; } bool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew) { LOCK(cs_vecPayments); int nMaxSignatures = 0; int nMasternode_Drift_Count = 0; std::string strPayeesPossible = ""; CAmount nReward = GetBlockValue(nBlockHeight); if (IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) { // Get a stable number of maxnodes by ignoring newly activated (< 8000 sec old) maxnodes nMasternode_Drift_Count = mnodeman.stable_size() + Params().MasternodeCountDrift(); } else { //account for the fact that all peers do not see the same maxnode count. A allowance of being off our maxnode count is given //we only need to look at an increased maxnode count because as count increases, the reward decreases. This code only checks //for mnPayment >= required, so it only makes sense to check the max node count allowed. nMasternode_Drift_Count = mnodeman.size() + Params().MasternodeCountDrift(); } CAmount requiredMasternodePayment = GetMasternodePayment(nBlockHeight, nReward, nMasternode_Drift_Count, txNew.IsZerocoinSpend()); //require at least 6 signatures BOOST_FOREACH (CMasternodePayee& payee, vecPayments) if (payee.nVotes >= nMaxSignatures && payee.nVotes >= MNPAYMENTS_SIGNATURES_REQUIRED) nMaxSignatures = payee.nVotes; // if we don't have at least 6 signatures on a payee, approve whichever is the longest chain if (nMaxSignatures < MNPAYMENTS_SIGNATURES_REQUIRED) return true; BOOST_FOREACH (CMasternodePayee& payee, vecPayments) { bool found = false; BOOST_FOREACH (CTxOut out, txNew.vout) { if (payee.scriptPubKey == out.scriptPubKey) { if(out.nValue >= requiredMasternodePayment) found = true; else LogPrint("maxnode","Masternode payment is out of drift range. Paid=%s Min=%s\n", FormatMoney(out.nValue).c_str(), FormatMoney(requiredMasternodePayment).c_str()); } } if (payee.nVotes >= MNPAYMENTS_SIGNATURES_REQUIRED) { if (found) return true; CTxDestination address1; ExtractDestination(payee.scriptPubKey, address1); CBitcoinAddress address2(address1); if (strPayeesPossible == "") { strPayeesPossible += address2.ToString(); } else { strPayeesPossible += "," + address2.ToString(); } } } LogPrint("maxnode","CMasternodePayments::IsTransactionValid - Missing required payment of %s to %s\n", FormatMoney(requiredMasternodePayment).c_str(), strPayeesPossible.c_str()); return false; } std::string CMasternodeBlockPayees::GetRequiredPaymentsString() { LOCK(cs_vecPayments); std::string ret = "Unknown"; BOOST_FOREACH (CMasternodePayee& payee, vecPayments) { CTxDestination address1; ExtractDestination(payee.scriptPubKey, address1); CBitcoinAddress address2(address1); if (ret != "Unknown") { ret += ", " + address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.nVotes); } else { ret = address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.nVotes); } } return ret; } std::string CMasternodePayments::GetRequiredPaymentsString(int nBlockHeight) { LOCK(cs_mapMasternodeBlocks); if (mapMasternodeBlocks.count(nBlockHeight)) { return mapMasternodeBlocks[nBlockHeight].GetRequiredPaymentsString(); } return "Unknown"; } bool CMasternodePayments::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { LOCK(cs_mapMasternodeBlocks); if (mapMasternodeBlocks.count(nBlockHeight)) { return mapMasternodeBlocks[nBlockHeight].IsTransactionValid(txNew); } return true; } void CMasternodePayments::CleanPaymentList() { LOCK2(cs_mapMasternodePayeeVotes, cs_mapMasternodeBlocks); int nHeight; { TRY_LOCK(cs_main, locked); if (!locked || chainActive.Tip() == NULL) return; nHeight = chainActive.Tip()->nHeight; } //keep up to five cycles for historical sake int nLimit = std::max(int(mnodeman.size() * 1.25), 1000); std::map<uint256, CMasternodePaymentWinner>::iterator it = mapMasternodePayeeVotes.begin(); while (it != mapMasternodePayeeVotes.end()) { CMasternodePaymentWinner winner = (*it).second; if (nHeight - winner.nBlockHeight > nLimit) { LogPrint("mnpayments", "CMasternodePayments::CleanPaymentList - Removing old Masternode payment - block %d\n", winner.nBlockHeight); maxnodeSync.mapSeenSyncMNW.erase((*it).first); mapMasternodePayeeVotes.erase(it++); mapMasternodeBlocks.erase(winner.nBlockHeight); } else { ++it; } } } bool CMasternodePaymentWinner::IsValid(CNode* pnode, std::string& strError) { CMasternode* pmn = mnodeman.Find(vinMasternode); if (!pmn) { strError = strprintf("Unknown Masternode %s", vinMasternode.prevout.hash.ToString()); LogPrint("maxnode","CMasternodePaymentWinner::IsValid - %s\n", strError); mnodeman.AskForMN(pnode, vinMasternode); return false; } if (pmn->protocolVersion < ActiveProtocol()) { strError = strprintf("Masternode protocol too old %d - req %d", pmn->protocolVersion, ActiveProtocol()); LogPrint("maxnode","CMasternodePaymentWinner::IsValid - %s\n", strError); return false; } int n = mnodeman.GetMasternodeRank(vinMasternode, nBlockHeight - 100, ActiveProtocol()); if (n > MNPAYMENTS_SIGNATURES_TOTAL) { //It's common to have maxnodes mistakenly think they are in the top 10 // We don't want to print all of these messages, or punish them unless they're way off if (n > MNPAYMENTS_SIGNATURES_TOTAL * 2) { strError = strprintf("Masternode not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL * 2, n); LogPrint("maxnode","CMasternodePaymentWinner::IsValid - %s\n", strError); //if (maxnodeSync.IsSynced()) Misbehaving(pnode->GetId(), 20); } return false; } return true; } bool CMasternodePayments::ProcessBlock(int nBlockHeight) { if (!fMasterNode) return false; //reference node - hybrid mode int n = mnodeman.GetMasternodeRank(activeMasternode.vin, nBlockHeight - 100, ActiveProtocol()); if (n == -1) { LogPrint("mnpayments", "CMasternodePayments::ProcessBlock - Unknown Masternode\n"); return false; } if (n > MNPAYMENTS_SIGNATURES_TOTAL) { LogPrint("mnpayments", "CMasternodePayments::ProcessBlock - Masternode not in the top %d (%d)\n", MNPAYMENTS_SIGNATURES_TOTAL, n); return false; } if (nBlockHeight <= nLastBlockHeight) return false; CMasternodePaymentWinner newWinner(activeMasternode.vin); if (budget.IsBudgetPaymentBlock(nBlockHeight)) { //is budget payment block -- handled by the budgeting software } else { LogPrint("maxnode","CMasternodePayments::ProcessBlock() Start nHeight %d - vin %s. \n", nBlockHeight, activeMasternode.vin.prevout.hash.ToString()); // pay to the oldest MN that still had no payment but its input is old enough and it was active long enough int nCount = 0; CMasternode* pmn = mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount); if (pmn != NULL) { LogPrint("maxnode","CMasternodePayments::ProcessBlock() Found by FindOldestNotInVec \n"); newWinner.nBlockHeight = nBlockHeight; CScript payee = GetScriptForDestination(pmn->pubKeyCollateralAddress.GetID()); newWinner.AddPayee(payee); CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrint("maxnode","CMasternodePayments::ProcessBlock() Winner payee %s nHeight %d. \n", address2.ToString().c_str(), newWinner.nBlockHeight); } else { LogPrint("maxnode","CMasternodePayments::ProcessBlock() Failed to find maxnode to pay\n"); } } std::string errorMessage; CPubKey pubKeyMasternode; CKey keyMasternode; if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { LogPrint("maxnode","CMasternodePayments::ProcessBlock() - Error upon calling SetKey: %s\n", errorMessage.c_str()); return false; } LogPrint("maxnode","CMasternodePayments::ProcessBlock() - Signing Winner\n"); if (newWinner.Sign(keyMasternode, pubKeyMasternode)) { LogPrint("maxnode","CMasternodePayments::ProcessBlock() - AddWinningMasternode\n"); if (AddWinningMasternode(newWinner)) { newWinner.Relay(); nLastBlockHeight = nBlockHeight; return true; } } return false; } void CMasternodePaymentWinner::Relay() { CInv inv(MSG_MASTERNODE_WINNER, GetHash()); RelayInv(inv); } bool CMasternodePaymentWinner::SignatureValid() { CMasternode* pmn = mnodeman.Find(vinMasternode); if (pmn != NULL) { std::string strMessage = vinMasternode.prevout.ToStringShort() + boost::lexical_cast<std::string>(nBlockHeight) + payee.ToString(); std::string errorMessage = ""; if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) { return error("CMasternodePaymentWinner::SignatureValid() - Got bad Masternode address signature %s\n", vinMasternode.prevout.hash.ToString()); } return true; } return false; } void CMasternodePayments::Sync(CNode* node, int nCountNeeded) { LOCK(cs_mapMasternodePayeeVotes); int nHeight; { TRY_LOCK(cs_main, locked); if (!locked || chainActive.Tip() == NULL) return; nHeight = chainActive.Tip()->nHeight; } int nCount = (mnodeman.CountEnabled() * 1.25); if (nCountNeeded > nCount) nCountNeeded = nCount; int nInvCount = 0; std::map<uint256, CMasternodePaymentWinner>::iterator it = mapMasternodePayeeVotes.begin(); while (it != mapMasternodePayeeVotes.end()) { CMasternodePaymentWinner winner = (*it).second; if (winner.nBlockHeight >= nHeight - nCountNeeded && winner.nBlockHeight <= nHeight + 20) { node->PushInventory(CInv(MSG_MASTERNODE_WINNER, winner.GetHash())); nInvCount++; } ++it; } node->PushMessage("ssc", MASTERNODE_SYNC_MNW, nInvCount); } std::string CMasternodePayments::ToString() const { std::ostringstream info; info << "Votes: " << (int)mapMasternodePayeeVotes.size() << ", Blocks: " << (int)mapMasternodeBlocks.size(); return info.str(); } int CMasternodePayments::GetOldestBlock() { LOCK(cs_mapMasternodeBlocks); int nOldestBlock = std::numeric_limits<int>::max(); std::map<int, CMasternodeBlockPayees>::iterator it = mapMasternodeBlocks.begin(); while (it != mapMasternodeBlocks.end()) { if ((*it).first < nOldestBlock) { nOldestBlock = (*it).first; } it++; } return nOldestBlock; } int CMasternodePayments::GetNewestBlock() { LOCK(cs_mapMasternodeBlocks); int nNewestBlock = 0; std::map<int, CMasternodeBlockPayees>::iterator it = mapMasternodeBlocks.begin(); while (it != mapMasternodeBlocks.end()) { if ((*it).first > nNewestBlock) { nNewestBlock = (*it).first; } it++; } return nNewestBlock; }
[ "faetos@yahoo.com" ]
faetos@yahoo.com
709d2a4ab9a43d491c40324ca41cdb4637e7a72f
2cff28468b2f463ae242ad9f8c2dbf47a94c47b6
/sia20_control/src/test3.cpp
df3d697f5da10470aa479137f2372964fac7227f
[]
no_license
harumo11/sia20
2e49890554d6b554a5603f0cb0d79012467296ad
8dbbac997701de4ddf486e62423582521130c0ef
refs/heads/master
2021-06-26T03:07:03.887460
2020-10-27T23:09:12
2020-10-27T23:09:12
160,215,058
3
2
null
null
null
null
UTF-8
C++
false
false
14,118
cpp
//このプログラムはdynetを使用して学習した箒の使用方法を実際に推測し,実行するための //プログラムです.学習済みモデルを読み込み,ニューラルネットを構築し //そこにリアルタイムで得たセンサーからの情報を入力として流し込み //出力として手先の速度を得ます.その後,ROSでその速度をpublishします. // //入力&出力は下記のURLを参照とのこと(レプトリノ含む) //https://harumo11.github.io/sia20/training_data/ #include <iostream> #include <algorithm> #include <fstream> #include <memory> #include <vector> #include <array> #include <eigen3/Eigen/Dense> #include <fanda/Csv.hpp> #include <dynet/io.h> #include <dynet/training.h> #include <dynet/expr.h> #include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <std_msgs/Float32MultiArray.h> #include <sensor_msgs/JointState.h> #include <moveit/move_group_interface/move_group_interface.h> #include <tf2/LinearMath/Matrix3x3.h> #include <tf2/LinearMath/Quaternion.h> #include <std_msgs/Float32MultiArray.h> #include <Gpop/Series.hpp> #include "cliping_leptorino.hpp" #include "average.hpp" void twist_zero_clear(geometry_msgs::Twist& msgs){ msgs.linear.x = 0; msgs.linear.y = 0; msgs.linear.z = 0; msgs.angular.x = 0; msgs.angular.y = 0; msgs.angular.z = 0; } class SensorListener { public: std_msgs::Float32MultiArray data; void call_back(const std_msgs::Float32MultiArray msgs){ this->data = msgs; } }; class PoseListener { public: geometry_msgs::Twist data; void call_back(const geometry_msgs::Twist msgs){ this->data = msgs; } }; std::vector<double> twist_to_vector(const geometry_msgs::Twist msgs){ std::vector<double> vec; //位置を挿入 vec.push_back(msgs.linear.x); vec.push_back(msgs.linear.y); vec.push_back(msgs.linear.z); //姿勢を挿入 vec.push_back(msgs.angular.x); vec.push_back(msgs.angular.y); vec.push_back(msgs.angular.z); return vec; } geometry_msgs::Twist pose_to_twist(const geometry_msgs::PoseStamped pose){ //Quaternionをrpyに変換 tf2::Quaternion quat(pose.pose.orientation.x, pose.pose.orientation.y, pose.pose.orientation.z, pose.pose.orientation.w); double r,p,w; tf2::Matrix3x3(quat).getRPY(r,p,w); //Twistに格納 geometry_msgs::Twist twist; twist.linear.x = pose.pose.position.x; twist.linear.y = pose.pose.position.y; twist.linear.z = pose.pose.position.z; twist.angular.x = r; twist.angular.y = p; twist.angular.z = w; return twist; } void update_hand_pose_arrays(std::array<std::array<double, 6>, 3> hand_pose_arrays, const geometry_msgs::PoseStamped current_pose){ // 最新の値を使えるように変換 auto latest_hand_pose_vector = twist_to_vector(pose_to_twist(current_pose)); // 1番めの配列を2番めに移す hand_pose_arrays.at(2) = hand_pose_arrays.at(1); // 0番目の配列を1番めに移す hand_pose_arrays.at(1) = hand_pose_arrays.at(0); // 最新の配列を0番目に入れる int count = 0; for (auto&& pose : hand_pose_arrays.at(0)){ pose = latest_hand_pose_vector.at(count); count++; } } int main(int argc, char* argv[]) { //ROS初期化 ros::init(argc, argv, "predict_node"); ros::NodeHandle node; ros::AsyncSpinner spinner(2); spinner.start(); //ros::Rate timer(40);// 以前成功したときは40を使用 ros::Rate timer(100); //リスナー宣言 PoseListener dirt_pose_listener; PoseListener broom_pose_listener; PoseListener goal_pose_listener; SensorListener sensor_listener; //サブスクライバー宣言 ros::Subscriber dirt_pose_subscriber = node.subscribe("/ar_dirt_pose", 1, &PoseListener::call_back, &dirt_pose_listener); ros::Subscriber broom_pose_subscriber = node.subscribe("/ar_broom_pose", 1, &PoseListener::call_back, &broom_pose_listener); ros::Subscriber goal_pose_subscriber = node.subscribe("/ar_goal_pose", 1, &PoseListener::call_back, &goal_pose_listener); ros::Subscriber leptorino_subscriber = node.subscribe("/sensor_data", 1, &SensorListener::call_back, &sensor_listener); //moveit初期化 moveit::planning_interface::MoveGroupInterface move_group("manipulator"); //全メッセージが到着するまで待つ ROS_INFO_STREAM("Waiting for dirt, goal, broom pose, and hand position."); ROS_INFO_STREAM("ar_dirt_pose message is searching"); ros::topic::waitForMessage<geometry_msgs::Twist>("ar_dirt_pose"); ROS_INFO_STREAM("ar_broom_pose message is searching"); ros::topic::waitForMessage<geometry_msgs::Twist>("ar_broom_pose"); ROS_INFO_STREAM("ar_goal_pose message is searching"); ros::topic::waitForMessage<geometry_msgs::Twist>("ar_goal_pose"); ROS_INFO_STREAM("joint_states message is searching"); ros::topic::waitForMessage<sensor_msgs::JointState>("joint_states"); ROS_INFO_STREAM("sensor_data message is searching"); ros::topic::waitForMessage<std_msgs::Float32MultiArray>("sensor_data"); ROS_INFO_STREAM("all message is found"); //パブリッシャー宣言 auto target_velocity_publisher = node.advertise<geometry_msgs::Twist>("pose_following/cmd_vel", 1); //dynet初期化 dynet::DynetParams params; params.weight_decay = 0; params.cpu_requested = true; dynet::initialize(params); //定数設定 const unsigned int INPUT_LAYER_DIMENSION = 37; //入力データの次元 const unsigned int HIDDEN_LAYER_DIMENSION = 20; //中間層の次元 const unsigned int OUTPUT_LAYER_DIMENSION = 6; //出力データの次元 //パラメータ作成(入力以外) dynet::ComputationGraph cg; dynet::ParameterCollection model; dynet::SimpleSGDTrainer trainer(model); ////L1 dynet::Parameter p_W1 = model.add_parameters({HIDDEN_LAYER_DIMENSION, INPUT_LAYER_DIMENSION}); dynet::Parameter p_b1 = model.add_parameters({HIDDEN_LAYER_DIMENSION}); ////L2 dynet::Parameter p_W2 = model.add_parameters({HIDDEN_LAYER_DIMENSION, HIDDEN_LAYER_DIMENSION}); dynet::Parameter p_b2 = model.add_parameters({HIDDEN_LAYER_DIMENSION}); /////L3 dynet::Parameter p_W3 = model.add_parameters({HIDDEN_LAYER_DIMENSION, HIDDEN_LAYER_DIMENSION}); dynet::Parameter p_b3 = model.add_parameters({HIDDEN_LAYER_DIMENSION}); /////L4 dynet::Parameter p_W4 = model.add_parameters({HIDDEN_LAYER_DIMENSION, HIDDEN_LAYER_DIMENSION}); dynet::Parameter p_b4 = model.add_parameters({HIDDEN_LAYER_DIMENSION}); /////L5 dynet::Parameter p_W5 = model.add_parameters({HIDDEN_LAYER_DIMENSION, HIDDEN_LAYER_DIMENSION}); dynet::Parameter p_b5 = model.add_parameters({HIDDEN_LAYER_DIMENSION}); ////L6 dynet::Parameter p_W6 = model.add_parameters({HIDDEN_LAYER_DIMENSION, HIDDEN_LAYER_DIMENSION}); dynet::Parameter p_b6 = model.add_parameters({HIDDEN_LAYER_DIMENSION}); ////L7 dynet::Parameter p_W7 = model.add_parameters({HIDDEN_LAYER_DIMENSION, HIDDEN_LAYER_DIMENSION}); dynet::Parameter p_b7 = model.add_parameters({HIDDEN_LAYER_DIMENSION}); ////L8 dynet::Parameter p_W8 = model.add_parameters({OUTPUT_LAYER_DIMENSION, HIDDEN_LAYER_DIMENSION}); dynet::Parameter p_b8 = model.add_parameters({OUTPUT_LAYER_DIMENSION}); //ノード作成 dynet::Expression W1 = dynet::parameter(cg, p_W1); dynet::Expression W2 = dynet::parameter(cg, p_W2); dynet::Expression W3 = dynet::parameter(cg, p_W3); dynet::Expression W4 = dynet::parameter(cg, p_W4); dynet::Expression W5 = dynet::parameter(cg, p_W5); dynet::Expression W6 = dynet::parameter(cg, p_W6); dynet::Expression W7 = dynet::parameter(cg, p_W7); dynet::Expression W8 = dynet::parameter(cg, p_W8); dynet::Expression b1 = dynet::parameter(cg, p_b1); dynet::Expression b2 = dynet::parameter(cg, p_b2); dynet::Expression b3 = dynet::parameter(cg, p_b3); dynet::Expression b4 = dynet::parameter(cg, p_b4); dynet::Expression b5 = dynet::parameter(cg, p_b5); dynet::Expression b6 = dynet::parameter(cg, p_b6); dynet::Expression b7 = dynet::parameter(cg, p_b7); dynet::Expression b8 = dynet::parameter(cg, p_b8); //入出力設定 auto x_value_ptr = std::make_shared<std::vector<dynet::real>>(); //センサデータののポインタ(入力) ////ノード作成 dynet::Expression x = dynet::input(cg, {INPUT_LAYER_DIMENSION}, x_value_ptr.get()); //computation graphの構築 dynet::Expression z1 = dynet::rectify(W1*x + b1); dynet::Expression z2 = dynet::rectify(W2*z1 + b2); dynet::Expression z3 = dynet::rectify(W3*z2 + b3); dynet::Expression z4 = dynet::rectify(W4*z3 + b4); dynet::Expression z5 = dynet::rectify(W5*z4 + b5); dynet::Expression z6 = dynet::rectify(W6*z5 + b6); dynet::Expression z7 = dynet::rectify(W7*z6 + b7); dynet::Expression y_pred = W8*z7 + b8; //パラメータを読み出し //dynet::TextFileLoader loader("/home/robot/program/cpp/sia20_learning/build/cliped_train_m2_w0.model"); dynet::TextFileLoader loader("/home/robot/program/cpp/sia20_learning/build/cliped_train_m2_w0_demo_30.model"); //dynet::TextFileLoader loader("/home/robot/program/cpp/sia20_learning/model/cliped_train_m2_w0.model"); loader.populate(model); //computation graphを描画 //std::cout << "=============================================" << std::endl; //cg.print_graphviz(); //std::cout << "=============================================" << std::endl; // 推測データ表示用のプロット Gpop::Series lin_x_plot("linear x"); Gpop::Series lin_y_plot("linear y"); Gpop::Series lin_z_plot("linear z"); lin_x_plot.limit_max_number(500); lin_x_plot.set_y_range(-0.01, 0.03); lin_x_plot.set_y_label("m/s"); lin_y_plot.limit_max_number(500); lin_y_plot.set_y_range(0, 0.03); lin_y_plot.set_y_label("m/s"); lin_z_plot.limit_max_number(500); lin_z_plot.set_y_range(-0.03, 0); lin_z_plot.set_y_label("m/s"); //ROS_INFO_STREAM("Press any key"); //std::cin.get(); int iter = 0; // hand_pose_arrays which contains hand_pose (t, t-1, t-2) std::array<std::array<double, 6>, 3> hand_pose_arrays; // hand_pose_arrays initialize auto current_hand_pose = move_group.getCurrentPose(); for (auto iter = std::rbegin(hand_pose_arrays); iter != std::rend(hand_pose_arrays); iter++){ auto hand_pose_vector = twist_to_vector(pose_to_twist(move_group.getCurrentPose())); int counter = 0; for (auto&& e : *iter){ e = hand_pose_vector.at(counter); counter++; } ros::Duration(0.01).sleep(); } //motomanのエラー回避のためここで速度0のコマンドを数回送る geometry_msgs::Twist initial_cmd_vel; twist_zero_clear(initial_cmd_vel); ROS_WARN_STREAM("starting to publish initial cmd_vel"); for (int i = 0; i < 100; i++) { target_velocity_publisher.publish(initial_cmd_vel); ros::Duration(0.01).sleep(); } ROS_WARN_STREAM("finishing to publish initial cmd_vel"); // 5点平均作成用のクラス Average ave_x(10); Average ave_y(10); Average ave_z(10); while (ros::ok()) { //センサデータ更新 ros::spinOnce(); //センサデータ受け取り(dirt, goal, broomの順に結合) std::vector<double> dirt_pose_vector = twist_to_vector(dirt_pose_listener.data); std::vector<double> goal_pose_vector = twist_to_vector(goal_pose_listener.data); std::vector<double> broom_pose_vector = twist_to_vector(broom_pose_listener.data); std::vector<double> hand_pose_vector = twist_to_vector(pose_to_twist(move_group.getCurrentPose())); double Li = sensor_listener.data.data.at(0); double leptorino_datum = leptorino::cliping(Li); // クリッピング // update hand_pose_arrays at here update_hand_pose_arrays(hand_pose_arrays, move_group.getCurrentPose()); // 入力ベクトルを空にする x_value_ptr->clear(); //受け取ったデータをベクトルx_value_ptrに格納 // end effector position t x_value_ptr->insert(x_value_ptr->end(), hand_pose_arrays.at(0).begin(), hand_pose_arrays.at(0).end()); // end effector position t-1 x_value_ptr->insert(x_value_ptr->end(), hand_pose_arrays.at(1).begin(), hand_pose_arrays.at(1).end()); // end effector position t-2 x_value_ptr->insert(x_value_ptr->end(), hand_pose_arrays.at(2).begin(), hand_pose_arrays.at(2).end()); // candy position x_value_ptr->insert(x_value_ptr->end(), dirt_pose_vector.begin(), dirt_pose_vector.begin()+6); // broom position x_value_ptr->insert(x_value_ptr->end(), broom_pose_vector.begin(), broom_pose_vector.begin()+6); // dustpan position x_value_ptr->insert(x_value_ptr->end(), goal_pose_vector.begin(), goal_pose_vector.begin()+6); // leptorino x_value_ptr->push_back(leptorino_datum); std::cout << "|||x value ptr size : " << x_value_ptr->size() << std::endl; if (x_value_ptr->size() != 37) { std::cerr << "x_value input has invalid dimension. exit()" << std::endl; std::exit(1); } for (int i = 0; i < x_value_ptr->size(); i++) { std::cout << "||| input x vector " << x_value_ptr->at(i) << " , "; } std::cout << std::endl; //推測を実行し,cmd_velを得る cg.forward(y_pred); std::vector<dynet::real> cmd_vel = dynet::as_vector(y_pred.value()); std::cout << "||| (x,y,z) = " << cmd_vel.at(0) << " , " << cmd_vel.at(1) << " , " << cmd_vel.at(2) << " (r,p,w) = " << cmd_vel.at(3) << " , " << cmd_vel.at(4) << " , " << cmd_vel.at(5) << std::endl; //推測したcmd_velを送る geometry_msgs::Twist cmd_vel_msgs; cmd_vel_msgs.linear.x = cmd_vel.at(0); cmd_vel_msgs.linear.y = cmd_vel.at(1); //もし,現在の手先座標が0.8以下だったらdz=0とする auto current_pose = move_group.getCurrentPose(); if (current_pose.pose.position.z <= 0.83) { cmd_vel_msgs.linear.z = 0.0; } else { cmd_vel_msgs.linear.z = cmd_vel.at(2); } cmd_vel_msgs.angular.x = cmd_vel.at(3); cmd_vel_msgs.angular.y = cmd_vel.at(4); cmd_vel_msgs.angular.z = cmd_vel.at(5); target_velocity_publisher.publish(cmd_vel_msgs); ROS_INFO_STREAM(cmd_vel_msgs); lin_x_plot.plot(cmd_vel.at(0)); lin_x_plot.plot(ave_x.get_average(cmd_vel.at(0))); lin_y_plot.plot(cmd_vel.at(1)); lin_y_plot.plot(ave_y.get_average(cmd_vel.at(1))); lin_z_plot.plot(cmd_vel.at(2)); lin_z_plot.plot(ave_z.get_average(cmd_vel.at(2))); lin_x_plot.pause(); lin_y_plot.pause(); lin_z_plot.pause(); ROS_INFO_STREAM("Publish Once"); timer.sleep(); } return 0; }
[ "s_harumo@hotmail.co.jp" ]
s_harumo@hotmail.co.jp
7ac2107457925504bc951c73fca455124153b5a3
eb46dbb888d661f8577da2ef3fdc744ffac1e5e4
/modules/gapi/opencv_test_gapi_pch.cpp
1200bcc902ae757b641c1b56e9043025f4dd710a
[]
no_license
gzhangx/opencv.builds
251d692767285d2dd9a84e934618fa348417a9fe
760936d44450a6660efb750cf8ad5726c33a4504
refs/heads/master
2023-08-03T09:46:02.559701
2021-09-17T22:19:37
2021-09-17T22:19:37
406,840,538
0
0
null
null
null
null
UTF-8
C++
false
false
67
cpp
#include "D:/work/acccn/opencv/modules/gapi/test/test_precomp.hpp"
[ "gzhangx@hotmail.com" ]
gzhangx@hotmail.com
5c5349eb3ad003606429df2a5261fa6b3e03add9
0c7e20a002108d636517b2f0cde6de9019fdf8c4
/Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/graphics/CAtlasEntry.cpp
0607b087d0bb881851fa73401db5ece4e085a4e9
[ "Apache-2.0" ]
permissive
kernal88/Elastos5
022774d8c42aea597e6f8ee14e80e8e31758f950
871044110de52fcccfbd6fd0d9c24feefeb6dea0
refs/heads/master
2021-01-12T15:23:52.242654
2016-10-24T08:20:15
2016-10-24T08:20:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,085
cpp
#include "elastos/droid/graphics/CAtlasEntry.h" namespace Elastos { namespace Droid { namespace Graphics { CAR_OBJECT_IMPL(CAtlasEntry) CAR_INTERFACE_IMPL(CAtlasEntry, Object, IAtlasEntry) CAtlasEntry::CAtlasEntry() : mX(0) , mY(0) , mRotated(FALSE) {} ECode CAtlasEntry::constructor() { return NOERROR; } ECode CAtlasEntry::SetX( /* [in] */ Int32 value) { mX = value; return NOERROR; } ECode CAtlasEntry::GetX( /* [out] */ Int32* value) { VALIDATE_NOT_NULL(value) *value = mX; return NOERROR; } ECode CAtlasEntry::SetY( /* [in] */ Int32 value) { mY = value; return NOERROR; } ECode CAtlasEntry::GetY( /* [out] */ Int32* value) { VALIDATE_NOT_NULL(value) *value = mY; return NOERROR; } ECode CAtlasEntry::SetRotated( /* [in] */ Boolean value) { mRotated = value; return NOERROR; } ECode CAtlasEntry::GetRotated( /* [out] */ Boolean* value) { VALIDATE_NOT_NULL(value) *value = mRotated; return NOERROR; } } // namespace Graphics } // namepsace Droid } // namespace Elastos
[ "luo.zhaohui@kortide.com" ]
luo.zhaohui@kortide.com
64773e2f0be7a01900744ef57adec5b6c816ebf3
06b542327f232e4d88dc2e79eb5b11675a4d12e4
/hoomd/md/EvaluatorPairZBL.h
41fcf0a74f4e6425353d16124a6f7bfefab8c15d
[ "BSD-3-Clause" ]
permissive
turalaksel/hoomd-blue
d0ed754b6fe7d0d2f808ba667f8c13b93c89f8e3
1286779b1b17adfa7d773f79a0f81118f1662638
refs/heads/master
2021-04-02T10:47:48.047279
2018-03-19T23:28:48
2018-03-19T23:28:48
124,343,898
0
1
null
2018-03-08T05:55:11
2018-03-08T05:55:11
null
UTF-8
C++
false
false
4,959
h
// Copyright (c) 2009-2017 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. #ifndef __PAIR_EVALUATOR_ZBL__ #define __PAIR_EVALUATOR_ZBL__ #ifndef NVCC #include <string> #endif #include "hoomd/HOOMDMath.h" /*! \file EvaluatorPairZBL.h \brief Defines the pair evaluator class for ZBL potentials */ // need to declare these class methods with __device__ qualifiers when building in nvcc #ifdef NVCC #define DEVICE __device__ #else #define DEVICE #endif //! Class for evaluating the ZBL pair potential. /*! EvaluatorPairZBL evaluates the function \f{eqnarray*} V_{\mathrm{ZBL}}(r) = & \frac{Z_i Z_j e^2}{4 \pi \epsilon_0 r_{ij}} \left[ 0.1818 \exp \left( -3.2 \frac{r_{ij}}{a_F} \right) + 0.5099 \exp \left( -0.9423 \frac{r_{ij}}{a_F} \right) + 0.2802 \exp \left( -0.4029 \frac{r_{ij}}{a_F} \right) + 0.02817 \exp \left( -0.2016 \frac{r_{ij}}{a_F} \right) \right], & r < r_{\mathrm{cut}} \\ = & 0, & r > r_{\mathrm{cut}} \\ \f} where \f[ a_F = \frac{0.8853 a_0}{ \left( Z_i^{0.23} + Z_j^{0.23} \right) } \f] and \a a_0 is the Bohr radius and \a Z_x denotes the atomic number of species \a x. */ class EvaluatorPairZBL { public: //! Define the parameter type used by this pair potential evaluator typedef Scalar2 param_type; //! Constructs the pair potential evaluator /*! \param _rsq Squared distance between the particles. \param _rcutsq Squared distance at which the potential goes to zero. \param _params Per type-pair parameters of this potential */ DEVICE EvaluatorPairZBL(Scalar _rsq, Scalar _rcutsq, const param_type& _params) : rsq(_rsq), rcutsq(_rcutsq), Zsq(_params.x), aF(_params.y) { } //! ZBL potential does not use particle diameters. DEVICE static bool needsDiameter() { return false; } //! Accept the optional diameter values /*! \param di Diameter of particle i \param dj Diameter of particle j */ DEVICE void setDiameter(Scalar di, Scalar dj) { } //! ZBL potential does not use particle charges DEVICE static bool needsCharge() { return false; } //! Accept the optional charge values /*! \param qi Charge of particle i \param qj Charge of particle j */ DEVICE void setCharge(Scalar qi, Scalar qj) { } //! Evaluate the force and energy. /*! \param force_divr Output parameter to write the computed force divided by r \param pair_eng Output parameter to write the computed pair energy \param energy_shift If true, the potential must be shifted so that V(r) is continuous at the cutoff \return True if they are evaluated or false if they are not because we are beyond the cutoff */ DEVICE bool evalForceAndEnergy(Scalar& force_divr, Scalar& pair_eng, bool energy_shift) { // compute the force divided by r in force_divr if (rsq < rcutsq && Zsq != 0 && aF != 0) { Scalar r2inv = Scalar(1.0) / rsq; Scalar rinv = fast::rsqrt(rsq); // precalculate the exponential terms Scalar exp1 = Scalar(0.1818) * fast::exp( Scalar(-3.2) / aF / rinv ); Scalar exp2 = Scalar(0.5099) * fast::exp( Scalar(-0.9423) / aF / rinv ); Scalar exp3 = Scalar(0.2802) * fast::exp( Scalar(-0.4029) / aF / rinv ); Scalar exp4 = Scalar(0.02817) * fast::exp( Scalar(-0.2016) / aF / rinv ); // evaluate the force force_divr = rinv * ( exp1 + exp2 + exp3 + exp4 ); force_divr += Scalar(1.0) / aF * ( Scalar(3.2) * exp1 \ + Scalar(0.9423) * exp2 + Scalar(0.4029) * exp3 \ + Scalar(0.2016) * exp4 ); force_divr *= Zsq * r2inv; // evaluate the pair energy pair_eng = Zsq * rinv * ( exp1 + exp2 + exp3 + exp4 ); return true; } else return false; } #ifndef NVCC //! Get the name of this potential /*! \returns The potential name. Must be short and all lowercase, as this is the name energies will be logged as via analyze.log. */ static std::string getName() { return std::string("zbl"); } #endif protected: Scalar rsq; //!< Stored rsq from the constructor Scalar rcutsq; //!< Stored rcutsq from the constructor Scalar Zsq; //!< Zsq parameter extracted from the params passed to the constructor Scalar aF; //!< aF parameter extracted from the params passed to the constructor }; #endif // __PAIR_EVALUATOR_ZBL__
[ "joaander@umich.edu" ]
joaander@umich.edu
d91302cec4c4563a3f7fae46104786ccf40dd79a
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5648941810974720_1/C++/Gaabs/a.cpp
c057fab95ead6fed65ae76022439542d85e8076b
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
2,413
cpp
#include <bits/stdc++.h> using namespace std; #define fr(i,a,b) for(int i = a; i < b; i++) #define fre(i,a,b) for(int i = a; i <= b; i++) #define frd(i,a,b) for(int i = a; i > b; i--) #define fred(i,a,b) for(int i = a; i >= b; i--) #define pb push_back #define SET(a,v) memset(a,v,sizeof a) #define INF 1e8 #define N 2010 typedef long long ll; typedef pair<int,int> ii; int t,len; int cnt[500]; int dig[10]; char str[N]; /* (S)EVEN FI(V)E T(H)REE T(W)O (T)EN FOU(R) (O)NE (N)INE */ void solve(){ SET(cnt,0); SET(dig,0); fr(i,0,len) cnt[str[i]]++; int temp; //(Z)ERO if (cnt['Z']){ temp = cnt['Z']; dig[0] += temp; cnt['Z'] -= temp; cnt['E'] -= temp; cnt['R'] -= temp; cnt['O'] -= temp; } //SI(X) if (cnt['X']){ temp = cnt['X']; dig[6] += temp; cnt['S'] -= temp; cnt['I'] -= temp; cnt['X'] -= temp; } //EI(G)HT if (cnt['G']){ temp = cnt['G']; dig[8] += temp; cnt['E'] -= temp; cnt['I'] -= temp; cnt['G'] -= temp; cnt['H'] -= temp; cnt['T'] -= temp; } //(S)EVEN if (cnt['S']){ temp = cnt['S']; dig[7] += temp; cnt['S'] -= temp; cnt['E'] -= temp; cnt['V'] -= temp; cnt['E'] -= temp; cnt['N'] -= temp; } //FI(V)E if (cnt['V']){ temp = cnt['V']; dig[5] += temp; cnt['F'] -= temp; cnt['I'] -= temp; cnt['V'] -= temp; cnt['E'] -= temp; } //T(H)REE if (cnt['H']){ temp = cnt['H']; dig[3] += temp; cnt['T'] -= temp; cnt['H'] -= temp; cnt['R'] -= temp; cnt['E'] -= temp; cnt['E'] -= temp; } //T(W)O if (cnt['W']){ temp = cnt['W']; dig[2] += temp; cnt['T'] -= temp; cnt['W'] -= temp; cnt['O'] -= temp; } //FOU(R) if (cnt['R']){ temp = cnt['R']; dig[4] += temp; cnt['F'] -= temp; cnt['O'] -= temp; cnt['U'] -= temp; cnt['R'] -= temp; } //(O)NE if (cnt['O']){ temp = cnt['O']; dig[1] += temp; cnt['O'] -= temp; cnt['N'] -= temp; cnt['E'] -= temp; } //N(I)NE if (cnt['I']){ temp = cnt['I']; dig[9] += temp; cnt['N'] -= temp; cnt['I'] -= temp; cnt['N'] -= temp; cnt['E'] -= temp; } } int main(){ scanf("%d",&t); fr(t2,0,t){ printf("Case #%d: ",t2+1); scanf("%s",str); len = strlen(str); solve(); fr(i,0,10){ fr(j,0,dig[i]) printf("%d",i); } puts(""); } return 0; }
[ "alexandra1.back@gmail.com" ]
alexandra1.back@gmail.com
40977f3d5e25f555be9d587ffea12e47077827af
cb8c337a790b62905ad3b30f7891a4dff0ae7b6d
/st-ericsson/multimedia/audio/noise_reduction/proxy/NoiseReductionNmfHost_PcmProcessing.h
75ff30399effbb8080b23956b039759fdb82028f
[]
no_license
CustomROMs/android_vendor
67a2a096bfaa805d47e7d72b0c7a0d7e4830fa31
295e660547846f90ac7ebe42a952e613dbe1b2c3
refs/heads/master
2020-04-27T15:01:52.612258
2019-03-11T13:26:23
2019-03-12T11:23:02
174,429,381
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,846
h
/*****************************************************************************/ /** * © ST-Ericsson, 2011 - All rights reserved * Reproduction and Communication of this document is strictly prohibited * unless specifically authorized in writing by ST-Ericsson * * \brief Noise Reduction Host nmf processing class header * \author ST-Ericsson */ /*****************************************************************************/ #ifndef _NOISE_REDUCTION_NMF_HOST_PCM_PROCESSING_H_ #define _NOISE_REDUCTION_NMF_HOST_PCM_PROCESSING_H_ #include "AFMNmfHost_PcmProcessing.h" #include "noise_reduction/nmfil/host/effect/configure.hpp" #include "noise_reduction/nmfil/host/effectWrapped.hpp" /** * Class that manages the Noise Reduction NMF component for the host CPU. */ class NoiseReductionNmfHost_PcmProcessing: public AFMNmfHost_PcmProcessing { public: NoiseReductionNmfHost_PcmProcessing(ENS_Component &enscomp) : AFMNmfHost_PcmProcessing(enscomp) {} virtual OMX_ERRORTYPE construct(void); virtual OMX_ERRORTYPE destroy(void); /** * Apply config to the NMF component. * * Called as a consequence of a setConfig call to the component. */ virtual OMX_ERRORTYPE applyConfig( OMX_INDEXTYPE config_index, OMX_PTR component_config_structure_p); protected: virtual OMX_ERRORTYPE instantiateAlgo(void); virtual OMX_ERRORTYPE startAlgo(void); virtual OMX_ERRORTYPE stopAlgo(void); virtual OMX_ERRORTYPE configureAlgo(void); virtual OMX_ERRORTYPE deInstantiateAlgo(void); virtual OMX_U32 nbBitPerSampleProcessed() { return 16; } private: void apply_settings(); // ejohsan FIXME! Inoise_reduction_nmfil_host_effect_configure mIConfig; }; #endif // _NOISE_REDUCTION_NMF_HOST_PCM_PROCESSING_H_
[ "xiangxin19960319@gmail.com" ]
xiangxin19960319@gmail.com
d8e3d9ebf6cbc91da39e0c13b444372b46ebf359
d68814db6fb3a3906efaa87e70a70d08cdefc6e2
/rotary_encoder_reader/rotary_encoder_reader.ino
9fc1fa9ab23b5dedf9cbaac3a0b1368e2ac744c3
[]
no_license
CML-lab/ARDUINO_RotaryChair
2b33229a0ae58e49ea4945b3156b70f6c51f2c13
2745fcba912a284d66850e5c17ba047b110dbd2a
refs/heads/master
2023-03-03T05:57:13.333283
2021-02-16T16:02:09
2021-02-16T16:02:09
337,789,590
0
0
null
null
null
null
UTF-8
C++
false
false
7,536
ino
/* Read optical incremental rotary encoder output. This code was modified from https://gist.github.com/kinverarity1/8ca395b85bb63e1e7471d7db0284c30b Serial output columns: 1. Absolute encoder position (pulses, integer) from startup 2. Change in encoder position from trial start (pulses, integer) 3. Encoder position at trial start (degrees, float) 4. Change in motor shaft position (degrees, float) 5. Time since trial start in (microseconds, integer) 6. Motor Shaft Speed (degrees per second, float) This code tracks absolute position of the chair in pulses from the time of startup, and converts that to relative position and velocity in degrees based on the current position and time at the start of each trial. volatile directive is used for variables that are modified in the interrupt service routines. */ // Pin definitions. // - enc_a is ENC Signal A line (Arduino digital pin 2) // - enc_b is ENC Signal B line (Arduino digital pin 3) #define ENC_A 2 #define ENC_B 3 #define triggerPinRE 12 //trigger/enable line from the motor driver Arduino // #define trialcountpin 13 //this pin will change state every X trials to help us keep count // Main loop refresh period. #define REFRESH_MS 50 // Main serial data connection to computer. #define BAUD_RATE 115200 // Encoder signal line states volatile boolean state_a = 0; volatile boolean state_b = 0; // Encoder position volatile int enc_pos = 0; int enc_pos_prev = 0; int enc_pos_change = 0; int enc_pos_trialstart = 0; float abs_pos_degrees = 0; float rel_pos_degrees = 0; float rel_pos_prev = 0; float rel_pos_change = 0; float abs_pos_trialstart = 0; float REratio = (200.0 / 268.7); //ratio of circumference of rotary encoder wheel to motor shaft //the rotary encoder has a 200 mm circumference float REppr = 1000.0; //the rotary encoder has 1000 pulses/revolution // Timing unsigned long micros_current = 0; unsigned long micros_prev = 0; unsigned long micros_trialstart = 0; long micros_change = 0; // keep track of enable signal int readEnable = LOW; int readPriorState = LOW; int trial = 0; // note that rather than send the trial number over (which will take ~8 pins), we will just count enables //keep track of whether we are actively printing the encoder output or not bool REenabled; bool REhold; unsigned long REholdstime; unsigned long REholdctime; long REholdetime; void setup() { pinMode(ENC_A, INPUT); pinMode(ENC_B, INPUT); pinMode(triggerPinRE, INPUT); state_a = (boolean) digitalRead(ENC_A); state_b = (boolean) digitalRead(ENC_B); readEnable = digitalRead(triggerPinRE); attachInterrupt(0, interrupt_enc_a, CHANGE); attachInterrupt(1, interrupt_enc_b, CHANGE); micros_prev = micros(); micros_trialstart = micros(); rel_pos_degrees = 0; abs_pos_trialstart = abs_pos_degrees; enc_pos_trialstart = enc_pos; rel_pos_prev = 0; rel_pos_change = 0; Serial.begin(BAUD_RATE); Serial.println("Ready to begin recording."); REenabled = 0; } void loop() { int n; float bounded_trialstart; unsigned long etime; readEnable = digitalRead(triggerPinRE); if (readPriorState == LOW && readEnable == HIGH) // if the enable signal just went high (START RECORDING) { //reset trial-based tracking variables back to 0 rel_pos_degrees = 0; abs_pos_trialstart = abs_pos_degrees; enc_pos_trialstart = enc_pos; rel_pos_prev = 0; rel_pos_change = 0; // Timing micros_trialstart = micros(); etime = 0; //enable updates REenabled = true; REhold = false; trial = trial + 1; Serial.print("\n"); Serial.print("<-*-*- TRIAL "); Serial.print(trial); Serial.println(" -*-*->"); readPriorState = readEnable; } else if (readPriorState == HIGH && readEnable == LOW) // if the enable signal just went low (STOP RECORDING) { //REenabled = false; // stop updating the position information REhold = true; REholdstime = micros(); //start a timer to delay when recordin shuts off readPriorState = readEnable; // stop } else if (REhold) { REholdctime = micros(); if (REholdctime < REholdstime) { REholdetime = REholdctime + (4294967295 - REholdstime); } else { REholdetime = REholdctime - REholdstime; } if (REholdetime > 1000000) //the timer has expired, stop recording { REhold = false; REenabled = false; // stop updating the position information } } //REenabled = 1; // Calculate change in encoder position. //enc_pos_change = enc_pos - enc_pos_prev; //enc_pos_change = abs(enc_pos_change); //abs_pos_degrees = enc_pos * .00074074 * 360; //(1/1350) abs_pos_degrees = -1 * enc_pos * (360.0 / REppr) * REratio; // number of pulses * (deg/pulse) * (motor rotation / encoder rotation) if (REenabled) { // Calculate elapsed time micros_current = micros(); if (micros_current < micros_prev) { micros_change = micros_current + (4294967295 - micros_prev); } else { micros_change = micros_current - micros_prev; } //calculate elapsed time since trial start if (micros_current < micros_trialstart) { etime = micros_current + (4294967295 - micros_trialstart); } else { etime = micros_current - micros_trialstart; } //calculate the relative position change (pulses) since trial start enc_pos_change = enc_pos - enc_pos_trialstart; // Calculate relative position change (degrees) since trial start rel_pos_degrees = abs_pos_degrees - abs_pos_trialstart; // this is bounded to [-360 360] by the motor_driver code rel_pos_change = abs(rel_pos_degrees - rel_pos_prev); //compute bounded absolute position at trial start if (abs_pos_trialstart >= 0) { n = floor(abs_pos_trialstart / 360); bounded_trialstart = abs_pos_trialstart - 360 * n; } else if (abs_pos_trialstart < 0) { n = floor(-abs_pos_trialstart / 360); bounded_trialstart = (360 + abs_pos_trialstart + (360 * n)); } // Emit data Serial.print(enc_pos); Serial.print("\t"); Serial.print(enc_pos_change); Serial.print("\t"); Serial.print(bounded_trialstart, 3); Serial.print("\t"); Serial.print(rel_pos_degrees, 3); Serial.print("\t"); Serial.print(etime); Serial.print("\t"); Serial.print(rel_pos_change / (micros_change / 1e6), 3); //Serial.print(enc_pos); //Serial.print("\t"); //Serial.print(enc_pos_change); //Serial.print("\t"); //Serial.print(micros_current); //Serial.print("\t"); //Serial.print(micros_change); //Serial.print("\t"); //Serial.print(enc_pos_change / (micros_change / 1e6)); Serial.print("\n"); micros_prev = micros_current; rel_pos_prev = rel_pos_degrees; } //enc_pos_prev = enc_pos; delay(REFRESH_MS); } // Detect pulses from depth encoder. void interrupt_enc_a() { if (!state_a) { state_b ? enc_pos++ : enc_pos--; } state_a = !state_a; } void interrupt_enc_b() { state_b = !state_b; }
[ "cognitivemotorlab@gmail.com" ]
cognitivemotorlab@gmail.com
6534ff4f71a3c5b65e099651b14def406d1c55b9
5df7293b4a7d7f3cf4e4d25921e252ac92c21b5f
/onnxruntime/core/providers/qnn/builder/opbuilder/conv_op_builder.cc
1f4d61f472a4e70cd4b0b08369ce70df97db2b36
[ "MIT" ]
permissive
Nifury/onnxruntime
ccd7fed07ad917fb3b63ae333c388895073f9263
198994d01d4e226fd3a8816e8b2fad00c84a691c
refs/heads/main
2023-04-08T21:40:39.383881
2023-04-05T00:34:13
2023-04-05T00:34:13
312,125,003
7
2
MIT
2020-11-12T00:28:40
2020-11-12T00:28:39
null
UTF-8
C++
false
false
21,075
cc
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/providers/common.h" #include "core/providers/shared/utils/utils.h" #include "core/framework/tensorprotoutils.h" #include "core/providers/qnn/builder/qnn_model_wrapper.h" #include "core/providers/qnn/builder/op_builder_factory.h" #include "core/common/safeint.h" #include "core/providers/qnn/builder/qnn_utils.h" #include "base_op_builder.h" namespace onnxruntime { namespace qnn { class ConvOpBuilder : public BaseOpBuilder { public: ConvOpBuilder() : BaseOpBuilder("ConvOpBuilder") {} ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(ConvOpBuilder); Status IsOpSupported(QnnModelWrapper& qnn_model_wrapper, const NodeUnit& node_unit, const logging::Logger& logger, bool is_quantized_model) const override final ORT_MUST_USE_RESULT; protected: Status ProcessInputs(QnnModelWrapper& qnn_model_wrapper, const NodeUnit& node_unit, const logging::Logger& logger, bool is_quantized_model, std::vector<std::string>& input_names, bool do_op_validation) const override ORT_MUST_USE_RESULT; Status ProcessAttributesAndOutputs(QnnModelWrapper& qnn_model_wrapper, const NodeUnit& node_unit, std::vector<std::string>&& input_names, const logging::Logger& logger, bool is_quantized_model, bool do_op_validation) const override ORT_MUST_USE_RESULT; private: Status GetInputChannelNumber(QnnModelWrapper& qnn_model_wrapper, const NodeUnit& node_unit, uint32_t& input_channel_number) const; Status AddDefaultBias(QnnModelWrapper& qnn_model_wrapper, const uint32_t weight_m, const std::string& node_name, const bool is_quantized_model, const logging::Logger& logger, std::vector<std::string>& input_names) const; }; // Conv, ConvTranspose ops are sensitive with data layout, no special validation so far // The nodes from 1st call of GetCapability do not get layout transformer applied, it's still NCHW // The nodes from 2nd call of GetCapability get layout transformer applied, it's NHWC // Need to do op validation in 1st call of GetCapability // TODO: Check if node domain == kMSInternalNHWCDomain to determine if the layout has been transformed. Status ConvOpBuilder::IsOpSupported(QnnModelWrapper& qnn_model_wrapper, const NodeUnit& node_unit, const logging::Logger& logger, bool is_quantized_model) const { ORT_UNUSED_PARAMETER(qnn_model_wrapper); ORT_UNUSED_PARAMETER(node_unit); ORT_UNUSED_PARAMETER(logger); ORT_UNUSED_PARAMETER(is_quantized_model); auto input_0 = node_unit.Inputs()[0]; std::vector<uint32_t> input_shape; ORT_RETURN_IF_NOT(qnn_model_wrapper.GetOnnxShape(input_0.node_arg, input_shape), "Cannot get shape"); if (input_shape.size() != 4) { return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "QNN Conv only support 2D!"); } return Status::OK(); } Status ConvOpBuilder::GetInputChannelNumber(QnnModelWrapper& qnn_model_wrapper, const NodeUnit& node_unit, uint32_t& input_channel_number) const { auto input_0 = node_unit.Inputs()[0]; input_channel_number = 0; std::vector<uint32_t> input_shape; ORT_RETURN_IF_NOT(qnn_model_wrapper.GetOnnxShape(input_0.node_arg, input_shape), "Cannot get shape"); // Conv input 0 is NHWC layout now, get the channel data from input_shape[3] input_channel_number = input_shape.at(3); return Status::OK(); } // TODO: bias is not required in QNN, but it failed for some case if remove this. That case has Weight as dynamic input // e.g. the Conv node test in Onnx repo like test_conv_with_autopad_same. Could be QNN issue, Still need to dig out more Status ConvOpBuilder::AddDefaultBias(QnnModelWrapper& qnn_model_wrapper, const uint32_t weight_m, const std::string& node_name, const bool is_quantized_model, const logging::Logger& logger, std::vector<std::string>& input_names) const { std::vector<uint32_t> bias_shape(1, weight_m); std::string bias_name = node_name + "_bias"; Qnn_DataType_t qnn_data_type = is_quantized_model ? QNN_DATATYPE_SFIXED_POINT_32 : QNN_DATATYPE_FLOAT_32; uint32_t data_size = weight_m * static_cast<uint32_t>(utils::GetElementSizeByType(qnn_data_type)); std::vector<uint8_t> default_bias_data(data_size, 0); LOGS(logger, VERBOSE) << "Add default bias: " << bias_name; Qnn_TensorType_t tensor_type = QNN_TENSOR_TYPE_STATIC; Qnn_QuantizeParams_t quantize_param = QNN_QUANTIZE_PARAMS_INIT; InitializeQuantizeParam(quantize_param, is_quantized_model); QnnTensorWrapper bias_tensorwrapper(bias_name, tensor_type, qnn_data_type, quantize_param, std::move(bias_shape), std::move(default_bias_data)); ORT_RETURN_IF_NOT(qnn_model_wrapper.AddTensorWrapper(std::move(bias_tensorwrapper)), "Failed to add tensor."); input_names.push_back(bias_name); return Status::OK(); } Status ConvOpBuilder::ProcessInputs(QnnModelWrapper& qnn_model_wrapper, const NodeUnit& node_unit, const logging::Logger& logger, bool is_quantized_model, std::vector<std::string>& input_names, bool do_op_validation) const { ORT_UNUSED_PARAMETER(do_op_validation); Qnn_QuantizeParams_t quantize_param = QNN_QUANTIZE_PARAMS_INIT; InitializeQuantizeParam(quantize_param, is_quantized_model); Qnn_DataType_t qnn_data_type = QNN_DATATYPE_FLOAT_32; uint32_t weight_m = 0; auto inputs = node_unit.Inputs(); for (size_t input_i = 0; input_i < inputs.size(); ++input_i) { const auto& input_name = inputs[input_i].node_arg.Name(); const auto* type_proto = inputs[input_i].node_arg.TypeAsProto(); ORT_RETURN_IF_ERROR(GetQnnDataType(is_quantized_model, type_proto, qnn_data_type)); std::vector<uint32_t> input_shape; ORT_RETURN_IF_NOT(qnn_model_wrapper.GetOnnxShape(inputs[input_i].node_arg, input_shape), "Cannot get shape"); ORT_RETURN_IF_NOT(qnn_model_wrapper.ProcessQuantizationParameter(inputs[input_i].quant_param, quantize_param.scaleOffsetEncoding.scale, quantize_param.scaleOffsetEncoding.offset), "Cannot get quantization parameter"); std::vector<uint8_t> unpacked_tensor; bool is_initializer_input = qnn_model_wrapper.IsInitializerInput(input_name); if (is_initializer_input) { const auto& input_tensor = qnn_model_wrapper.GetInitializerTensors().at(input_name); if (1 == input_i) { // qnn Conv weight requires HWCN if (node_unit.OpType() == "Conv") { ORT_RETURN_IF_ERROR(TransposeFromNchwToHwcn(*input_tensor, qnn_model_wrapper.GetAllocator(), unpacked_tensor)); } else if (node_unit.OpType() == "ConvTranspose") { ORT_RETURN_IF_ERROR(TransposeFromCnhwToHwcn(*input_tensor, qnn_model_wrapper.GetAllocator(), unpacked_tensor)); } else { ORT_THROW("Unexpected operator %s", node_unit.OpType()); } } else { ORT_RETURN_IF_ERROR(onnxruntime::utils::UnpackInitializerData(*input_tensor, unpacked_tensor)); } } std::string input_tensor_name(input_name); std::vector<uint32_t> new_input_shape; if (1 == input_i) { new_input_shape.resize(input_shape.size()); // Change shape to HWCN, it could be initializer or normal input if (node_unit.OpType() == "Conv") { ORT_RETURN_IF_ERROR(NchwShapeToHwcn(input_shape, new_input_shape)); } else if (node_unit.OpType() == "ConvTranspose") { ORT_RETURN_IF_ERROR(CnhwShapeToHwcn(input_shape, new_input_shape)); } else { ORT_THROW("Unexpected operator %s", node_unit.OpType()); } weight_m = new_input_shape.at(3); // Add Transpose node NCHW->HWCN after the graph input (exclude initializer) for Conv weight input if (!is_initializer_input) { bool is_graph_input = qnn_model_wrapper.IsGraphInput(input_name); std::string transpose_output_name = input_name + "_trans"; LOGS(logger, VERBOSE) << "Add HWCN Transpose node after input: " << input_name; if (node_unit.OpType() == "Conv") { ORT_RETURN_IF_ERROR(qnn_model_wrapper.AddNchwToHwcnTranspose(node_unit.Index(), input_name, transpose_output_name, input_shape, new_input_shape, qnn_data_type, quantize_param, is_graph_input)); } else if (node_unit.OpType() == "ConvTranspose") { ORT_RETURN_IF_ERROR(qnn_model_wrapper.AddCnhwToHwcnTranspose(node_unit.Index(), input_name, transpose_output_name, input_shape, new_input_shape, qnn_data_type, quantize_param, is_graph_input)); } else { ORT_THROW("Unexpected operator %s", node_unit.OpType()); } input_tensor_name = transpose_output_name; } input_shape = new_input_shape; } input_names.push_back(input_tensor_name); if (qnn_model_wrapper.IsQnnTensorWrapperExist(input_name)) { LOGS(logger, VERBOSE) << "Tensor already added, skip it: " << input_name; continue; } Qnn_TensorType_t tensor_type = GetInputTensorType(qnn_model_wrapper, input_name); QnnTensorWrapper input_tensorwrapper(input_name, tensor_type, qnn_data_type, quantize_param, std::move(input_shape), std::move(unpacked_tensor)); ORT_RETURN_IF_NOT(qnn_model_wrapper.AddTensorWrapper(std::move(input_tensorwrapper)), "Failed to add tensor."); } if (inputs.size() < 3) { // Add default bais ORT_RETURN_IF_ERROR(AddDefaultBias(qnn_model_wrapper, weight_m, GetNodeName(node_unit), is_quantized_model, logger, input_names)); } return Status::OK(); } Status ConvOpBuilder::ProcessAttributesAndOutputs(QnnModelWrapper& qnn_model_wrapper, const NodeUnit& node_unit, std::vector<std::string>&& input_names, const logging::Logger& logger, bool is_quantized_model, bool do_op_validation) const { ORT_UNUSED_PARAMETER(do_op_validation); NodeAttrHelper node_helper(node_unit); std::vector<std::string> param_tensor_names; std::vector<uint32_t> output_padding; uint32_t output_padding_0 = 0; uint32_t output_padding_1 = 0; // Conv attribute dilations auto dilation_values = node_helper.Get("dilations", std::vector<int32_t>{1, 1}); std::vector<uint32_t> dilations; std::transform(dilation_values.cbegin(), dilation_values.cend(), std::back_inserter(dilations), [](int32_t item) { return SafeInt<uint32_t>(item); }); // keep a copy for later user since it will be invalid after move uint32_t dilations_0 = dilations[0]; uint32_t dilations_1 = dilations[1]; uint32_t dialitions_size = static_cast<uint32_t>(dilations.size()); std::vector<uint32_t> dialitions_dim; dialitions_dim.push_back(dialitions_size); if (node_unit.OpType() == "Conv") { QnnParamWrapper dilation_paramwrapper(node_unit.Index(), node_unit.Name(), qnn_def::dilation, std::move(dialitions_dim), std::move(dilations)); param_tensor_names.push_back(dilation_paramwrapper.GetParamTensorName()); qnn_model_wrapper.AddParamWrapper(std::move(dilation_paramwrapper)); } else if (node_unit.OpType() == "ConvTranspose") { // Add output_padding param auto output_padding_values = node_helper.Get("output_padding", std::vector<int32_t>{0, 0}); std::transform(output_padding_values.cbegin(), output_padding_values.cend(), std::back_inserter(output_padding), [](int32_t item) { return SafeInt<uint32_t>(item); }); // keep a copy for later user since it will be invalid after move output_padding_0 = output_padding[0]; output_padding_1 = output_padding[1]; std::vector<uint32_t> output_padding_dim{static_cast<uint32_t>(output_padding.size())}; QnnParamWrapper output_padding_paramwrapper(node_unit.Index(), node_unit.Name(), qnn_def::output_padding, std::move(output_padding_dim), std::move(output_padding)); param_tensor_names.push_back(output_padding_paramwrapper.GetParamTensorName()); qnn_model_wrapper.AddParamWrapper(std::move(output_padding_paramwrapper)); } else { ORT_THROW("Unexpected operator %s", node_unit.OpType()); } // Conv/ConvTranspose output const auto& outputs = node_unit.Outputs(); const auto& output_name = outputs[0].node_arg.Name(); std::vector<uint32_t> output_shape; ORT_RETURN_IF_NOT(qnn_model_wrapper.GetOnnxShape(outputs[0].node_arg, output_shape), "Cannot get shape"); // Conv attribute strides auto stride_values = node_helper.Get("strides", std::vector<int32_t>{1, 1}); std::vector<uint32_t> strides; std::transform(stride_values.cbegin(), stride_values.cend(), std::back_inserter(strides), [](int32_t item) { return SafeInt<uint32_t>(item); }); uint32_t strides_size = static_cast<uint32_t>(strides.size()); std::vector<uint32_t> strides_dim{strides_size}; QnnParamWrapper stride_amount_paramwrapper(node_unit.Index(), node_unit.Name(), qnn_def::stride, std::move(strides_dim), std::move(strides)); param_tensor_names.push_back(stride_amount_paramwrapper.GetParamTensorName()); qnn_model_wrapper.AddParamWrapper(std::move(stride_amount_paramwrapper)); std::vector<int32_t> pad_values = {0, 0, 0, 0}; auto auto_pad = node_helper.Get("auto_pad", std::string("NOTSET")); if (auto_pad.compare("NOTSET") != 0) { auto input_0 = node_unit.Inputs()[0]; auto input_1 = node_unit.Inputs()[1]; std::vector<uint32_t> input_0_shape; std::vector<uint32_t> input_1_shape; ORT_RETURN_IF_NOT(qnn_model_wrapper.GetOnnxShape(input_0.node_arg, input_0_shape), "Cannot get shape"); ORT_RETURN_IF_NOT(qnn_model_wrapper.GetOnnxShape(input_1.node_arg, input_1_shape), "Cannot get shape"); int32_t total_padding[2]; if (node_unit.OpType() == "ConvTranspose") { total_padding[0] = stride_values[0] * (input_0_shape[1] - 1) + output_padding_0 + (input_1_shape[2] - 1) * dilations_0 + 1 - output_shape[1]; total_padding[1] = stride_values[1] * (input_0_shape[2] - 1) + output_padding_1 + (input_1_shape[3] - 1) * dilations_1 + 1 - output_shape[2]; } else { total_padding[0] = output_shape[1] * stride_values[0] - input_0_shape[1] + 1; total_padding[1] = output_shape[1] * stride_values[0] - input_0_shape[2] + 1; } if (auto_pad.compare("SAME_UPPER")) { pad_values[0] = total_padding[0] / 2; pad_values[1] = total_padding[1] / 2; pad_values[2] = total_padding[0] - pad_values[0]; pad_values[3] = total_padding[1] - pad_values[1]; } else if (auto_pad.compare("SAME_LOWER")) { pad_values[2] = total_padding[0] / 2; pad_values[3] = total_padding[1] / 2; pad_values[0] = total_padding[0] - pad_values[2]; pad_values[1] = total_padding[1] - pad_values[3]; } } else { // Conv/ConvTranspose attribute pads pad_values = node_helper.Get("pads", pad_values); } ReArranagePads(pad_values); std::vector<uint32_t> pads; std::transform(pad_values.cbegin(), pad_values.cend(), std::back_inserter(pads), [](int32_t item) { return SafeInt<uint32_t>(item); }); // Qnn Conv2d must use dims {2, 2} std::vector<uint32_t> pad_dims{2, 2}; QnnParamWrapper pad_amount_paramwrapper(node_unit.Index(), node_unit.Name(), qnn_def::pad_amount, std::move(pad_dims), std::move(pads)); param_tensor_names.push_back(pad_amount_paramwrapper.GetParamTensorName()); qnn_model_wrapper.AddParamWrapper(std::move(pad_amount_paramwrapper)); Qnn_QuantizeParams_t output_quantize_param = QNN_QUANTIZE_PARAMS_INIT; InitializeQuantizeParam(output_quantize_param, is_quantized_model); const auto* type_proto = outputs[0].node_arg.TypeAsProto(); Qnn_DataType_t qnn_data_type = QNN_DATATYPE_FLOAT_32; ORT_RETURN_IF_ERROR(GetQnnDataType(is_quantized_model, type_proto, qnn_data_type)); ORT_RETURN_IF_NOT(qnn_model_wrapper.ProcessQuantizationParameter(outputs[0].quant_param, output_quantize_param.scaleOffsetEncoding.scale, output_quantize_param.scaleOffsetEncoding.offset), "Cannot get quantization parameter"); const uint32_t group = SafeInt<uint32_t>(node_helper.Get("group", static_cast<int64_t>(1))); uint32_t num_output = output_shape[3]; uint32_t num_input_channel = 0; ORT_RETURN_IF_ERROR(GetInputChannelNumber(qnn_model_wrapper, node_unit, num_input_channel)); LOGS(logger, VERBOSE) << (node_unit.OpType() == "Conv" ? "Conv:" : "ConvTranspose:") << " num_output: " << num_output << ", num_input_channel: " << num_input_channel << ", group: " << group; const static std::string depthwise_conv2d = "DepthWiseConv2d"; bool is_depthwise_conv2d = false; if ((node_unit.OpType() == "Conv") && (num_input_channel == num_output) && (group == num_output)) { is_depthwise_conv2d = true; } else { // DepthWiseConv2d does not need group // Conv attribute group Qnn_Scalar_t group_qnn_scalar = QNN_SCALAR_INIT; group_qnn_scalar.dataType = QNN_DATATYPE_UINT_32; group_qnn_scalar.uint32Value = group; QnnParamWrapper group_paramwrapper(node_unit.Index(), node_unit.Name(), qnn_def::group, group_qnn_scalar); param_tensor_names.push_back(group_paramwrapper.GetParamTensorName()); qnn_model_wrapper.AddParamWrapper(std::move(group_paramwrapper)); } const std::string& output_node_type = is_depthwise_conv2d ? depthwise_conv2d : GetQnnOpType(node_unit.OpType()); bool is_graph_output = qnn_model_wrapper.IsGraphOutput(output_name); Qnn_TensorType_t tensor_type = is_graph_output ? QNN_TENSOR_TYPE_APP_READ : QNN_TENSOR_TYPE_NATIVE; QnnTensorWrapper output_tensorwrapper(output_name, tensor_type, qnn_data_type, output_quantize_param, std::move(output_shape)); ORT_RETURN_IF_NOT(qnn_model_wrapper.AddTensorWrapper(std::move(output_tensorwrapper)), "Failed to add tensor."); ORT_RETURN_IF_NOT(qnn_model_wrapper.CreateQnnNode(GetNodeName(node_unit), qnn_def::package_name, output_node_type, std::move(input_names), {output_name}, std::move(param_tensor_names)), "Failed to add node."); return Status::OK(); } void CreateConvOpBuilder(const std::string& op_type, OpBuilderRegistrations& op_registrations) { op_registrations.AddOpBuilder(op_type, std::make_unique<ConvOpBuilder>()); } } // namespace qnn } // namespace onnxruntime
[ "noreply@github.com" ]
noreply@github.com
cc3d44757a379f26e4157f53697515a2a3f3e097
80f579c4a9b22ca4c9ad49310d89839a944807ca
/Programmers/Lv5/Lv5_파일명정렬.cpp
274a2c111b15cfe66824bd23c635b8cd4fe4d2d8
[]
no_license
wh2per/Programmers-Algorithm
ba2abdf6966d11aa1a8c80630eab5e9d30b45e4d
9c3a01c4525c8b67fa2a0be4aabb14b4011adb19
refs/heads/master
2022-04-30T16:16:11.418261
2022-04-03T16:54:28
2022-04-03T16:54:28
165,787,650
27
14
null
null
null
null
UTF-8
C++
false
false
1,157
cpp
#include <string> #include <vector> #include <iostream> #include <algorithm> using namespace std; struct info_file { string head; int num; int recent; }; bool cmp_file(info_file a, info_file b) { if (a.head < b.head) return true; else if (a.head == b.head) { if (a.num < b.num) return true; else if (a.num == b.num) { if (a.recent < b.recent) return true; else return false; } else return false; } else return false; } vector<string> solution(vector<string> files) { vector<string> answer; vector<info_file> order; for (int i = 0; i < files.size(); ++i) { string file = files[i]; int t1 = 0; while (file[t1] < 48 || file[t1] > 57) // 숫자가 아닐때 ++t1; string head = file.substr(0, t1); int t2 = t1; while (file[t2] >= 48 && file[t2] <= 57) // 숫자 일때 ++t2; for (int j = 0; j < head.length(); ++j) head[j] = tolower(head[j]); int num = atoi((file.substr(t1, t2 - t1)).c_str()); order.push_back({head,num,i}); } sort(order.begin(), order.end(), cmp_file); for (int i = 0; i < order.size(); ++i) answer.push_back(files[order[i].recent]); return answer; }
[ "93negaro@gmail.com" ]
93negaro@gmail.com
b40e81f79927bf132b5e9c58bd84c2a1d29f40be
14d915325d5dd97e908d387da1a02fcebd603a8c
/projekt3/Tic-tac-toe/Tic-tac-toe/Window.h
ae88f7a216c4c838fa218f6dee52f1678d5d0165
[]
no_license
KarolinaGl/Projektowanie-algorytmow
d2af45ae35cffcfee0a75f90cc9d76f59dd6ebbd
e587b7f46e57947b72c6ba0fa6e5af74db8f289a
refs/heads/master
2021-04-24T06:17:21.596561
2020-06-16T19:36:29
2020-06-16T19:36:29
250,089,716
0
0
null
null
null
null
UTF-8
C++
false
false
370
h
#pragma once #include <vector> #include <iostream> #include <SFML/Graphics.hpp> #include "Board.h" #include "Button.h" #include "View.h" #include "MenuView.h" #include "GameView.h" #include "Constants.h" class Window { public: View* view; sf::RenderWindow* window; Window(); void run(); void changeView(View* newView) { delete view; view = newView; } };
[ "karolina.gluszek6@gmail.com" ]
karolina.gluszek6@gmail.com
b10a4d202391ee955d292c54ed221d44c991b0b1
caceb4994bd2a3e2dda5eea1674fda41f8907aba
/Hello_World_Rahul/Arduino/constants.cc
da81790ea31b156130660806dc3b1f4201ce440e
[]
no_license
rssr25/TinyML
978669e230fc91774f51216c3ba7ef618ed8bee2
a34aa7041f9eb646e02fb2976657d86782fa9a74
refs/heads/master
2022-11-20T19:37:51.712116
2020-07-23T06:57:38
2020-07-23T06:57:38
281,366,462
2
0
null
null
null
null
UTF-8
C++
false
false
110
cc
#include "tensorflow/lite/micro/examples/hello_world_rahul/constants.h" const int kInferencesPerCycle = 1000;
[ "rahulsharmacs50@gmail.com" ]
rahulsharmacs50@gmail.com
75f28a4acf5dc29dfc20168eb29315c8fe032760
52a4efd8d21a7eb5e2e7106e6eb3965ca7623b58
/src/qt/addressbookpage.cpp
d015bfc0c4b9587cff23d1ad972359ad25f4f34c
[ "MIT" ]
permissive
MobioCrypto/MBO
344cda9e68b9d5dc9d13717553f95340049dbd4a
949f83bdde9815ab0beaf4a7cd28f2910b0c16f3
refs/heads/master
2020-04-14T21:14:15.128776
2019-01-04T15:13:35
2019-01-04T15:13:35
164,122,182
0
1
null
null
null
null
UTF-8
C++
false
false
10,172
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017 The Mobio developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/mobio-config.h" #endif #include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "bitcoingui.h" #include "csvmodelwriter.h" #include "editaddressdialog.h" #include "guiutil.h" #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> AddressBookPage::AddressBookPage(Mode mode, Tabs tab, QWidget* parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), mode(mode), tab(tab) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); #endif switch (mode) { case ForSelection: switch (tab) { case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break; case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break; } connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->closeButton->setText(tr("C&hoose")); ui->exportButton->hide(); break; case ForEditing: switch (tab) { case SendingTab: setWindowTitle(tr("Sending addresses")); break; case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break; } break; } switch (tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your Mobio addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your Mobio addresses for receiving payments. It is recommended to use a new receiving address for each transaction.")); ui->deleteAddress->setVisible(false); break; } // Context menu actions QAction* copyAddressAction = new QAction(tr("&Copy Address"), this); QAction* copyLabelAction = new QAction(tr("Copy &Label"), this); QAction* editAction = new QAction(tr("&Edit"), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if (tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel* model) { this->model = model; if (!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch (tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(selectNewAddress(QModelIndex, int, int))); selectionChanged(); } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if (!model) return; if (!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if (indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress, this); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_newAddress_clicked() { if (!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if (dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView* table = ui->tableView; if (!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if (!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView* table = ui->tableView; if (!table->selectionModel()) return; if (table->selectionModel()->hasSelection()) { switch (tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); break; } ui->copyAddress->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->copyAddress->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView* table = ui->tableView; if (!table->selectionModel() || !table->model()) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); foreach (QModelIndex index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if (returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName(this, tr("Export Address List"), QString(), tr("Comma separated file (*.csv)"), NULL); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if (!writer.write()) { QMessageBox::critical(this, tr("Exporting Failed"), tr("There was an error trying to save the address list to %1. Please try again.").arg(filename)); } } void AddressBookPage::contextualMenu(const QPoint& point) { QModelIndex index = ui->tableView->indexAt(point); if (index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex& parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if (idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } }
[ "46378708+MobioCrypto@users.noreply.github.com" ]
46378708+MobioCrypto@users.noreply.github.com
2974ec65b701f6453e7c3bba05a24728baca4ee1
1d9e60a377ce2b0b94234e90c3156f212f2a7e9b
/6/View/TestView3.cpp
e84f0d5a7859f250e17a6a21f7155f3ee1ab5414
[]
no_license
seehunter/visual_c-_reff_skill_code
fd13ceec2c34bd827f2556638bbc190be46d9b93
1a99bd875c32a04cbcc07c785b61270821c58341
refs/heads/master
2020-04-09T21:28:33.030596
2018-12-06T01:59:25
2018-12-06T01:59:25
160,603,401
0
0
null
null
null
null
UTF-8
C++
false
false
1,302
cpp
// TestView3.cpp : implementation file // #include "stdafx.h" #include "View.h" #include "TestView3.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTestView3 IMPLEMENT_DYNCREATE(CTestView3, CFormView) CTestView3::CTestView3() : CFormView(CTestView3::IDD) { //{{AFX_DATA_INIT(CTestView3) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT } CTestView3::~CTestView3() { } void CTestView3::DoDataExchange(CDataExchange* pDX) { CFormView::DoDataExchange(pDX); //{{AFX_DATA_MAP(CTestView3) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CTestView3, CFormView) //{{AFX_MSG_MAP(CTestView3) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTestView3 diagnostics #ifdef _DEBUG void CTestView3::AssertValid() const { CFormView::AssertValid(); } void CTestView3::Dump(CDumpContext& dc) const { CFormView::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CTestView3 message handlers
[ "seehunter@163.com" ]
seehunter@163.com
68a786df0a32d792caf12d12c952200e0a94b1ea
3e8e42b902fc21d3d399260473990a186398f7c8
/demo_ballDrop.cpp
38743b11abe1e809440668fceaea4589603f9488
[ "MIT" ]
permissive
melanz/demo-ball-drop
23c0c08f19fc667f24c12329f492666624d950f6
2a9c54fa404d07a18ee8e60dd6867b0e6134a71a
refs/heads/master
2016-09-11T08:53:14.758267
2013-11-19T21:25:21
2013-11-19T21:25:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,391
cpp
#include "common/common.h" template<class T> void RunTimeStep(T* mSys, const int frame) { // add code here that you want to execute at each timestep } int main(int argc, char* argv[]) { bool visualize = true; int threads = 8; int config = 0; real gravity = -9.81; //acceleration due to gravity real timestep = .01; //step size real time_to_run = 1; //length of simulation real current_time = 0; int num_steps = time_to_run / timestep; int max_iteration = 15; int tolerance = 0; //========================================================================================================= // Create system //========================================================================================================= ChSystemParallel * system_gpu = new ChSystemParallel; //========================================================================================================= // Populate the system with bodies/constraints/forces/etc. //========================================================================================================= ChVector<> lpos(0, 0, 0); ChQuaternion<> quat(1, 0, 0, 0); real container_width = 5; //width of area with particles real container_length = 25; //length of area that roller will go over real container_thickness = .25; //thickness of container walls real container_height = 2; //height of the outer walls real particle_radius = .58; // Create a material (will be used by both objects) ChSharedPtr<ChMaterialSurface> material; material = ChSharedPtr<ChMaterialSurface>(new ChMaterialSurface); material->SetFriction(0.4); // Create a ball ChSharedBodyPtr ball = ChSharedBodyPtr(new ChBody(new ChCollisionModelParallel)); InitObject(ball, 1, // mass ChVector<>(0, 10, 0), // position ChQuaternion<>(1, 0, 0, 0), // rotation material, // material true, // collide? false, // static? -15, -15); // collision family ball->SetPos_dt(ChVector<>(0,0,10)); AddCollisionGeometry(ball, SPHERE, particle_radius, lpos, quat); FinalizeObject(ball, (ChSystemParallel *) system_gpu); // Create a bin for the ball to fall into ChSharedBodyPtr bin = ChSharedBodyPtr(new ChBody(new ChCollisionModelParallel)); InitObject(bin, 1, // mass ChVector<>(0, 0, 0), // position ChQuaternion<>(1, 0, 0, 0), // rotation material, // material true, // collide? true, // static? -20, -20); // collision family AddCollisionGeometry(bin, BOX, ChVector<>(container_width, container_thickness, container_length), lpos, quat); AddCollisionGeometry(bin, BOX, Vector(container_thickness, container_height, container_length), Vector(-container_width + container_thickness, container_height, 0), quat); AddCollisionGeometry(bin, BOX, Vector(container_thickness, container_height, container_length), Vector(container_width - container_thickness, container_height, 0), quat); AddCollisionGeometry(bin, BOX, Vector(container_width, container_height, container_thickness), Vector(0, container_height, -container_length + container_thickness), quat); AddCollisionGeometry(bin, BOX, Vector(container_width, container_height, container_thickness), Vector(0, container_height, container_length - container_thickness), quat); FinalizeObject(bin, (ChSystemParallel *) system_gpu); //========================================================================================================= // Edit system settings //========================================================================================================= system_gpu->SetIntegrationType(ChSystem::INT_ANITESCU); system_gpu->SetParallelThreadNumber(threads); system_gpu->SetMaxiter(max_iteration); system_gpu->SetIterLCPmaxItersSpeed(max_iteration); system_gpu->SetTol(1e-3); system_gpu->SetTolSpeeds(1e-3); system_gpu->Set_G_acc(ChVector<>(0, gravity, 0)); system_gpu->SetStep(timestep); ((ChLcpSolverParallel *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIteration(max_iteration); ((ChLcpSolverParallel *) (system_gpu->GetLcpSolverSpeed()))->SetTolerance(0); ((ChLcpSolverParallel *) (system_gpu->GetLcpSolverSpeed()))->SetCompliance(0, 0, 0); ((ChLcpSolverParallel *) (system_gpu->GetLcpSolverSpeed()))->SetContactRecoverySpeed(300); ((ChLcpSolverParallel *) (system_gpu->GetLcpSolverSpeed()))->SetSolverType(ACCELERATED_PROJECTED_GRADIENT_DESCENT); ((ChCollisionSystemParallel *) (system_gpu->GetCollisionSystem()))->SetCollisionEnvelope(particle_radius * .05); ((ChCollisionSystemParallel *) (system_gpu->GetCollisionSystem()))->setBinsPerAxis(R3(10, 10, 10)); ((ChCollisionSystemParallel *) (system_gpu->GetCollisionSystem()))->setBodyPerBin(100, 50); omp_set_num_threads(threads); //========================================================================================================= // Enter the time loop and render the simulation //========================================================================================================= if (visualize) { ChOpenGLManager * window_manager = new ChOpenGLManager(); ChOpenGL openGLView(window_manager, system_gpu, 800, 600, 0, 0, "Test_Solvers"); openGLView.render_camera->camera_pos = Vector(0, 5, -20); openGLView.render_camera->look_at = Vector(0, 0, 0); openGLView.SetCustomCallback(RunTimeStep); openGLView.StartSpinning(window_manager); window_manager->CallGlutMainLoop(); } return 0; }
[ "daniel.melanz@gmail.com" ]
daniel.melanz@gmail.com
a15da5c234cabd47216481f6d1f733243f743d1f
fef98cc8ed59c2f13410f1c5ddc126cf08427a05
/src/s2/s2shape_index.h
9c9aecff1bc9139782a9d163be492d4769d15dae
[ "Apache-2.0" ]
permissive
romange/s2geometry
ac14ddf1f25e8cd1805521bfcaa2ed16224391d9
5c584fa3c3c1464dd9ce254e341857fbc9749bb4
refs/heads/master
2020-04-02T21:42:15.570372
2018-10-26T10:48:31
2018-10-26T10:48:31
154,808,921
0
0
Apache-2.0
2018-10-26T09:17:39
2018-10-26T09:17:39
null
UTF-8
C++
false
false
29,323
h
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: ericv@google.com (Eric Veach) // // S2ShapeIndex is an abstract base class for indexing polygonal geometry in // memory. The main documentation is with the class definition below. // (Some helper classes are defined first.) #ifndef S2_S2SHAPE_INDEX_H_ #define S2_S2SHAPE_INDEX_H_ #include <array> #include <atomic> #include <cstddef> #include <iterator> #include <memory> #include <utility> #include <vector> #include "s2/base/logging.h" #include "s2/base/mutex.h" #include "s2/base/spinlock.h" #include "s2/_fp_contract_off.h" #include "s2/s2cell_id.h" #include "s2/s2pointutil.h" #include "s2/s2shape.h" #include "s2/third_party/absl/base/integral_types.h" #include "s2/third_party/absl/base/macros.h" #include "s2/third_party/absl/base/thread_annotations.h" #include "s2/third_party/absl/memory/memory.h" #include "s2/util/gtl/compact_array.h" class R1Interval; class S2PaddedCell; // S2ClippedShape represents the part of a shape that intersects an S2Cell. // It consists of the set of edge ids that intersect that cell, and a boolean // indicating whether the center of the cell is inside the shape (for shapes // that have an interior). // // Note that the edges themselves are not clipped; we always use the original // edges for intersection tests so that the results will be the same as the // original shape. class S2ClippedShape { public: // The shape id of the clipped shape. int shape_id() const; // Returns true if the center of the S2CellId is inside the shape. Returns // false for shapes that do not have an interior. bool contains_center() const; // The number of edges that intersect the S2CellId. int num_edges() const; // Returns the edge id of the given edge in this clipped shape. Edges are // sorted in increasing order of edge id. // // REQUIRES: 0 <= i < num_edges() int edge(int i) const; // Returns true if the clipped shape contains the given edge id. bool ContainsEdge(int id) const; private: // This class may be copied by value, but note that it does *not* own its // underlying data. (It is owned by the containing S2ShapeIndexCell.) friend class MutableS2ShapeIndex; friend class S2ShapeIndexCell; friend class S2Stats; // Internal methods are documented with their definition. void Init(int32 shape_id, int32 num_edges); void Destruct(); bool is_inline() const; void set_contains_center(bool contains_center); void set_edge(int i, int edge); // All fields are packed into 16 bytes (assuming 64-bit pointers). Up to // two edge ids are stored inline; this is an important optimization for // clients that use S2Shapes consisting of a single edge. int32 shape_id_; uint32 contains_center_ : 1; // shape contains the cell center uint32 num_edges_ : 31; // If there are more than two edges, this field holds a pointer. // Otherwise it holds an array of edge ids. union { int32* edges_; // Owned by the containing S2ShapeIndexCell. std::array<int32, 2> inline_edges_; }; }; // S2ShapeIndexCell stores the index contents for a particular S2CellId. // It consists of a set of clipped shapes. class S2ShapeIndexCell { public: S2ShapeIndexCell() {} ~S2ShapeIndexCell(); // Returns the number of clipped shapes in this cell. int num_clipped() const { return shapes_.size(); } // Returns the clipped shape at the given index. Shapes are kept sorted in // increasing order of shape id. // // REQUIRES: 0 <= i < num_clipped() const S2ClippedShape& clipped(int i) const { return shapes_[i]; } // Returns a pointer to the clipped shape corresponding to the given shape, // or nullptr if the shape does not intersect this cell. const S2ClippedShape* find_clipped(const S2Shape* shape) const; const S2ClippedShape* find_clipped(int shape_id) const; // Convenience method that returns the total number of edges in all clipped // shapes. int num_edges() const; // Appends an encoded representation of the S2ShapeIndexCell to "encoder". // "num_shape_ids" should be set to index.num_shape_ids(); this information // allows the encoding to be more compact in some cases. // // REQUIRES: "encoder" uses the default constructor, so that its buffer // can be enlarged as necessary by calling Ensure(int). void Encode(int num_shape_ids, Encoder* encoder) const; // Decodes an S2ShapeIndexCell, returning true on success. // "num_shape_ids" should be set to index.num_shape_ids(). bool Decode(int num_shape_ids, Decoder* decoder); private: friend class MutableS2ShapeIndex; friend class EncodedS2ShapeIndex; friend class S2Stats; // Internal methods are documented with their definitions. S2ClippedShape* add_shapes(int n); static void EncodeEdges(const S2ClippedShape& clipped, Encoder* encoder); static bool DecodeEdges(int num_edges, S2ClippedShape* clipped, Decoder* decoder); using S2ClippedShapeSet = gtl::compact_array<S2ClippedShape>; S2ClippedShapeSet shapes_; S2ShapeIndexCell(const S2ShapeIndexCell&) = delete; void operator=(const S2ShapeIndexCell&) = delete; }; // S2ShapeIndex is an abstract base class for indexing polygonal geometry in // memory. The objects in the index are known as "shapes", and may consist of // points, polylines, and/or polygons, possibly overlapping. The index makes // it very fast to answer queries such as finding nearby shapes, measuring // distances, testing for intersection and containment, etc. // // Each object in the index implements the S2Shape interface. An S2Shape is a // collection of edges that optionally defines an interior. The edges do not // need to be connected, so for example an S2Shape can represent a polygon // with multiple shells and/or holes, or a set of polylines, or a set of // points. All geometry within a single S2Shape must have the same dimension, // so for example if you want to create an S2ShapeIndex containing a polyline // and 10 points, then you will need at least two different S2Shape objects. // // The most important type of S2ShapeIndex is MutableS2ShapeIndex, which // allows you to build an index incrementally by adding or removing shapes. // Soon there will also be an EncodedS2ShapeIndex type that makes it possible // to keep the index data in encoded form. Code that only needs read-only // ("const") access to an index should use the S2ShapeIndex base class as the // parameter type, so that it will work with any S2ShapeIndex subtype. For // example: // // void DoSomething(const S2ShapeIndex& index) { // ... works with MutableS2ShapeIndex or EncodedS2ShapeIndex ... // } // // There are a number of built-in classes that work with S2ShapeIndex objects. // Generally these classes accept any collection of geometry that can be // represented by an S2ShapeIndex, i.e. any combination of points, polylines, // and polygons. Such classes include: // // - S2ContainsPointQuery: returns the shape(s) that contain a given point. // // - S2ClosestEdgeQuery: returns the closest edge(s) to a given point, edge, // S2CellId, or S2ShapeIndex. // // - S2CrossingEdgeQuery: returns the edge(s) that cross a given edge. // // - S2BooleanOperation: computes boolean operations such as union, // and boolean predicates such as containment. // // - S2ShapeIndexRegion: computes approximations for a collection of geometry. // // - S2ShapeIndexBufferedRegion: computes approximations that have been // expanded by a given radius. // // Here is an example showing how to index a set of polygons and then // determine which polygon(s) contain each of a set of query points: // // void TestContainment(const vector<S2Point>& points, // const vector<S2Polygon*>& polygons) { // MutableS2ShapeIndex index; // for (auto polygon : polygons) { // index.Add(absl::make_unique<S2Polygon::Shape>(polygon)); // } // auto query = MakeS2ContainsPointQuery(&index); // for (const auto& point : points) { // for (S2Shape* shape : query.GetContainingShapes(point)) { // S2Polygon* polygon = polygons[shape->id()]; // ... do something with (point, polygon) ... // } // } // } // // This example uses S2Polygon::Shape, which is one example of an S2Shape // object. S2Polyline and S2Loop also have nested Shape classes, and there are // additional S2Shape types defined in *_shape.h. // // Internally, an S2ShapeIndex is essentially a map from S2CellIds to the set // of shapes that intersect each S2CellId. It is adaptively refined to ensure // that no cell contains more than a small number of edges. // // In addition to implementing a shared set of virtual methods, all // S2ShapeIndex subtypes define an Iterator type with the same API. This // makes it easy to convert code that uses a particular S2ShapeIndex subtype // to instead use the abstract base class (or vice versa). You can also // choose to avoid the overhead of virtual method calls by making the // S2ShapeIndex type a template argument, like this: // // template <class IndexType> // void DoSomething(const IndexType& index) { // for (typename IndexType::Iterator it(&index, S2ShapeIndex::BEGIN); // !it.done(); it.Next()) { // ... // } // } // // Subtypes provided by the S2 library have the same thread-safety properties // as std::vector. That is, const methods may be called concurrently from // multiple threads, and non-const methods require exclusive access to the // S2ShapeIndex. class S2ShapeIndex { protected: class IteratorBase; public: virtual ~S2ShapeIndex() {} // Returns the number of distinct shape ids in the index. This is the same // as the number of shapes provided that no shapes have ever been removed. // (Shape ids are never reused.) virtual int num_shape_ids() const = 0; // Returns a pointer to the shape with the given id, or nullptr if the shape // has been removed from the index. virtual S2Shape* shape(int id) const = 0; // Allows iterating over the indexed shapes using range-based for loops: // // for (S2Shape* shape : index) { ... } // // CAVEAT: Returns nullptr for shapes that have been removed from the index. class ShapeIterator : public std::iterator<std::forward_iterator_tag, S2Shape*> { public: ShapeIterator() = default; S2Shape* operator*() const; ShapeIterator& operator++(); ShapeIterator operator++(int); // REQUIRES: "it" and *this must reference the same S2ShapeIndex. bool operator==(ShapeIterator it) const; // REQUIRES: "it" and *this must reference the same S2ShapeIndex. bool operator!=(ShapeIterator it) const; private: friend class S2ShapeIndex; ShapeIterator(const S2ShapeIndex* index, int shape_id) : index_(index), shape_id_(shape_id) {} const S2ShapeIndex* index_ = nullptr; int shape_id_ = 0; }; ShapeIterator begin() const; ShapeIterator end() const; // Returns the number of bytes currently occupied by the index (including any // unused space at the end of vectors, etc). virtual size_t SpaceUsed() const = 0; // Minimizes memory usage by requesting that any data structures that can be // rebuilt should be discarded. This method invalidates all iterators. // // Like all non-const methods, this method is not thread-safe. virtual void Minimize() = 0; // The possible relationships between a "target" cell and the cells of the // S2ShapeIndex. If the target is an index cell or is contained by an index // cell, it is "INDEXED". If the target is subdivided into one or more // index cells, it is "SUBDIVIDED". Otherwise it is "DISJOINT". enum CellRelation { INDEXED, // Target is contained by an index cell SUBDIVIDED, // Target is subdivided into one or more index cells DISJOINT // Target does not intersect any index cells }; // When passed to an Iterator constructor, specifies whether the iterator // should be positioned at the beginning of the index (BEGIN), the end of // the index (END), or arbitrarily (UNPOSITIONED). By default iterators are // unpositioned, since this avoids an extra seek in this situation where one // of the seek methods (such as Locate) is immediately called. enum InitialPosition { BEGIN, END, UNPOSITIONED }; // A random access iterator that provides low-level access to the cells of // the index. Cells are sorted in increasing order of S2CellId. class Iterator { public: // Default constructor; must be followed by a call to Init(). Iterator() : iter_(nullptr) {} // Constructs an iterator positioned as specified. By default iterators // are unpositioned, since this avoids an extra seek in this situation // where one of the seek methods (such as Locate) is immediately called. // // If you want to position the iterator at the beginning, e.g. in order to // loop through the entire index, do this instead: // // for (S2ShapeIndex::Iterator it(&index, S2ShapeIndex::BEGIN); // !it.done(); it.Next()) { ... } explicit Iterator(const S2ShapeIndex* index, InitialPosition pos = UNPOSITIONED) : iter_(index->NewIterator(pos)) {} // Initializes an iterator for the given S2ShapeIndex. This method may // also be called in order to restore an iterator to a valid state after // the underlying index has been updated (although it is usually easier // just to declare a new iterator whenever required, since iterator // construction is cheap). void Init(const S2ShapeIndex* index, InitialPosition pos = UNPOSITIONED) { iter_ = index->NewIterator(pos); } // Iterators are copyable and movable. Iterator(const Iterator&); Iterator& operator=(const Iterator&); Iterator(Iterator&&); Iterator& operator=(Iterator&&); // Returns the S2CellId of the current index cell. If done() is true, // returns a value larger than any valid S2CellId (S2CellId::Sentinel()). S2CellId id() const { return iter_->id(); } // Returns the center point of the cell. // REQUIRES: !done() S2Point center() const { return id().ToPoint(); } // Returns a reference to the contents of the current index cell. // REQUIRES: !done() const S2ShapeIndexCell& cell() const { return iter_->cell(); } // Returns true if the iterator is positioned past the last index cell. bool done() const { return iter_->done(); } // Positions the iterator at the first index cell (if any). void Begin() { iter_->Begin(); } // Positions the iterator past the last index cell. void Finish() { iter_->Finish(); } // Positions the iterator at the next index cell. // REQUIRES: !done() void Next() { iter_->Next(); } // If the iterator is already positioned at the beginning, returns false. // Otherwise positions the iterator at the previous entry and returns true. bool Prev() { return iter_->Prev(); } // Positions the iterator at the first cell with id() >= target, or at the // end of the index if no such cell exists. void Seek(S2CellId target) { iter_->Seek(target); } // Positions the iterator at the cell containing "target". If no such cell // exists, returns false and leaves the iterator positioned arbitrarily. // The returned index cell is guaranteed to contain all edges that might // intersect the line segment between "target" and the cell center. bool Locate(const S2Point& target) { return IteratorBase::LocateImpl(target, this); } // Let T be the target S2CellId. If T is contained by some index cell I // (including equality), this method positions the iterator at I and // returns INDEXED. Otherwise if T contains one or more (smaller) index // cells, it positions the iterator at the first such cell I and returns // SUBDIVIDED. Otherwise it returns DISJOINT and leaves the iterator // positioned arbitrarily. CellRelation Locate(S2CellId target) { return IteratorBase::LocateImpl(target, this); } private: // Although S2ShapeIndex::Iterator can be used to iterate over any // index subtype, it is more efficient to use the subtype's iterator when // the subtype is known at compile time. For example, MutableS2ShapeIndex // should use a MutableS2ShapeIndex::Iterator. // // The following declarations prevent accidental use of // S2ShapeIndex::Iterator when the actual subtype is known. (If you // really want to do this, you can down_cast the index argument to // S2ShapeIndex.) template <class T> explicit Iterator(const T* index, InitialPosition pos = UNPOSITIONED) {} template <class T> void Init(const T* index, InitialPosition pos = UNPOSITIONED) {} std::unique_ptr<IteratorBase> iter_; }; // ShapeFactory is an interface for decoding vectors of S2Shapes. It allows // random access to the shapes in order to support lazy decoding. See // s2shapeutil_coding.h for useful subtypes. class ShapeFactory { public: virtual ~ShapeFactory() {} // Returns the number of S2Shapes in the vector. virtual int size() const = 0; // Returns the S2Shape object corresponding to the given "shape_id". // Returns nullptr if a shape cannot be decoded or a shape is missing // (e.g., because MutableS2ShapeIndex::Release() was called). virtual std::unique_ptr<S2Shape> operator[](int shape_id) const = 0; // Returns a deep copy of this ShapeFactory. virtual std::unique_ptr<ShapeFactory> Clone() const = 0; }; protected: // Each subtype of S2ShapeIndex should define an Iterator type derived // from the following base class. class IteratorBase { public: virtual ~IteratorBase() {} IteratorBase(const IteratorBase&); IteratorBase& operator=(const IteratorBase&); // Returns the S2CellId of the current index cell. If done() is true, // returns a value larger than any valid S2CellId (S2CellId::Sentinel()). S2CellId id() const; // Returns the center point of the cell. // REQUIRES: !done() S2Point center() const; // Returns a reference to the contents of the current index cell. // REQUIRES: !done() const S2ShapeIndexCell& cell() const; // Returns true if the iterator is positioned past the last index cell. bool done() const; // Positions the iterator at the first index cell (if any). virtual void Begin() = 0; // Positions the iterator past the last index cell. virtual void Finish() = 0; // Positions the iterator at the next index cell. // REQUIRES: !done() virtual void Next() = 0; // If the iterator is already positioned at the beginning, returns false. // Otherwise positions the iterator at the previous entry and returns true. virtual bool Prev() = 0; // Positions the iterator at the first cell with id() >= target, or at the // end of the index if no such cell exists. virtual void Seek(S2CellId target) = 0; // Positions the iterator at the cell containing "target". If no such cell // exists, returns false and leaves the iterator positioned arbitrarily. // The returned index cell is guaranteed to contain all edges that might // intersect the line segment between "target" and the cell center. virtual bool Locate(const S2Point& target) = 0; // Let T be the target S2CellId. If T is contained by some index cell I // (including equality), this method positions the iterator at I and // returns INDEXED. Otherwise if T contains one or more (smaller) index // cells, it positions the iterator at the first such cell I and returns // SUBDIVIDED. Otherwise it returns DISJOINT and leaves the iterator // positioned arbitrarily. virtual CellRelation Locate(S2CellId target) = 0; protected: IteratorBase() : id_(S2CellId::Sentinel()), cell_(nullptr) {} // Sets the iterator state. "cell" typically points to the cell contents, // but may also be given as "nullptr" in order to implement decoding on // demand. In that situation, the first that the client attempts to // access the cell contents, the GetCell() method is called and "cell_" is // updated in a thread-safe way. void set_state(S2CellId id, const S2ShapeIndexCell* cell); // Sets the iterator state so that done() is true. void set_finished(); // Returns the current contents of the "cell_" field, which may be nullptr // if the cell contents have not been decoded yet. const S2ShapeIndexCell* raw_cell() const; // This method is called to decode the contents of the current cell, if // set_state() was previously called with a nullptr "cell" argument. This // allows decoding on demand for subtypes that keep the cell contents in // an encoded state. It does not need to be implemented at all if // set_state() is always called with (cell != nullptr). // // REQUIRES: This method is thread-safe. // REQUIRES: Multiple calls to this method return the same value. virtual const S2ShapeIndexCell* GetCell() const = 0; // Returns an exact copy of this iterator. virtual std::unique_ptr<IteratorBase> Clone() const = 0; // Makes a copy of the given source iterator. // REQUIRES: "other" has the same concrete type as "this". virtual void Copy(const IteratorBase& other) = 0; // The default implementation of Locate(S2Point). It is instantiated by // each subtype in order to (1) minimize the number of virtual method // calls (since subtypes are typically "final") and (2) ensure that the // correct versions of non-virtual methods such as cell() are called. template <class Iter> static bool LocateImpl(const S2Point& target, Iter* it); // The default implementation of Locate(S2CellId) (see comments above). template <class Iter> static CellRelation LocateImpl(S2CellId target, Iter* it); private: friend class Iterator; // This method is "const" because it is used internally by "const" methods // in order to implement decoding on demand. void set_cell(const S2ShapeIndexCell* cell) const; S2CellId id_; mutable std::atomic<const S2ShapeIndexCell*> cell_; }; // Returns a new iterator positioned as specified. virtual std::unique_ptr<IteratorBase> NewIterator(InitialPosition pos) const = 0; }; ////////////////// Implementation details follow //////////////////// inline int S2ClippedShape::shape_id() const { return shape_id_; } inline bool S2ClippedShape::contains_center() const { return contains_center_; } inline int S2ClippedShape::num_edges() const { return num_edges_; } inline int S2ClippedShape::edge(int i) const { return is_inline() ? inline_edges_[i] : edges_[i]; } // Initialize an S2ClippedShape to hold the given number of edges. inline void S2ClippedShape::Init(int32 shape_id, int32 num_edges) { shape_id_ = shape_id; num_edges_ = num_edges; contains_center_ = false; if (!is_inline()) { edges_ = new int32[num_edges]; } } // Free any memory allocated by this S2ClippedShape. We don't do this in // the destructor because S2ClippedShapes are copied by STL code, and we // don't want to repeatedly copy and free the edge data. Instead the data // is owned by the containing S2ShapeIndexCell. inline void S2ClippedShape::Destruct() { if (!is_inline()) delete[] edges_; } inline bool S2ClippedShape::is_inline() const { return num_edges_ <= inline_edges_.size(); } // Set "contains_center_" to indicate whether this clipped shape contains the // center of the cell to which it belongs. inline void S2ClippedShape::set_contains_center(bool contains_center) { contains_center_ = contains_center; } // Set the i-th edge of this clipped shape to be the given edge of the // original shape. inline void S2ClippedShape::set_edge(int i, int edge) { if (is_inline()) { inline_edges_[i] = edge; } else { edges_[i] = edge; } } inline const S2ClippedShape* S2ShapeIndexCell::find_clipped( const S2Shape* shape) const { return find_clipped(shape->id()); } // Inline because an index cell frequently contains just one shape. inline int S2ShapeIndexCell::num_edges() const { int n = 0; for (int i = 0; i < num_clipped(); ++i) n += clipped(i).num_edges(); return n; } inline S2Shape* S2ShapeIndex::ShapeIterator::operator*() const { return index_->shape(shape_id_); } inline S2ShapeIndex::ShapeIterator& S2ShapeIndex::ShapeIterator::operator++() { ++shape_id_; return *this; } inline S2ShapeIndex::ShapeIterator S2ShapeIndex::ShapeIterator::operator++( int) { return ShapeIterator(index_, shape_id_++); } inline bool S2ShapeIndex::ShapeIterator::operator==(ShapeIterator it) const { S2_DCHECK_EQ(index_, it.index_); return shape_id_ == it.shape_id_; } inline bool S2ShapeIndex::ShapeIterator::operator!=(ShapeIterator it) const { S2_DCHECK_EQ(index_, it.index_); return shape_id_ != it.shape_id_; } inline S2ShapeIndex::ShapeIterator S2ShapeIndex::begin() const { return ShapeIterator(this, 0); } inline S2ShapeIndex::ShapeIterator S2ShapeIndex::end() const { return ShapeIterator(this, num_shape_ids()); } inline S2ShapeIndex::IteratorBase::IteratorBase(const IteratorBase& other) : id_(other.id_), cell_(other.raw_cell()) { } inline S2ShapeIndex::IteratorBase& S2ShapeIndex::IteratorBase::operator=(const IteratorBase& other) { id_ = other.id_; set_cell(other.raw_cell()); return *this; } inline S2CellId S2ShapeIndex::IteratorBase::id() const { return id_; } inline const S2ShapeIndexCell& S2ShapeIndex::IteratorBase::cell() const { // Like other const methods, this method is thread-safe provided that it // does not overlap with calls to non-const methods. S2_DCHECK(!done()); auto cell = raw_cell(); if (cell == nullptr) { cell = GetCell(); set_cell(cell); } return *cell; } inline bool S2ShapeIndex::IteratorBase::done() const { return id_ == S2CellId::Sentinel(); } inline S2Point S2ShapeIndex::IteratorBase::center() const { S2_DCHECK(!done()); return id().ToPoint(); } inline void S2ShapeIndex::IteratorBase::set_state( S2CellId id, const S2ShapeIndexCell* cell) { id_ = id; set_cell(cell); } inline void S2ShapeIndex::IteratorBase::set_finished() { id_ = S2CellId::Sentinel(); set_cell(nullptr); } inline const S2ShapeIndexCell* S2ShapeIndex::IteratorBase::raw_cell() const { return cell_.load(std::memory_order_relaxed); } inline void S2ShapeIndex::IteratorBase::set_cell( const S2ShapeIndexCell* cell) const { cell_.store(cell, std::memory_order_relaxed); } template <class Iter> inline bool S2ShapeIndex::IteratorBase::LocateImpl( const S2Point& target_point, Iter* it) { // Let I = cell_map_->lower_bound(T), where T is the leaf cell containing // "target_point". Then if T is contained by an index cell, then the // containing cell is either I or I'. We test for containment by comparing // the ranges of leaf cells spanned by T, I, and I'. S2CellId target(target_point); it->Seek(target); if (!it->done() && it->id().range_min() <= target) return true; if (it->Prev() && it->id().range_max() >= target) return true; return false; } template <class Iter> inline S2ShapeIndex::CellRelation S2ShapeIndex::IteratorBase::LocateImpl(S2CellId target, Iter* it) { // Let T be the target, let I = cell_map_->lower_bound(T.range_min()), and // let I' be the predecessor of I. If T contains any index cells, then T // contains I. Similarly, if T is contained by an index cell, then the // containing cell is either I or I'. We test for containment by comparing // the ranges of leaf cells spanned by T, I, and I'. it->Seek(target.range_min()); if (!it->done()) { if (it->id() >= target && it->id().range_min() <= target) return INDEXED; if (it->id() <= target.range_max()) return SUBDIVIDED; } if (it->Prev() && it->id().range_max() >= target) return INDEXED; return DISJOINT; } inline S2ShapeIndex::Iterator::Iterator(const Iterator& other) : iter_(other.iter_->Clone()) { } inline S2ShapeIndex::Iterator& S2ShapeIndex::Iterator::operator=( const Iterator& other) { iter_->Copy(*other.iter_); return *this; } inline S2ShapeIndex::Iterator::Iterator(Iterator&& other) : iter_(std::move(other.iter_)) { } inline S2ShapeIndex::Iterator& S2ShapeIndex::Iterator::operator=( Iterator&& other) { iter_ = std::move(other.iter_); return *this; } #endif // S2_S2SHAPE_INDEX_H_
[ "jmr@google.com" ]
jmr@google.com
9670c329d495c468325bf30d85125fe95e61e512
3971983e59390620c53007c51774bb752f52ea34
/The Ethereal Land/Animator.hpp
327f1768ff08e7ae798ee261f2003530eb850dfa
[]
no_license
legalquentin/The-Ethereal-Land
b8e03a2779f1fccf6d462b0e603792ad2dd0a432
24a6d3c364855259a52a08603ccb6e2039e219b9
refs/heads/master
2021-01-11T16:50:20.525072
2017-01-24T20:25:18
2017-01-24T20:25:18
79,681,573
0
0
null
null
null
null
UTF-8
C++
false
false
2,297
hpp
// // Utilities.hpp // The Ethereal Land // // Created by Quentin Le Gal on 19/01/2017. // Copyright © 2017 Quentin Le Gal. All rights reserved. // #pragma once #ifndef Utilities_hpp #define Utilities_hpp #include <SFML/Audio.hpp> #include <SFML/Graphics.hpp> #include <stdio.h> #include <string> #include <list> class Animator { public : std::string GetCurrentAnimationName(); struct Animation { std::string m_Name; sf::Texture m_Texture; bool m_playing; std::vector<sf::IntRect> m_Frames; sf::Time m_Duration; bool m_Looping; // Constructor Animation(std::string const &name, sf::Texture &texture, sf::Time const &duration, bool looping) : m_Name(name), m_Texture(texture), m_Duration(duration), m_Looping(looping) { m_playing = true; } // Add Frames Horizontally void AddFrames(sf::Vector2i const& startFrom, sf::Vector2i const& frameSize, unsigned int frames) { sf::Vector2i current = startFrom; for (unsigned int i = 0; i < frames; i++) { // // Add current Frame from position and frame size m_Frames.push_back(sf::IntRect(current.x, current.y, frameSize.x, frameSize.y)); // Advance current Frame horizontally current.x += frameSize.x; } } }; Animator(sf::Sprite& sprite); Animation& CreateAnimation(std::string const& name, sf::Texture& texture, sf::Time const& duration, bool loop = true); void update(sf::Time const& dt); // return if the switch was successful bool SwitchAnimation(std::string const& name); std::string getCurrentAnimationName() const; void bakeAnimation(Animator &animator, int count, int dimX, sf::Vector2i spriteSize, sf::Texture &texture); void SwitchAnimation(Animation* animation); bool IsAnimationPlaying(); private : // Return with the passed name // return nullptr if no animation is found Animation* Findanimation(std::string const& Name); // references to the sprite sf::Sprite& m_Sprite; sf::Time m_CurrentTime; std::list<Animation> m_Animations; Animation* m_CurrentAnimation; }; #endif /* Utilities_hpp */
[ "legal.quentin@gmail.com" ]
legal.quentin@gmail.com
630ae6008d50b091b1df0b896a9d12f9064a2f98
c6a6a000cd67f06f3a51d80b131b941df034b3c5
/cmake-build-debug/controllers/controller_autogen/mocs_compilation.cpp
04dad76c6821d4a0c5e3d31c268f3a57f2bc8ec7
[]
no_license
eerimez/tf2blog
ff822aaf4e6ccdc17e23d3d4095d1bc6293103ef
f24f904742bc73af70fdf4f2666bd987c0fff6c5
refs/heads/master
2023-06-22T19:18:49.465478
2019-11-14T16:01:33
2019-11-14T16:01:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
157
cpp
// This file is autogenerated. Changes will be overwritten. #include "EWIEGA46WW/moc_applicationcontroller.cpp" #include "EWIEGA46WW/moc_blogcontroller.cpp"
[ "john@qlcorp.net" ]
john@qlcorp.net
ae24f38fa3fe353d94fef7f5eaccec1dc183adeb
07e6fc323f657d1fbfc24f861a278ab57338b80a
/cpp/apps/SailWar_Multi/test_buoyancy.cpp
5236114579e2dee2c83861a754db8b013c2d63b6
[ "MIT" ]
permissive
ProkopHapala/SimpleSimulationEngine
99cf2532501698ee8a03b2e40d1e4bedd9a12609
47543f24f106419697e82771289172d7773c7810
refs/heads/master
2022-09-05T01:02:42.820199
2022-08-28T10:22:41
2022-08-28T10:22:41
40,007,027
35
4
null
null
null
null
UTF-8
C++
false
false
5,028
cpp
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <vector> #include <algorithm> #include <math.h> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include "Draw2D.h" #include "fastmath.h" #include "Vec2.h" #include "VecN.h" #include "PolyLinear1d.h" #include "geom2D.h" #include "Convex2d.h" #include "AppSDL2OGL.h" #include "buoyancy.h" #include "testUtils.h" // ====================== TestApp class TestAppTerrainCubic : public AppSDL2OGL { public: double angle =0.0d; double dAngle=0.0005d; constexpr static int nPhis = 500; double phis[ nPhis ]; double wts [ nPhis ]; double Ms [ nPhis ]; constexpr static int np = 4; Convex2d * hull; double yLs [ np ]; double yRs [ np ]; double xs [ np ]; // ---- function declarations virtual void draw (); virtual void drawHUD(); void evalPolar( double phi_min, double phi_max, double displacement ); TestAppTerrainCubic( int& id, int WIDTH_, int HEIGHT_ ); }; TestAppTerrainCubic::TestAppTerrainCubic( int& id, int WIDTH_, int HEIGHT_ ) : AppSDL2OGL( id, WIDTH_, HEIGHT_ ) { hull = new Convex2d( np ); hull->corners[0].set( -1.0, -1.0 ); hull->corners[1].set( +1.0, -1.0 ); hull->corners[2].set( +1.0, +1.0 ); hull->corners[3].set( -1.0, +1.0 ); /* hull->corners[0].set( -1.0, -1.0 ); hull->corners[1].set( +1.0, -1.0 ); hull->corners[2].set( +1.5, +1.0 ); hull->corners[3].set( -1.5, +1.0 ); */ /* hull->corners[0].set( -1.5, -1.0 ); hull->corners[1].set( +1.5, -1.0 ); hull->corners[2].set( +1.0, +1.0 ); hull->corners[3].set( -1.0, +1.0 ); */ evalPolar( -1.5, 1.5, 2.0 ); //exit(0); } void TestAppTerrainCubic::evalPolar( double phi_min, double phi_max, double displacement ){ double dphi = ( phi_max - phi_min ) / (nPhis-1); for( int i=0; i<nPhis; i++ ){ double phi = phi_min + dphi * i; Vec2d dir; dir.set( sin( phi ), cos( phi ) ); hull->projectToLine( dir, xs, yLs, yRs ); double watterline; double moment = integrate_moment( np, xs, yLs, yRs, displacement, watterline ); phis[i] = phi; Ms [i] = moment; wts [i] = watterline; printf( " %i %f %f %f \n", i, phi, moment, watterline ); } } void TestAppTerrainCubic::draw(){ glClearColor( 1.0f, 1.0f, 1.0f, 0.0f ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glDisable( GL_DEPTH_TEST ); // ============== project to line Convex Polygons glColor3f( 0.7f, 0.7f, 0.7f ); Draw2D::drawConvexPolygon( np, hull->corners, false ); //Vec2d dir; dir.set( +1.0, 0.1 ); dir.normalize( ); //ouble angle = ( frameCount%100 - 50 ) * 0.007; //angle = 0.3d; angle += dAngle; if ( ( angle > 1.5 ) && ( dAngle > 0 ) ){ dAngle = -dAngle; } else if ( ( angle < -1.5 ) && ( dAngle < 0 ) ){ dAngle = -dAngle; }; Vec2d dir; dir.set( sin( angle ), cos( angle ) ); hull->projectToLine( dir, xs, yLs, yRs ); //printArray( base.n, xs ); //printArray( base.n, yLs ); //printArray( base.n, yRs ); double ys [ np ]; VecN::sub( np, yLs, yRs, ys ); double displacement = 2.0; /* PolyLinear1d pline( np, xs, ys ); pline.n = np; pline.xs = xs; pline.ys = ys; //double V = pline.integrate( -1000.0, 1000.0 ); double V = pline.integrate_ibounds( 0, pline.n ); double x_disp = pline.x_of_integral( displacement ); //double V_disp = pline.integrate( -1000.0, x_disp ); double V_disp = NAN; printf( " V %f xhalf %f Vhalf %f Vtarget %f \n", V, x_disp, V_disp, displacement ); pline.detach(); */ double watterline; double moment = integrate_moment( np, xs, yLs, yRs, displacement, watterline ); //printf( " V %f xtarget %f %f Vtarget %f %f moment %f \n", V, x_disp, watterline, V_disp, displacement, moment ); //printf( " %i %f %f \n", frameCount, watterline, moment ); glColor3f( 0.2f, 0.9f, 0.2f ); Draw2D::drawLine( { -10.0, watterline }, { +10.0, watterline } ); glColor3f( 0.9f, 0.9f, 0.9f ); Draw2D::drawLine( { 0.0, -10.0 }, { 0.0, +10.0 } ); Draw2D::drawLine( {-10.0, 0.0 }, {+10.0, 0.0 } ); glColor3f( 0.9f, 0.2f, 0.2f ); Draw2D::plot( np, yLs, xs ); glColor3f( 0.2f, 0.2f, 0.9f ); Draw2D::plot( np, yRs, xs ); glColor3f( 0.0f, 0.0f, 0.0f ); Draw2D::plot( np, ys, xs ); glColor3f( 0.9f, 0.2f, 0.9f ); Draw2D::plot( nPhis, phis, Ms ); Draw2D::drawPointCross_d( { angle, moment }, 0.1 ); glColor3f( 0.2f, 0.7f, 0.9f ); Draw2D::plot( nPhis, phis, wts ); Draw2D::drawPointCross_d( { angle, watterline }, 0.1 ); // ============== Mouse Raycast Convex Polygons //STOP = true; }; void TestAppTerrainCubic::drawHUD(){} // ===================== MAIN TestAppTerrainCubic * testApp; int main(int argc, char *argv[]){ SDL_Init(SDL_INIT_VIDEO); SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 1); int junk; testApp = new TestAppTerrainCubic( junk , 800, 600 ); testApp->loop( 1000000 ); return 0; }
[ "ProkopHapala@gmail.com" ]
ProkopHapala@gmail.com
2e23dff8a6768d1b86f704080adf4bbfcdf96dac
489718e32bdcacf338e75630a2f7f75ac6668c72
/freeglut project 3D/Llanta.h
aebdb706ce9d9b9060331df990c51ca41976a44c
[]
no_license
antoniofmp/snowman_graphics_freeglut
7697efb3de2d252da6f1f59551a378b7e3558f6d
200cdff6aa9e8391d9c1017db69a4e294d3975f5
refs/heads/master
2022-04-18T16:02:11.586081
2020-04-20T06:45:40
2020-04-20T06:45:40
257,185,906
0
0
null
null
null
null
UTF-8
C++
false
false
317
h
#include <GL/glut.h> #include <Windows.h> #include <gl/GL.h> #include <gl/GLU.h> #include "Objeto3D.h" class Llanta : public Objeto3D{ public: GLUquadricObj* llanta1; //objeto para el tronco //constructor y destructor Llanta(); ~Llanta(); void dibuja(); // para dibujar en el main.cpp };
[ "antoniofmp@gmail.com" ]
antoniofmp@gmail.com
100fef3e9043d31ccfc50426905e45f2db7603e3
adbc979313cbc1f0d42c79ac4206d42a8adb3234
/Source Code/李沿橙 2017-10-3/competition/source/武汉 张志立/ping.cpp
1105775fd0736067206416af585cca5e7511f1ee
[]
no_license
UnnamedOrange/Contests
a7982c21e575d1342d28c57681a3c98f8afda6c0
d593d56921d2cde0c473b3abedb419bef4cf3ba4
refs/heads/master
2018-10-22T02:26:51.952067
2018-07-21T09:32:29
2018-07-21T09:32:29
112,301,400
1
0
null
null
null
null
UTF-8
C++
false
false
934
cpp
#include<iostream> #include<cmath> #include<cstdio> #include<cstring> using namespace std; int i,j,k,m,n,a,b; int l[17][17]; int u[115],v[115]; int bb[115][17]; int bj[115],sum[17]; int ans[17]; int z[17],zb[17]; void dfs(int a,int b,int s) { if(a==b) for(j=1;j<=s-1;j++) bb[i][z[j]]=1; else for(int j=1;j<=n;j++) { if(l[a][j] && zb[j]) { z[s]=j; zb[j]=false; dfs(j,b,s+1); z[s]=0; zb[j]=true; } } } int main() { //freopen("ping.in","r",stdin); //freopen("ping.out","w",stdout); cin>>n>>m; for(i=1;i<=m;i++) { cin>>a>>b; l[a][b]=l[b][a]=1; } cin>>k; for(i=1;i<=k;i++) { cin>>u[i]>>v[i]; } for(i=1;i<=n;i++) { zb[i]=true; } for(i=1;i<=k;i++) { dfs(u[i],v[i],1); } for(j=1;j<=k;j++) { for(i=1;i<=n;i++) cout<<bb[j][i]<<' '; cout<<endl; } return 0; }
[ "lycheng1215@sina.com" ]
lycheng1215@sina.com
b622a008327566766728831d4d586f9e17b3bd43
bf4ebb891673e4d2345ba08ede6ef7a99dced447
/work/DCMConverter/DCMConverter.cpp
9c68f3c860a13eae1a3b418ad7f8b99d33b8f662
[]
no_license
pglen/xraynotes
1fc500da9d8ba5584bbf0024028ee273971bf51c
2cb7f1fda78a03e4c98a1f8aa1d8ee27f113b340
refs/heads/master
2021-01-22T01:19:19.821846
2017-09-02T20:20:42
2017-09-02T20:20:42
102,216,286
2
0
null
null
null
null
UTF-8
C++
false
false
2,076
cpp
// DCMConverter.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "DCMConverter.h" #include "DCMConverterDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDCMConverterApp BEGIN_MESSAGE_MAP(CDCMConverterApp, CWinApp) //{{AFX_MSG_MAP(CDCMConverterApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDCMConverterApp construction CDCMConverterApp::CDCMConverterApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CDCMConverterApp object CDCMConverterApp theApp; ///////////////////////////////////////////////////////////////////////////// // CDCMConverterApp initialization BOOL CDCMConverterApp::InitInstance() { AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif CDCMConverterDlg dlg; m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
[ "peterglen99@gmail.com" ]
peterglen99@gmail.com
c826bf28c8ab91fc630079e56d17fe757372d095
485faf9d4ec7def9a505149c6a491d6133e68750
/include/inv/misc/SoCallbackList.H
49c00bd0704d957f777422c10428c84c4f2741dc
[ "LicenseRef-scancode-warranty-disclaimer", "ECL-2.0" ]
permissive
ohlincha/ECCE
af02101d161bae7e9b05dc7fe6b10ca07f479c6b
7461559888d829338f29ce5fcdaf9e1816042bfe
refs/heads/master
2020-06-25T20:59:27.882036
2017-06-16T10:45:21
2017-06-16T10:45:21
94,240,259
1
1
null
null
null
null
UTF-8
C++
false
false
3,484
h
/* * * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Further, this software is distributed without any warranty that it is * free of the rightful claim of any third person regarding infringement * or the like. Any license provided herein, whether implied or * otherwise, applies only to this software file. Patent licenses, if * any, provided herein do not apply to combinations of this program with * other software, or any other product whatsoever. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy, * Mountain View, CA 94043, or: * * http://www.sgi.com * * For further information regarding this notice, see: * * http://oss.sgi.com/projects/GenInfo/NoticeExplan/ * */ // -*- C++ -*- /* * Copyright (C) 1991 Silicon Graphics, Inc. * _______________________________________________________________________ ______________ S I L I C O N G R A P H I C S I N C . ____________ | | $Revision: 22148 $ | | Description: | Callback list - a list of callback functions and associated data, | with member functions to add, remove, and invoke callbacks. | | Classes: SoCallbackList | | Author(s): David Mott | ______________ S I L I C O N G R A P H I C S I N C . ____________ _______________________________________________________________________ */ #ifndef _SO_CALLBACK_LIST_ #define _SO_CALLBACK_LIST_ #include "inv/SbPList.H" ////////////////////////////////////////////////////////////////////////////// // // Class: SoCallbackList // ////////////////////////////////////////////////////////////////////////////// // Callback functions that are registered with this class should // be cast to this type. typedef void SoCallbackListCB(void *userData, void *callbackData); // C-api: prefix=SoCBList class SoCallbackList { public: SoCallbackList(); ~SoCallbackList(); // // Managing callback functions // At callback time, f will be called with userData as the first // parameter, and callback specific data as the second parameter. // e.g. (*f)(userData, callbackData); // C-api: name=addCB void addCallback(SoCallbackListCB *f, void *userData = NULL); // C-api: name=removeCB void removeCallback(SoCallbackListCB *f, void *userData = NULL); // C-api: name=clearCB void clearCallbacks() { list.truncate(0); } // C-api: name=getNumCB int getNumCallbacks() const { return list.getLength(); } // C-api: name=invokeCB void invokeCallbacks(void *callbackData); private: // callbackList holds a list of functions and user data SbPList list; }; #endif /* _SO_CALLBACK_LIST_ */
[ "andre.ohlin@umu.se" ]
andre.ohlin@umu.se
13b91595037516a63606a6253ab2c79bbc7784af
8c13b36ed2760ac3397df16ae877af22561fd567
/server-streaming/src/services/protocols/audio_frame_protocol.h
674555846228ddc3a7999e239a9ffe1afed99a03
[]
no_license
vietanhdev/gict-meeting
f30e0ea1825c88a693c8b08d595c2c8de0e68ab0
b04c23edade48928078eeac06871bbbf1ddd50e8
refs/heads/master
2021-11-23T23:31:29.445715
2021-10-21T15:22:39
2021-10-21T15:22:39
175,574,112
3
1
null
null
null
null
UTF-8
C++
false
false
1,313
h
// The basic protocol transmits raw, uncompressed audio frames only. This is // the most basic audio protocol. #ifndef AUDIO_FRAME_PROTOCOL_H #define AUDIO_FRAME_PROTOCOL_H #include <vector> #include "protocol.h" #include "conference.h" #include "message_type.h" class AudioFrameProtocolData : public ProtocolData { public: std::vector<unsigned char> packageData() const override; std::vector<unsigned char> packageConferenceAudioFrame(unsigned char client_id, const std::vector<unsigned char> &data) const; std::vector<unsigned char> unpackPayload( const std::vector<unsigned char>& raw_bytes); // Return true if unpack successfully // Otherwise return false bool unpackHeader(const std::vector<unsigned char>& raw_bytes) override; void unpackData( const std::vector<unsigned char>& raw_bytes, std::vector<unsigned char>& data ); // Return client id of packet (Who sent this packet?) unsigned char getClientId() const; int getClientAuthKey() const; // Return message of packet unsigned char getMessage() const; const std::vector<unsigned char>& getHeaderData() const; private: unsigned char client_id; int client_auth_key; unsigned char message; std::vector<unsigned char> header_data; }; #endif // AUDIO_FRAME_PROTOCOL_H
[ "vietanh@vietanhdev.com" ]
vietanh@vietanhdev.com
625dcbcf7405cf2e5619071efb249cd291940f54
137352bada7bf748ad197657f53361015fdb05d2
/C++/OpenGL/Program 6 - Creature Watcher/Team Final/ParticleEngine.h
08c4a31d51691c639ad1ad6da44b48e3afc109bf
[]
no_license
ryanpsloan/cnm
7b25cb32debfa728b9d90933ce6bcb46afbfe516
6b22a43bf4386b148f3ecd12dfa436ff44aceeca
refs/heads/master
2020-04-20T12:50:48.114979
2014-11-22T02:09:17
2014-11-22T02:09:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
590
h
//Ryan Sloan //Particle Definition for Particle Engine // - SloanP6 - //OpenGL //CIS 2270 //rsloan2@cnm.edu #include <windows.h> // Must have for Windows platform builds #include <gl\gl.h> // Microsoft OpenGL headers (version 1.1 by themselves) #include <gl\glu.h> // OpenGL Utilities #include <gl\glut.h> #include "Particle.h" #include "Functions.h" #ifndef _PARTICLE_ENGINE_H #define _PARTICLE_ENGINE_H class ParticleEngine : public Particle { public: Particle Particles[MAX_PARTICLES]; ParticleEngine(); void Pos(); void Neg(); void Neu(); void RenderFire(); }; #endif
[ "ryansdeal@hotmail.com" ]
ryansdeal@hotmail.com
5b6ff2becb92f949ddec8da25b29af4ec88f092a
20d129f8b674c47cd32947bf7b14a4287cfb543d
/t1/t1/t1.cpp
b54293b5e2dd96227dbed99f211af117785b9e32
[]
no_license
OwenKDuffy/CompArch2
6ef1ab6bd236ee06702328b5f63eb0c02c167724
9652f1ebe37d1a1349ff9dc4dc4e0e84758eb71c
refs/heads/master
2020-03-29T22:18:52.789410
2018-11-29T20:02:25
2018-11-29T20:02:25
150,413,723
0
0
null
null
null
null
UTF-8
C++
false
false
121
cpp
// t1.cpp : Defines the entry point for the console application. // #include "stdafx.h" int main() { return 0; }
[ "duffyow@tcd.ie" ]
duffyow@tcd.ie
02155096aa0523182361edaa5f6064cef3338934
13e15674dffc2a3d7feb0cfa879d4ed201d1996c
/Engine/Entity.h
d1a156de02a2db84a5a28a8dd4fc583812e9b166
[]
no_license
SreeDev-4522/PooGame
3097a0efd749da9d77bcfe64c5560beaec206de6
737c72b7a8b83a61aba10821df5cd9526fc81906
refs/heads/master
2022-12-14T00:52:31.241281
2020-08-10T13:59:23
2020-08-10T13:59:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
592
h
#pragma once #include "Graphics.h" #include "Vec2D.h" class Entity { public: // Data Members Vec2D coordinate; // Top Left Coordinates of the object Vec2D velocity; // Velocity of the object int r = 255, g = 255, b = 255; // Colour of the object int width; protected: // Member Functions public: Entity() = delete; Entity(Vec2D& coordinate, int width = 24); Entity(Vec2D& coordinate, int r, int g, int b, int width = 24); static bool checkCollision(const Entity& player, const Entity& poo); virtual void keepInFrame(Vec2D& vertice); virtual void draw(Graphics& gfx) const = 0; };
[ "shubh.agarwal@live.com" ]
shubh.agarwal@live.com
891d20af6c4ce3e83c62f106f79eab371e8e4610
fdec81cec63805cdcedef2d5b93274e13be2e9b7
/src/TopDileptonPlots_t.cpp
0e1daee903ed85b3b46cd5d06d4acf8194579381
[]
no_license
ddboline/top_dilepton_me
15c54ddb5e455d847eb6d55481a73d13b5b62827
e80a78d0297882f15adc20cc45f37c1d679c64ac
refs/heads/master
2016-09-08T01:52:26.053371
2015-09-09T13:53:42
2015-09-09T13:53:42
25,307,711
0
0
null
null
null
null
UTF-8
C++
false
false
79
cpp
#include "top_dilepton_me/TopDileptonPlots.hpp" int main() { return( 0 ); }
[ "ddboline@gmail.com" ]
ddboline@gmail.com
ef3339ce56775b3efc8cee64a14f3d6d407eddd6
a52e5bf6bf2340e238655e914ab7947b4b601a7b
/Source1.cpp
83976bf41a16b0742036a20bffad47d17783e470
[]
no_license
MahiPalihawadana/DIP
4dca78a979f429a5f68ebd2621a8c8fc7a84f836
af4852c9bbabf7c7f5b5ca0463a09ead39b2774c
refs/heads/master
2023-06-15T08:22:35.630941
2021-07-14T04:00:27
2021-07-14T04:00:27
385,145,275
0
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
#include "cv.h" #include "highgui.h" int main(int argc, char* argv[]) { IplImage* img; img = cvLoadImage(argv[1], CV_LOAD_IMAGE_COLOR); if (!img){ printf("Could not load image file: %s\n", argv[1]); return -1; } cvNamedWindow("Image"); cvShowImage("Image", img); cvWaitKey(0); cvDestroyWindow("Image"); cvReleaseImage(&img); return 0; }
[ "dilkipalihawadana95@gmail.com" ]
dilkipalihawadana95@gmail.com
998192cfab85600fec504fdda2aa0d097b28c92b
18e9db71a0e207dbc7654135123bceaa7b3339e4
/6.学习文档/1.c++/note-master/C++/stlbookcode/c1/1config3.cpp
e322471e50d166c9ec37445c339ef06a1ddfb4b5
[]
no_license
TheIslland/learning-in-collegelife
358490cc74914b87d4d626a6485c2fe1ff06462f
1794e18addfd05e32cf8108895ac1585586394e1
refs/heads/master
2021-07-08T00:51:00.908370
2020-07-11T01:04:35
2020-07-11T01:04:35
144,252,958
2
0
null
null
null
null
UTF-8
C++
false
false
984
cpp
//file:1config3.cpp //测试在class template中拥有static data members //test __STL_STATIC_TEMPLATE_MEMBER_BUG,define in <slt_config.h> // //编译器:clang-800.0.42.1 #include <iostream> using namespace std; template <typename T> class testclass { public: static int _data; }; template<> int testclass<int>::_data = 1; template<> int testclass<char>::_data = 2; int main() { cout<<testclass<int>::_data<<endl; //1 cout<<testclass<char>::_data<<endl; //2 testclass<int> obji1, obji2; testclass<char> objc1, objc2; cout<<obji1._data<<endl; //1 cout<<obji2._data<<endl; //1 cout<<objc1._data<<endl; //2 cout<<objc2._data<<endl; //2 obji1._data = 3; objc2._data = 4; cout<<obji1._data<<endl; //3 cout<<obji2._data<<endl; //3 cout<<objc1._data<<endl; //4 cout<<objc2._data<<endl; //4 return 1; }
[ "861436930@qq.com" ]
861436930@qq.com
ade2d710441e51117d4cda6287595e2431add6ab
688cd6b75839ba98141d0aa089d1dee28f2a0c77
/C/ACM/51Nod/1283 最小周长.cpp
a8d0efe83457cc5130fc59ecedfdbe030fa181ad
[]
no_license
chenwei182729/code
c3e1208264e96c3146c8b6e4044eaed12fd269b3
ac9c81da6c010bd134d61127d72ea5a8e651f17d
refs/heads/master
2020-06-30T20:36:35.557266
2016-12-02T12:40:52
2016-12-02T12:40:52
74,349,006
0
0
null
null
null
null
UTF-8
C++
false
false
409
cpp
#include<iostream> #include<cmath> #define LOCAL using namespace std; int main() { #ifdef LOCAL freopen("1283.in","r",stdin); freopen("1283.out","w",stdout); #endif int S=0,r=0,d=0,tmp=0,sum=0; cin>>S; r=sqrt(S); for(d=0;d<=r;d++) { tmp=S%(r+d); if(tmp==0) { tmp=S/(r+d); break; } } cout<<"r="<<r<<",tmp="<<tmp<<"d="<<d<<endl; sum=2*(S/tmp+tmp); cout<<sum<<endl; return 0; }
[ "chenwei182729@163.com" ]
chenwei182729@163.com
4c2155ebf483ddc9998f5d15c511a4e0e755f523
7a92206984e9007948afaa363adbb95c06897a74
/demo/CppBaseTest/for_each.cpp
04126544ad0eba8a611ef9e39b73fa7afdfb08f9
[]
no_license
fengbingchun/Messy_Test
6a801414a36581bce16edbde122b66ac86b57ddb
b55fcfc4b8adc538f9ac70bf78aa391a50b20241
refs/heads/master
2023-06-26T18:07:59.679346
2023-06-22T06:23:16
2023-06-22T06:23:16
55,020,860
305
171
null
null
null
null
UTF-8
C++
false
false
6,217
cpp
#include "for_each.hpp" #include <iostream> #include <algorithm> // for_each #include <vector> #include <string> // Blog: http://blog.csdn.net/fengbingchun/article/details/52294862 //////////////////////////////////////////// // reference: http://en.cppreference.com/w/cpp/algorithm/for_each struct Sum { Sum() : sum{ 0 } { } void operator()(int n) { sum += n; } int sum; }; int test_for_each1() { std::vector<int> nums{ 3, 4, 2, 8, 15, 267 }; std::cout << "before:"; for (auto const &n : nums) { std::cout << ' ' << n; } std::cout << '\n'; std::for_each(nums.begin(), nums.end(), [](int &n){ n++; }); // calls Sum::operator() for each number Sum s = std::for_each(nums.begin(), nums.end(), Sum()); std::cout << "after: "; for (auto const &n : nums) { std::cout << ' ' << n; } std::cout << '\n'; std::cout << "sum: " << s.sum << '\n'; return 0; } //////////////////////////////////////////////////// // reference: http://www.cplusplus.com/reference/algorithm/for_each/ void myfunction(int i) { // function: std::cout << ' ' << i; } struct myclass { // function object type: void operator() (int i) { std::cout << ' ' << i; } } myobject; int test_for_each2() { std::vector<int> myvector; myvector.push_back(10); myvector.push_back(20); myvector.push_back(30); std::cout << "myvector contains:"; for_each(myvector.begin(), myvector.end(), myfunction); std::cout << '\n'; // or: std::cout << "myvector contains:"; for_each(myvector.begin(), myvector.end(), myobject); std::cout << '\n'; return 0; } ///////////////////////////////////////////////// // reference: http://thispointer.com/stdfor_each-tutorial-usage-details-with-examples/ void addNames(std::vector<std::string> & vecNames) { vecNames.push_back("Varun"); vecNames.push_back("Ajay"); vecNames.push_back("John"); vecNames.push_back("Rita"); } void printName(std::string name) { std::cout << name << std::endl; } class NameChecker { std::string m_biggerName; int m_nameCount; public: NameChecker() : m_biggerName(""), m_nameCount(0) {} void operator()(std::string name) { if (m_biggerName.size() < name.size()) m_biggerName = name; m_nameCount++; } const std::string& getBiggerName() const { return m_biggerName; } int getNameCount() const { return m_nameCount; } }; void example_1(std::vector<std::string> & vecNames) { // Display Each name in vector using std::for_each and global function std::for_each(vecNames.begin(), vecNames.end(), printName); } void example_2(std::vector<std::string> & vecNames) { // Now Display Each name in vector using std::for_each and Lambda function std::for_each(vecNames.begin(), vecNames.end(), [](std::string name) { std::cout << name << std::endl; }); } void example_3(std::vector<std::string> & vecNames) { // Now count the number of names and in end print the biggest name // Let's do this with std::for_each and a function object. NameChecker nameCheckerObj = std::for_each(vecNames.begin(), vecNames.end(), NameChecker()); std::cout << std::endl << "Biggest Name = " << nameCheckerObj.getBiggerName() << std::endl; std::cout << std::endl << "Total Names = " << nameCheckerObj.getNameCount() << std::endl; } int test_for_each3() { std::vector<std::string> vecNames; addNames(vecNames); example_1(vecNames); example_2(vecNames); example_3(vecNames); return 0; } /////////////////////////////////////////////////// // reference: https://msdn.microsoft.com/en-us/library/e5sk9w9k.aspx // The function object multiplies an element by a Factor template <class Type> class MultValue { private: Type Factor; // The value to multiply by public: // Constructor initializes the value to multiply by MultValue(const Type& _Val) : Factor(_Val) { } // The function call for the element to be multiplied void operator ( ) (Type& elem) const { elem *= Factor; } }; // The function object to determine the average class Average { private: long num; // The number of elements long sum; // The sum of the elements public: // Constructor initializes the value to multiply by Average() : num(0), sum(0) { } // The function call to process the next elment void operator ( ) (int elem) { num++; // Increment the element count sum += elem; // Add the value to the partial sum } // return Average operator double() { return static_cast <double> (sum) / static_cast <double> (num); } }; int test_for_each4() { using namespace std; vector <int> v1; vector <int>::iterator Iter1; // Constructing vector v1 for (int i = -4; i <= 2; i++) { v1.push_back(i); } cout << "Original vector v1 = ( "; for (Iter1 = v1.begin(); Iter1 != v1.end(); Iter1++) cout << *Iter1 << " "; cout << ")." << endl; // Using for_each to multiply each element by a Factor for_each(v1.begin(), v1.end(), MultValue<int>(-2)); cout << "Multiplying the elements of the vector v1\n " << "by the factor -2 gives:\n v1mod1 = ( "; for (Iter1 = v1.begin(); Iter1 != v1.end(); Iter1++) cout << *Iter1 << " "; cout << ")." << endl; // The function object is templatized and so can be // used again on the elements with a different Factor for_each(v1.begin(), v1.end(), MultValue<int>(5)); cout << "Multiplying the elements of the vector v1mod\n " << "by the factor 5 gives:\n v1mod2 = ( "; for (Iter1 = v1.begin(); Iter1 != v1.end(); Iter1++) cout << *Iter1 << " "; cout << ")." << endl; // The local state of a function object can accumulate // information about a sequence of actions that the // return value can make available, here the Average double avemod2 = for_each(v1.begin(), v1.end(), Average()); cout << "The average of the elements of v1 is:\n Average ( v1mod2 ) = " << avemod2 << "." << endl; return 0; } ////////////////////////////////////////////////////// // reference: https://www.tutorialcup.com/cplusplus/for-each-loop.htm void fun1(int x) { std::cout << x << " "; } struct Class1 { // object type function void operator() (int x) { std::cout << x << " "; } } obj1; int test_for_each5() { int arr[] = { 11, 21, 4, 13 }; std::for_each(arr, arr + 4, fun1); std::cout << std::endl; std::for_each(arr, arr + 4, obj1); return 0; }
[ "fengbingchun@163.com" ]
fengbingchun@163.com
3e1e2703eb02c45bd645857184b5f8947c576b68
5d07b105147d5f20ad67f8c15f2670e98ed4430c
/MakerbotFEMSim/MakerbotFEMSim/BaseStepper.cpp
1bb9a29388f6c5ba03512c1df35bb50b011c899d
[]
no_license
arjunnar/MakerbotFEMSim
da5bd11288aeb5abffd4311a4a04a8fc9f1d4b51
3a34537ae2eea8a2e3a505049e6de3d8e809404b
refs/heads/master
2021-01-19T11:43:11.514497
2014-05-15T16:59:56
2014-05-15T16:59:56
18,683,982
0
0
null
null
null
null
UTF-8
C++
false
false
98
cpp
#include "BaseStepper.h" BaseStepper::BaseStepper(ElementMesh * mesh) { this->mesh = mesh; }
[ "lusmyk@mit.edu" ]
lusmyk@mit.edu
ee10046512f27f145ea15f948c5d9d98c9ed003e
4be1e4021a834f7996765a14e91e0f7f41f273d9
/nn.h
12f593cb48b92b6c291e99a736e679d4dd8c53c6
[]
no_license
wolverineq/nn
bdad1bcddf90aef279478268430afc21d69a4676
6798a7688a27ff17379be5114e34d80670b2dd19
refs/heads/master
2021-05-14T19:22:57.678863
2017-12-20T23:26:47
2017-12-20T23:26:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,325
h
#ifndef NN_H #define NN_H #include "autodiff/autodiff.h" #include "nn/tensor-tree.h" namespace nn { struct pred_nn_t { std::shared_ptr<autodiff::op_t> logprob; }; pred_nn_t make_pred_nn(std::shared_ptr<tensor_tree::vertex> var_tree, std::shared_ptr<autodiff::op_t> input); std::shared_ptr<tensor_tree::vertex> make_pred_tensor_tree(); struct log_loss { la::cpu::tensor_like<double> const& gold; la::cpu::tensor_like<double> const& pred; log_loss(la::cpu::tensor_like<double> const& gold, la::cpu::tensor_like<double> const& pred); double loss(); la::cpu::tensor<double> grad(double scale=1); }; struct l2_loss { la::cpu::tensor_like<double> const& gold; la::cpu::tensor_like<double> const& pred; l2_loss(la::cpu::tensor_like<double> const& gold, la::cpu::tensor_like<double> const& pred); double loss(); la::cpu::tensor<double> grad(double scale=1); }; struct seq_pred_nn_t { std::vector<std::shared_ptr<autodiff::op_t>> logprob; }; seq_pred_nn_t make_seq_pred_nn( std::shared_ptr<tensor_tree::vertex> var_tree, std::vector<std::shared_ptr<autodiff::op_t>> const& feat); } #endif
[ "haotang@ttic.edu" ]
haotang@ttic.edu
f46e47cb980b3ddf8d23349c84731b35c6f98546
31589435071cbff4c5e95b357d8f3fa258f43269
/PPTVForWin8/ppbox_1.2.0/src/p2p/server_mod/ImageServer/SessionManager.cpp
c7fe04c0f3d5adb816373d443ac63b344666bc94
[]
no_license
huangyt/MyProjects
8d94656f41f6fac9ae30f089230f7c4bfb5448ac
cd17f4b0092d19bc752d949737c6ed3a3ef00a86
refs/heads/master
2021-01-17T20:19:35.691882
2013-05-03T07:19:31
2013-05-03T07:19:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
133
cpp
#include "Common.h" #include "SessionManager.h" SessionManager::SessionManager(void) { } SessionManager::~SessionManager(void) { }
[ "penneryu@outlook.com" ]
penneryu@outlook.com
9beb862bccf152dc83f12ef1e1a4964b5747135f
f856ad2e96263a38a6c717eca995f8a3f66b3f2f
/tools/compiler/dr/src/parse/parse.cc
a4fbbe36d486aea09de9a19dd84a4538f7d5c8e8
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "BSL-1.0", "Apache-2.0", "BSD-2-Clause", "MIT" ]
permissive
xiake-1024/Pebble
befaee5868905fb804c50d895e80d3489d464200
283310f67f5b30adaed5a21df97f706560b3617f
refs/heads/master
2022-12-09T14:24:51.785830
2020-09-26T03:05:05
2020-09-26T03:05:05
296,327,254
0
0
NOASSERTION
2020-09-17T13:00:05
2020-09-17T13:00:04
null
UTF-8
C++
false
false
1,403
cc
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include "t_type.h" #include "t_typedef.h" #include "../md5.h" #include "../main.h" void t_type::generate_fingerprint() { if (! has_fingerprint()) { pdebug("generating fingerprint for %s", get_name().c_str()); std::string material = get_fingerprint_material(); md5_state_t ctx; md5_init(&ctx); md5_append(&ctx, (md5_byte_t*)(material.data()), (int)material.size()); md5_finish(&ctx, (md5_byte_t*)fingerprint_); } } t_type* t_type::get_true_type() { t_type* type = this; while (type->is_typedef()) { type = ((t_typedef*)type)->get_type(); } return type; }
[ "chexiongsheng@qq.com" ]
chexiongsheng@qq.com
359c2a1c8c28166d04a89e9b01dfaceabaffca83
1b547e4ff87c7c4f4fe0acd9b45a714455b14fa3
/opencv/opencv/源.cpp
92635240d4365bc14ae5227e6906536ec4729e88
[]
no_license
wisdombyzf/opencv
fff34ba6cda7c8b9974015ebf965c0b0d79e13a1
bfb443b4a68175c8c0a45bcc8559a4ac185a8128
refs/heads/master
2021-05-07T15:44:00.320417
2017-10-28T06:17:54
2017-10-28T06:17:54
108,533,841
0
0
null
null
null
null
GB18030
C++
false
false
780
cpp
/* 调用nameWindow函数和imshow函数,显示出两个窗口时将debug模式改为release模式即可 */ #include<iostream> #include<opencv2\core.hpp> #include<opencv2\highgui\highgui.hpp> #include<opencv2\opencv.hpp> #include<opencv2\objdetect.hpp> //物体侦测头文件 #include<opencv2\imgproc.hpp> #include"简单图形绘制.h" #include"GUI设置.h" #include"基本操作.h" #include"腐蚀与膨胀.h" #include"图像模糊.h" #include"边缘检测.h" #include"视频基本操作.h" #include"人脸检测.h" using namespace cv; using namespace std; int main(void) { string name; cout << "请输入将要进行人脸检测的视频文件名(包括后缀)" << endl; cin >> name; cv_8(name); system("pause"); return 0; }
[ "781516223@qq.com" ]
781516223@qq.com
41bf5407560de6e585090d8036011a163547c4a5
147ca0f5523e06c012a60d8b388fa53489d5d570
/codejam/nested.cpp
dad21d9081e2d9b40a3f5553d621fe715c80defc
[]
no_license
Shubhamsk1/cp
f24b2dd532f8b14d533e9bd4e359e1ae9ea574a4
26380d2439a14b70c798fb742f1bc1891bc3fe43
refs/heads/main
2023-05-28T21:39:50.220206
2021-06-14T04:11:29
2021-06-14T04:11:29
372,040,761
0
0
null
null
null
null
UTF-8
C++
false
false
410
cpp
#include<bits/stdc++.h> #include <string> using namespace std; string nested(string arr,string curstring,int open, int close,int max) { if(max==1) curstring+("("*arr[max-1])+arr[max-1]+(")"*arr[max-1]); } int main() { int t; cin>>t; while(t--) { queue<char> q; string arr; cin>>arr; string newstr=nested(arr,"",0,0,0); cout<<newstr; } }
[ "shubahmsk1@gmail.com" ]
shubahmsk1@gmail.com
4b12dad2811a3e0aff49ee9e1bfa88930ff910be
b25b72c9728e772e1d9ec5bbfbd6a730251a600a
/src/brisk_descriptor.h
47db2d40672d404c6f3cce68ff70fe1403a4fce1
[]
no_license
powei-lin/vfx2017panorama
85d0ea6f8d5ef48a246b3bdc2f720eb3f515efc3
44adb92976416f7aeb464cd7fefc0a2f2796d830
refs/heads/master
2021-11-06T12:44:40.438525
2017-05-14T14:30:18
2017-05-14T14:30:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
718
h
#ifndef BRISK_DESCIPTOR_H #define BRISK_DESCIPTOR_H #include "opencv2/imgcodecs.hpp" #include "opencv2/core.hpp" #include "opencv2/features2d.hpp" #include <opencv2/highgui.hpp> #include <opencv2/opencv.hpp> #include <iostream> #include <string> #include <vector> #include <cmath> struct pt_pair{ cv::Point2f start; cv::Point2f end; double dist; double S_I; double E_I; }; struct pt_value{ cv::Point2f point; double I; }; double get_gs_value(const cv::Mat& src, cv::Point pt); cv::Mat brisk_short(const cv::Mat& src,cv::KeyPoint kp, double rad); double brisk_compare(const cv::Mat &a, const cv::Mat &b); int key_pair(const cv::Mat& a, const std::vector<cv::Mat> &b, int thres); #endif
[ "b01501122@ntu.edu.tw" ]
b01501122@ntu.edu.tw
2cb20a03e31bdc449a4478f6b8d902fb7ad0e6b8
fb45d4c91a45a94405794b4f52437a26733a8e7a
/game/src/main/jni/Socket.cpp
c44743c3f8a7a3081de8bc7abd6dc6c4893d83d5
[]
no_license
hockey92/platformer
be15408ed1d5d49c7eac776a1bbb1b24583a15eb
a0af47a406b11315781cb94b89dd5d7a3cdbb6d8
refs/heads/master
2020-04-11T09:56:32.869171
2016-11-20T07:56:17
2016-11-20T07:56:17
68,041,156
0
0
null
2016-09-18T16:38:54
2016-09-12T19:35:13
C++
UTF-8
C++
false
false
1,332
cpp
// // Created by qwerty on 29.10.16. // #include "Socket.h" bool Socket::open(unsigned short port) { handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (handle <= 0) { printf("failed to create socket\n"); return false; } sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons((unsigned short) port); if (bind(handle, (const sockaddr *) &address, sizeof(sockaddr_in)) < 0) { printf("failed to bind socket\n"); return false; } int nonBlocking = 1; if (fcntl(handle, F_SETFL, O_NONBLOCK, nonBlocking) == -1) { printf("failed to set non-blocking\n"); return false; } return true; } Socket::Socket() { } Socket::~Socket() { } bool Socket::send(Address &address, const void *data, int size) { int sentBytes = sendto(handle, (const char *) data, size, 0, (sockaddr *) address.getSockAddr(), sizeof(sockaddr)); if (sentBytes != size) { printf("failed to send packet\n"); return false; } return true; } void Socket::destroy() { close(handle); } bool Socket::isOpen() const { return true; }
[ "shibachel@gmail.com" ]
shibachel@gmail.com
d0607e78cbe0c52cf834d480ec8d46f8dd3b0b4b
af21eb6ee11e0506a879a34774e19f8d89ce4c27
/WS08/lab/Line.h
967eae72afbd524372132be79c627ea7abef9e2c
[]
no_license
Genne23v/myOOP244_Workshop
ecef307ef98c7049e9eae05783af396a06e58b93
3a7d8fb6e294e1ec5aebf5d66edacd54c2a9b8f9
refs/heads/main
2023-07-06T18:16:14.605906
2021-04-08T02:11:54
2021-04-08T02:11:54
336,471,026
0
0
null
null
null
null
UTF-8
C++
false
false
722
h
/********************************************************** * Name: Wonkeun No * Student ID: 145095196 * Seneca email: wno@myseneca.ca * Section: NGG **********************************************************/ #ifndef __LINE_H__ #define __LINE_H__ #include <iostream> #include "LblShape.h" namespace sdds { class Line : public LblShape { int m_length = 0; public: Line(); Line(const char* label, int length); Line(const Line& src) {}; Line& operator=(const Line& src); void draw(std::ostream& os) const override; void getSpecs(std::istream& is)override; Line& operator&(const Line& src) ; }; /*void operator<<(std::ostream& os, Line& src); void operator>>(std::istream& is, Line& src);*/ } #endif
[ "59734889+Genne23v@users.noreply.github.com" ]
59734889+Genne23v@users.noreply.github.com
a539831d4e223f8f630e14e94cdf876fef28f76b
4e04b0940d62d55283ec0d163b189f94d77dccd7
/src/share/vm/oops/annotations.cpp
19dcc755e5e15c0d263cc0bea68c0a740edfcfbc
[]
no_license
lightvelocity/cpp_jvm8
bd51ac0247123c759e8b657f22928e6f64362ac2
f464d5cf03291f92d13858cfbe3e45b7ce389906
refs/heads/master
2021-09-05T05:20:06.182196
2018-01-24T10:41:25
2018-01-24T10:41:25
115,502,694
0
0
null
null
null
null
UTF-8
C++
false
false
3,375
cpp
/* * annotations.cpp * * Created on: 2018年1月18日 * Author: limaozhi */ // OK #include "precompiled.hpp" #include "classfile/classLoaderData.hpp" #include "memory/heapInspection.hpp" #include "memory/metadataFactory.hpp" #include "memory/oopFactory.hpp" #include "oops/annotations.hpp" #include "oops/instanceKlass.hpp" #include "utilities/ostream.hpp" // Allocate annotations in metadata area Annotations* Annotations::allocate(ClassLoaderData* loader_data, TRAPS) { return new (loader_data, size(), true, MetaspaceObj::AnnotationType, THREAD) Annotations(); } // helper void Annotations::free_contents(ClassLoaderData* loader_data, Array<AnnotationArray*>* p) { if (p != NULL) { for (int i = 0; i < p->length(); i++) { MetadataFactory::free_array <u1>(loader_data, p->at(i)); } MetadataFactory::free_array<AnnotationArray*>(loader_data, p); } } void Annotations::deallocate_contents(ClassLoaderData* loader_data) { if (class_annotations() != NULL) { MetadataFactory::free_array<u1>(loader_data, class_annotations()); } free_contents(loader_data, fields_annotations()); if (class_type_annotations() != NULL) { MetadataFactory::free_array<u1>(loader_data, class_type_annotations()); } free_contents(loader_data, fields_type_annotations()); } // Copy annotations to JVM call or reflection to the java heap. // The alternative to creating this array and adding to Java heap pressure // is to have a hashtable of the already created typeArrayOops typeArrayOop Annotations::make_java_array(AnnotationArray* annotations, TRAPS) { if (annotations != NULL) { int length = annotations->length(); typeArrayOop copy = oopFactory::new_byteArray(length, CHECK_NULL); for (int i = 0; i < length; i++) { copy->byte_at_put(i, annotations->at(i)); } return copy; } else { return NULL; } } void Annotations::print_value_on(outputStream* st) const { st->print("Anotations(" INTPTR_FORMAT ")", this); } #if INCLUDE_SERVICES // Size Statistics julong Annotations::count_bytes(Array<AnnotationArray*>* p) { julong bytes = 0; if (p != NULL) { for (int i = 0; i < p->length(); i++) { bytes += KlassSizeStats::count_array(p->at(i)); } bytes += KlassSizeStats::count_array(p); } return bytes; } void Annotations::collect_statistics(KlassSizeStats *sz) const { sz->_annotations_bytes = sz->count(this); sz->_class_annotations_bytes = sz->count(class_annotations()); sz->_class_type_annotations_bytes = sz->count(class_type_annotations()); sz->_fields_annotations_bytes = count_bytes(fields_annotations()); sz->_fields_type_annotations_bytes = count_bytes(fields_type_annotations()); sz->_annotations_bytes += sz->_class_annotations_bytes + sz->_class_type_annotations_bytes + sz->_fields_annotations_bytes + sz->_fields_type_annotations_bytes; sz->_ro_bytes += sz->_annotations_bytes; } #endif // INCLUDE_SERVICES #define BULLET " - " #ifndef PRODUCT void Annotations::print_on(outputStream* st) const { st->print(BULLET"class_annotations ");class_annotations()->print_value_on(st); st->print(BULLET"fields_annotations ");fields_annotations()->print_value_on(st); st->print(BULLET"class_type_annotations ");class_type_annotations()->print_value_on(st); st->print(BULLET"fields_type_annotations ");fields_type_annotations()->print_value_on(st); } #endif // PRODUCT
[ "hzlimaozhi@gmail.com" ]
hzlimaozhi@gmail.com
b0c280dcfa6f9948f53a426f8f6828ade5991daf
8077ae53610c54d4c97f49c22f35353e01eb9843
/Engine/src/Graphics/RenderingEngine.h
b66e0ac11bb72a0ce194a25689b8c162273e3750
[]
no_license
Paolo5150/397Project
6fc3cab18526ab5d27e134f3b08afc818ab212fe
2324941d0110c264e230c2676f4cb2c4b866a44b
refs/heads/master
2022-01-11T19:51:21.785897
2019-05-30T13:43:56
2019-05-30T13:43:56
173,710,285
0
0
null
null
null
null
UTF-8
C++
false
false
3,948
h
#pragma once #include "GL/glew.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "..\Core\Application.h" #include "..\Components\Renderer.h" #include <map> class FrameBuffer; /** * @class RenderingEngine * @brief Manages renderer and rendering mechanics * * @author Paolo Ferri * @version 01 * @date 15/03/2019 * * * @bug No known bugs. */ class RenderingEngine { public: static bool godRays; /** * @brief Return the rendering engine instance * @pre The instance is created * @post The instance is returned * @return The rendering engine instance */ static RenderingEngine& Instance(); /** * @brief Destroy the rendering engine object * @pre The instance exists * @post The instance is rdestroyed */ ~RenderingEngine(); /** * @brief Initialize the rendering engine * @pre The instance exists * @post The instance is initialized */ void Initialize(); /** * @brief Render the current buffer of renderers with a specified material and all available cameras * @pre The instance exists * @post The renderers are drawn to the screen */ void RenderBuffer(MaterialType mt = DEFAULT); /** * @brief Render the current buffer of renderers with a specified material and camera * @pre The instance exists * @post The renderers are drawn to the screen */ void RenderBuffer(Camera* camera, MaterialType mt = DEFAULT); /** * @brief Render the current buffer of renderers with a specified material and camera * @pre The instance exists * @post The renderers are drawn to the screen */ /** * @brief Render the current buffer of renderers with a specified material and all available cameras * @pre The instance exists * @post The renderers are drawn to the screen */ void RenderBufferToTexture(MaterialType mt = DEFAULT); /** * @brief Render the current buffer of renderers with a specified material and camera and force a color to the renderers * @pre The instance exists * @post The renderers are drawn to the screen with the color applied */ void RenderBufferOverrideColor(Camera* camera, glm::vec3 color, MaterialType mt = DEFAULT); /** * @brief Add a renderer to the list of renderers to draw * @pre The instance exists * @post The renderer component is added to the list * @param rend The renderer to be added */ void SubmitRenderer(Renderer* rend); /** * @brief Clear the renderer list * @pre The instance exists * @post The renderer list is cleared */ void ClearRendererList(); /** * @brief The list of renderer components */ static std::vector<Renderer*> allRenderers; FrameBuffer* renderTexture; FrameBuffer* occludedTexture; FrameBuffer* godraysTexture; Shader* postProcessShader; Shader* godRayShader; Texture2D* distortionTexture; private: /** * @brief The lconstructor, private as this is a singleton */ RenderingEngine(); RenderingEngine& operator=(const RenderingEngine& e) = delete; RenderingEngine(const RenderingEngine& e) = delete; /** * @brief Helper method to render the list of renderer components * @pre The instance exists * @post The renderers are drawn to the screen * @param cam The camera to be used for rendering * @param r The vector to be render * @param m The material type that the renderer components will use */ void RenderVector(Camera& cam, std::vector<Renderer*>& r, MaterialType m = MaterialType::DEFAULT); /** * @brief Helper method to render the list of renderer components * @pre The instance exists * @post The renderers are drawn to the screen * @param cam The camera to be used for rendering * @param r The vector to be render * @param m The material type that the renderer components will use * @param color The color that will be applied to the material */ void RenderVectorOverrideColor(Camera& cam, std::vector<Renderer*>& r, glm::vec3 color,MaterialType m = MaterialType::DEFAULT); Mesh* quadMesh; };
[ "p.ferri1986@gmail.com" ]
p.ferri1986@gmail.com
8cfd0ba177e979a1f9a3a735080cf07631c070b2
a9adbed43b238da95b003c1c9a6a52e15f996210
/Source/TBS/Private/Grid/TBSGridPathRenderer.cpp
fefdd3eb73613c1df4b8c7fcbecb1e0720d083de
[]
no_license
idleplaythings/tbs
765ed5933e598df53a774bd0df514b8720565288
4a6a0ccb08138db53e7c288facdc285d913a7186
refs/heads/master
2021-03-24T11:42:51.489773
2016-10-06T10:40:04
2016-10-06T10:40:04
46,412,053
0
0
null
null
null
null
UTF-8
C++
false
false
2,202
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "TBS.h" #include "TBSGridPathRenderer.h" // Sets default values ATBSGridPathRenderer::ATBSGridPathRenderer() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = false; static ConstructorHelpers::FObjectFinder<UStaticMesh> Mesh(TEXT("StaticMesh'/Engine/BasicShapes/Cylinder.Cylinder'")); PathComponentMesh = Mesh.Object; static ConstructorHelpers::FObjectFinder<UMaterial> Material(TEXT("Material'/Game/Materials/M_GridPathmat.M_GridPathmat'")); PathComponentMaterial = Material.Object; RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("Root")); } // Called when the game starts or when spawned void ATBSGridPathRenderer::BeginPlay() { Super::BeginPlay(); } // Called every frame void ATBSGridPathRenderer::Tick( float DeltaTime ) { Super::Tick( DeltaTime ); } void ATBSGridPathRenderer::Initialise(ATBSGrid* InGrid, ATBSGridUI* InGridUI) { Grid = InGrid; GridUI = InGridUI; } void ATBSGridPathRenderer::RenderPath(TArray<FIntVector> InPath) { if (RenderedPath.Num() < InPath.Num()) { int ComponentsToAdd = InPath.Num() - RenderedPath.Num(); for (int i = 0; i < ComponentsToAdd; i++) { RenderedPath.Add(CreatePathComponent()); } } for (int i = 0; i < InPath.Num(); i++) { FCoordinateLocations Locations = GridUI->GetCoordinateLocations(InPath[i]); RenderedPath[i]->SetRelativeLocation(Locations.Center); RenderedPath[i]->SetVisibility(true); } } void ATBSGridPathRenderer::ClearPath() { for (auto& PathComponent : RenderedPath) { PathComponent->SetVisibility(false); } } UStaticMeshComponent* ATBSGridPathRenderer::CreatePathComponent() { UStaticMeshComponent* PathComponent = NewObject<UStaticMeshComponent>(this); PathComponent->SetStaticMesh(PathComponentMesh); PathComponent->SetMaterial(0, PathComponentMaterial); PathComponent->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform); PathComponent->SetRelativeScale3D(FVector(0.3, 0.3, 0.01)); FinishAndRegisterComponent(PathComponent); return PathComponent; }
[ "niko@nevala.fi" ]
niko@nevala.fi
95b42466d66ebab568bedabb1c5eb82385622703
963118795aaf7b70bc817b6d4428783d1a3c9f05
/Water-3D-simulation/Content/Sample3DSceneRenderer.cpp
4674a28d708d138f906f71c00a4ec6c5bba36cc9
[]
no_license
idomaz00/DirectX11-3Dsimulation
93d4bb5d57171029b9d757fa3e2d47c733b9cb69
daa3a8e7f0188a79508e23f30bdb713ee5955d80
refs/heads/master
2020-05-29T09:16:30.613656
2016-09-28T18:17:12
2016-09-28T18:17:12
69,491,181
1
0
null
null
null
null
UTF-8
C++
false
false
8,768
cpp
#include "pch.h" #include "Sample3DSceneRenderer.h" #include "..\Common\DirectXHelper.h" using namespace Water_3D_simulation; using namespace DirectX; using namespace Windows::Foundation; // Loads vertex and pixel shaders from files and instantiates the cube geometry. Sample3DSceneRenderer::Sample3DSceneRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources) : m_loadingComplete(false), m_degreesPerSecond(45), m_indexCount(0), m_tracking(false), m_deviceResources(deviceResources) { CreateDeviceDependentResources(); CreateWindowSizeDependentResources(); } // Initializes view parameters when the window size changes. void Sample3DSceneRenderer::CreateWindowSizeDependentResources() { Size outputSize = m_deviceResources->GetOutputSize(); float aspectRatio = outputSize.Width / outputSize.Height; float fovAngleY = 70.0f * XM_PI / 180.0f; // This is a simple example of change that can be made when the app is in // portrait or snapped view. if (aspectRatio < 1.0f) { fovAngleY *= 2.0f; } // Note that the OrientationTransform3D matrix is post-multiplied here // in order to correctly orient the scene to match the display orientation. // This post-multiplication step is required for any draw calls that are // made to the swap chain render target. For draw calls to other targets, // this transform should not be applied. // This sample makes use of a right-handed coordinate system using row-major matrices. XMMATRIX perspectiveMatrix = XMMatrixPerspectiveFovRH( fovAngleY, aspectRatio, 0.01f, 100.0f ); XMFLOAT4X4 orientation = m_deviceResources->GetOrientationTransform3D(); XMMATRIX orientationMatrix = XMLoadFloat4x4(&orientation); XMStoreFloat4x4( &m_constantBufferData.projection, XMMatrixTranspose(perspectiveMatrix * orientationMatrix) ); // Eye is at (0,0.7,1.5), looking at point (0,-0.1,0) with the up-vector along the y-axis. static const XMVECTORF32 eye = { 0.0f, 0.7f, 1.5f, 0.0f }; static const XMVECTORF32 at = { 0.0f, -0.1f, 0.0f, 0.0f }; static const XMVECTORF32 up = { 0.0f, 1.0f, 0.0f, 0.0f }; XMStoreFloat4x4(&m_constantBufferData.view, XMMatrixTranspose(XMMatrixLookAtRH(eye, at, up))); } // Called once per frame, rotates the cube and calculates the model and view matrices. void Sample3DSceneRenderer::Update(DX::StepTimer const& timer) { if (!m_tracking) { // Convert degrees to radians, then convert seconds to rotation angle float radiansPerSecond = XMConvertToRadians(m_degreesPerSecond); double totalRotation = timer.GetTotalSeconds() * radiansPerSecond; float radians = static_cast<float>(fmod(totalRotation, XM_2PI)); Rotate(radians); } } // Rotate the 3D cube model a set amount of radians. void Sample3DSceneRenderer::Rotate(float radians) { // Prepare to pass the updated model matrix to the shader XMStoreFloat4x4(&m_constantBufferData.model, XMMatrixTranspose(XMMatrixRotationY(radians))); } void Sample3DSceneRenderer::StartTracking() { m_tracking = true; } // When tracking, the 3D cube can be rotated around its Y axis by tracking pointer position relative to the output screen width. void Sample3DSceneRenderer::TrackingUpdate(float positionX) { if (m_tracking) { float radians = XM_2PI * 2.0f * positionX / m_deviceResources->GetOutputSize().Width; Rotate(radians); } } void Sample3DSceneRenderer::StopTracking() { m_tracking = false; } // Renders one frame using the vertex and pixel shaders. void Sample3DSceneRenderer::Render() { // Loading is asynchronous. Only draw geometry after it's loaded. if (!m_loadingComplete) { return; } auto context = m_deviceResources->GetD3DDeviceContext(); // Prepare the constant buffer to send it to the graphics device. context->UpdateSubresource( m_constantBuffer.Get(), 0, NULL, &m_constantBufferData, 0, 0 ); // Each vertex is one instance of the VertexPositionColor struct. UINT stride = sizeof(VertexPositionColor); UINT offset = 0; context->IASetVertexBuffers( 0, 1, m_vertexBuffer.GetAddressOf(), &stride, &offset ); context->IASetIndexBuffer( m_indexBuffer.Get(), DXGI_FORMAT_R16_UINT, // Each index is one 16-bit unsigned integer (short). 0 ); context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); context->IASetInputLayout(m_inputLayout.Get()); // Attach our vertex shader. context->VSSetShader( m_vertexShader.Get(), nullptr, 0 ); // Send the constant buffer to the graphics device. context->VSSetConstantBuffers( 0, 1, m_constantBuffer.GetAddressOf() ); // Attach our pixel shader. context->PSSetShader( m_pixelShader.Get(), nullptr, 0 ); // Draw the objects. context->DrawIndexed( m_indexCount, 0, 0 ); } void Sample3DSceneRenderer::CreateDeviceDependentResources() { // Load shaders asynchronously. auto loadVSTask = DX::ReadDataAsync(L"SampleVertexShader.cso"); auto loadPSTask = DX::ReadDataAsync(L"SamplePixelShader.cso"); // After the vertex shader file is loaded, create the shader and input layout. auto createVSTask = loadVSTask.then([this](const std::vector<byte>& fileData) { DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateVertexShader( &fileData[0], fileData.size(), nullptr, &m_vertexShader ) ); static const D3D11_INPUT_ELEMENT_DESC vertexDesc [] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateInputLayout( vertexDesc, ARRAYSIZE(vertexDesc), &fileData[0], fileData.size(), &m_inputLayout ) ); }); // After the pixel shader file is loaded, create the shader and constant buffer. auto createPSTask = loadPSTask.then([this](const std::vector<byte>& fileData) { DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreatePixelShader( &fileData[0], fileData.size(), nullptr, &m_pixelShader ) ); CD3D11_BUFFER_DESC constantBufferDesc(sizeof(ModelViewProjectionConstantBuffer) , D3D11_BIND_CONSTANT_BUFFER); DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateBuffer( &constantBufferDesc, nullptr, &m_constantBuffer ) ); }); // Once both shaders are loaded, create the mesh. auto createCubeTask = (createPSTask && createVSTask).then([this] () { // Load mesh vertices. Each vertex has a position and a color. static const VertexPositionColor cubeVertices[] = { {XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT3(0.0f, 0.0f, 0.0f)}, {XMFLOAT3(-0.5f, -0.5f, 0.5f), XMFLOAT3(0.0f, 0.0f, 1.0f)}, {XMFLOAT3(-0.5f, 0.5f, -0.5f), XMFLOAT3(0.0f, 1.0f, 0.0f)}, {XMFLOAT3(-0.5f, 0.5f, 0.5f), XMFLOAT3(0.0f, 1.0f, 1.0f)}, {XMFLOAT3( 0.5f, -0.5f, -0.5f), XMFLOAT3(1.0f, 0.0f, 0.0f)}, {XMFLOAT3( 0.5f, -0.5f, 0.5f), XMFLOAT3(1.0f, 0.0f, 1.0f)}, {XMFLOAT3( 0.5f, 0.5f, -0.5f), XMFLOAT3(1.0f, 1.0f, 0.0f)}, {XMFLOAT3( 0.5f, 0.5f, 0.5f), XMFLOAT3(1.0f, 1.0f, 1.0f)}, }; D3D11_SUBRESOURCE_DATA vertexBufferData = {0}; vertexBufferData.pSysMem = cubeVertices; vertexBufferData.SysMemPitch = 0; vertexBufferData.SysMemSlicePitch = 0; CD3D11_BUFFER_DESC vertexBufferDesc(sizeof(cubeVertices), D3D11_BIND_VERTEX_BUFFER); DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateBuffer( &vertexBufferDesc, &vertexBufferData, &m_vertexBuffer ) ); // Load mesh indices. Each trio of indices represents // a triangle to be rendered on the screen. // For example: 0,2,1 means that the vertices with indexes // 0, 2 and 1 from the vertex buffer compose the // first triangle of this mesh. static const unsigned short cubeIndices [] = { 0,2,1, // -x 1,2,3, 4,5,6, // +x 5,7,6, 0,1,5, // -y 0,5,4, 2,6,7, // +y 2,7,3, 0,4,6, // -z 0,6,2, 1,3,7, // +z 1,7,5, }; m_indexCount = ARRAYSIZE(cubeIndices); D3D11_SUBRESOURCE_DATA indexBufferData = {0}; indexBufferData.pSysMem = cubeIndices; indexBufferData.SysMemPitch = 0; indexBufferData.SysMemSlicePitch = 0; CD3D11_BUFFER_DESC indexBufferDesc(sizeof(cubeIndices), D3D11_BIND_INDEX_BUFFER); DX::ThrowIfFailed( m_deviceResources->GetD3DDevice()->CreateBuffer( &indexBufferDesc, &indexBufferData, &m_indexBuffer ) ); }); // Once the cube is loaded, the object is ready to be rendered. createCubeTask.then([this] () { m_loadingComplete = true; }); } void Sample3DSceneRenderer::ReleaseDeviceDependentResources() { m_loadingComplete = false; m_vertexShader.Reset(); m_inputLayout.Reset(); m_pixelShader.Reset(); m_constantBuffer.Reset(); m_vertexBuffer.Reset(); m_indexBuffer.Reset(); }
[ "v-izabela.domazet@dump.hr" ]
v-izabela.domazet@dump.hr