hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
78cd4335005ea39fcde4093816fcdab094753daa | 5,115 | cpp | C++ | VC2010Samples/MFC/advanced/collect/strlstvw.cpp | alonmm/VCSamples | 6aff0b4902f5027164d593540fcaa6601a0407c3 | [
"MIT"
] | 300 | 2019-05-09T05:32:33.000Z | 2022-03-31T20:23:24.000Z | VC2010Samples/MFC/advanced/collect/strlstvw.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 9 | 2016-09-19T18:44:26.000Z | 2018-10-26T10:20:05.000Z | VC2010Samples/MFC/advanced/collect/strlstvw.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 633 | 2019-05-08T07:34:12.000Z | 2022-03-30T04:38:28.000Z | // strlstvw.cpp : implementation file
//
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#include "stdafx.h"
#include "collect.h"
#include "colledoc.h"
#include "strlstvw.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CStringListView
IMPLEMENT_DYNCREATE(CStringListView, CFormView)
CStringListView::CStringListView()
: CFormView(CStringListView::IDD)
{
//{{AFX_DATA_INIT(CStringListView)
m_strElement = "";
//}}AFX_DATA_INIT
}
CStringListView::~CStringListView()
{
}
void CStringListView::OnInitialUpdate()
{
CFormView::OnInitialUpdate();
// Copy all of the strings from the document's CStringList
// to the listbox.
m_ctlList.ResetContent();
CStringList& stringList = GetDocument()->m_stringList;
POSITION pos = stringList.GetHeadPosition();
while (pos != NULL)
{
CString str = stringList.GetNext(pos);
m_ctlList.AddString(str);
}
}
void CStringListView::DoDataExchange(CDataExchange* pDX)
{
CFormView::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CStringListView)
DDX_Control(pDX, IDC_LIST, m_ctlList);
DDX_Text(pDX, IDC_ELEMENT, m_strElement);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CStringListView, CFormView)
//{{AFX_MSG_MAP(CStringListView)
ON_BN_CLICKED(IDC_ADD, OnAdd)
ON_BN_CLICKED(IDC_REMOVE, OnRemove)
ON_BN_CLICKED(IDC_REMOVE_ALL, OnRemoveAll)
ON_BN_CLICKED(IDC_UPDATE, OnUpdateElement)
ON_LBN_SELCHANGE(IDC_LIST, OnSelChangeList)
ON_BN_CLICKED(IDC_INSERT_BEFORE, OnInsertBefore)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CStringListView diagnostics
#ifdef _DEBUG
void CStringListView::AssertValid() const
{
CFormView::AssertValid();
}
void CStringListView::Dump(CDumpContext& dc) const
{
CFormView::Dump(dc);
}
CCollectDoc* CStringListView::GetDocument() // non-debug version is inline
{
return STATIC_DOWNCAST(CCollectDoc, m_pDocument);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CStringListView internal implementation
BOOL CStringListView::FindString(int& nSel, POSITION& pos)
{
nSel = m_ctlList.GetCurSel();
if (nSel == LB_ERR)
{
AfxMessageBox(IDS_SELECT_STRING_FIRST);
return FALSE;
}
// The currently selected string in the listbox is the string
// to be updated or removed .
CString strOld;
m_ctlList.GetText(nSel, strOld);
// Find the string to be updated or replaced in the CStringList.
CStringList& stringList = GetDocument()->m_stringList;
pos = stringList.Find(strOld);
// If the string is in the listbox, it should also be in the
// CStringList.
ASSERT(pos != NULL);
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CStringListView message handlers
void CStringListView::OnAdd()
{
if (UpdateData() != TRUE)
return;
// Add new string to the CStringList
GetDocument()->m_stringList.AddTail(m_strElement);
// Add new string to the listbox.
m_ctlList.AddString(m_strElement);
}
void CStringListView::OnInsertBefore()
{
if (UpdateData() != TRUE)
return;
int nSel;
POSITION pos;
// Find the string in both the CStringList and in the listbox.
if (FindString(nSel, pos) != TRUE)
return;
// Insert in front of the string found in the CStringList
GetDocument()->m_stringList.InsertBefore(pos, m_strElement);
// Insert new string in the listbox
m_ctlList.InsertString(nSel, m_strElement);
}
void CStringListView::OnUpdateElement()
{
if (UpdateData() != TRUE)
return;
int nSel;
POSITION pos;
// Find the string in both the CStringList and in the listbox.
if (FindString(nSel, pos) != TRUE)
return;
// Replace the value of the string in the CStringList.
GetDocument()->m_stringList.SetAt(pos, m_strElement);
// Replace the value of the string in the listbox by
// removing the old string and adding the new string.
m_ctlList.DeleteString(nSel);
m_ctlList.InsertString(nSel, m_strElement);
}
void CStringListView::OnRemove()
{
int nSel;
POSITION pos;
// FInd the string in both the CStringList and in the listbox.
if (FindString(nSel, pos) != TRUE)
return;
// Remove the string from the CStringList.
GetDocument()->m_stringList.RemoveAt(pos);
// Remove the string from the listbox.
m_ctlList.DeleteString(nSel);
}
void CStringListView::OnRemoveAll()
{
// Remove all of the strings from the CStringList.
GetDocument()->m_stringList.RemoveAll();
// Remove all of the strings from the listbox.
m_ctlList.ResetContent();
}
void CStringListView::OnSelChangeList()
{
// Update the edit control to reflect the new selection
// in the listbox.
m_ctlList.GetText(m_ctlList.GetCurSel(), m_strElement);
UpdateData(FALSE);
}
| 24.241706 | 77 | 0.705181 | alonmm |
78d02b3c0d130e661cd828c104dfd78565f16f0d | 1,739 | cpp | C++ | src/dumpContigsFromHeader.cpp | timmassingham/vcflib | e0cb656cb0e224dc078ba1e06079a88a5ea7b6ab | [
"MIT"
] | 379 | 2016-01-29T00:01:51.000Z | 2022-03-21T21:07:03.000Z | src/dumpContigsFromHeader.cpp | timmassingham/vcflib | e0cb656cb0e224dc078ba1e06079a88a5ea7b6ab | [
"MIT"
] | 245 | 2016-01-31T19:05:29.000Z | 2022-03-31T13:17:17.000Z | src/dumpContigsFromHeader.cpp | timmassingham/vcflib | e0cb656cb0e224dc078ba1e06079a88a5ea7b6ab | [
"MIT"
] | 168 | 2016-02-11T19:30:52.000Z | 2022-02-10T09:20:34.000Z | /*
vcflib C++ library for parsing and manipulating VCF files
Copyright © 2010-2020 Erik Garrison
Copyright © 2020 Pjotr Prins
This software is published under the MIT License. See the LICENSE file.
*/
#include "Variant.h"
#include "split.h"
#include "var.hpp"
#include <string>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
using namespace vcflib;
int main(int argc, char** argv) {
if (argc == 2) {
string h_flag = argv[1];
if (argc == 2 && (h_flag == "-h" || h_flag == "--help")) {
cerr << R"(
Dump contigs from header
Usage: dumpContigsFromHeader file
Example:
dumpContigsFromHeader samples/scaffold612.vcf
##contig=<ID=scaffold4,length=1524>
##contig=<ID=scaffold12,length=56895>
(...)
output
scaffold4 1524
scaffold12 56895
(...)
Type: transformation
)";
exit(1);
}
}
string filename = argv[1];
VariantCallFile variantFile;
variantFile.open(filename);
vector<string> headerLines = split (variantFile.header, "\n");
for(vector<string>::iterator it = headerLines.begin(); it != headerLines.end(); it++){
// cerr << "h:" << (*it) << endl;
if((*it).substr(0,8) == "##contig"){
string contigInfo = (*it).substr(10, (*it).length() -11);
// cerr << contigInfo << endl;
vector<string> info = split(contigInfo, ",");
for(vector<string>::iterator sub = info.begin(); sub != info.end(); sub++){
// cerr << "s:" << (*sub) << endl;
vector<string> subfield = split((*sub), "=");
if(subfield[0] == "ID"){
cout << subfield[1] << "\t";
}
if(subfield[0] == "length"){
cout << subfield[1] << endl;
}
}
}
}
}
| 20.458824 | 88 | 0.581369 | timmassingham |
78d0de5c68dea901ad43bdef95a59b9d50e7af50 | 257 | cxx | C++ | functional_bit_and.cxx | cmbrandt/stl-algorithms | 9eb0bc664e8423fb066c29aa501a72f4e672be1d | [
"MIT"
] | null | null | null | functional_bit_and.cxx | cmbrandt/stl-algorithms | 9eb0bc664e8423fb066c29aa501a72f4e672be1d | [
"MIT"
] | null | null | null | functional_bit_and.cxx | cmbrandt/stl-algorithms | 9eb0bc664e8423fb066c29aa501a72f4e672be1d | [
"MIT"
] | null | null | null | #include <iostream>
#include <functional.hxx>
template <typename T, typename B = cmb::bit_and<>>
T bit_test( T a, T b, B bit = B{ } )
{
return bit(a, b);
}
int main()
{
auto r = bit_test(5, 9);
std::cout << "result = " << r << std::endl; // = 1
} | 15.117647 | 52 | 0.560311 | cmbrandt |
78d2083342a63a9350ea517c9fe7fd47adc694ab | 103,179 | cpp | C++ | sources/FEM/matrix_routines.cpp | wolf-pf/ogs_kb1 | 97ace8bc8fb80b033b8a32f6ed4a20983caa241f | [
"BSD-4-Clause"
] | 1 | 2019-11-13T23:01:08.000Z | 2019-11-13T23:01:08.000Z | sources/FEM/matrix_routines.cpp | wolf-pf/ogs_kb1 | 97ace8bc8fb80b033b8a32f6ed4a20983caa241f | [
"BSD-4-Clause"
] | null | null | null | sources/FEM/matrix_routines.cpp | wolf-pf/ogs_kb1 | 97ace8bc8fb80b033b8a32f6ed4a20983caa241f | [
"BSD-4-Clause"
] | null | null | null | /**************************************************************************
ROCKFLOW - Modul: matrix.c
Aufgabe:
Verwaltung von nxn - Matrizen mit verschiedenen Speichertechniken und
Bereitstellung entsprechender Zugriffsfunktionen sowie einfacher
mathematischer Operationen auf die entsprechende Matrix.
Benoetigte Vektoren werden als eindimensionale double-Felder erwartet.
Speichertechniken: (1) vollbesetzte Matrix
( param1 = Dimension )
(2) nur A[i,j]!=0 werden gespeichert (Sparse)
( param1 = Dimension )
(3) symmetrische sparse Matrix
fuer Preconditioner "incomplete Cholesky"
nur Aik !=0 mit k>=i werden gespeichert
( param1 = Dimension )
(4) unsymmetrische sparse Matrix
fuer Preconditioner "incomplete LDU-Zerlegung"
nur Aik !=0 werden gespeichert
( param1 = Dimension )
Benutzungsbeispiel fuer 2 Matrizen:
long dummy =0; Dummy-Variable mit beliebigem Wert
void *A = NULL; Zeiger A fuer Matrix-Wurzel definieren
void *B = NULL; Zeiger B fuer Matrix-Wurzel definieren
A =MXSetupMatrix (10l, 1, dummy); 10x10-Matrix erzeugen, Modell 1
B =MXSetupMatrix (100l, 2, dummy); 100x100-Matrix erzeugen, Modell 2
MXSetMatrixPointer(A); Aktuelle Matrix ist A
MXInitMatrix(); Matrix A mit Nullen fuellen
MXSet(0,0,2*3.1415926); Beispiel: A[0,0] = 2*Pi;
MXSetMatrixPointer(B); Aktuelle Matrix ist B
MXInitMatrix(); Matrix B mit Nullen fuellen
MXSet(2,3,3.1415926); Beispiel: B[2,3] = Pi;
printf("%f",MXGet(0,0)); Beispiel: Pi wieder ausgeben
MXSetMatrixPointer(A); Aktuelle Matrix ist A
printf("%f",MXGet(0,0)); Beispiel: 2*Pi wieder ausgeben
A =MXDestroyMatrix(); Speicher wieder freigeben, A =NULL setzen
B =MXDestroyMatrix(); Speicher wieder freigeben, B =NULL setzen
Programmaenderungen:
11/1995 MSR Erste Version
04/1999 AH Das zuletzt bearbeitetes Speichermodell wird
in der Variable matrix_type gemerkt.
Damit werden die Funktionszeiger nicht mehr
veraendert, wenn das gleiche Speichermodell
angewaehlt wird. Sinnvoll wenn verschiedenen
Matrizen in staendigem Wechsel bearbeitet wedren.
11/1999 CT Neuer Vorkonditionierer, hilfreich bei Systemen
mit grossem konstantem Anteil in der Loesung
2/2000 Ra Speichermodelle 3 und 4
3/2000 Ra Alle Modelle: Besser lesbare Fassung mit Makros
3/2000 Ra Modelle 1/2: NumDif zugefuegt: Differenz von
Zeilen/Spaltennummern. Verkuerzt Abfragen beim
Einarbeiten von Randbedingungen
3/2000 Ra Routine MX_Randbed zugefuegt: Einarbeiten
von Randbedingungen in Matrix und Rechte Seite,
alle Modelle
4/2000 CT Neu: MXGetMatrixPointer
7/2000 CT Fehler in M34Randbed beseitigt
Modell34 optimiert
Diagonalenvorkonditionierung fuer Modell34
Neue Zugriffmethode mit impliziter Speicherung des Matrixtyps
1/2001 C.Thorenz Diagonale bleibt bei Randbedingungseinbau und
Irr.Knotenbehandlung auf Wert.
3/2000 C.Thorenz CBLAS fuer M2MatVek eingehaengt
NumDif korrigiert
Speichermodell 2 vereinfacht
7/2002 C.Thorenz Speichermodell 2 merkt sich max/min Spalteneintrag
-> schnelleres Suchen
**************************************************************************/
#include "makros.h"
#include "solver.h"
#include <cfloat>
#define noTESTMATRIX_PERF
#define noDUMP
/* Header / Andere intern benutzte Module */
#include "memory.h"
#include "display.h"
#include "files0.h"
#include "mathlib.h"
#include "matrix_routines.h"
// MSHLib
#include "msh_mesh.h"
#include "msh_node.h"
extern MeshLib::CFEMesh* FEMGet(const std::string&);
using MeshLib::CNode;
#ifdef _OPENMP
#include <omp.h>
#endif
/* Interne (statische) Deklarationen */
static void* wurzel = NULL; /* interner Matrix-Wurzelzeiger */
/* Allgemeine Funktionen ohne Modellspezifisches */
int MXSetFunctionPointers(int matrix_type); /* Setzt Funktionszeiger */
int MXGetMatrixType(void); /* Liefert Matrixtyp */
int MX_Dec(long i, long j, double aij_dec);
int MX_Div(long i, long j, double aij_div);
void MX_Trans(long i, long j, long ii, long jj);
/* Struktur und Funktionen zu Speichermodell 1 (vollbesetzte Matrix) */
typedef struct
{
long info[2]; /* Muss immer zuerst kommen, enthaelt Dimension und Matrixtyp */
long max_size;
long NumDif; /* max. Differenz |Spalten-Zeilennummer| */
double* matrix;
}
Modell1;
void* M1CreateMatrix(long param1, long param2, long param3);
void* M1DestroyMatrix(void);
void M1ResizeMatrix(long dimension);
void M1InitMatrix(void);
int M1Set(long i, long j, double aij);
int M1Inc(long i, long j, double aij_inc);
int M1Mul(long i, long j, double aij_mul);
double M1Get(long i, long j);
void M1MatVek(double* vektor, double* ergebnis);
void M1MatTVek(double* vektor, double* ergebnis);
void M1Vorkond(int aufgabe, double* x, double* b);
int M1CopyToAMG1R5Structure( double* A,
int* IA,
int* JA,
int NDA,
int NDIA,
int NDJA,
double*,
double*,
double*,
double*);
/* Strukturen und Funktionen zu Speichermodell 2 (i, j, Wert) */
typedef struct
{
int max_anz; /* Anzahl der allokierten Spalten (ohne Diagonale) */
int anz; /* Anzahl der belegten Spalten (ohne Diagonale) */
int min_col; /* Kleinste Spaltennummer */
int max_col; /* Groesste Spaltennummer */
long* index; /* Index fuer Spalteneintraege */
double* wert; /* Spalteneintraege */
} M2_Zeile;
typedef struct
{
long info[2]; /* Muss immer zuerst kommen, enthaelt Dimension und Matrixtyp */
long max_size;
long NumDif; /* max. Differenz |Spalten-Zeilennummer| */
M2_Zeile* zeile; /* Eintraege in den Zeilen; Diagonale in zeile[0] */
} Modell2;
typedef struct
{
long NumDif; //dummy
}
Modell5;
void* M2CreateMatrix(long param1, long param2, long param3);
void* M2DestroyMatrix(void);
void M2ResizeMatrix(long dimension);
void M2InitMatrix(void);
int M2Set(long i, long j, double aij);
int M2Inc(long i, long j, double aij_inc);
int M2Mul(long i, long j, double aij_mul);
double M2Get(long i, long j);
void M2MatVek(double* vektor, double* ergebnis);
/*-----------------------------------------------------------------------
* JAD format Modell 5
* */
int M5Inc(long i, long j, double aij_inc);
double M5Get(long i, long j);
int M5Set(long i, long j, double e_val);
void M5MatVek( double* b, double* erg);
void M5InitMatrix(void);
void* M5DestroyMatrix(void);
void M5Vorkond(int aufgabe, double* x, double* b);
//void M5CreateMatrix(void);
void* M5CreateMatrix(long param1, long param2, long param3);
void insertionSort1_des(int numbers[],int numbers1[], int array_size);
void transM2toM5(void);
int* jd_ptr1, * jd_ptr2, * jd_ptr, * jd_ptrf, * col_ind;
long* diag5_i;
double* temp_ergebnis,* jdiag;
int m_count, jd_ptr_max, Dim_L;
/*-----------------------------------------------------------------------
* ITPACKV format Modell 6
* */
void M6MatVek( double* b, double* erg);
void transM2toM6(void);
double* itpackv;
int* it_col;
int itpack_max;
/*----------------------------------------------------------------------*/
void M2MatTVek(double* vektor, double* ergebnis);
void M2Vorkond(int aufgabe, double* x, double* b);
int M2CopyToAMG1R5Structure( double* A,
int* IA,
int* JA,
int NDA,
int NDIA,
int NDJA,
double*,
double*,
double*,
double*);
/* Strukturen und Funktionen zu Speichermodell 3/4 (i, j, Wert) */
typedef struct
{ /* einzelner Eintrag in der Spalte k mit Index i */
long Index;
double Aik[4];
} M34_aik;
typedef struct
{ /* Spalte k der Obermatrix (Zeile k der Untermatrix) */
int max_anz; /* Anzahl der allokierten Elemente i (ohne Diagonale) */
int anz; /* Anzahl eingespeicherter Aik (ohne Diagonale) */
long rechts; /* rechts[k]: letzte Spalte j, die ein Akj enthaelt */
M34_aik* Ak; /* Spalten/Zeilenelemente */
} M34_Spalte;
typedef struct
{
long info[2]; /* Muss immer zuerst kommen, enthaelt Dimension und Matrixtyp */
long max_size;
int usym; /* 0: symmetrisch, Modell 3 */
/* 1: unsymmetrisch, Modell 4 */
int stat; /* -1: nicht initialisiert */
/* 0: initialisiert */
/* 1: aik eingespeichert oder veraendert, */
/* 2: ILU-Zerlegung gelaufen */
int l34_Aik; /* L�nge von Aik */
/* 2: symmetrisch, 4: unsymmetrisch */
int i34_Bik; /* Start Bik (Preconditioner) innerhalb aik */
/* 1: symmetrisch, 2: unsymmetrisch */
double* Diag; /* Akk als Vektor */
double* PreD; /* Bkk (ILU-Preconditioner) */
M34_Spalte* Spalte; /* Obermatrixspalten (Untermatrixzeilen) */
} Modell34;
/* Die nachfolgenden Makros dienen der besseren Lesbarkeit (Kuerze!)
des Codes. Sie werden am Ende dieser Quelle saemtlich undefiniert!
Allgemeines: */
#define dim ((long*)wurzel)[0] /* Dimension der aktuellen Matrix */
#define matrix_type ((long*)wurzel)[1] /* Speichermodell der aktuellen Matrix */
#define Maxim(x,v) if(x < (v)) x = v /* x =max(x,v) */
#define Minim(x,v) if(x > (v)) x = v
/* x =min(x,v)
Modell 1: */
#define Matrix1 w->matrix
#define Aik1(i,k) Matrix1[i* dim + k]
/* Modell 2: */
#define Zeil2(i) w->zeile[i]
#define Aik2(i,j) Zeil2(i).wert[j]
#define Ind2(i,j) Zeil2(i).index[j]
#define Diag2(i) Zeil2(i).wert[0]
/* Modelle 3,4: */
#define Sp34(k) w->Spalte[k]
#define Aik34(k,j,teil) Sp34(k).Ak[j].Aik[teil]
#define Bik34(k,j,teil) Sp34(k).Ak[j].Aik[(w->i34_Bik) + teil]
#define Ind34(k,j) Sp34(k).Ak[j].Index
void* M34CreateMatrix(long param1, long param2, long param3);
void* M34DestroyMatrix(void);
void M34ResizeMatrix(long dimension);
void M34InitMatrix(void);
int M34Set(long i, long j, double aij);
int M34Inc(long i, long j, double aij_inc);
int M34Mul(long i, long j, double aij_mul);
double M34Get(long i, long j);
void M34MatVek(double* vektor, double* ergebnis);
void M34MatTVek(double* vektor, double* ergebnis);
void M34Vorkond(int aufgabe, double* x, double* b);
int M34CopyToAMG1R5Structure( double* A,
int* IA,
int* JA,
int NDA,
int NDIA,
int NDJA,
double*,
double*,
double*,
double*);
void MX_Exit(const char* caller, int errcode)
{
char text[1024];
strcpy(text,caller);
strcat(text, ": ");
switch (errcode)
{
case 0:
strcat(text, "Negative Dimension");
break;
case 1:
strcat(text, "Keine Wurzel eingetragen");
break;
case 2:
strcat(text, "Feldgrenzenueberschreitung");
break;
case 3:
strcat(text, "Nullzeiger");
break;
case 4:
strcat(text, "Unbekanntes Speichermodell");
break;
case 5:
strcat(text, "Argumente falsch");
break;
}
DisplayErrorMsg(strcat(text, " -> Abbruch!"));
exit(1);
}
/* Definitionen */
MXPCreateMatrix MXCreateMatrix;
MXPDestroyMatrix MXDestroyMatrix;
MXPResizeMatrix MXResizeMatrix;
MXPInitMatrix MXInitMatrix;
MXPSet MXSet;
MXPInc MXInc;
MXPDec MXDec;
MXPMul MXMul;
MXPDiv MXDiv;
MXPGet MXGet;
MXPTrans MXTrans;
MXPMatVek MXMatVek;
MXPMatTVek MXMatTVek;
MXPVorkond MXVorkond;
MXPCopyToAMG1R5Structure MXCopyToAMG1R5Structure;
/* allgemeine Funktionen */
/*************************************************************************
ROCKFLOW - Funktion: MXSetupMatrix
Aufgabe:
Setzt Funktionszeiger, erzeugt neue Matrix-Struktur, initialisiert
die Matrix
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E long param1: Dimension der Matrix
E long param2: Speichertechnik der Matrix
E long param3: nicht benutzt
Ergebnis:
Matrix-Wurzelzeiger
Programmaenderungen:
7/2000 CT Erste Version
*************************************************************************/
void* MXSetupMatrix(long param1, long param2, long param3)
{
MXSetFunctionPointers((int) param2);
wurzel = MXCreateMatrix(param1, param2, param3);
MXSetMatrixPointer(wurzel);
MXInitMatrix();
return wurzel;
}
/*************************************************************************
ROCKFLOW - Funktion: MXSetFunctionPointers
Aufgabe:
Setzt die MX-Funktionszeiger auf die entsprechenden Funktionen des
angegebenen Speichermodells
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E int type: Speichermodell
Ergebnis:
0 bei unzulaessigem Modelltyp, sonst 1
Programmaenderungen:
11/1995 MSR Erste Version
*************************************************************************/
int MXSetFunctionPointers(int type)
{
switch (type)
{
case 1:
MXCreateMatrix = M1CreateMatrix;
MXDestroyMatrix = M1DestroyMatrix;
MXResizeMatrix = M1ResizeMatrix;
MXInitMatrix = M1InitMatrix;
MXSet = M1Set;
MXInc = M1Inc;
MXMul = M1Mul;
MXGet = M1Get;
MXMatVek = M1MatVek;
MXMatTVek = M1MatTVek;
MXVorkond = M1Vorkond;
MXCopyToAMG1R5Structure = M1CopyToAMG1R5Structure;
break;
case 2:
MXCreateMatrix = M2CreateMatrix;
MXDestroyMatrix = M2DestroyMatrix;
MXResizeMatrix = M2ResizeMatrix;
MXInitMatrix = M2InitMatrix;
MXSet = M2Set;
MXInc = M2Inc;
MXMul = M2Mul;
MXGet = M2Get;
MXMatVek = M2MatVek;
MXMatTVek = M2MatTVek;
MXVorkond = M2Vorkond;
MXCopyToAMG1R5Structure = M2CopyToAMG1R5Structure;
break;
case 3:
MXCreateMatrix = M34CreateMatrix;
MXDestroyMatrix = M34DestroyMatrix;
MXResizeMatrix = M34ResizeMatrix;
MXInitMatrix = M34InitMatrix;
MXSet = M34Set;
MXInc = M34Inc;
MXMul = M34Mul;
MXGet = M34Get;
MXMatVek = M34MatVek;
MXMatTVek = M34MatTVek;
MXVorkond = M34Vorkond;
MXCopyToAMG1R5Structure = M34CopyToAMG1R5Structure;
break;
case 4:
MXCreateMatrix = M34CreateMatrix;
MXDestroyMatrix = M34DestroyMatrix;
MXResizeMatrix = M34ResizeMatrix;
MXInitMatrix = M34InitMatrix;
MXSet = M34Set;
MXInc = M34Inc;
MXMul = M34Mul;
MXGet = M34Get;
MXMatVek = M34MatVek;
MXMatTVek = M34MatTVek;
MXVorkond = M34Vorkond;
MXCopyToAMG1R5Structure = M34CopyToAMG1R5Structure;
break;
case 5:
MXCreateMatrix = M5CreateMatrix;
MXDestroyMatrix = M5DestroyMatrix;
MXResizeMatrix = M2ResizeMatrix;
MXInitMatrix = M5InitMatrix;
MXSet = M5Set;
MXInc = M5Inc; //M2Inc;
MXMul = M2Mul;
MXGet = M5Get;
MXMatVek = M5MatVek;
MXMatTVek = M2MatTVek;
MXVorkond = M5Vorkond;
MXCopyToAMG1R5Structure = M2CopyToAMG1R5Structure;
break;
case 6:
MXCreateMatrix = M2CreateMatrix;
MXDestroyMatrix = M2DestroyMatrix;
MXResizeMatrix = M2ResizeMatrix;
MXInitMatrix = M2InitMatrix;
MXSet = M2Set;
MXInc = M2Inc;
MXMul = M2Mul;
MXGet = M2Get;
MXMatVek = M6MatVek;
MXMatTVek = M2MatTVek;
MXVorkond = M2Vorkond;
MXCopyToAMG1R5Structure = M2CopyToAMG1R5Structure;
break;
default:
return 0;
}
MXDec = MX_Dec; /* nicht modellspezifisch */
MXDiv = MX_Div;
MXTrans = MX_Trans;
return 1;
}
/*************************************************************************
ROCKFLOW - Funktion: MXSetMatrixPointer
Aufgabe:
Setzt den internen Matrix-Wurzelzeiger auf die angegebene Matrix-Wurzel.
Alle folgenden Aufrufe der MX-Funktionen beziehen sich dann auf die
gewaehlte Matrix. Dadurch entfaellt die Parameteruebergabe des
Matrix-Wurzelzeigers, das Verfahren ermoeglicht aber trotzdem das
Verwalten verschiedener Matrizen (Gleichungssysteme) gleichzeitig.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E void *matrix_pointer: Matrix-Wurzelzeiger
Ergebnis:
- void -
Programmaenderungen:
11/1995 MSR Erste Version
7/2000 CT Speichermodell implizit in Matrix-Datenstruktur
*************************************************************************/
void MXSetMatrixPointer(void* matrix_pointer)
{
wurzel = matrix_pointer;
MXSetFunctionPointers(matrix_type);
}
/*************************************************************************
ROCKFLOW - Funktion: MXGetMatrixPointer
Aufgabe:
Liefert den internen Matrix-Wurzelzeiger fuer aktuelle Matrix
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
Ergebnis:
void *matrix_pointer: Matrix-Wurzelzeiger-
Programmaenderungen:
3/2000 C.Thorenz Erste Version
*************************************************************************/
void* MXGetMatrixPointer(void)
{
return wurzel;
}
/*************************************************************************
ROCKFLOW - Funktion: MXGetDim
Aufgabe:
Liefert die Dimension der zuvor mit MXSetMatrixPointer angegebenen
Matrix-Struktur.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
- void -
Ergebnis:
Dimension der Matrix
Programmaenderungen:
11/1995 MSR Erste Version
*************************************************************************/
long MXGetDim(void)
{
return dim;
}
/*************************************************************************
ROCKFLOW - Funktion: MXGetMatrixType
Aufgabe:
Liefert das Speichermodell der aktuellen Matrix-Struktur.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
- void -
Ergebnis:
Speichermodell der Matrix
Programmaenderungen:
04/1999 AH Erste Version
7/2000 CT Speichermodell implizit in Matrix-Datenstruktur
*************************************************************************/
int MXGetMatrixType(void)
{
return matrix_type;
}
/*************************************************************************
ROCKFLOW - Funktion: M#CreateMatrix
Aufgabe:
Erzeugen einer neuen Matrix-Struktur
speziell Modelle 2, 3, 4:
Die Struktur muss vor Benutzung unbedingt initialisiert werden!
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E long param1: Dimension der Matrix
E long param2: Speichertechnik der Matrix
E long param3: nicht benutzt
Ergebnis:
Matrix-Wurzelzeiger
Programmaenderungen:
Modell 1: 11/1995 MSR Erste Version
Modell 2: 11/1995 MSR Erste Version
Modell 3, 4: 2/2000 Ra Letzte Version
7/2000 CT Speichermodell implizit in Matrix-Datenstruktur
*** Modell 1 ************************************************************/
void* M1CreateMatrix(long param1, long param2, long /*param3*/)
{
static Modell1* w;
#ifdef ERROR_CONTROL
if (param1 < 0)
MX_Exit("M1CreateMatrix", 0);
#endif
w = (Modell1*) Malloc(sizeof(Modell1));
MXSetMatrixPointer((void*) w);
Matrix1 = (double*) Malloc(param1 * param1 * sizeof(double));
dim = w->max_size = param1;
matrix_type = param2;
w->NumDif = 0;
return (void*) w;
}
/**** Modell 2 ************************************************************/
void* M2CreateMatrix(long param1, long param2, long /*param3*/)
{
static Modell2* w;
static long i;
#ifdef ERROR_CONTROL
if (param1 < 0)
MX_Exit("M2CreateMatrix", 0);
#endif
w = (Modell2*) Malloc(sizeof(Modell2));
MXSetMatrixPointer((void*) w);
w->zeile = (M2_Zeile*) Malloc(param1 * sizeof(M2_Zeile));
for (i = 0; i < param1; i++)
{
Zeil2(i).index = (long*) Malloc(sp2_start * sizeof(long));
Zeil2(i).wert = (double*) Malloc(sp2_start * sizeof(double));
Zeil2(i).max_anz = sp2_start;
Zeil2(i).anz = 0;
Zeil2(i).min_col = i;
Zeil2(i).max_col = i;
}
dim = w->max_size = param1;
matrix_type = param2;
w->NumDif = 0;
return (void*) w;
}
/**** Modell 3 und 4 ******************************************************/
void* M34CreateMatrix(long param1, long param2, long /*param3*/)
{
Modell34* w = NULL;
register long i;
#ifdef ERROR_CONTROL
if (param1 < 0)
MX_Exit("M34CreateMatrix", 0);
#endif
w = (Modell34*) Malloc(sizeof(Modell34));
MXSetMatrixPointer((void*) w);
dim = w->max_size = param1;
matrix_type = param2;
w->usym = matrix_type - 3;
w->stat = -1;
w->l34_Aik = (w->usym + 1) * 2;
w->i34_Bik = w->usym + 1;
w->Diag = (double*) Malloc(param1 * sizeof(double));
/* Diag. Precond. */
w->PreD = (double*) Malloc(param1 * sizeof(double));
w->Spalte = (M34_Spalte*) Malloc(param1 * sizeof(M34_Spalte));
for (i = 0; i < param1; i++)
{ /* Start- und Inkrementlaengen wie Modell 2 */
Sp34(i).max_anz = sp2_start;
Sp34(i).anz = 0;
Sp34(i).rechts = 0;
Sp34(i).Ak = (M34_aik*) Malloc(sp2_start * sizeof(M34_aik));
}
return (void*) w; /* Die ILU-Pointer sind auch schon initialisiert */
}
/*************************************************************************
ROCKFLOW - Funktion: MxDestroyMatrix
Aufgabe:
Freigeben der zuvor mit MXSetMatrixPointer angegebenen Matrix-Struktur.
Formalparameter: keine
Ergebnis:
NULL
Programmaenderungen:
Modell 1: 11/1995 MSR Erste Version
Modell 2: 11/1995 MSR Erste Version
Modell 3, 4: 2/2000 Ra Letzte Version
*** Modell 1 ************************************************************/
void* M1DestroyMatrix(void)
{
Modell1* w = (Modell1*) wurzel;
if (wurzel == NULL)
return NULL;
Matrix1 = (double*) Free(Matrix1);
wurzel = Free(w);
return NULL;
}
/**** Modell 2 ************************************************************/
void* M2DestroyMatrix(void)
{
Modell2* w = (Modell2*) wurzel;
static long i;
if (wurzel == NULL)
return NULL;
#ifdef TESTMATRIX_PERF
/* statistische Auswertung der Speicherstruktur */
{
long j, anz_inc = 0, max_inc = 0, zaehler = 0;
for (j = 0; j < w->max_size; j++)
{
Maxim(max_inc, Zeil2(j).max_anz);
if (Zeil2(j).max_anz > sp2_start)
{
anz_inc++;
zaehler += ((Zeil2(j).max_anz - sp2_start) / sp2_inc);
}
}
DisplayMsgLn("Statistische Auswertung der Speicherstruktur:");
DisplayMsg(" - max. Dimension des Gleichungssystems: ");
DisplayLong(w->max_size);
DisplayMsgLn("");
DisplayMsg(" - Ausgangsgroesse der Zeileneintraege sp2_start: ");
DisplayLong((long) sp2_start);
DisplayMsgLn("");
DisplayMsg(" - Erhoehung der Zeileneintraege sp2_inc: ");
DisplayLong((long) sp2_inc);
DisplayMsgLn("");
DisplayMsg(" - Anzahl der erhoehten Zeileneintraege: ");
DisplayLong(anz_inc);
DisplayMsgLn("");
DisplayMsg(" - Groesste Groesse eines Zeileneintrages: ");
DisplayLong(max_inc);
DisplayMsgLn("");
DisplayMsg(" - Gesamtzahl der Erhoehungen aller Zeileneintraege: ");
DisplayLong(zaehler);
DisplayMsgLn("");
}
#endif
for (i = 0; i < w->max_size; i++)
{
Zeil2(i).index = (long*) Free(Zeil2(i).index);
Zeil2(i).wert = (double*) Free(Zeil2(i).wert);
}
w->zeile = (M2_Zeile*) Free(w->zeile);
wurzel = Free(w);
return NULL;
}
/**** Modell 3, 4 *********************************************************/
void* M34DestroyMatrix(void)
{
register long i;
Modell34* w = (Modell34*) wurzel;
if (w == NULL)
return NULL;
#ifdef TESTMATRIX_PERF
{ /* statistische Auswertung der Speicherstruktur */
long anz_inc = 0, max_inc = 0, zaehler = 0;
for (j = 0; j < w->max_size; j++)
{
Maxim(max_inc, Sp34(j).max_anz);
if (Sp34(j).max_anz > sp2_start)
{
anz_inc++;
zaehler += (Sp34(j).max_anz - sp2_start) / sp2_inc;
}
}
DisplayMsgLn("Statistische Auswertung der Speicherstruktur:");
DisplayMsg(" - max. Dimension des Gleichungssystems: ");
DisplayLong(w->max_size);
DisplayMsgLn("");
DisplayMsg(" - Ausgangsgroesse der Zeileneintraege sp2_start: ");
DisplayLong((long) sp2_start);
DisplayMsgLn("");
DisplayMsg(" - Erhoehung der Zeileneintraege sp2_inc: ");
DisplayLong((long) sp2_inc);
DisplayMsgLn("");
DisplayMsg(" - Anzahl der erhoehten Zeileneintraege: ");
DisplayLong(anz_inc);
DisplayMsgLn("");
DisplayMsg(" - Groesste Groesse eines Zeileneintrages: ");
DisplayLong(max_inc);
DisplayMsgLn("");
DisplayMsg(" - Gesamtzahl der Erhoehungen aller Zeileneintraege: ");
DisplayLong(zaehler);
DisplayMsgLn("");
}
#endif
for (i = 0; i < w->max_size; i++)
Sp34(i).Ak = (M34_aik*) Free(Sp34(i).Ak);
w->Spalte = (M34_Spalte*) Free(w->Spalte);
w->Diag = (double*) Free(w->Diag);
w->PreD = (double*) Free(w->PreD);
wurzel = Free(w);
return NULL;
}
/**** Modell 5 ************************************************************/
//WW/PA 08/02/2006
void* M5DestroyMatrix(void)
{
free(jd_ptr1);
free(jd_ptr2);
free(jd_ptr);
free(jd_ptrf);
free(temp_ergebnis);
free(col_ind);
free(jdiag);
free(diag5_i);
return (void*) 1;
}
/*************************************************************************
ROCKFLOW - Funktion: M#ResizeMatrix
Aufgabe:
Veraendern der Groesse der zuvor mit MXSetMatrixPointer angegebenen
Matrix-Struktur. Der Wurzelzeiger bleibt erhalten, die bisher
eingetragenen Werte nicht. Die Matrix wird nur vergroessert, nie
verkleinert.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E long dimension: Dimension der Matrix
Ergebnis:
- void -
Programmaenderungen:
Modell 1: 11/1995 MSR Erste Version
Modell 2: 11/1995 MSR Erste Version
Modell 3,4 2/2000 Ra Letzte Version
*** Modell 1 ************************************************************/
void M1ResizeMatrix(long dimension)
{
Modell1* w = (Modell1*) wurzel;
#ifdef ERROR_CONTROL
if (w == NULL)
MX_Exit("M1ResizeMatrix", 1);
if (dimension < 0)
MX_Exit("M1ResizeMatrix", 0);
#endif
dim = dimension;
if (w->max_size < dimension)
{
Matrix1 = (double*) Free(w->matrix);
Matrix1 = (double*) Malloc(dim * dim * sizeof(double));
w->max_size = dim;
}
}
/**** Modell 2 ************************************************************/
void M2ResizeMatrix(long dimension)
{
Modell2* w = (Modell2*) wurzel;
static long i;
#ifdef ERROR_CONTROL
if (w == NULL)
MX_Exit("M2ResizeMatrix", 1);
if (dimension < 0)
MX_Exit("M2ResizeMatrix", 0);
#endif
dim = dimension;
if (w->max_size < dim)
{
w->zeile = (M2_Zeile*) Realloc(w->zeile, dim * sizeof(M2_Zeile));
for (i = w->max_size; i < dim; i++)
{
Zeil2(i).index = (long*) Malloc(sp2_start * sizeof(long));
Zeil2(i).wert = (double*) Malloc(sp2_start * sizeof(double));
Zeil2(i).max_anz = sp2_start;
Zeil2(i).anz = 0;
Zeil2(i).min_col = i;
Zeil2(i).max_col = i;
}
w->max_size = dim;
}
}
/**** Modell 3, 4 *********************************************************/
void M34ResizeMatrix(long dimension)
{
register long i;
Modell34* w = (Modell34*) wurzel;
#ifdef ERROR_CONTROL
if (w == NULL)
MX_Exit("M34ResizeMatrix", 1);
if (dimension < 0)
MX_Exit("M34ResizeMatrix", 0);
#endif
dim = dimension;
w->stat = -1;
if (w->max_size < dim)
{
w->Spalte = (M34_Spalte*) Realloc(w->Spalte, dim * sizeof(M34_Spalte));
w->Diag = (double*) Realloc(w->Diag, dim * sizeof(double));
w->PreD = (double*) Realloc(w->PreD, dim * sizeof(double));
for (i = w->max_size; i < dim; i++)
{ /* Laengen wie Modell 2 */
Sp34(i).max_anz = sp2_start;
Sp34(i).anz = 0;
Sp34(i).rechts = 0;
Sp34(i).Ak = (M34_aik*) Malloc(sp2_start * sizeof(M34_aik));
}
w->max_size = dim;
}
}
/*************************************************************************
ROCKFLOW - Funktion: M#InitMatrix
Aufgabe:
Initialisieren (A[i,j] = 0.0) aller Elemente der zuvor mit
MXSetMatrixPointer angegebenen Matrix-Struktur.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
- void -
Ergebnis: - void -
Programmaenderungen:
Modell 1: 11/1995 MSR Erste Version
Modell 2: 11/1995 MSR Erste Version
Modell 3,4: 2/2000 Ra Letzte Version
*** Modell 1 ************************************************************/
void M1InitMatrix(void)
{
Modell1* w = (Modell1*) wurzel;
register long i, j = dim * dim;
for (i = 0; i < j; i++)
Matrix1[i] = 0.0;
w->NumDif = 0;
}
/**** Modell 2 ************************************************************/
void M2InitMatrix(void)
{
register long i;
register int j;
Modell2* w = (Modell2*) wurzel;
for (i = 0; i < dim; i++)
{
Zeil2(i).anz = 1;
for (j = 0; j < Zeil2(i).max_anz; j++)
Aik2(i, j) = 0.0;
Ind2(i, 0) = i; /* Diagonale immer in Zeilenelement 0! */
Zeil2(i).min_col = i;
Zeil2(i).max_col = i;
}
w->NumDif = 0;
}
/**** Modell 3,4 **********************************************************/
void M34InitMatrix(void)
{
register long i;
Modell34* w = (Modell34*) wurzel;
for (i = 0; i < dim; i++)
{
w->Diag[i] = 0.0; /* Diagonale */
Sp34(i).anz = 0; /* geloescht, keine Nebenelemente */
Sp34(i).rechts = i; /* fuer RDB */
}
w->stat = 0;
}
/**** Modell 5 ************************************************************/
//WW/PA 08/02/2006
void M5InitMatrix(void)
{
long k;
for (k = 0; k < m_count; k++)
jdiag[k] = 0.0;
}
/**************************************************************************/
/* ROCKFLOW - Funktion: M#Set
Aufgabe:
Setzen des Wertes aij als Matrixwert A[i,j] der zuvor mit
MXSetMatrixPointer angegebenen Matrix-Struktur.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E long i, j: Indizes der Matrixposition
E double aij: Wert A[i,j]
Ergebnis:
0
Programmaenderungen:
Modell 1: 11/1995 MSR Erste Version
Modell 2: 11/1995 MSR Erste Version
Modell 3,4 2/2000 Ra Letzte Version
*** Modell 1 *********************************************************** */
int M1Set(long i, long j, double aij)
{
Modell1* w = (Modell1*) wurzel;
#ifdef ERROR_CONTROL
if ((i >= dim) || (j >= dim) || (i < 0) || (j < 0))
MX_Exit("M1Set", 2);
#endif
Aik1(i, j) = aij;
Maxim(w->NumDif, labs(i - j));
return 0;
}
/**** Modell 2 ************************************************************/
int M2Set(long i, long j, double aij)
{
Modell2* w = (Modell2*) wurzel;
register int k = 0;
#ifdef ERROR_CONTROL
if ((i >= dim) || (j >= dim) || (i < 0) || (j < 0))
MX_Exit("M2Set", 2);
#endif
if(j < Zeil2(i).min_col)
Zeil2(i).min_col = j;
if(j > Zeil2(i).max_col)
Zeil2(i).max_col = j;
/* Alle Spalteneintraege durchsuchen */
while (k < Zeil2(i).anz)
{
if (j == Ind2(i, k))
{
Aik2(i, k) = aij;
return 0;
} /* gefunden! */
k++;
}
if (fabs(aij) < MKleinsteZahl )
return 0; /* Abbruch bei Nullwert */
(Zeil2(i).anz)++;
/* Neuen Speicher holen */
if (Zeil2(i).anz > Zeil2(i).max_anz)
{
Zeil2(i).max_anz += sp2_inc; /* Tabelle vergroessern */
Zeil2(i).index = (long*) Realloc(Zeil2(i).index, Zeil2(i).max_anz * sizeof(long));
Zeil2(i).wert = (double*) Realloc(Zeil2(i).wert, Zeil2(i).max_anz * sizeof(double));
}
Ind2(i, k) = j;
Aik2(i, k) = aij;
Maxim(w->NumDif, labs(i - j));
return 0;
}
/**** Modell 3,4 **********************************************************/
int M34Set(long i1, long k1, double aik)
{
register int j = 0;
register long i = i1, k = k1;
int u = 0, j1;
Modell34* w = (Modell34*) wurzel;
#ifdef ERROR_CONTROL
if ((i >= dim) || (k >= dim) || (i < 0) || (k < 0))
MX_Exit("M34Set", 2);
#endif
w->stat = 1;
if (i == k)
{
w->Diag[i] = aik;
return 0;
} /* Diagonalelement */
if (i > k)
{ /* Untermatrixelement */
if (!(w->usym))
return 0; /* symmetrische Matrix, ignorieren */
u = 1;
i = k;
k = i1;
}
/* Alle Spalteneintraege durchsuchen */
while (j < Sp34(k).anz && i >= Ind34(k, j))
{
if (i == Ind34(k, j))
{
Aik34(k, j, u) = aik;
return 0;
} /* vorhanden */
j++;
}
/* Das Element ist noch nicht vorhanden */
//WW if (fabs(aik)< MKleinsteZahl)
if (fabs(aik) < DBL_MIN)
return 0;
if (Sp34(k).anz == Sp34(k).max_anz)
{ /* Spalte verlaengern */
j1 = Sp34(k).max_anz;
Sp34(k).max_anz += sp2_inc;
Sp34(k).Ak = (M34_aik*) Realloc(Sp34(k).Ak, Sp34(k).max_anz * sizeof(M34_aik));
}
/* Spalteneintraege sind nach aufsteigender Zeilennummer sortiert! */
for (j1 = Sp34(k).anz; j1 > j; j1--) /* Rest verschieben */
Sp34(k).Ak[j1] = Sp34(k).Ak[j1 - 1];
Sp34(k).anz++;
Ind34(k, j) = i;
if (w->usym)
Aik34(k, j, 1 - u) = 0.0;
Aik34(k, j, u) = aik;
Maxim(Sp34(i).rechts, k); /* fuer RDB */
return 0;
}
/*************************************************************************
ROCKFLOW - Funktion: M#Inc
Aufgabe:
Inkrementieren des Matrixwertes A[i,j] der zuvor mit
MXSetMatrixPointer angegebenen Matrix-Struktur um den Wert aij_inc.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E long i, j: Indizes der Matrixposition
E double aij_inc: Inkrement von A[i,j]
Ergebnis:
0
Programmaenderungen:
Modell 1,2 11/1995 MSR Erste Version
Modell 3,4 2/2000 Ra Letzte Version
3/2002 CT NumDif korrigiert
*** Modell 1 ************************************************************/
int M1Inc(long i, long j, double aij_inc)
{
Modell1* w = (Modell1*) wurzel;
#ifdef ERROR_CONTROL
if ((i >= dim) || (j >= dim) || (i < 0) || (j < 0))
MX_Exit("M1Inc", 2);
#endif
Maxim(w->NumDif, labs(i - j));
Aik1(i, j) += aij_inc;
return 0;
}
/**** Modell 2 ************************************************************/
int M2Inc(long i, long j, double aij_inc)
{
Modell2* w = (Modell2*) wurzel;
register int k = 0;
#ifdef ERROR_CONTROL
if ((i >= dim) || (j >= dim) || (i < 0) || (j < 0))
MX_Exit("M2Inc", 2);
#endif
if (fabs(aij_inc) < MKleinsteZahl)
return 0; /* Abbruch bei Nullwert */
while (k < Zeil2(i).anz)
{ /* alle Eintraege durchsuchen */
if (j == Ind2(i, k))
{
Aik2(i, k) += aij_inc;
return 0;
} /* gefunden! */
k++;
}
Maxim(w->NumDif, labs(i - j));
return M2Set(i, j, aij_inc); /* neuer Eintrag */
}
/**** Modell 3, 4 *********************************************************/
int M34Inc(long i1, long k1, double aik)
{
register int j = 0;
register long i = i1, k = k1;
int u = 0;
Modell34* w = (Modell34*) wurzel;
#ifdef ERROR_CONTROL
if ((i >= dim) || (k >= dim) || (i < 0) || (k < 0))
MX_Exit("M34Inc", 2);
#endif
w->stat = 1;
if (i == k)
{
w->Diag[i] += aik;
return 0;
} /* Diagonalelement */
if (i > k)
{ /* Untermatrixelement */
if (!(w->usym))
return 0; /* symmetrische Matrix, ignorieren */
u = 1;
i = k;
k = i1;
}
/* Alle Spalteneintraege durchsuchen */
while (j < Sp34(k).anz && i >= Ind34(k, j))
{
if (i == Ind34(k, j))
{
Aik34(k, j, u) += aik;
return 0;
}
j++;
}
return M34Set(i1, k1, aik); /* war noch nicht vorhanden */
}
/*************************************************************************
ROCKFLOW - Funktion: MX#Dec
Aufgabe:
Dekrementieren des Matrixwertes A[i,j] der zuvor mit
MXSetMatrixPointer angegebenen Matrix-Struktur um den Wert aij_dec.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E long i, j: Indizes der Matrixposition
E double aij_dec: Dekrement von A[i,j]
Ergebnis:
0
Programmaenderungen:
Modell 1, 2: 11/1995 MSR Erste Version
alle Modelle : 2/2000 Ra Neufassung mit MXInc
*** nicht modellspezifisch! *********************************************/
int MX_Dec(long i, long j, double aij_dec)
{
return MXInc(i, j, -aij_dec);
}
/*************************************************************************
ROCKFLOW - Funktion: M#Mul
Aufgabe:
Multiplizieren des Matrixwertes A[i,j] der zuvor mit
MXSetMatrixPointer angegebenen Matrix-Struktur mit dem Wert aij_mul.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E long i, j: Indizes der Matrixposition
E double aij_mul: Faktor von A[i,j]
Ergebnis:
0
Programmaenderungen:
Modell 1, 2: 11/1995 MSR Erste Version
Modell 3, 4: 2/2000 Ra Letzte Version
*** Modell 1 ************************************************************/
int M1Mul(long i, long j, double aij_mul)
{
Modell1* w = (Modell1*) wurzel;
#ifdef ERROR_CONTROL
if ((i >= dim) || (j >= dim) || (i < 0) || (j < 0))
MX_Exit("M1Mul", 2);
#endif
Aik1(i, j) *= aij_mul;
return 0;
}
/**** Modell 2 ************************************************************/
int M2Mul(long i, long j, double aij_mul)
{
Modell2* w = (Modell2*) wurzel;
register int k = 0;
#ifdef ERROR_CONTROL
if ((i >= dim) || (j >= dim) || (i < 0) || (j < 0))
MX_Exit("M2Mul", 2);
#endif
while (k < Zeil2(i).anz)
{ /* Alle Eintraege durchsuchen */
if (j == Ind2(i, k))
{
Aik2(i, k) *= aij_mul;
return 0;
} /* gefunden! */
k++;
}
return 0;
}
/**** Modell 3, 4 *********************************************************/
int M34Mul(long i1, long k1, double aik)
{
Modell34* w = (Modell34*) wurzel;
register int j = 0;
register long i = i1, k = k1;
int u = 0;
#ifdef ERROR_CONTROL
if ((i >= dim) || (k >= dim) || (i < 0) || (k < 0))
MX_Exit("M34Mul", 2);
#endif
w->stat = 1;
if (i == k)
{
w->Diag[i] *= aik;
return 0;
} /* Diagonalelement */
if (i > k)
{ /* Untermatrixelement */
if (!(w->usym))
return 0; /* symmetrische Matrix, ignorieren */
u = 1;
i = k;
k = i1;
}
/* Alle Spalteneintraege durchsuchen */
while (j < Sp34(k).anz && i >= Ind34(k, j))
{
if (i == Ind34(k, j))
{
Aik34(k, j, u) *= aik;
return 0;
}
j++;
}
return 0; /* Element nicht vorhanden */
}
/*************************************************************************
ROCKFLOW - Funktion: M#Div
Aufgabe:
Dividieren des Matrixwertes A[i,j] der zuvor mit
MXSetMatrixPointer angegebenen Matrix-Struktur durch den Wert aij_div.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E long i, j: Indizes der Matrixposition
E double aij_div: Divisor von A[i,j]
Ergebnis:
0
Programmaenderungen:
Modell 1, 2: 11/1995 MSR Erste Version
alle Modelle : 2/2000 Ra Neufassung mit MXMul
*** nicht modellspezifisch! *********************************************/
int MX_Div(long i, long j, double aij_div)
{
return MXMul(i, j, (double) 1.0 / aij_div);
}
/*************************************************************************
ROCKFLOW - Funktion: M#Get
Aufgabe:
Ergebnis ist der Matrixwert A[i,j] der zuvor mit MXSetMatrixPointer
angegebenen Matrix-Struktur.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E long i, j: Indizes der Matrixposition
Ergebnis:
A[i,j]
Programmaenderungen:
Modell 1, 2: 11/1995 MSR Erste Version
Modell 3, 4: 2/2000 Ra Letzte Version
*** Modell 1 ************************************************************/
double M1Get(long i, long j)
{
Modell1* w = (Modell1*) wurzel;
#ifdef ERROR_CONTROL
if ((i >= dim) || (j >= dim) || (i < 0) || (j < 0))
MX_Exit("M1Get", 2);
#endif
return Aik1(i, j);
}
/**** Modell 2 ************************************************************/
double M2Get(long i, long j)
{
Modell2* w = (Modell2*) wurzel;
register int k = 0;
#ifdef ERROR_CONTROL
if ((i >= dim) || (j >= dim) || (i < 0) || (j < 0))
MX_Exit("M2Get", 2);
#endif
if ((j < Zeil2(i).min_col) || (j > Zeil2(i).max_col))
return 0.;
while (k < Zeil2(i).anz)
{ /* Alle Eintraege durchsuchen */
if (j == Ind2(i, k))
return Aik2(i, k); /* gefunden! */
k++;
}
return 0.0; /* Kein Eintrag gefunden */
}
/**** Modell 3,4 **********************************************************/
double M34Get(long i1, long k1)
{
Modell34* w = (Modell34*) wurzel;
register int j = 0;
register long i = i1, k = k1;
int u = 0;
#ifdef ERROR_CONTROL
if ((i >= dim) || (k >= dim) || (i < 0) || (k < 0))
MX_Exit("M34Get", 2);
#endif
if (i == k)
return w->Diag[i]; /* Diagonalelement */
if (i > k)
{
u = w->usym;
i = k;
k = i1;
} /* Untermatrixelement */
/* Alle Spalteneintraege durchsuchen */
while (j < Sp34(k).anz && i >= Ind34(k, j))
{
if (i == Ind34(k, j))
return Aik34(k, j, u);
j++;
}
return 0.0; /* Element ist nicht vorhanden */
}
//WW/PA 08/02/2006
double M5Get(long i, long j)
{
MeshLib::CFEMesh const* const mesh (FEMGet("GROUNDWATER_FLOW"));
const long dim1 = mesh->NodesInUsage();
#ifdef ERROR_CONTROL
if ((i >= dim1) || (j >= dim1) || (i < 0) || (j < 0))
MX_Exit("M5Get", 2);
#endif
const size_t jj (mesh->Eqs2Global_NodeIndex[j]);
CNode const* const nod_i (mesh->nod_vector[mesh->Eqs2Global_NodeIndex[i]]);
std::vector<size_t> const& connected_nodes (nod_i->getConnectedNodes());
const size_t n_connected_nodes (connected_nodes.size());
for(size_t k = 0; k < n_connected_nodes; k++)
if(connected_nodes[k] == jj)
//TEST WW return jdiag[m_nod_i->m5_index[k]];
break;
return 0.0; /* Kein Eintrag gefunden */
}
//WW/PA 08/02/2006
int M5Set(long i, long j, double e_val)
{
long dim1;
e_val = e_val; //OK411
MeshLib::CFEMesh const* const mesh(FEMGet("GROUNDWATER_FLOW"));
// CNode *m_nod_j = NULL;
dim1 = mesh->NodesInUsage();
#ifdef ERROR_CONTROL
if ((i >= dim1) || (j >= dim1) || (i < 0) || (j < 0))
MX_Exit("M5Get", 2);
#endif
const size_t jj (mesh->Eqs2Global_NodeIndex[j]);
CNode const* const nod_i (mesh->nod_vector[mesh->Eqs2Global_NodeIndex[i]]);
std::vector<size_t> const& connected_nodes (nod_i->getConnectedNodes());
const size_t n_connected_nodes (connected_nodes.size());
for(size_t k = 0; k < n_connected_nodes; k++)
if(connected_nodes[k] == jj)
//TEST WW jdiag[m_nod_i->m5_index[k]] = e_val;
break;
return 0; /* Kein Eintrag gefunden */
}
/*************************************************************************
ROCKFLOW - Funktion: MxCopyToAMG1R5Structure
Aufgabe:
Uebertraegt die RockFlow-Interne Speicherstruktur in die
Struktur fuer den AMG1R5-Loeser
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
Zu komplex es hier darzulegen
Ergebnis:
0: korrekte Ausfuehrung
Programmaenderungen:
3/2002 C.Thorenz Erste Version
1/2004 TK Compiler Warning: Unreferenced formal parameters deleted
*****************************************************************************/
int M1CopyToAMG1R5Structure(double* A,
int* IA,
int* JA,
int /*NDA*/,
int /*NDIA*/,
int /*NDJA*/,
double* x,
double* U,
double* b,
double* F)
{
long i, j, NNA = 0, NIA = 0;
double a;
for (i = 0; i < dim; i++)
{
/* Vektoren umkopieren */
U[i] = x[i];
F[i] = b[i];
/* Diagonale eintragen */
j = i;
a = MXGet(i,j);
A[NNA] = a;
JA[NNA] = j + 1;
NNA++;
IA[NIA] = NNA;
NIA++;
for (j = 0; j < dim; j++)
{
/* Restmatrix eintragen */
a = MXGet(i,j);
if((fabs(a) > MKleinsteZahl) && (i != j))
{
A[NNA] = a;
JA[NNA] = j + 1;
NNA++;
}
}
}
IA[NIA] = NNA + 1;
return 0;
}
int M2CopyToAMG1R5Structure(double* A,
int* IA,
int* JA,
int /*NDA*/,
int /*NDIA*/,
int /*NDJA*/,
double* x,
double* U,
double* b,
double* F)
{
long i, j;
long NNA = 0, NIA = 0;
double a;
Modell2* w = (Modell2*) wurzel;
register int k;
for (i = 0; i < dim; i++)
{
/* Vektoren umkopieren */
U[i] = x[i];
F[i] = b[i];
j = i;
a = Aik2(i, 0);
A[NNA] = a;
JA[NNA] = j + 1;
NNA++;
IA[NIA] = NNA;
NIA++;
k = 1; /* Diagonale ist schon beruecksichtigt */
while (k < Zeil2(i).anz)
{ /* Alle Eintraege durchsuchen */
j = Ind2(i, k);
a = Aik2(i, k);
A[NNA] = a;
JA[NNA] = j + 1;
NNA++;
k++;
}
}
IA[NIA] = NNA + 1;
return 0;
}
int M34CopyToAMG1R5Structure(double* A,
int* IA,
int* JA,
int /*NDA*/,
int /*NDIA*/,
int /*NDJA*/,
double* x,
double* U,
double* b,
double* F)
{
long i, j, NNA = 0, NIA = 0;
double a;
for (i = 0; i < dim; i++)
{
j = i;
/* Vektoren umkopieren */
U[i] = x[i];
F[i] = b[i];
a = MXGet(i,j);
A[NNA] = a;
JA[NNA] = j + 1;
NNA++;
IA[NIA] = NNA;
NIA++;
for (j = 0; j < dim; j++)
{
a = MXGet(i,j);
if((fabs(a) > MKleinsteZahl) && (i != j))
{
A[NNA] = a;
JA[NNA] = j + 1;
NNA++;
}
}
}
IA[NIA] = NNA + 1;
return 0;
}
/*************************************************************************
ROCKFLOW - Funktion: M#Trans
Aufgabe:
Fuehrt in der zuvor mit MXSetMatrixPointer angegebenen Matrix-Struktur
folgende Operation durch: A[i,j] = A[ii,jj]
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E long i, j: Indizes der Matrixposition 1
E long ii, jj: Indizes der Matrixposition 2
Ergebnis: - void -
Programmaenderungen:
Modell 1,2: 11/1995 MSR Erste Version
alle Modelle : 2/2000 Ra Neufassung mit MXGet/MXSet
*** nicht modellspezifisch! *********************************************/
void MX_Trans(long i, long j, long ii, long jj)
{
MXSet(i, j, MXGet(ii, jj));
}
/*************************************************************************
ROCKFLOW - Funktion: M#MatVek
Aufgabe:
Ausfuehren des Matrix-Vektor-Produktes "A * vektor = ergebnis" mit der
zuvor mit MXSetMatrixPointer angegebenen Matrix-Struktur. "ergebnis"
wird komplett ueberschrieben; der Speicher muss bereits allokiert sein.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E double *vektor: mit der Matrix zu multiplizierender Vektor
E double *ergebnis: Ergebnis der Multiplikation
Ergebnis:
- void -
Programmaenderungen:
Modell 1,2: 11/1995 MSR Erste Version
Modell 3,4: 2/2000 Ra Letzte Version
Modell 2: 3/2002 CT CBLAS eingehaengt
*** Modell 1 ************************************************************/
void M1MatVek(double* vektor, double* ergebnis)
{
Modell1* w = (Modell1*) wurzel;
register long i, k;
#ifdef ERROR_CONTROL
if ((vektor == NULL) || (ergebnis == NULL))
MX_Exit("M1MatVek", 3);
#endif
for (i = 0; i < dim; i++)
{
ergebnis[i] = 0.0;
#ifdef SX
#pragma cdir nodep
#endif
for (k = 0; k < dim; k++)
ergebnis[i] += Aik1(i, k) * vektor[k];
}
}
/****** Permutation when transforming from Modell2 to Modell 5 JAD ********/
/**** Modell 2 ************************************************************/
//WW/PA 08/02/2006
int M5Inc(long i, long j, double aij_inc)
{
MeshLib::CFEMesh const* const mesh(FEMGet("GROUNDWATER_FLOW"));
const long dim1(mesh->NodesInUsage());
#ifdef ERROR_CONTROL
if ((i >= dim1) || (j >= dim1) || (i < 0) || (j < 0))
MX_Exit("M5Inc", 2);
#endif
if (fabs(aij_inc) < MKleinsteZahl)
return 0; /* Abbruch bei Nullwert */
const size_t jj(mesh->Eqs2Global_NodeIndex[j]);
CNode const* const nod_i(mesh->nod_vector[mesh->Eqs2Global_NodeIndex[i]]);
std::vector<size_t> const& connected_nodes(nod_i->getConnectedNodes());
const size_t n_connected_nodes(connected_nodes.size());
for (size_t k = 0; k < n_connected_nodes; k++)
if (connected_nodes[k] == jj)
//TEST WW jdiag[m_nod_i->m5_index[k]] += aij_inc;
break;
return 1;
}
//WW/PA 08/02/2006
/*
void Write_Matrix_M5(double *b, ostream& os)
{
long i,j , dim1;
MeshLib::CFEMesh* m_msh = NULL;
m_msh = FEMGet("GROUNDWATER_FLOW");
#ifdef SX
#pragma cdir nodep
#endif
dim1 = m_msh->NodesInUsage();
for (i = 0; i < dim1; i++)
{
for (j = 0; j < dim1; j++)
{
if(fabs(MXGet(i,j))>MKleinsteZahl)
os<<i<<" "<<j<<" "<<MXGet(i,j)<<"\n";
}
if(fabs(b[i])>MKleinsteZahl)
os<<i<<" "<<dim1+1<<" "<<b[i]<<"\n"; // os<<"\n";
}
}
*/
//void transM2toM5(void)
//void M5CreateMatrix(void)
//PA/WW 08/02/2006
void* M5CreateMatrix(long param1, long param2, long param3)
{
param1 = param1;
param3 = param3;
//
Modell5* w = (Modell5*) wurzel;
w = (Modell5*) Malloc(sizeof(Modell5));
MXSetMatrixPointer((void*) w);
matrix_type = param2;
int i, ii,jj,count1;
long k, index, Size, dim1; //OK
/*------------------------------------------------------------*/
jd_ptr_max = 0;
MeshLib::CFEMesh* m_msh = NULL;
m_msh = FEMGet("GROUNDWATER_FLOW");
#ifdef SX
#pragma cdir nodep
#endif
dim1 = m_msh->NodesInUsage();
Dim_L = dim1;
for (k = 0; k < dim1; k++)
{
index = m_msh->Eqs2Global_NodeIndex[k]; //
//WW
Size = (int)m_msh->nod_vector[index]->getConnectedNodes().size();
if ( Size > jd_ptr_max )
jd_ptr_max = Size;
#ifdef SX
#pragma cdir nodep
#endif
for (i = 0; i < Size; i++)
m_count++;
}
/*------------------------------------------------------------*/
jd_ptr1 = (int*)malloc(dim1 * sizeof(int));
jd_ptr2 = (int*)malloc(dim1 * sizeof(int));
/*------------------------------------------------------------*/
jd_ptr = (int*)malloc(jd_ptr_max * sizeof(int));
jd_ptrf = (int*)malloc((jd_ptr_max + 1) * sizeof(int));
temp_ergebnis = (double*)malloc(dim1 * sizeof(double));
col_ind = (int*)malloc(m_count * sizeof(int));
jdiag = (double*)malloc(m_count * sizeof(double));
diag5_i = (long*)malloc(dim1 * sizeof(long));
/*------------------------------------------------------------*/
for (k = 0; k < jd_ptr_max; k++)
jd_ptr[k] = 0;
for (k = 0; k < dim1; k++)
{
index = m_msh->Eqs2Global_NodeIndex[k]; //
//WW
Size = (int)m_msh->nod_vector[index]->getConnectedNodes().size();
for (i = 0; i < Size; i++)
jd_ptr[i]++;
}
// printf("In transM2toM5 dim=%ld\n",dim1);
for (k = 0; k < dim1; k++)
{
// printf("Zeil2(%d).anz=%d\n",k,Zeil2(k).anz);
index = m_msh->Eqs2Global_NodeIndex[k]; //
// Zeil2(k).anz;
jd_ptr1[k] = (int)m_msh->nod_vector[index]->getConnectedNodes().size();
jd_ptr2[k] = k;
}
/* printf("Before insertionSort1_des\n");
for(k=0;k<dim;k++)
printf("jd_ptr1[%d]=%d\n",k,jd_ptr1[k]);
for(k=0;k<dim;k++)
printf("jd_ptr2[%d]=%d\n",k,jd_ptr2[k]);
*/
insertionSort1_des(jd_ptr1,jd_ptr2, dim1);
/*
printf("After insertionSort1_des\n");
for(k=0;k<dim;k++)
printf("jd_ptr1[%d]=%d\n",k,jd_ptr1[k]);
for(k=0;k<dim;k++)
printf("jd_ptr2[%d]=%d\n",k,jd_ptr2[k]);
*/
for (k = 0; k < jd_ptr_max + 1; k++)
jd_ptrf[0] = 0;
for (k = 0; k < jd_ptr_max; k++)
jd_ptrf[k + 1] = jd_ptrf[k] + jd_ptr[k];
//
/*
count1 = 0;
for (k = 0; k < jd_ptr_max; k++)
{
for (i = 0; i < jd_ptr[k]; i++)
{
ii = jd_ptr2[i];
jdiag[count1] = Aik2(ii, k);
// col_ind[count1] = Ind2(ii, k);
//TEST WW OUT
cout<<ii<<" "<< col_ind[count1]<<" ";
count1++;
}
cout<<"\n";
}
//TEST WW OUT
cout<<"----------------------------"<<"\n";
*/
count1 = 0;
long col_i = 0;
for (k = 0; k < jd_ptr_max; k++)
for (i = 0; i < jd_ptr[k]; i++)
{
// Row of equation system
ii = jd_ptr2[i];
index = m_msh->Eqs2Global_NodeIndex[ii];
// col_ind[count1] = m_msh->go[m_msh->nod_vector[index]->connected_nodes[k]];
col_i = m_msh->nod_vector[index]->getConnectedNodes()[k];
col_ind[count1] = m_msh->nod_vector[col_i]->GetEquationIndex();
jj = col_ind[count1];
//TEST WW m_msh->nod_vector[index]->m5_index[k]=count1;
if(ii == jj)
diag5_i[ii] = count1;
//TEST WW OUT
// cout<<" Row: "<< ii<<" "<< col_ind[count1]<<" ";
// cout<<ii<<" ";
// cout<< col_ind[count1]<<" ";
//////////////////////////////////
count1++;
}
//TEST WW
// cout<<"\n";
////////////////////
return (void*) w;
}
/*-------------------------------------------------------------*/
#ifdef SX
void insertionSort1_des(int* restrict numbers,int* restrict numbers1, int array_size)
#else
void insertionSort1_des(int* numbers,int* numbers1, int array_size)
#endif
{
int i, j, index, index1;
#ifdef SX
#pragma cdir nodep
#endif
for (i = 1; i < array_size; i++)
{
index = numbers[i];
index1 = numbers1[i];
j = i;
while ((j > 0) && (numbers[j - 1] < index))
{
numbers[j] = numbers[j - 1];
numbers1[j] = numbers1[j - 1];
j = j - 1;
}
numbers[j] = index;
numbers1[j] = index1;
}
} /*End of insertionSort1_des.*/
/****** Transforming from Modell2 to Modell 6 ITPACKV ********/
void transM2toM6(void)
{
Modell2* w = (Modell2*) wurzel;
int i,k,count1,dim1;
dim1 = ((long*)wurzel)[0];
/*------------------------------------ TEST ----------------------
*
for (k = 0; k < dim1; k++)
{
printf("Zeil2(%d).anz=%d\n",k, Zeil2(k).anz);
for (i = 0; i < Zeil2(k).anz; i++)
{
printf("Ind2(%d,%d) = %d\n",k,i,Ind2(k, i));
}
}
for (k = 0; k < dim1; k++)
{
printf("Zeil2(%d).anz=%d\n",k, Zeil2(k).anz);
for (i = 0; i < Zeil2(k).anz; i++)
{
printf("Aik2(%d,%d) = %le\n",k,i,Aik2(k, i));
}
}
------------------------------------ TEST ----------------------*/
/*------------------------------------------------------------*/
itpack_max = 0;
#ifdef SX
#pragma cdir nodep
#endif
for (k = 0; k < dim1; k++)
if ( Zeil2(k).anz > itpack_max )
itpack_max = Zeil2(k).anz;
itpackv = (double*)malloc(itpack_max * dim1 * sizeof(double));
it_col = (int*)malloc(itpack_max * dim1 * sizeof(int));
// temp_ergebnis = (double *)malloc(dim*sizeof(double));
count1 = 0;
for(i = 0; i < itpack_max; i++)
for(k = 0; k < dim1; k++)
{
if (i < Zeil2(k).anz )
{
itpackv[count1] = Aik2(k,i);
it_col[count1] = Ind2(k,i);
count1++;
}
else
{
itpackv[count1] = 0.0;
it_col[count1] = Ind2(0,0);
count1++;
}
}
printf("AT End of transM2toM6\n");
/*---------------------------------------------------------
for(k=0; k<count1; k++)
{
printf("itpackv[%d]=%le\n",k,itpackv[k]);
}
for(k=0; k<count1; k++)
{
printf("it_col[%d]=%d\n",k,it_col[k]);
}
*/
}
/**** Modell 2 ************************************************************/
void M2MatVek(double* vektor, double* ergebnis)
{
Modell2* w = (Modell2*) wurzel;
register long k;
register int i;
#ifdef CBLAS_M2MatVek
double* help;
help = (double*) Malloc(dim * sizeof(double));
#endif
#ifdef ERROR_CONTROL
if ((vektor == NULL) || (ergebnis == NULL))
MX_Exit("M2MatVek", 3);
#endif
for (k = 0; k < dim; k++)
{
#ifndef CBLAS_M2MatVek
ergebnis[k] = 0.0;
#ifdef SX
#pragma cdir nodep
#endif
for (i = 0; i < Zeil2(k).anz; i++)
ergebnis[k] += Aik2(k, i) * vektor[Ind2(k, i)];
#else
for (i = 0; i < Zeil2(k).anz; i++)
help[i] = vektor[Ind2(k, i)];
ergebnis[k] = cblas_ddot(Zeil2(k).anz, Zeil2(k).wert, 1, help, 1);
#endif
}
#ifdef CBLAS_M2MatVek
help = (double*) Free(help);
#endif
}
/*--------------------------------------------------------------------
* Matrxi-Vektor Multiply with Jagged Diagonal Format (Modell 5)
PA Initial version
---------------------------------------------------------------------*/
#ifdef SX
void M5MatVek(double* restrict b, double* restrict erg)
#else
void M5MatVek(double* b, double* erg)
#endif
{
// Modell2 *w = (Modell2 *) wurzel;
int i, dim1; //k,
int j, num;
long col_len;
MeshLib::CFEMesh* m_msh = NULL; //WW
m_msh = FEMGet("GROUNDWATER_FLOW");
dim1 = m_msh->NodesInUsage();
#ifdef SX
#pragma cdir nodep
#endif
for (i = 0; i < dim1; i++)
erg[i] = 0.0;
for (i = 0; i < dim1; i++)
temp_ergebnis[i] = 0.0;
for (i = 0; i < jd_ptr_max; i++)
{
col_len = jd_ptrf[i + 1] - jd_ptrf[i];
num = jd_ptrf[i];
// printf("num=%d\n",num);
// printf("col_len=%d\n",col_len);
#ifdef _OPENMP
#pragma omp parallel for private(j) shared(temp_ergebnis,jdiag,b,num,col_ind)
#endif
#ifdef SX
#pragma cdir nodep
#endif
for (j = 0; j < col_len; j++)
temp_ergebnis[j] += jdiag[num + j] * b[col_ind[num + j]];
}
#ifdef SX
#pragma cdir nodep
#endif
for(i = 0; i < dim1; i++)
erg[jd_ptr2[i]] = temp_ergebnis[i];
}
/*--------------------------------------------------------------------
* Matrxi-Vektor Multiply with ITPACKV
--------------------------------------------------------------------*/
#ifdef SX
void M6MatVek(double* restrict b, double* restrict erg)
#else
void M6MatVek(double* b, double* erg)
#endif
{
// Modell2 *w = (Modell2 *) wurzel;
int i,j,num, dim1;
dim1 = ((long*)wurzel)[0];
#ifdef SX
#pragma cdir nodep
#endif
for (i = 0; i < dim1; i++)
erg[i] = 0.0;
num = 0;
// printf("In M6MatVek itpack_max=%d\n",itpack_max);
for (i = 0; i < itpack_max; i++)
{
//#pragma omp parallel for private(j) shared(erg,itpackv,b,num,it_col)
#ifdef SX
#pragma cdir nodep
#endif
for (j = 0; j < dim1; j++)
erg[j] = erg[j] + itpackv[num + j] * b[it_col[num + j]];
num = num + dim1;
}
}
/**** Modell 3,4 **********************************************************/
void H_MX34_mul(double* x, double* r, int o)
/* Hilfsroutine zu Matrix-Vektorprodukt Modelle 3 und 4
Ergebnis: r = A*x bei o=0
bzw. r = At*x bei o=1
A = Matrix Modell 3/4
Die Vektoren x und r muessen allokiert sein!
*/
{
Modell34* w = (Modell34*) wurzel;
register long k, i;
register int j;
int u = 1 - o; /* o=0: normal, o=1: mit Transponierter */
#ifdef ERROR_CONTROL
if ((x == NULL) || (r == NULL))
MX_Exit("M34Mat(T)Vek", 3);
#endif
if (!(w->usym))
{
o = 0;
u = 0;
} /* symmetrische Matrix: Oik=Uki */
for (k = 0; k < dim; k++)
{
r[k] = w->Diag[k] * x[k];
#ifdef SX
#pragma cdir nodep
#endif
for (j = 0; j < Sp34(k).anz; j++)
{
i = Ind34(k, j);
r[i] += Aik34(k, j, o) * x[k];
r[k] += Aik34(k, j, u) * x[i];
}
}
}
void M34MatVek(double* vektor, double* ergebnis)
{
H_MX34_mul(vektor, ergebnis, (int) 0);
}
/*************************************************************************
ROCKFLOW - Funktion: M#MatTVek
Aufgabe:
Ausfuehren des Matrix-Vektor-Produktes "A^T * vektor = ergebnis" mit der
zuvor mit MXSetMatrixPointer angegebenen Matrix-Struktur. "ergebnis"
wird komplett ueberschrieben; der Speicher muss bereits allokiert sein.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E double *vektor: mit der transponierten Matrix zu multiplizierender
Vektor
E double *ergebnis: Ergebnis der Multiplikation
Ergebnis:
- void -
Programmaenderungen:
Modell 1,2: 11/1995 MSR Erste Version
Modell 3,4: 2/2000 Ra Letzte Version
*** Modell 1 ***********************************************************/
void M1MatTVek(double* vektor, double* ergebnis)
{
Modell1* w = (Modell1*) wurzel;
register long i, k;
#ifdef ERROR_CONTROL
if ((vektor == NULL) || (ergebnis == NULL))
MX_Exit("M1MatTVek", 3);
#endif
for (i = 0; i < dim; i++)
{
ergebnis[i] = 0.0;
for (k = 0; k < dim; k++)
ergebnis[i] += Aik1(k, i) * vektor[k];
}
}
/**** Modell 2 ***********************************************************/
void M2MatTVek(double* vektor, double* ergebnis)
{
Modell2* w = (Modell2*) wurzel;
register long k;
register int i;
#ifdef ERROR_CONTROL
if ((vektor == NULL) || (ergebnis == NULL))
MX_Exit("M2MatTVek", 3);
#endif
for (k = 0; k < dim; k++)
ergebnis[k] = 0.0;
for (k = 0; k < dim; k++)
for (i = 0; i < Zeil2(k).anz; i++)
ergebnis[Ind2(k, i)] += Aik2(k, i);
}
/**************************************************************************/
void M34MatTVek(double* vektor, double* ergebnis)
{
H_MX34_mul(vektor, ergebnis, (int) 1); /* siehe M34MatVek */
}
/*************************************************************************
ROCKFLOW - Funktion: MXResiduum
Aufgabe:
Berechnet das Residuum "r = b - A x" mit der zuvor mit
MXSetMatrixPointer angegebenen Matrix-Struktur. "ergebnis" wird
komplett ueberschrieben; der Speicher muss bereits allokiert sein.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E double *x: Vektor x
E double *b: Vektor b
E double *ergebnis: Residuum
Ueberschreiben: b und ergebnis duerfen _nicht_ gleich sein (CT) */
/* Ergebnis:
- void -
Programmaenderungen:
Modell 1,2: 11/1995 MSR Erste Version
10/1998 C.Thorenz Hilfsvariable gegen kleine Differenzen
grosser Zahlen
Modell 3,4: 2/2000 Ra Letzte Version
Alle Modelle: 3/2002 CT Vereinfacht und alle Modelle zusammengefasst
*/
void MXResiduum(double* x, double* b, double* ergebnis)
{
#ifdef ERROR_CONTROL
if ((x == NULL) || (b == NULL) || (ergebnis == NULL))
MX_Exit("MXResiduum", 3);
if (b == ergebnis)
MX_Exit("MXResiduum", 5);
#endif
MXMatVek(x, ergebnis);
//WW
long Dimension = 0;
if(matrix_type == 5)
Dimension = Dim_L;
else
Dimension = dim;
//
//WW
MAddSkalVektoren(ergebnis, -1., b, 1., ergebnis, Dimension);
}
/*************************************************************************
ROCKFLOW - Funktion: MXRandbed
Aufgabe:
Vorgegebene Randbedingung Xi= Ri in Matrix und Rechte Seite einbauen
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E long ir : Gleichungsnummer, fuer die Randbedingung vorgegeben wird
E double Ri: vorgegebener Wert der Randbedingung
E double *ReSei: Zeiger auf Rechte Seite
Ergebnis: - void -
Programmaenderungen:
alle Modelle: 3/2000 Ra Erste Version
6/2000 C.Thorenz Fehler in Modell 34 beseitigt
1/2001 C.Thorenz Diagonale bleibt auf Wert, stattdessen wird
der rechte Seite Eintrag skaliert
=> keine boese Veraenderung an einer Stelle der Diagonale
12/2001 C.Thorenz Diagonalwert = 0 abgefangen
02/2006 WW/PA M5 storage
*** Unterscheidung nach Modell innerhalb der Prozedur! ******************/
void MXRandbed(long ir, double Ri, double* ReSei)
{
register long i=0, ip, im;
long p, q;
int k;
double diag;
/* Diagonalelement holen */
diag = MXGet(ir, ir);
/* Wenn das Diagonalelement ~= 0 ist, ein anderes suchen.
Sollte eigentlich nicht vorkommen. */
if (fabs(diag) < DBL_MIN) // TODO This probably won't work as intended
for (i = 0; i < dim; i++)
{
ip = ir + i;
im = ir - i;
if(ip < dim)
if(fabs(diag = MXGet(ip, ip)) > DBL_MIN)
break;
if(im >= 0)
if(fabs(diag = MXGet(im, im)) > DBL_MIN)
break;
}
/* Dieser Fall sollte _nie_ auftreten */
if (fabs(diag) < DBL_MIN)
diag = MKleinsteZahl;
//TEST WW
/*
#ifdef ERROR_CONTROL
if ((ir >= dim) || (ir < 0))
MX_Exit("MXRandbed", 2);
if (ReSei == NULL)
MX_Exit("MXRandbed", 3);
#endif
*/
switch (matrix_type)
{
case 1:
{
Modell1* w = (Modell1*) wurzel;
p = ir - w->NumDif;
if (p < 0)
p = 0;
q = ir + w->NumDif + 1;
if (q > dim)
q = dim;
for (i = p; i < q; i++)
{
ReSei[i] -= Aik1(i, ir) * Ri; /* Spalte ausmultiplizieren */
Aik1(i, ir) = Aik1(ir, i) = 0.0; /* Spalte und Zeile Null setzen */
}
ReSei[ir] = Ri * diag; /* Randwert einsetzen */
MXSet(ir, ir, diag);
}
break;
case 2:
{
Modell2* w = (Modell2*) wurzel;
p = ir - w->NumDif;
if (p < 0)
p = 0;
q = ir + w->NumDif + 1;
if (q > dim)
q = dim;
for (i = p; i < q; i++)
if (i != ir)
{ /* alle anderen Zeilen mit Spalte iR */
k = 0;
while (++k < Zeil2(i).anz) /* Alle Eintraege (ausser Diag.) */
if (ir == Ind2(i, k))
{
ReSei[i] -= Aik2(i, k) * Ri;
Aik2(i, k) = 0.0;
goto End_Zeil;
} /*[i,iR] */
End_Zeil:;
}
for (k = 0; k < Zeil2(ir).anz; k++)
Aik2(ir, k) = 0.0; /* Rest der Zeile Null */
ReSei[ir] = Ri * diag; /* Randwert einsetzen */
MXSet(ir, ir, diag);
}
break;
case 3:
case 4:
{
Modell34* w = (Modell34*) wurzel;
int u = w->usym;
for (k = 0; k < Sp34(ir).anz; k++)
{ /* ueber (links von) Diag. */
/* Obermatrix ausmultipl. */
ReSei[Ind34(ir, k)] -= Aik34(ir, k, 0) * Ri;
/* Zeile / Spalte Null */
Aik34(ir, k, 0) = Aik34(ir, k, u) = 0.0;
}
MXSet(ir, ir, diag); /* Randwert einsetzen */
ReSei[ir] = Ri * diag;
for (i = ir + 1; i <= Sp34(ir).rechts; i++)
for (k = 0; k < Sp34(i).anz; k++)
{
if (Ind34(i, k) > ir)
break;
if (Ind34(i, k) == ir)
{
ReSei[i] -= Aik34(i, k, u) * Ri; /* Untermatrix ausmult. */
/* Zeile / Spalte Null */
Aik34(i, k, 0) = Aik34(i, k, u) = 0.0;
}
}
w->stat = 1; /* Matrix veraendert! */
}
break;
case 5: //WW/PA 08/02/2006
{
//WW long dim1;
long jr;
MeshLib::CFEMesh const* const mesh(FEMGet("GROUNDWATER_FLOW"));
CNode* m_nod_j = NULL;
//WW dim1 = m_msh->NodesInUsage();
ReSei[ir] = Ri * MXGet(ir,ir);
CNode const* const nod_i(mesh->nod_vector[mesh->Eqs2Global_NodeIndex[i]]); // TODO check this. i could be 0.
std::vector<size_t> const& connected_nodes(nod_i->getConnectedNodes());
const size_t n_connected_nodes(connected_nodes.size());
for(size_t k = 0; k < n_connected_nodes; k++)
{
m_nod_j = mesh->nod_vector[connected_nodes[k]];
jr = m_nod_j->GetEquationIndex();
if(ir == jr)
continue;
MXSet(ir,jr,0.0);
ReSei[jr] -= MXGet(jr,ir) * Ri;
MXSet(jr,ir,0.0);
}
}
break;
case 6:
{
Modell2* w = (Modell2*) wurzel;
p = ir - w->NumDif;
if (p < 0)
p = 0;
q = ir + w->NumDif + 1;
if (q > dim)
q = dim;
for (i = p; i < q; i++)
if (i != ir)
{ /* alle anderen Zeilen mit Spalte iR */
k = 0;
while (++k < Zeil2(i).anz) /* Alle Eintraege (ausser Diag.) */
if (ir == Ind2(i, k))
{
ReSei[i] -= Aik2(i, k) * Ri;
Aik2(i, k) = 0.0;
goto End_Zeil6;
} /*[i,iR] */
End_Zeil6:;
}
for (k = 0; k < Zeil2(ir).anz; k++)
Aik2(ir, k) = 0.0; /* Rest der Zeile Null */
ReSei[ir] = Ri * diag; /* Randwert einsetzen */
MXSet(ir, ir, diag);
}
break;
#ifdef ERROR_CONTROL
default:
MX_Exit("MXRandbed", 4);
#endif
}
} /* MXRandbed */
/*************************************************************************
ROCKFLOW - Funktion: MXEliminateIrrNode
Aufgabe:
Eliminieren eines irr. Knotens aus dem fertig aufgestellten
Gesamtgleichungssystem und Eintragen der Zwangsbedingungen
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E long index: Index des irr. Knotens
E int anz_nachbarn: Anzahl (2 oder 4) der reg. Nachbarknoten
E long *nachbarn_index: Feld mit den Indizes der Nachbarn
E double *rechts: Rechte Seite Vektor
Ergebnis: - void -
Programmaenderungen:
9/2000 C.Thorenz Erste Version
1/2001 C.Thorenz Diagonale bleibt auf Wert, stattdessen werden
die Zwangsbedingungen skaliert
=> keine boese Veraenderung an einer Stelle der Diagonale
************************************************************************/
void MXEliminateIrrNode(long index, int anz_nachbarn, long* nachbarn_index, double* rechts)
{
long zeile, spalte, j, k, l;
double inc, gewicht = 1. / (double) anz_nachbarn, diag = MXGet(index, index);
#ifdef ERROR_CONTROL
if ((index >= dim) || (index < 0))
MX_Exit("MXEliminateIrrNode", 2);
if (rechts == NULL)
MX_Exit("MXEliminateIrrNode", 3);
#endif
switch (matrix_type)
{
default:
{
/* Spalte des irr. Knotens eliminieren : */
/* Ueber alle Zeilen gehen, um nach Eintragen fuer den Knoten zu suchen */
for (j = 0l; j < dim; j++)
{
/* Der Knoteneintrag wird ausmultipliziert und den Nachbarn zugeschlagen */
/* index ist der irregulaere Knoten, j ist die Zeile, nachbarn_index die Spalte */
inc = gewicht * MXGet(j, index);
if (fabs(inc) > 0.)
for (k = 0; k < anz_nachbarn; k++)
MXInc(j, nachbarn_index[k], inc);
/* Spalte des Knotens zu Null setzen, da der Wert oben verteilt wurde */
if (fabs(MXGet(j, index)) > 0.)
MXSet(j, index, 0.);
} /* endfor j */
#ifdef DUMP
MXDumpGLS("a_spalte", 1, rechts, rechts);
#endif
/* Zeile des irr. Knotens eliminieren : */
/* Ueber Zeilen der regulaeren Nachbarn gehen */
/* Der Knoteneintrag wird ausmultipliziert und den Nachbarn zugeschlagen */
for (k = 0; k < dim; k++)
{
inc = gewicht * MXGet(index, k);
if (fabs(inc) > 0.)
{
for (j = 0l; j < anz_nachbarn; j++)
MXInc(nachbarn_index[j], k, inc);
/* Zeile des Knotens zu Null setzen, da hier die Interpolation eingesetzt wird */
MXSet(index, k, 0.);
} /* endif */
}
/* Der rechte Seite-Eintrag wird den Nachbarn zugeschlagen */
for (j = 0l; j < anz_nachbarn; j++)
rechts[nachbarn_index[j]] += gewicht * rechts[index];
#ifdef DUMP
MXDumpGLS("a_zeile", 1, rechts, rechts);
#endif
/* Neuer Zeileneintrag fuer den irr. Knoten, dies ist
die Zwangsbedingung aus der Interpolation */
MXSet(index, index, diag);
rechts[index] = 0.;
for (k = 0; k < anz_nachbarn; k++)
/* i ist die Zeile des irregulaere Knoten, nachbarn_index die Spalte */
MXSet(index, nachbarn_index[k], -gewicht * diag);
#ifdef DUMP
MXDumpGLS("a_zwang", 1, rechts, rechts);
#endif
}
break;
case 2:
{
Modell2* w = (Modell2*) wurzel;
/* Spalte des irr. Knotens eliminieren : */
/* Ueber alle Zeilen gehen, um nach Eintragen fuer den Knoten zu suchen */
for (zeile = 0l; zeile < dim; zeile++)
{
/* Der Knoteneintrag wird ausmultipliziert und den Nachbarn zugeschlagen */
/* index ist der irregulaere Knoten, nachbarn_index[] die Spalte */
spalte = index;
k = 0;
while (k < Zeil2(zeile).anz)
{ /* Alle Eintraege durchsuchen */
if (spalte == Ind2(zeile, k))
{ /* gefunden! */
inc = gewicht * Aik2(zeile, k); /* Mit dem Gewicht multiplizieren */
Aik2(zeile, k) = 0.; /* Eigenen Eintrag loeschen */
for (l = 0; l < anz_nachbarn; l++)
/* Den reg. Nachbarn zuschlagen */
MXInc(zeile, nachbarn_index[l], inc);
break;
}
else
k++;
}
} /* endfor j */
/* Zeile des irr. Knotens eliminieren : */
/* Ueber Zeilen der regulaeren Nachbarn gehen */
for (spalte = 0; spalte < dim; spalte++)
{
zeile = index;
k = 0;
while (k < Zeil2(zeile).anz)
{ /* Alle Eintraege durchsuchen */
if (spalte == Ind2(zeile, k))
{ /* gefunden! */
inc = gewicht * Aik2(zeile, k); /* Mit dem Gewicht multiplizieren */
Aik2(zeile, k) = 0.; /* Eigenen Eintrag loeschen */
for (l = 0; l < anz_nachbarn; l++)
/* Den reg. Nachbarn zuschlagen */
MXInc(nachbarn_index[l], spalte, inc);
break;
}
else
k++;
} /* endwhile */
} /* endfor */
for (j = 0l; j < anz_nachbarn; j++)
/* Der rechte Seite-Eintrag wird den Nachbarn zugeschlagen */
rechts[nachbarn_index[j]] += gewicht * rechts[index];
/* endfor j */
/* Neuer Zeileneintrag fuer den irr. Knoten, dies ist
die Zwangsbedingung aus der Interpolation */
MXSet(index, index, diag);
for (k = 0; k < anz_nachbarn; k++)
/* i ist die Zeile des irregulaere Knoten, nachbarn_index die Spalte */
MXSet(index, nachbarn_index[k], -gewicht * diag);
rechts[index] = 0.;
}
break;
case 3:
case 4:
{
Modell34* w = (Modell34*) wurzel;
long i34, j34, k34;
int u;
/* Spalte des irr. Knotens eliminieren : */
/* Ueber alle Zeilen gehen, um nach Eintragen fuer den Knoten zu suchen */
for (j = 0l; j < dim; j++)
{
/* Der Knoteneintrag wird ausmultipliziert und den Nachbarn zugeschlagen */
inc = 0.;
if (j == index)
{
inc = gewicht * (w->Diag[j]); /* Diagonalelement */
w->Diag[j] = 0.;
}
else
{
/* Variablen setzen */
j34 = 0;
/* Untermatrixelement? */
if (j > index)
{
u = w->usym;
i34 = index;
k34 = j;
}
else
{
u = 0;
i34 = j;
k34 = index;
}
/* Alle Spalteneintraege durchsuchen */
while (j34 < Sp34(k34).anz && i34 >= Ind34(k34, j34))
{
if (i34 == Ind34(k34, j34))
{
inc = gewicht * Aik34(k34, j34, u);
/* Spalte des Knotens zu Null setzen, da der Wert mit "inc" verteilt wird */
Aik34(k34, j34, u) = 0.;
break;
}
j34++;
}
} /* endif */
if (fabs(inc) > 0.)
for (k = 0; k < anz_nachbarn; k++)
MXInc(j, nachbarn_index[k], inc);
} /* endfor j */
#ifdef DUMP
MXDumpGLS("b_spalte", 1, rechts, rechts);
#endif
/* Zeile des irr. Knotens eliminieren : */
/* Ueber Zeilen der regulaeren Nachbarn gehen */
/* Der Knoteneintrag wird ausmultipliziert und den Nachbarn zugeschlagen */
for (k = 0; k < dim; k++)
{
inc = 0.;
if (index == k)
{
inc = gewicht * (w->Diag[k]); /* Diagonalelement */
w->Diag[k] = 0.;
}
else
{
/* Variablen setzen */
j34 = 0;
/* Untermatrixelement */
if (index > k)
{
u = w->usym;
i34 = k;
k34 = index;
}
else
{
u = 0;
i34 = index;
k34 = k;
}
/* Alle Spalteneintraege durchsuchen */
while (j34 < Sp34(k34).anz && i34 >= Ind34(k34, j34))
{
if (i34 == Ind34(k34, j34))
{
inc = gewicht * Aik34(k34, j34, u);
/* Spalte des Knotens zu Null setzen, da der Wert mit "inc" verteilt wird */
Aik34(k34, j34, u) = 0.;
for (j = 0l; j < anz_nachbarn; j++)
MXInc(nachbarn_index[j], k, inc);
break;
}
j34++;
} /* endwhile */
} /* endif */
} /* endfor */
/* Der rechte Seite-Eintrag wird den Nachbarn zugeschlagen */
for (j = 0l; j < anz_nachbarn; j++)
rechts[nachbarn_index[j]] += gewicht * rechts[index];
/* endfor j */
#ifdef DUMP
MXDumpGLS("b_zeile", 1, rechts, rechts);
#endif
/* Neuer Zeileneintrag fuer den irr. Knoten, dies ist
die Zwangsbedingung aus der Interpolation */
MXSet(index, index, diag);
rechts[index] = 0.;
for (k = 0; k < anz_nachbarn; k++)
/* i ist die Zeile des irregulaere Knoten, nachbarn_index die Spalte */
MXSet(index, nachbarn_index[k], -gewicht * diag);
#ifdef DUMP
MXDumpGLS("b_zwang", 1, rechts, rechts);
#endif
break;
}
case 5:
{
Modell2* w = (Modell2*) wurzel;
/* Spalte des irr. Knotens eliminieren : */
/* Ueber alle Zeilen gehen, um nach Eintragen fuer den Knoten zu suchen */
for (zeile = 0l; zeile < dim; zeile++)
{
/* Der Knoteneintrag wird ausmultipliziert und den Nachbarn zugeschlagen */
/* index ist der irregulaere Knoten, nachbarn_index[] die Spalte */
spalte = index;
k = 0;
while (k < Zeil2(zeile).anz)
{ /* Alle Eintraege durchsuchen */
if (spalte == Ind2(zeile, k))
{ /* gefunden! */
inc = gewicht * Aik2(zeile, k); /* Mit dem Gewicht multiplizieren */
Aik2(zeile, k) = 0.; /* Eigenen Eintrag loeschen */
for (l = 0; l < anz_nachbarn; l++)
/* Den reg. Nachbarn zuschlagen */
MXInc(zeile, nachbarn_index[l], inc);
break;
}
else
k++;
}
} /* endfor j */
/* Zeile des irr. Knotens eliminieren : */
/* Ueber Zeilen der regulaeren Nachbarn gehen */
for (spalte = 0; spalte < dim; spalte++)
{
zeile = index;
k = 0;
while (k < Zeil2(zeile).anz)
{ /* Alle Eintraege durchsuchen */
if (spalte == Ind2(zeile, k))
{ /* gefunden! */
inc = gewicht * Aik2(zeile, k); /* Mit dem Gewicht multiplizieren */
Aik2(zeile, k) = 0.; /* Eigenen Eintrag loeschen */
for (l = 0; l < anz_nachbarn; l++)
/* Den reg. Nachbarn zuschlagen */
MXInc(nachbarn_index[l], spalte, inc);
break;
}
else
k++;
} /* endwhile */
} /* endfor */
for (j = 0l; j < anz_nachbarn; j++)
/* Der rechte Seite-Eintrag wird den Nachbarn zugeschlagen */
rechts[nachbarn_index[j]] += gewicht * rechts[index];
/* endfor j */
/* Neuer Zeileneintrag fuer den irr. Knoten, dies ist
die Zwangsbedingung aus der Interpolation */
MXSet(index, index, diag);
for (k = 0; k < anz_nachbarn; k++)
/* i ist die Zeile des irregulaere Knoten, nachbarn_index die Spalte */
MXSet(index, nachbarn_index[k], -gewicht * diag);
rechts[index] = 0.;
}
break;
case 6:
{
Modell2* w = (Modell2*) wurzel;
/* Spalte des irr. Knotens eliminieren : */
/* Ueber alle Zeilen gehen, um nach Eintragen fuer den Knoten zu suchen */
for (zeile = 0l; zeile < dim; zeile++)
{
/* Der Knoteneintrag wird ausmultipliziert und den Nachbarn zugeschlagen */
/* index ist der irregulaere Knoten, nachbarn_index[] die Spalte */
spalte = index;
k = 0;
while (k < Zeil2(zeile).anz)
{ /* Alle Eintraege durchsuchen */
if (spalte == Ind2(zeile, k))
{ /* gefunden! */
inc = gewicht * Aik2(zeile, k); /* Mit dem Gewicht multiplizieren */
Aik2(zeile, k) = 0.; /* Eigenen Eintrag loeschen */
for (l = 0; l < anz_nachbarn; l++)
/* Den reg. Nachbarn zuschlagen */
MXInc(zeile, nachbarn_index[l], inc);
break;
}
else
k++;
}
} /* endfor j */
/* Zeile des irr. Knotens eliminieren : */
/* Ueber Zeilen der regulaeren Nachbarn gehen */
for (spalte = 0; spalte < dim; spalte++)
{
zeile = index;
k = 0;
while (k < Zeil2(zeile).anz)
{ /* Alle Eintraege durchsuchen */
if (spalte == Ind2(zeile, k))
{ /* gefunden! */
inc = gewicht * Aik2(zeile, k); /* Mit dem Gewicht multiplizieren */
Aik2(zeile, k) = 0.; /* Eigenen Eintrag loeschen */
for (l = 0; l < anz_nachbarn; l++)
/* Den reg. Nachbarn zuschlagen */
MXInc(nachbarn_index[l], spalte, inc);
break;
}
else
k++;
} /* endwhile */
} /* endfor */
for (j = 0l; j < anz_nachbarn; j++)
/* Der rechte Seite-Eintrag wird den Nachbarn zugeschlagen */
rechts[nachbarn_index[j]] += gewicht * rechts[index];
/* endfor j */
/* Neuer Zeileneintrag fuer den irr. Knoten, dies ist
die Zwangsbedingung aus der Interpolation */
MXSet(index, index, diag);
for (k = 0; k < anz_nachbarn; k++)
/* i ist die Zeile des irregulaere Knoten, nachbarn_index die Spalte */
MXSet(index, nachbarn_index[k], -gewicht * diag);
rechts[index] = 0.;
}
break;
}
}
/*************************************************************************
ROCKFLOW - Funktion: M#Vorkond
Aufgabe:
Vorkonditionierer nach dem mit vorkond gewaehleten Verfahren.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E int aufgabe: 0:Start des Vork., (vor Loesen des GLS)
Matrix und b (bei Extraktion auch x) werden veraendert
1:Ende des Vork. (nach Loesen des GLS)
Ruecktransformation, nur x wird bearbeitet, free
(neu 3/2000) 2:Linkstransformation mit der genaeherten Inversen L:
x <-- L*b, x darf gleich b sein
(mehrfach innerhalb des Loesers aufrufbar)
3:Linkstransformation mit der genaeherten Inversen L(trans)
x <-- L(t)*b, x darf gleich b sein
(mehrfach innerhalb des Loesers aufrufbar)
Es ist L ~= A**(-1). Das GLS A*x =b wird transformiert zu
L*A *x ~= I*x = L*b
zu transformieren sind die Residuen r = L*(b-Ax) -> Aufgabe 2
oder bei quadriertem Problem r = A(t)*L(t)*L*(b-Ax) -> Aufgabe 3
E double *b : Vektor b
E double *x : Vektor x
Ergebnis: - void -
Programmaenderungen:
Modell 1: 11/1995 MSR Erste Version
3/2000 Ra Gauss-Precond. (direkte Loesung)
6/2000 C.Thorenz Hilfsvariable Diagonalenskalierung
Modell 2: 11/1995 MSR Erste Version
10/1999 C.Thorenz Zweite Version
6/2000 C.Thorenz Hilfsvariable Diagonalenskalierung
Modell 3,4: 2/2000 Ra 1. Version (nur Extraktion und ILU)
6/2000 C.Thorenz Diagonalenskalierung eingebaut (Nur Mod.4)
*** Definitionen fuer Preconditioner ************************************/
#define fastNull MKleinsteZahl
#define VK_Skalierung 1
#define VK_Extraktion 10
#define VK_iLDU 100
#define VK_Modus(vk) ((int)(vorkond % (vk * 10) / vk))
/* werden am Ende von matrix.c undefiniert
Hilfsfunktion Skalarprodukt a*b, (Elementabstand da in a, 1 in db) */
double H_M1skprod(double* a, long da, double* b, long n)
{
double s = 0.0;
register long j, i = 0;
for (j = 0; j < n; j++)
{
s += a[i] * b[j];
i += da;
}
return s;
}
/**** Modell 1 ************************************************************/
void M1Vorkond(int aufgabe, double* x, double* b)
{
Modell1* w = (Modell1*) wurzel;
register long i, k;
register double h;
static double* x0, * r0, * Gik = NULL;
#ifdef ERROR_CONTROL
if (b == NULL || x == NULL)
MX_Exit("M1Vorkond", 3);
#endif
switch (aufgabe)
{
case 0: /* Start des Vorkonditionierers */
if VK_Modus
(VK_Extraktion)
{ /* immer zuerst! */
x0 = (double*) Malloc(sizeof(double) * dim);
r0 = (double*) Malloc(sizeof(double) * dim);
MXResiduum(x, b, r0); /* Rechte Seite ex A*(Startloesung x) */
for (i = 0; i < dim; i++)
{
b[i] = r0[i];
x0[i] = x[i];
x[i] = 0.0;
}
r0 = (double*) Free(r0);
}
if VK_Modus
(VK_Skalierung)
{ /* Diagonal-Skalierung */
for (i = 0; i < dim; i++)
{
if(fabs(Aik1(i, i)) > DBL_MIN)
{
h = 1. / Aik1(i, i);
b[i] *= h;
for (k = 0; k < dim; k++)
Aik1(i, k) *= h;
}
else
{
DisplayMsg("!!! Equation system: Line: ");
DisplayLong(i);
DisplayMsg(" Value: ");
DisplayDouble(Aik1(i, i), 0, 0);
DisplayMsgLn(
"!!! Diagonal near zero! Disable diagonal preconditioner!");
exit(1);
}
}
}
break;
case 1: /* Ende des Vorkonditionierers */
if VK_Modus
(VK_iLDU) Gik = (double*) Free(Gik);
if VK_Modus
(VK_Extraktion)
{ /* immer zuletzt: Startloesung addieren */
for (i = 0; i < dim; i++)
x[i] += x0[i];
x0 = (double*) Free(x0);
}
break;
case 2: /* Linkstransformation des Gesamtsystems x <= L*b */
if VK_Modus
(VK_iLDU)
{ /* Gauss anstelle L(D)U-Zerlegung */
long ia, diag, ka = 0;
if (Gik == NULL)
{ /* Matrix kopieren (transponiert!) und zerlegen */
long ig = 0;
Gik = (double*) Malloc(dim * dim * sizeof(double));
for (k = 0; k < dim; k++)
{
ia = k;
for (i = 0; i < dim; i++)
{
Gik[ig++] = w->matrix[ia];
ia += dim;
}
}
for (k = 0; k < dim; k++)
{ /* alle Spalten/Zeilen */
diag = 0;
for (i = 0; i < k; i++)
{ /* Spalte ohne Okk */
Gik[ka + i] -= H_M1skprod(&Gik[i], dim, &Gik[ka], i);
Gik[ka + i] *= Gik[diag];
diag += dim + 1; /* /Uii (Kehrwert) */
} /* i */
ia = 0; /* Spaltenanfang Spalte i */
for (i = 0; i <= k; i++)
{ /* Zeile incl. Ukk */
Gik[ia + k] -= H_M1skprod(&Gik[k], dim, &Gik[ia], i);
ia += dim; /* Uik */
} /* i */
Gik[diag] = 1.0 / Gik[diag]; /* 1.0/Ukk */
ka += dim; /* naechste Spalte k */
}
} /* k - Matrix zerlegt */
/* Gleichungssystem aufloesen */
diag = 0;
for (i = 0; i < dim; i++)
{ /* vorwaerts einsetzen mit Uik */
x[i] = (b[i] - H_M1skprod(&Gik[i], dim, x, i)) * Gik[diag];
diag += dim + 1; /* naechstes Diagonalelement */
}
diag--; /* rechts neben letztem Diagonalelement */
for (i = dim; i > 0; i--)
{ /* rueckwaerts einsetzen mit Oik */
x[i - 1] -= H_M1skprod(&Gik[diag], dim, &x[i], dim - i);
diag -= dim + 1;
} /* i */
} /* Modus iLDU, (zerlegen und) aufloesen */
case 3: /* Linkstransformation des Gesamtsystems x <= L(t)*b */
if VK_Modus
(VK_iLDU)
{ /* Gauss anstelle L(D)U-Zerlegung */
long ia = 0, diag = dim * dim - 1;
/* Nur aufloesen, Matrix ist immer schon zerlegt! */
for (i = 0; i < dim; i++)
{ /* vorwaerts einsetzen mit Oik */
x[i] = b[i] - H_M1skprod(&Gik[ia], 1l, x, i);
ia += dim;
}
ia--; /* rechts neben letztem Diagonalelement */
for (i = dim; i > 0; i--)
{ /* rueckwaerts einsetzen mit Uik */
x[i - 1] -= H_M1skprod(&Gik[ia], 1l, &x[i], dim - i);
x[i - 1] *= Gik[diag];
diag -= dim + 1;
} /* i */
} /* Modus iLDU, aufloesen mit L(t) */
} /* aufgabe */
} /* M1Vorkond */
/**** Modell 2 ************************************************************/
void M2Vorkond(int aufgabe, double* x, double* b)
{
Modell2* w = (Modell2*) wurzel;
register long k;
register int i;
static double* x0, * r0, h;
#ifdef ERROR_CONTROL
if (b == NULL || x == NULL)
MX_Exit("M2Vorkond", 3);
#endif
//======================================================================
switch (aufgabe)
{
//--------------------------------------------------------------------
case 0: /* Start des Vorkonditionierers */
if VK_Modus
(VK_Extraktion)
{ /* immer zuerst! */
x0 = (double*) Malloc(sizeof(double) * dim);
r0 = (double*) Malloc(sizeof(double) * dim);
MXResiduum(x, b, r0); /* Rechte Seite ex A*(Startloesung x) */
for (i = 0; i < dim; i++)
{
b[i] = r0[i];
x0[i] = x[i];
x[i] = 0.0;
}
r0 = (double*) Free(r0);
}
if VK_Modus
(VK_Skalierung)
{ /* Diagonal-Skalierung */
for (k = 0; k < dim; k++)
{
if(fabs(Diag2(k)) > DBL_MIN)
{
h = 1. / Diag2(k);
b[k] *= h;
for (i = 0; i < Zeil2(k).anz; i++)
Aik2(k, i) *= h;
}
else
{
DisplayMsg("!!! Equation system: Line: ");
DisplayLong(k);
DisplayMsg(" Value: ");
DisplayDouble(Diag2(k), 0, 0);
DisplayMsgLn("");
DisplayMsgLn(
"!!! Diagonal near zero! Disable diagonal preconditioner!");
exit(1);
}
}
}
break;
//--------------------------------------------------------------------
case 1: /* Ende des Vorkonditionierers */
if VK_Modus
(VK_Extraktion)
{ /* immer zuletzt: Startloesung addieren */
for (i = 0; i < dim; i++)
x[i] += x0[i];
x0 = (double*) Free(x0);
}
break;
//--------------------------------------------------------------------
case 2:
if VK_Modus // JODNEW - fell into case 3
(VK_iLDU) /* incomplete L(D)U-Zerlegung geht nicht! */
DisplayMsgLn("Modell 2: kein ILU-Vorkonditionierer!");
break;
//--------------------------------------------------------------------
case 3: /* Linkstransformationen */
if VK_Modus
(VK_iLDU) /* incomplete L(D)U-Zerlegung geht nicht! */
DisplayMsgLn("Modell 2: kein ILU-Vorkonditionierer!");
break;
//--------------------------------------------------------------------
default:
DisplayMsgLn("Error in M2Vorkond()");
}
//======================================================================
}
/**** Modell 3,4 **********************************************************/
void M34Vorkond(int aufgabe, double* x, double* b)
{
Modell34* w = (Modell34*) wurzel;
long i, k, l;
register long zk;
register int ji, jk;
int j, u = w->usym, o = 0;
double Oik, Uki = 0.0, Dkk, r;
static double* x0, * r0, h;
#ifdef ERROR_CONTROL
if (b == NULL || x == NULL)
MX_Exit("M34Vorkond", 3);
#endif
switch (aufgabe)
{
case 0: /* Start des Vorkonditionierers - ILU! */
if (VK_Modus(VK_Extraktion)) /* immer zuerst! */
{
x0 = (double*) Malloc(sizeof(double) * dim);
r0 = (double*) Malloc(sizeof(double) * dim);
MXResiduum(x, b, r0); /* Rechte Seite ex A*(Startloesung x) */
for (i = 0; i < dim; i++)
{
b[i] = r0[i];
x0[i] = x[i];
x[i] = 0.0;
}
r0 = (double*) Free(r0);
}
if (VK_Modus (VK_Skalierung))
{
for (k = 0; k < dim; k++)
if(fabs(w->Diag[k]) > DBL_MIN)
{
h = 1. / w->Diag[k];
b[k] *= h;
for (l = 0; l < dim; l++)
M34Mul(k, l, h);
}
/*
else {
DisplayMsg("!!! Equation system: Line: ");
DisplayLong(k);
DisplayMsg(" Value: ");
DisplayDouble(w -> Diag[k], 0, 0);
DisplayMsgLn("");
DisplayMsgLn("!!! Diagonal near zero! Disable diagonal preconditioner!");
exit(1);
}*/
#ifdef geht_nicht
for (k = 0; k < dim; k++)
for (j = 0; j < Sp34(k).anz; j++)
{
i = Ind34(k, j);
Aik34(k, j, u) /= w->Diag[k]; /* Untermatrix */
Aik34(k, j, 0) /= w->Diag[i]; /* Obermatrix o=0! */
}
for (k = 0; k < dim; k++)
w->Diag[k] = 1.;
#endif
}
break;
case 1: /* Ende des Vorkonditionierers */
if (VK_Modus (VK_Extraktion)) /* immer zuletzt: Startloesung addieren */
{
for (i = 0; i < dim; i++)
x[i] += x0[i];
x0 = (double*) Free(x0);
}
break; /* Matrix fuer ILU-Zerlegung wird nicht freigegeben! */
case 3: /* Linkstransformation des Gesamtsystems x <= L(t)*b */
u = 0;
o = w->usym;
/* kein break! "Fall through" nach Aufgabe 2 */
case 2: /* Linkstransformation x <= L*b */
if (VK_Modus (VK_iLDU)) /* incomplete L(D)U-Zerlegung */
{
if (w->stat < 2) /* Matrix ist noch nicht zerlegt */
{
for (k = 0; k < dim; k++) /* Spalten reduzieren */
{
for (j = 0; j < Sp34(k).anz; j++)
{
Oik = Aik34(k, j, o);
if (u)
Uki = Aik34(k, j, u);
i = Ind34(k, j);
/* Skalarprodukte abziehen */
jk = 0;
zk = Ind34(k, jk); /* oberstes Element Spalte k */
for (ji = 0; ji < Sp34(i).anz; ji++)
{
while (Ind34(i, ji) > zk)
zk = Ind34(k, ++jk); /* zk existiert! */
if (zk == Ind34(i, ji))
{
Oik -= Bik34(i, ji, u) * Bik34(k,
jk,
o);
if (u)
Uki -=
Bik34(i, ji,
o) * Bik34(k,
jk,
u);
}
} /* Ende ji Skalarprodukt */
Bik34(k, j, o) = Oik;
if (u)
Bik34(k, j, u) = Uki;
} /* j, Spaltenelemente staffeln */
/* Diagonale extrahieren mit Sk.prod. fuer Diagonalelement */
Dkk = w->Diag[k];
for (jk = 0; jk < Sp34(k).anz; jk++)
{
Oik = Bik34(k, jk, o);
zk = Ind34(k, jk);
Bik34(k, jk, o) *= w->PreD[zk];
if (u)
Bik34(k, jk, u) *= w->PreD[zk];
Dkk -= Bik34(k, jk, u) * Oik;
}
if (fabs(Dkk) < fastNull)
/*sign */
Dkk = (Dkk < 0.0) ? -fastNull : fastNull;
w->PreD[k] = 1.0 / Dkk; /* Kehrwert speichern */
}
w->stat = 2; /* merken! */
} /* Ende der Zerlegung */
/* genaeherte Loesung von A*x = b. Ergebnis: x */
for (k = 0; k < dim; k++) /* vorwaerts einsetzen mit Untermatrix */
{
r = b[k];
for (j = 0; j < Sp34(k).anz; j++)
r -= Bik34(k, j, u) * x[Ind34(k, j)];
x[k] = r;
}
for (k = 0; k < dim; k++)
x[k] *= w->PreD[k]; /* Diagonal-Normierung */
for (k = dim - 1; k > 0; k--) /* rueckwaerts einsetzen mit Obermatrix */
{
r = x[k];
for (j = 0; j < Sp34(k).anz; j++)
x[Ind34(k, j)] -= Bik34(k, j, o) * r;
}
} /* Ende ILU-Vorkonditionierer */
} /* switch aufgabe */
} /*M34Precond */
/**** Modell 5 ************************************************************/
// WW/PA 16/02/2006
void M5Vorkond(int aufgabe, double* x, double* b)
{
Modell2* w = (Modell2*) wurzel;
register long k;
register int i;
static double* x0, * r0, h;
long ii; //, count1;
double v_diag = 0.0;
#ifdef ERROR_CONTROL
if (b == NULL || x == NULL)
MX_Exit("M2Vorkond", 3);
#endif
//======================================================================
switch (aufgabe)
{
//--------------------------------------------------------------------
case 0: /* Start des Vorkonditionierers */
if VK_Modus
(VK_Extraktion)
{ /* immer zuerst! */
x0 = (double*) Malloc(sizeof(double) * dim);
r0 = (double*) Malloc(sizeof(double) * dim);
MXResiduum(x, b, r0); /* Rechte Seite ex A*(Startloesung x) */
for (i = 0; i < dim; i++)
{
b[i] = r0[i];
x0[i] = x[i];
x[i] = 0.0;
}
r0 = (double*) Free(r0);
}
if VK_Modus
(VK_Skalierung)
{
for (k = 0; k < Dim_L; k++)
{
v_diag = jdiag[diag5_i[k]];
if(fabs(v_diag) > DBL_MIN)
{
h = 1. / v_diag;
b[k] *= h;
}
else
{
DisplayMsg("!!! Equation system: Line: ");
DisplayLong(k);
DisplayMsg(" Value: ");
DisplayDouble(Diag2(k), 0, 0);
DisplayMsgLn("");
DisplayMsgLn(
"!!! Diagonal near zero! Disable diagonal preconditioner!");
exit(1);
}
}
// For test, must be improved
double val;
for (k = 0; k < Dim_L; k++)
{
v_diag = MXGet(k,k);
for (ii = 0; ii < Dim_L; ii++)
{
val = MXGet(k,ii);
val /= v_diag;
MXSet(k,ii,val);
}
}
/*
long count1 = 0;
for (k = 0; k < jd_ptr_max; k++)
{
for (i = 0; i < jd_ptr[k]; i++)
{
// Row of equation system
ii = jd_ptr2[i];
v_diag = jdiag[diag5_i[ii]];
if(fabs(v_diag) > DBL_MIN)
jdiag[count1] /= v_diag; //
count1++;
}
}
*/
/////////////////////////////////////////////////
/*
// Diagonal-Skalierung
for (k = 0; k < dim; k++)
{
if(fabs(Diag2(k)) > DBL_MIN) {
h = 1. / Diag2(k);
b[k] *= h;
for (i = 0; i < Zeil2(k).anz; i++)
Aik2(k, i) *= h;
} else {
DisplayMsg("!!! Equation system: Line: ");
DisplayLong(k);
DisplayMsg(" Value: ");
DisplayDouble(Diag2(k), 0, 0);
DisplayMsgLn("");
DisplayMsgLn("!!! Diagonal near zero! Disable diagonal preconditioner!");
exit(1);
}
}
*/
}
break;
//--------------------------------------------------------------------
case 1: /* Ende des Vorkonditionierers */
if VK_Modus
(VK_Extraktion)
{ /* immer zuletzt: Startloesung addieren */
for (i = 0; i < dim; i++)
x[i] += x0[i];
x0 = (double*) Free(x0);
}
break;
//--------------------------------------------------------------------
case 2:
//--------------------------------------------------------------------
case 3: /* Linkstransformationen */
if VK_Modus
(VK_iLDU) /* incomplete L(D)U-Zerlegung geht nicht! */
DisplayMsgLn("Modell 2: kein ILU-Vorkonditionierer!");
//--------------------------------------------------------------------
}
//======================================================================
}
/*************************************************************************
ROCKFLOW - Funktion: MXDumpGLS
Aufgabe:
Erzeugt einen Dump des Gleichungssystems
Die Matrix muss mit MXSetMatrixPointer aktiviert worden sein.
Der Vektor muss die zugehoerige Laenge (dim) haben, die von MXGetDim
geliefert wird.
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E char name : Filename fuer die Ausgabedatei
E int modus : modus=0 : Komplettes GLS wird ausgegebeen
: modus=1 : Eine Map der ungleich-Null Werte wird erzeugt
: modus=2 : Komplette Matrix wird ausgegebeen
: modus=3 : Eine Map der ungleich-Null Werte der Matrix wird erzeugt
E double *rechts : rechte Seite des GLS
E double *ergebnis: Ergebnis des GLS
Ergebnis:
- void -
Programmaenderungen:
3/1998 C. Thorenz Erste Version
5/1998 C. Thorenz Verallgemeinert
09/2002 OK besser > 0 als > MKleinsteZahl
*** benutzt keine modellspezifischen Dinge ******************************/
void MXDumpGLS(const char* name, int modus, double* rechts, double* ergebnis)
{
register long i, j;
long NonZeroMatrix = 0, NonZeroRHS = 0;
FILE* dumpfile;
dumpfile = fopen(name, "w");
if (dumpfile == NULL)
return;
for (i = 0; i < dim; i++)
{ /* Nicht-Null-Elemente zaehlen */
for (j = 0; j < dim; j++) /* !quadratisches Problem! (Ra) */
if (fabs(MXGet(i, j)) > MKleinsteZahl)
NonZeroMatrix++;
if (fabs(rechts[i]) > MKleinsteZahl)
NonZeroRHS++;
}
if (modus == 0)
{ /* Map des gesamten GLS */
FilePrintString(dumpfile, "Variables=i,j,X\nZone, i=");
FilePrintLong(dumpfile, dim * (dim + 2));
FilePrintString(dumpfile, ", f=point\n");
for (i = 0; i < dim; i++)
{
for (j = 0; j < dim; j++)
FilePrintDouble(dumpfile, MXGet(i, j));
FilePrintDouble(dumpfile, rechts[i]);
FilePrintDouble(dumpfile, ergebnis[i]);
FilePrintString(dumpfile, "\n");
}
}
if (modus == 1)
{ /* Map der ungleich-null Werte des GLS */
FilePrintString(dumpfile, "Variables=i,j,X\n");
for (i = 0; i < dim; i++)
{
for (j = 0; j < dim; j++)
if (fabs(MXGet(i, j)) > 0.0)
{
FilePrintDouble(dumpfile, (double) i);
FilePrintDouble(dumpfile, (double) j);
FilePrintDouble(dumpfile, MXGet(i, j));
FilePrintString(dumpfile, "\n");
}
/*
if (fabs(rechts[i]) > 0.0)
{
FilePrintDouble(dumpfile, (double) i);
FilePrintDouble(dumpfile, (double) (dim + 1));
FilePrintDouble(dumpfile, rechts[i]);
FilePrintString(dumpfile, "\n");
}
*/
if (ergebnis)
if (fabs(ergebnis[i]) > MKleinsteZahl)
{
FilePrintDouble(dumpfile, (double) i);
FilePrintDouble(dumpfile, (double) (dim + 2));
FilePrintDouble(dumpfile, ergebnis[i]);
FilePrintString(dumpfile, "\n");
}
}
//TEST WW
FilePrintString(dumpfile, "RHS\n");
for (i = 0; i < dim; i++)
{
FilePrintDouble(dumpfile, (double) i);
FilePrintDouble(dumpfile, rechts[i]);
FilePrintString(dumpfile, "\n");
}
}
if (modus == 2)
{
FilePrintString(dumpfile, "Variables=i,j,X\nZone, i=");
FilePrintLong(dumpfile, dim * dim);
FilePrintString(dumpfile, ", f=point\n");
for (i = 0; i < dim; i++)
{
for (j = 0; j < dim; j++)
FilePrintDouble(dumpfile, MXGet(i, j));
FilePrintString(dumpfile, "\n");
}
}
if (modus == 3)
{
FilePrintString(dumpfile, "Variables=i,j,X\n");
for (i = 0; i < dim; i++)
{
for (j = 0; j < dim; j++)
if (fabs(MXGet(i, j)) > MKleinsteZahl)
{
FilePrintDouble(dumpfile, (double) i);
FilePrintDouble(dumpfile, (double) j);
FilePrintDouble(dumpfile, MXGet(i, j));
FilePrintString(dumpfile, "\n");
}
}
}
fclose(dumpfile);
}
/*************************************************************************
ROCKFLOW - Funktion: MXEstimateStartVector
Aufgabe:
Versucht, eine gute Startloesung fuer das GLS zu finden
Modell 1 und 2: mit Zeilen-Masslumping (Thorenz)
Modell 3 und 4: ueber Preconditioner (Ratke)
Die Matrix muss mit MXSetMatrixPointer aktiviert worden sein und
die Vektoren muessen die zugehoerige Laenge (dim) haben!
Formalparameter: (E: Eingabe; R: Rueckgabe; X: Beides)
E double *ReSei : Rechte Seite des GLS
E double *x0 : Ermittelter Startvektor
Ergebnis:
- void -
Programmaenderungen:
3/1998 C. Thorenz Erste Version
10/1998 C. Thorenz Erste Version
3/2000 R. Ratke Benutzung von MXMatVek (modellunabhaeng,
vermeidet quadratischen Aufwand!)
*************************************************************************/
void MXEstimateStartVector(double* ReSei, double* x0)
{
register long i;
if (VK_Modus(VK_iLDU) && matrix_type != 2)
MXVorkond(2, x0, ReSei); /* Startvektor aus ILU-Zerlegung */
else
{ /* Startvektor aus Zeilen-Lumping */
double* sum = (double*) Malloc(dim * sizeof(double));
for (i = 0; i < dim; i++)
x0[i] = 1.0;
MXMatVek(x0, sum); /* sum: Zeilensummen von A */
for (i = 0; i < dim; i++)
x0[i] = ReSei[i] / sum[i];
sum = (double*) Free(sum);
}
}
/* lokale Makros entfernen ******************************* */
#undef dim
#undef matrix_type
#undef Maxim
#undef Minim
/* Modell 1: */
#undef Matrix1
#undef Aik1
/* Modell 2: */
#undef Zeil2
#undef Aik2
#undef Ind2
#undef Diag2
/* Modelle 3,4: */
#undef Sp34
#undef Aik34
#undef Bik34
#undef Ind34
/* Makros fuer Preconditioner entfernen */
#undef fastNull
#undef VK_Skalierung
#undef VK_Extraktion
#undef VK_iLDU
#undef VK_Modus
/* Ende Matrix.c */
| 27.6249 | 110 | 0.532686 | wolf-pf |
78d4bb421c4506f17470f2f108d78780658c24a6 | 4,577 | cpp | C++ | PostGL/GLMirrorPlane.cpp | febiosoftware/FEBioStudio | 324d76b069a60e99328500b9b25eb79cf5a019e8 | [
"MIT"
] | 27 | 2020-06-25T06:34:52.000Z | 2022-03-11T08:58:57.000Z | PostGL/GLMirrorPlane.cpp | febiosoftware/FEBioStudio | 324d76b069a60e99328500b9b25eb79cf5a019e8 | [
"MIT"
] | 42 | 2020-06-15T18:40:57.000Z | 2022-03-24T05:38:54.000Z | PostGL/GLMirrorPlane.cpp | febiosoftware/FEBioStudio | 324d76b069a60e99328500b9b25eb79cf5a019e8 | [
"MIT"
] | 12 | 2020-06-27T13:58:57.000Z | 2022-03-24T05:39:10.000Z | /*This file is part of the FEBio Studio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio-Studio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 "stdafx.h"
#include "GLMirrorPlane.h"
#include "GLModel.h"
using namespace Post;
CGLMirrorPlane::CGLMirrorPlane(CGLModel* fem) : CGLPlot(fem)
{
static int n = 1;
m_id = n;
char szname[128] = { 0 };
sprintf(szname, "MirrorPlane.%02d", n++);
SetName(szname);
AddIntParam(0, "Mirror Plane")->SetEnumNames("X\0Y\0Z\0");
AddBoolParam(true, "Show plane");
AddDoubleParam(0.25, "Transparency")->SetFloatRange(0.0, 1.0);
AddDoubleParam(0.f, "Offset");
m_plane = 0;
m_showPlane = true;
m_transparency = 0.25f;
m_offset = 0.f;
UpdateData(false);
}
bool CGLMirrorPlane::UpdateData(bool bsave)
{
if (bsave)
{
m_plane = GetIntValue(PLANE);
m_showPlane = GetBoolValue(SHOW_PLANE);
m_transparency = GetFloatValue(TRANSPARENCY);
m_offset = GetFloatValue(OFFSET);
}
else
{
SetIntValue(PLANE, m_plane);
SetBoolValue(SHOW_PLANE, m_showPlane);
SetFloatValue(TRANSPARENCY, m_transparency);
SetFloatValue(OFFSET, m_offset);
}
return false;
}
int CGLMirrorPlane::m_render_id = -1;
void CGLMirrorPlane::Render(CGLContext& rc)
{
// need to make sure we are not calling this recursively
if ((m_render_id != -1) && (m_id >= m_render_id)) return;
// plane normal
vec3f scl;
switch (m_plane)
{
case 0: m_norm = vec3f(1.f, 0.f, 0.f); scl = vec3f(-1.f, 1.f, 1.f); break;
case 1: m_norm = vec3f(0.f, 1.f, 0.f); scl = vec3f(1.f, -1.f, 1.f); break;
case 2: m_norm = vec3f(0.f, 0.f, 1.f); scl = vec3f(1.f, 1.f, -1.f); break;
}
// render the flipped model
CGLModel* m = GetModel();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(-m_offset*m_norm.x, -m_offset*m_norm.y, -m_offset*m_norm.z);
glScalef(scl.x, scl.y, scl.z);
int old_id = m_render_id;
m_render_id = m_id;
int frontFace;
glGetIntegerv(GL_FRONT_FACE, &frontFace);
glFrontFace(frontFace == GL_CW ? GL_CCW : GL_CW);
m->Render(rc);
glFrontFace(frontFace == GL_CW ? GL_CW : GL_CCW);
m_render_id = old_id;
glPopMatrix();
// render the plane
if (m_showPlane) RenderPlane();
}
//-----------------------------------------------------------------------------
void CGLMirrorPlane::RenderPlane()
{
CGLModel* mdl = GetModel();
BOX box = mdl->GetFEModel()->GetBoundingBox();
// plane center
vec3d rc = box.Center();
switch (m_plane)
{
case 0: rc.x = 0.f; break;
case 1: rc.y = 0.f; break;
case 2: rc.z = 0.f; break;
}
glPushMatrix();
glTranslatef(rc.x, rc.y, rc.z);
glTranslatef(-0.5f*m_offset*m_norm.x, -0.5f*m_offset*m_norm.y, -0.5f*m_offset*m_norm.z);
quatd q = quatd(vec3d(0, 0, 1), m_norm);
float w = q.GetAngle();
if (w != 0)
{
vec3d v = q.GetVector();
glRotated(w * 180 / PI, v.x, v.y, v.z);
}
float R = box.Radius();
// store attributes
glPushAttrib(GL_ENABLE_BIT);
GLdouble r = fabs(m_norm.x);
GLdouble g = fabs(m_norm.y);
GLdouble b = fabs(m_norm.z);
glColor4d(r, g, b, m_transparency);
glDepthMask(false);
glNormal3f(0, 0, 1);
glBegin(GL_QUADS);
{
glVertex3f(-R, -R, 0);
glVertex3f(R, -R, 0);
glVertex3f(R, R, 0);
glVertex3f(-R, R, 0);
}
glEnd();
glDepthMask(true);
glColor3ub(255, 255, 0);
glDisable(GL_LIGHTING);
glBegin(GL_LINE_LOOP);
{
glVertex3f(-R, -R, 0);
glVertex3f(R, -R, 0);
glVertex3f(R, R, 0);
glVertex3f(-R, R, 0);
}
glEnd();
glPopMatrix();
// restore attributes
glPopAttrib();
}
| 25.569832 | 89 | 0.689753 | febiosoftware |
78da793829745e9cc332fcf7b12077de0c6ae62a | 2,202 | cpp | C++ | 10706 Number Sequence.cpp | zihadboss/UVA-Solutions | 020fdcb09da79dc0a0411b04026ce3617c09cd27 | [
"Apache-2.0"
] | 86 | 2016-01-20T11:36:50.000Z | 2022-03-06T19:43:14.000Z | 10706 Number Sequence.cpp | Mehedishihab/UVA-Solutions | 474fe3d9d9ba574b97fd40ca5abb22ada95654a1 | [
"Apache-2.0"
] | null | null | null | 10706 Number Sequence.cpp | Mehedishihab/UVA-Solutions | 474fe3d9d9ba574b97fd40ca5abb22ada95654a1 | [
"Apache-2.0"
] | 113 | 2015-12-04T06:40:57.000Z | 2022-02-11T02:14:28.000Z | #include <iostream>
#include <algorithm>
using namespace std;
typedef unsigned long long ull;
// Exclusive
const int MaxIndex = 31268;
// To search:
// Binary search on lengthBefore, to cut out most
// Then binary search on lengthOf for rest. Can use the digit in that equal to the diff of rest and lengthOf[i]
// The number added is the index to access
// the lengthOf[i] is the length of i added to lengthOf[i - 1]
int lengthBefore[MaxIndex + 5];
int lengthOf[MaxIndex + 5];
int getNumDigits(ull currentHighest)
{
int numDigits = 0;
while (currentHighest)
{
++numDigits;
currentHighest /= 10;
}
return numDigits;
}
void GenerateData()
{
int i = 1, totalLength = 0, currentLength = 1;
while (i < MaxIndex)
{
totalLength += currentLength;
lengthBefore[i] = totalLength;
lengthOf[i] = currentLength;
++i;
currentLength += getNumDigits(i);
}
}
int GetNumber(int position)
{
// Want lower, because will decrease index by 1 so it doesn't exactly match
int * nextOne = lower_bound(lengthBefore, lengthBefore + MaxIndex, position);
position -= *(nextOne - 1);
// Now, find the addition number that it is part of:
// Want lower, because need to use the first one that is at least as long as it.
// This ensures that it is part of i, where i is lengthOf[i] found by the lower_bound
int * numberLengthOf = lower_bound(lengthOf, lengthOf + MaxIndex, position);
// This is the index, which is also the actual value of it
int numberPartOf = numberLengthOf - lengthOf;
int totalDigits = getNumDigits(numberPartOf);
// How far past the previous entry it is
int positionInNumberFromFront = position - *(numberLengthOf - 1);
int digitsToRemove = totalDigits - positionInNumberFromFront;
while (digitsToRemove)
{
numberPartOf /= 10;
--digitsToRemove;
}
return numberPartOf % 10;
}
int main()
{
GenerateData();
int T;
cin >> T;
while (T--)
{
int pos;
cin >> pos;
cout << GetNumber(pos) << '\n';
}
} | 24.197802 | 115 | 0.624886 | zihadboss |
78db32c42f63de3902fd14c8d2a8c5a72ae65bee | 6,443 | cpp | C++ | rocsolver/clients/gtest/getf2_getrf_strided_batched_gtest.cpp | leekillough/rocSOLVER | a0fa2af65be983dcec60081ed618b0642867aef0 | [
"BSD-2-Clause"
] | null | null | null | rocsolver/clients/gtest/getf2_getrf_strided_batched_gtest.cpp | leekillough/rocSOLVER | a0fa2af65be983dcec60081ed618b0642867aef0 | [
"BSD-2-Clause"
] | null | null | null | rocsolver/clients/gtest/getf2_getrf_strided_batched_gtest.cpp | leekillough/rocSOLVER | a0fa2af65be983dcec60081ed618b0642867aef0 | [
"BSD-2-Clause"
] | null | null | null | /* ************************************************************************
* Copyright 2018 Advanced Micro Devices, Inc.
*
* ************************************************************************ */
#include "testing_getf2_getrf_strided_batched.hpp"
#include "utility.h"
#include <gtest/gtest.h>
#include <math.h>
#include <stdexcept>
#include <vector>
using ::testing::Combine;
using ::testing::TestWithParam;
using ::testing::Values;
using ::testing::ValuesIn;
using namespace std;
typedef std::tuple<vector<int>, vector<int>> getf2_getrf_tuple;
// **** ONLY TESTING NORMNAL USE CASES
// I.E. WHEN STRIDEA >= LDA*N AND STRIDEP >= MIN(M,N) ****
// vector of vector, each vector is a {M, lda, stA};
// if stA == 0: strideA is lda*N
// if stA == 1: strideA > lda*N
const vector<vector<int>> matrix_size_range = {
{0, 1, 0}, {-1, 1, 0}, {20, 5, 0}, {50, 50, 1}, {70, 100, 0}
};
// each is a {N, stP}
// if stP == 0: stridep is min(M,N)
// if stP == 1: stridep > min(M,N)
const vector<vector<int>> n_size_range = {
{-1, 0}, {0, 0}, {20, 0}, {40, 1}, {100, 0}
};
const vector<vector<int>> large_matrix_size_range = {
{192, 192, 1}, {640, 640, 0}, {1000, 1024, 0},
};
const vector<vector<int>> large_n_size_range = {
{45, 1}, {64, 0}, {520, 0}, {1000, 0}, {1024, 0},
};
Arguments setup_arguments(getf2_getrf_tuple tup)
{
vector<int> matrix_size = std::get<0>(tup);
vector<int> n_size = std::get<1>(tup);
Arguments arg;
arg.M = matrix_size[0];
arg.N = n_size[0];
arg.lda = matrix_size[1];
arg.bsp = min(arg.M, arg.N) + n_size[1];
arg.bsa = arg.lda * arg.N + matrix_size[2];
arg.timing = 0;
arg.batch_count = 3;
return arg;
}
class LUfact_sb : public ::TestWithParam<getf2_getrf_tuple> {
protected:
LUfact_sb() {}
virtual ~LUfact_sb() {}
virtual void SetUp() {}
virtual void TearDown() {}
};
TEST_P(LUfact_sb, getf2_strided_batched_float) {
Arguments arg = setup_arguments(GetParam());
rocblas_status status = testing_getf2_getrf_strided_batched<float,float,0>(arg);
// if not success, then the input argument is problematic, so detect the error
// message
if (status != rocblas_status_success) {
if (arg.M < 0 || arg.N < 0 || arg.lda < arg.M) {
EXPECT_EQ(rocblas_status_invalid_size, status);
} else {
cerr << "unknown error...";
EXPECT_EQ(1000, status);
}
}
}
TEST_P(LUfact_sb, getf2_strided_batched_float_complex) {
Arguments arg = setup_arguments(GetParam());
rocblas_status status = testing_getf2_getrf_strided_batched<rocblas_float_complex,float,0>(arg);
// if not success, then the input argument is problematic, so detect the error
// message
if (status != rocblas_status_success) {
if (arg.M < 0 || arg.N < 0 || arg.lda < arg.M) {
EXPECT_EQ(rocblas_status_invalid_size, status);
} else {
cerr << "unknown error...";
EXPECT_EQ(1000, status);
}
}
}
TEST_P(LUfact_sb, getf2_strided_batched_double) {
Arguments arg = setup_arguments(GetParam());
rocblas_status status = testing_getf2_getrf_strided_batched<double,double,0>(arg);
// if not success, then the input argument is problematic, so detect the error
// message
if (status != rocblas_status_success) {
if (arg.M < 0 || arg.N < 0 || arg.lda < arg.M) {
EXPECT_EQ(rocblas_status_invalid_size, status);
} else {
cerr << "unknown error...";
EXPECT_EQ(1000, status);
}
}
}
TEST_P(LUfact_sb, getf2_strided_batched_double_complex) {
Arguments arg = setup_arguments(GetParam());
rocblas_status status = testing_getf2_getrf_strided_batched<rocblas_double_complex,double,0>(arg);
// if not success, then the input argument is problematic, so detect the error
// message
if (status != rocblas_status_success) {
if (arg.M < 0 || arg.N < 0 || arg.lda < arg.M) {
EXPECT_EQ(rocblas_status_invalid_size, status);
} else {
cerr << "unknown error...";
EXPECT_EQ(1000, status);
}
}
}
TEST_P(LUfact_sb, getrf_strided_batched_float) {
Arguments arg = setup_arguments(GetParam());
rocblas_status status = testing_getf2_getrf_strided_batched<float,float,1>(arg);
// if not success, then the input argument is problematic, so detect the error
// message
if (status != rocblas_status_success) {
if (arg.M < 0 || arg.N < 0 || arg.lda < arg.M) {
EXPECT_EQ(rocblas_status_invalid_size, status);
} else {
cerr << "unknown error...";
EXPECT_EQ(1000, status);
}
}
}
TEST_P(LUfact_sb, getrf_strided_batched_float_complex) {
Arguments arg = setup_arguments(GetParam());
rocblas_status status = testing_getf2_getrf_strided_batched<rocblas_float_complex,float,1>(arg);
// if not success, then the input argument is problematic, so detect the error
// message
if (status != rocblas_status_success) {
if (arg.M < 0 || arg.N < 0 || arg.lda < arg.M) {
EXPECT_EQ(rocblas_status_invalid_size, status);
} else {
cerr << "unknown error...";
EXPECT_EQ(1000, status);
}
}
}
TEST_P(LUfact_sb, getrf_strided_batched_double) {
Arguments arg = setup_arguments(GetParam());
rocblas_status status = testing_getf2_getrf_strided_batched<double,double,1>(arg);
// if not success, then the input argument is problematic, so detect the error
// message
if (status != rocblas_status_success) {
if (arg.M < 0 || arg.N < 0 || arg.lda < arg.M) {
EXPECT_EQ(rocblas_status_invalid_size, status);
} else {
cerr << "unknown error...";
EXPECT_EQ(1000, status);
}
}
}
TEST_P(LUfact_sb, getrf_strided_batched_double_complex) {
Arguments arg = setup_arguments(GetParam());
rocblas_status status = testing_getf2_getrf_strided_batched<rocblas_double_complex,double,1>(arg);
// if not success, then the input argument is problematic, so detect the error
// message
if (status != rocblas_status_success) {
if (arg.M < 0 || arg.N < 0 || arg.lda < arg.M) {
EXPECT_EQ(rocblas_status_invalid_size, status);
} else {
cerr << "unknown error...";
EXPECT_EQ(1000, status);
}
}
}
INSTANTIATE_TEST_CASE_P(daily_lapack, LUfact_sb,
Combine(ValuesIn(large_matrix_size_range),
ValuesIn(large_n_size_range)));
INSTANTIATE_TEST_CASE_P(checkin_lapack, LUfact_sb,
Combine(ValuesIn(matrix_size_range),
ValuesIn(n_size_range)));
| 29.555046 | 100 | 0.645662 | leekillough |
78dc2e5d5bdfb6c1657aea6520d41f35c59f5c93 | 926 | cpp | C++ | Data Structures/Dynamic Programming/2-D DP/Grid Unique Paths/Tabulation.cpp | ravikjha7/Competitive_Programming | 86df773c258d6675bb3244030e6d71aa32e01fce | [
"MIT"
] | null | null | null | Data Structures/Dynamic Programming/2-D DP/Grid Unique Paths/Tabulation.cpp | ravikjha7/Competitive_Programming | 86df773c258d6675bb3244030e6d71aa32e01fce | [
"MIT"
] | null | null | null | Data Structures/Dynamic Programming/2-D DP/Grid Unique Paths/Tabulation.cpp | ravikjha7/Competitive_Programming | 86df773c258d6675bb3244030e6d71aa32e01fce | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define mod 1000000007
void file()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
// Time Complexity : O(n*m)
// Space Complexity : O(n*m)
int GridUniquePaths(int n,int m) {
vector<vector<int>> dp(n,vector<int>(m,-1));
// Initialising First Row With 1
for(int i = 0; i < n; i++) dp[i][0] = 1;
// Initialising First Column With 1
for(int i = 0; i < m; i++) dp[0][i] = 1;
for(int i = 1; i < n; i++)
{
for(int j = 1; j < m; j++)
{
// up -> dp[i-1][j]
// left -> dp[i][j-1]
dp[i][j] = dp[i][j-1] + dp[i-1][j];
}
}
return dp[n-1][m-1];
}
void solve()
{
int n,m;
cin >> n >> m;
cout << GridUniquePaths(n,m) << endl;
}
int main()
{
file();
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t = 1;
// cin >> t;
while(t--)
{
solve();
}
return 0;
} | 15.965517 | 45 | 0.546436 | ravikjha7 |
78df233c5cfa07cff79df6c7dcc968a9637f8964 | 458 | cpp | C++ | ch15/ex15.42_c/orquery.cpp | shawabhishek/Cpp-Primer | c93143965e62c7ab833f43586ab1c759a5707cfc | [
"CC0-1.0"
] | 7,897 | 2015-01-02T04:35:38.000Z | 2022-03-31T08:32:50.000Z | ch15/ex15.42_c/orquery.cpp | shawabhishek/Cpp-Primer | c93143965e62c7ab833f43586ab1c759a5707cfc | [
"CC0-1.0"
] | 456 | 2015-01-01T15:47:52.000Z | 2022-02-07T04:17:56.000Z | ch15/ex15.42_c/orquery.cpp | shawabhishek/Cpp-Primer | c93143965e62c7ab833f43586ab1c759a5707cfc | [
"CC0-1.0"
] | 3,887 | 2015-01-01T13:23:23.000Z | 2022-03-31T15:05:21.000Z | #include "orquery.h"
#include <memory>
using std::make_shared;
#include <set>
using std::set;
#include "queryresult.h"
#include "textquery.h"
#include "query.h"
QueryResult
OrQuery::eval(const TextQuery &text) const
{
auto right = rhs.eval(text);
auto left = lhs.eval(text);
auto ret_lines = make_shared<set<line_no>>(left.begin(), left.end());
ret_lines->insert(right.begin(), right.end());
return QueryResult(rep(), ret_lines, left.get_file());
}
| 20.818182 | 70 | 0.709607 | shawabhishek |
78e6e054e08096cdb0bfb80316711ee02f3db9b2 | 3,350 | cpp | C++ | test/resource/erfwriter.cpp | seedhartha/revan | b9a98007ca2f510b42894ecd09fb623571b433dc | [
"MIT"
] | 37 | 2020-06-27T18:50:48.000Z | 2020-08-02T14:13:51.000Z | test/resource/erfwriter.cpp | seedhartha/revan | b9a98007ca2f510b42894ecd09fb623571b433dc | [
"MIT"
] | null | null | null | test/resource/erfwriter.cpp | seedhartha/revan | b9a98007ca2f510b42894ecd09fb623571b433dc | [
"MIT"
] | 1 | 2020-07-14T13:32:15.000Z | 2020-07-14T13:32:15.000Z | /*
* Copyright (c) 2020-2022 The reone project contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <boost/test/unit_test.hpp>
#include "../../src/common/stream/bytearrayoutput.h"
#include "../../src/common/stringbuilder.h"
#include "../../src/resource/format/erfwriter.h"
#include "../checkutil.h"
using namespace std;
using namespace reone;
using namespace reone::resource;
BOOST_AUTO_TEST_SUITE(erf_writer)
BOOST_AUTO_TEST_CASE(should_write_erf) {
// given
auto expectedOutput = StringBuilder()
// header
.append("ERF V1.0")
.append("\x00\x00\x00\x00", 4) // number of languages
.append("\x00\x00\x00\x00", 4) // size of localized strings
.append("\x01\x00\x00\x00", 4) // number of entries
.append("\xa0\x00\x00\x00", 4) // offset to localized strings
.append("\xa0\x00\x00\x00", 4) // offset to key list
.append("\xb8\x00\x00\x00", 4) // offset to resource list
.append("\x00\x00\x00\x00", 4) // build year
.append("\x00\x00\x00\x00", 4) // build day
.append("\xff\xff\xff\xff", 4) // description strref
.repeat('\x00', 116) // reserved
// key list
.append("Aa\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16) // resref
.append("\x00\x00\x00\x00", 4) // resid
.append("\xe6\x07", 2) // restype
.append("\x00\x00", 2) // unused
// resource list
.append("\xc0\x00\x00\x00", 4) // offset to resource
.append("\x02\x00\x00\x00", 4) // resource size
// resource data
.append("Bb")
.build();
auto bytes = ByteArray();
auto stream = ByteArrayOutputStream(bytes);
auto writer = ErfWriter();
writer.add(ErfWriter::Resource {"Aa", ResourceType::Txi, ByteArray {'B', 'b'}});
// when
writer.save(ErfWriter::FileType::ERF, stream);
// then
auto actualOutput = string(&bytes[0], bytes.size());
BOOST_TEST((expectedOutput == actualOutput), notEqualMessage(expectedOutput, actualOutput));
}
BOOST_AUTO_TEST_SUITE_END()
| 42.405063 | 114 | 0.52 | seedhartha |
78e88da16e897b9e95a76fe790e2a8d6299871dd | 769 | cpp | C++ | Elysium-Engine/Elysium/src/Core/Application/Threads/ElysiumThread.cpp | Kney-Delach/Elysium-Puzzle-Engine | 21eafc5bdad993ea5ffc9e70c910f36ce440b355 | [
"Apache-2.0"
] | null | null | null | Elysium-Engine/Elysium/src/Core/Application/Threads/ElysiumThread.cpp | Kney-Delach/Elysium-Puzzle-Engine | 21eafc5bdad993ea5ffc9e70c910f36ce440b355 | [
"Apache-2.0"
] | null | null | null | Elysium-Engine/Elysium/src/Core/Application/Threads/ElysiumThread.cpp | Kney-Delach/Elysium-Puzzle-Engine | 21eafc5bdad993ea5ffc9e70c910f36ce440b355 | [
"Apache-2.0"
] | null | null | null | /**
* FILENAME : ElysiumThread.cpp
* Name : Ori Lazar
* Student ID : b9061712
* Date : 21/10/2019
* Description : This header contains the implementation for the abstract thread class for this engine, used to run the application.
*/
#include "empch.h"
#include "ElysiumThread.h"
#ifdef EM_PLATFORM_WINDOWS
#include <windows.h>
namespace Elysium
{
namespace Application
{
DWORD ThreadFunction(LPVOID T)
{
ElysiumThread* t = static_cast<ElysiumThread*>(T);
t->Run();
return NULL;
}
void ElysiumThread::Start()
{
m_Handle = CreateThread(
NULL,
0,
(LPTHREAD_START_ROUTINE)&ThreadFunction,
(LPVOID)this,
0,
&m_Id);
}
void ElysiumThread::Join()
{
WaitForSingleObject(m_Handle, INFINITE);
}
}
}
#endif | 18.309524 | 132 | 0.674902 | Kney-Delach |
78eb0998384d6c09d3d4d87d934a1db961695d71 | 3,825 | cpp | C++ | main.cpp | p-col/Z3Ann | 36f3fead68212a772b8ab746c8a01d233b2c97fb | [
"MIT"
] | 1 | 2021-11-01T12:58:17.000Z | 2021-11-01T12:58:17.000Z | main.cpp | p-col/Z3Ann | 36f3fead68212a772b8ab746c8a01d233b2c97fb | [
"MIT"
] | null | null | null | main.cpp | p-col/Z3Ann | 36f3fead68212a772b8ab746c8a01d233b2c97fb | [
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include "z3++.h"
#include "z3ann.hpp"
#include "Z3SolutionConverter.hpp"
#include "BackendC.hpp"
#include "Frontend.hpp"
void diabetesTest(void)
{
Frontend fe;
if (!fe.loadDataFromFile("testfiles/diabietes2.train"))
{
std::cerr << "File not found." << std::endl;
return;
}
std::cout << "File succesfully loaded" << std::endl;
//FIXME create auto finder hidden layer size
z3ann ann(8, 2, 2, -1, 1);
ann.setAllLink(false);
ann.setSelfLink(false);
// ann.setRangeLink(0, 7, 8, 11, true);
// ann.setRangeLink(8, 11, 12, 13, true);
ann.setRangeLink(0, 7, 8, 9, true);
ann.setRangeLink(8, 9, 10, 11, true);
// I1
// ann.setLink(0, 13, false);
// ann.setLink(0, 14, false);
// ann.setLink(0, 4, true);
// ann.setAllLink(true);
ann.loadTrainingDataSet(fe.getData());
ann.solve();
std::cout << "========= C Backend Output ==========" << std::endl;
BackendC output(ann);
std::cout << output.getOutput();
}
int main()
{
// diabetesTest();
// return 0;
std::cout << "+-------------------------------+" << std::endl;
std::cout << "| XOR example |" << std::endl;
std::cout << "+-------------------------------+" << std::endl;
std::cout << "| Set 1: Input{-1, -1} |" << std::endl;
std::cout << "| Set 2: Input{ 1, -1} |" << std::endl;
std::cout << "| Set 3: Input{-1, 1} |" << std::endl;
std::cout << "| Set 4: Input{ 1, 1} |" << std::endl;
std::cout << "+-------------------------------+" << std::endl;
std::cout << "| 0 -> -1 | activation : |" << std::endl;
std::cout << "| 1 -> 1 | -> Sum(Ii* Wij) > 0 |" << std::endl;
std::cout << "| | then 1 else -1 |" << std::endl;
std::cout << "+---------+---------------------+" << std::endl;
std::cout << "| o2 |" << std::endl;
std::cout << "| / \\ |" << std::endl;
std::cout << "| Input 1 -> o0 \\ |" << std::endl;
std::cout << "| \\ \\ |" << std::endl;
std::cout << "| 3o---o5 -> Output|" << std::endl;
std::cout << "| / / |" << std::endl;
std::cout << "| Input 2 -> o1 / |" << std::endl;
std::cout << "| \\ / |" << std::endl;
std::cout << "| o4 |" << std::endl;
std::cout << "+-------------------------------+" << std::endl << std::endl;
std::vector<trainingData> data;
data.resize(4);
data[0].input.resize(2);
data[1].input.resize(2);
data[2].input.resize(2);
data[3].input.resize(2);
data[0].output.resize(1);
data[1].output.resize(1);
data[2].output.resize(1);
data[3].output.resize(1);
data[0].input[0] = -1;
data[0].input[1] = -1;
data[0].output[0] = -1;
data[1].input[0] = 1;
data[1].input[1] = -1;
data[1].output[0] = 1;
data[2].input[0] = -1;
data[2].input[1] = 1;
data[2].output[0] = 1;
data[3].input[0] = 1;
data[3].input[1] = 1;
data[3].output[0] = -1;
z3ann ann(2, 3, 1, -1, 1);
ann.setAllLink(false);
// I1
ann.setLink(0, 2, true);
ann.setLink(0, 3, true);
ann.setLink(0, 4, true);
// I2
ann.setLink(1, 2, true);
ann.setLink(1, 3, true);
ann.setLink(1, 4, true);
// hidden to output layer
ann.setLink(2, 5, true);
ann.setLink(3, 5, true);
ann.setLink(4, 5, true);
// ann.setAllLink(true);
ann.loadTrainingDataSet(data);
ann.solve();
std::cout << "========= C Backend Output ==========" << std::endl;
BackendC output(ann);
std::cout << output.getOutput();
return 0;
}
| 29.882813 | 79 | 0.45098 | p-col |
78ec3f0ed641b0c5e552b400150ad9041a533753 | 342 | cpp | C++ | yellow/w3_01_sum_reserve_sort/sum_reverse_sort.cpp | avptin/coursera-c-plus-plus | 18146f023998a073ee8e34315789d049b7fa0d7c | [
"MIT"
] | null | null | null | yellow/w3_01_sum_reserve_sort/sum_reverse_sort.cpp | avptin/coursera-c-plus-plus | 18146f023998a073ee8e34315789d049b7fa0d7c | [
"MIT"
] | null | null | null | yellow/w3_01_sum_reserve_sort/sum_reverse_sort.cpp | avptin/coursera-c-plus-plus | 18146f023998a073ee8e34315789d049b7fa0d7c | [
"MIT"
] | null | null | null | #include "sum_reverse_sort.h"
using namespace std;
int Sum(int x, int y) { return x + y; }
string Reverse(string s) {
string result;
for (auto rit = s.rbegin(); rit != s.rend(); ++rit) {
result.push_back(*rit);
}
return result;
};
void Sort(vector<int>& nums) { return sort(nums.begin(), nums.end()); }
int main() { return 0; } | 22.8 | 71 | 0.625731 | avptin |
78f746137db2125bdc2b3695e3070c3cc71ebe08 | 2,548 | hpp | C++ | include/x11/events.hpp | corngood/polybar | 385572ec643ea6d35483b652a17e74b01229b267 | [
"MIT"
] | 1 | 2020-05-08T14:47:00.000Z | 2020-05-08T14:47:00.000Z | include/x11/events.hpp | corngood/polybar | 385572ec643ea6d35483b652a17e74b01229b267 | [
"MIT"
] | null | null | null | include/x11/events.hpp | corngood/polybar | 385572ec643ea6d35483b652a17e74b01229b267 | [
"MIT"
] | 1 | 2020-05-08T15:26:36.000Z | 2020-05-08T15:26:36.000Z | #pragma once
#include <xpp/event.hpp>
#include "common.hpp"
POLYBAR_NS
class connection;
namespace evt {
// window focus events
using focus_in = xpp::x::event::focus_in<connection&>;
using focus_out = xpp::x::event::focus_out<connection&>;
// cursor events
using enter_notify = xpp::x::event::enter_notify<connection&>;
using leave_notify = xpp::x::event::leave_notify<connection&>;
using motion_notify = xpp::x::event::motion_notify<connection&>;
// keyboard events
using button_press = xpp::x::event::button_press<connection&>;
using button_release = xpp::x::event::button_release<connection&>;
using key_press = xpp::x::event::key_press<connection&>;
using key_release = xpp::x::event::key_release<connection&>;
using keymap_notify = xpp::x::event::keymap_notify<connection&>;
// render events
using circulate_notify = xpp::x::event::circulate_notify<connection&>;
using circulate_request = xpp::x::event::circulate_request<connection&>;
using colormap_notify = xpp::x::event::colormap_notify<connection&>;
using configure_notify = xpp::x::event::configure_notify<connection&>;
using configure_request = xpp::x::event::configure_request<connection&>;
using create_notify = xpp::x::event::create_notify<connection&>;
using destroy_notify = xpp::x::event::destroy_notify<connection&>;
using expose = xpp::x::event::expose<connection&>;
using graphics_exposure = xpp::x::event::graphics_exposure<connection&>;
using gravity_notify = xpp::x::event::gravity_notify<connection&>;
using map_notify = xpp::x::event::map_notify<connection&>;
using map_request = xpp::x::event::map_request<connection&>;
using mapping_notify = xpp::x::event::mapping_notify<connection&>;
using no_exposure = xpp::x::event::no_exposure<connection&>;
using reparent_notify = xpp::x::event::reparent_notify<connection&>;
using resize_request = xpp::x::event::resize_request<connection&>;
using unmap_notify = xpp::x::event::unmap_notify<connection&>;
using visibility_notify = xpp::x::event::visibility_notify<connection&>;
// data events
using client_message = xpp::x::event::client_message<connection&>;
using ge_generic = xpp::x::event::ge_generic<connection&>;
using property_notify = xpp::x::event::property_notify<connection&>;
// selection events
using selection_clear = xpp::x::event::selection_clear<connection&>;
using selection_notify = xpp::x::event::selection_notify<connection&>;
using selection_request = xpp::x::event::selection_request<connection&>;
}
POLYBAR_NS_END
| 42.466667 | 74 | 0.741366 | corngood |
78f93ab42dbe0b9cfc9e23a37d1ef9809a00cddc | 1,052 | cpp | C++ | SOURCE/ArchitectBossLevel.cpp | OnionBurger/DungeonsOfPain | cb56c138a12bdc08376a2ba04f02d24527344202 | [
"MIT"
] | null | null | null | SOURCE/ArchitectBossLevel.cpp | OnionBurger/DungeonsOfPain | cb56c138a12bdc08376a2ba04f02d24527344202 | [
"MIT"
] | null | null | null | SOURCE/ArchitectBossLevel.cpp | OnionBurger/DungeonsOfPain | cb56c138a12bdc08376a2ba04f02d24527344202 | [
"MIT"
] | null | null | null | #include "ArchitectBossLevel.h"
ArchitectBossLevel::ArchitectBossLevel() {
}
void ArchitectBossLevel::generate() {
sizeX = 13;
sizeY = 17;
allocate();
fillWith(T_WALL);
for (unsigned i = 2; i <= 10; ++i)
for (unsigned j = 2; j <= 12; ++j)
lvl[i][j] = T_EMPTY;
for (unsigned i = 3; i <= 9; ++i) {
lvl[i][1] = T_EMPTY;locsItem.push_back(t_point(i, 1));
}
locPlayer = t_point(6, 11);
locsEnemy.push_back(t_point(6, 6));
lvl[1][4] = T_EMPTY;locsItem.push_back(t_point(1, 4));
lvl[11][4] = T_EMPTY;locsItem.push_back(t_point(11, 4));
lvl[1][10] = T_EMPTY;locsItem.push_back(t_point(1, 10));
lvl[11][10] = T_EMPTY;locsItem.push_back(t_point(11, 10));
lvl[2][13] = T_EMPTY;locsItem.push_back(t_point(2, 13));
lvl[9][13] = T_EMPTY;locsItem.push_back(t_point(9, 13));
lvl[4][13] = T_EMPTY;lvl[4][14] = T_EMPTY;locsItem.push_back(t_point(4, 14));
lvl[8][13] = T_EMPTY;lvl[8][14] = T_EMPTY;locsItem.push_back(t_point(8, 14));
lvl[6][13] = T_EMPTY;lvl[6][14] = T_EMPTY;lvl[6][15] = T_EMPTY;locsItem.push_back(t_point(6, 15));
} | 30.057143 | 99 | 0.652091 | OnionBurger |
60015c3d442c8134c22e971915ea5b011299ff91 | 6,861 | cpp | C++ | Game/src/PlatformGameState.cpp | DanielParra159/EngineAndGame | 45af7439633054aa6c9a8e75dd0453f9ce297626 | [
"CC0-1.0"
] | 1 | 2017-04-08T14:33:04.000Z | 2017-04-08T14:33:04.000Z | Game/src/PlatformGameState.cpp | DanielParra159/EngineAndGame | 45af7439633054aa6c9a8e75dd0453f9ce297626 | [
"CC0-1.0"
] | 1 | 2017-04-05T01:56:28.000Z | 2017-04-05T01:56:28.000Z | Game/src/PlatformGameState.cpp | DanielParra159/EngineAndGame | 45af7439633054aa6c9a8e75dd0453f9ce297626 | [
"CC0-1.0"
] | null | null | null | #include "PlatformGameState.h"
#include "MenuState.h"
#include "Platformmer/PlatformerWall.h"
#include "Platformmer/PlatformerPlayer.h"
#include "Platformmer/PlatformerGrass.h"
#include "Platformmer/PlatformerCoin.h"
#include "Platformmer/PlatformerBackground.h"
#include "Input/InputManager.h"
#include "Input/IController.h"
#include "Input/KeyboardController.h"
#include "Input/MouseController.h"
#include "Input/InputAction.h"
#include "Graphics/RenderManager.h"
#include "Graphics/Camera.h"
#include "Graphics/Light.h"
#include "UI/MenuManager.h"
#include "UI/Menu.h"
#include "Core/Log.h"
#include "Core/Game.h"
#include "Logic/World.h"
#include "Audio/AudioManager.h"
#include "Audio/Sound2D.h"
#include "IO/FileSystem.h"
#include "Script/ScriptManager.h"
#include "System/Time.h"
#include "Support/Math.h"
#include "Core/Log.h"
#include "Defs.h"
namespace
{
void AddWall(game::PlatformerWall* aGameObject)
{
logic::World::Instance()->AddGameObject(aGameObject, TRUE);
}
void AddPlayer(game::PlatformerPlayer* aGameObject)
{
logic::World::Instance()->AddGameObject(aGameObject, TRUE);
}
void AddDetail(float32 aX, float32 aY, float32 aZ, int32 aType)
{
game::PlatformerGrass::Instance->AddElement(aX, aY, aZ, aType);
}
void AddCoin(game::PlatformerCoin* aGameObject)
{
logic::World::Instance()->AddGameObject(aGameObject, TRUE);
}
}
//HACK to register lua functions once
static BOOL firstTime = TRUE;
namespace game
{
BOOL PlatformGameState::Init()
{
GET_INPUT_MANAGER;
lInputManager->ClearAllActionInput();
input::IController* lController;
if ((lController = lInputManager->CreateController(input::ETypeControls::eKeyboard)) == 0)
return FALSE;
lController->RegisterInputAction(ePltatformmerExit, input::KeyboardController::eEscape);
lController->RegisterInputAction(ePltatformmerUp, input::KeyboardController::eUp);
lController->RegisterInputAction(ePltatformmerDown, input::KeyboardController::eDown);
lController->RegisterInputAction(ePltatformmerLeft, input::KeyboardController::eLeft);
lController->RegisterInputAction(ePltatformmerRight, input::KeyboardController::eRight);
lController->RegisterInputAction(ePltatformmerJump, input::KeyboardController::eSpace);
lController->RegisterInputAction(ePltatformmerKunai, input::KeyboardController::eQ);
lController->RegisterInputAction(ePltatformmerMelee, input::KeyboardController::eLeftControl);
/*if ((lController = lInputManager->CreateController(input::ETypeControls::eMouse)) == 0)
return FALSE;*/
GET_WORLD;
lWorld->Init();
graphics::Camera* lCamera = graphics::RenderManager::Instance()->CreatePerspectiveCamera(Vector3D<float32>(2.0f, 10.2f, 12.0f),
Vector3D<float32>(2.0f, 7.0f, 0.0f),
Vector3D<float32>(0.0f, 0.0f, -1.0f),
75.0f, 800.0f / 600.0f, 1.0f, 1000.0f);
graphics::RenderManager::Instance()->SetRenderCamera(lCamera);
graphics::RenderManager::Instance()->SetUIRenderCamera(graphics::RenderManager::Instance()->CreateOrthographicCamera(0.0f, 800.0f, 600.0f, 0.0f, -1.0f, 1.0f));
logic::IGameObject* lGameObject = new logic::IGameObject();
lGameObject->AddComponent(lCamera);
lWorld->AddGameObject(lGameObject, TRUE);
graphics::RenderManager::Instance()->SetClearColor(Color32(0.5f, 0.75f, 0.92f, 1.0f));
graphics::RenderManager::Instance()->CreateMainLight(Vector3D<float32>(0.0f, 8.0f, 8.0f));
io::FileSystem::Instance()->ChangeDirectory(".\\audio");
mMusic = audio::AudioManager::Instance()->CreateSound2D("PlatformGame.wav");
mMusic->Play(audio::eAudioGroups::eMusic, TRUE);
PlatformerGrass* lPlatformerGrass = new PlatformerGrass();
lWorld->AddGameObject(lPlatformerGrass, TRUE);
lPlatformerGrass->Init(TRUE, 0, 0);
PlatformerBackground* lPlatformerBackground = new PlatformerBackground();
lWorld->AddGameObject(lPlatformerBackground, TRUE);
lPlatformerBackground->Init(TRUE);
if (firstTime)
{
firstTime = FALSE;
luabind::module(script::ScriptManager::Instance()->GetNativeInterpreter())
[
luabind::def("AddWall", AddWall, luabind::adopt(_1)),
luabind::def("AddPlayer", AddPlayer, luabind::adopt(_1)),
luabind::def("AddCoin", AddCoin, luabind::adopt(_1)),
luabind::def("AddDetail", AddDetail)
];
luabind::module(script::ScriptManager::Instance()->GetNativeInterpreter())
[
luabind::class_<game::PlatformerWall>("PlatformmerWall")
.def(luabind::constructor<>())
.def("Init", (void(game::PlatformerWall::*)(float32, float32, float32, float32, int32))&game::PlatformerWall::LuaInit)
];
luabind::module(script::ScriptManager::Instance()->GetNativeInterpreter())
[
luabind::class_<game::PlatformerPlayer>("PlatformmerPlayer")
.def(luabind::constructor<>())
.def("Init", (void(game::PlatformerPlayer::*)(float32, float32))&game::PlatformerPlayer::LuaInit)
];
luabind::module(script::ScriptManager::Instance()->GetNativeInterpreter())
[
luabind::class_<game::PlatformerCoin>("PlatformmerCoin")
.def(luabind::constructor<>())
.def("Init", (void(game::PlatformerCoin::*)(float32, float32, int32))&game::PlatformerCoin::LuaInit)
];
}
io::FileSystem::Instance()->ChangeDirectory(".\\Maps");
script::ScriptManager::Instance()->LoadScript("MapParser.lua");
std::string lDir = io::FileSystem::Instance()->GetCurrentDir();
lDir.replace(lDir.find("\\"), 1, "/");
lDir.replace(lDir.find("\\"), 1, "/");
lDir += "/Map02.lua";
std::string lAux = "ParseMap(\""+ lDir+"\",\"Map02\")";
script::ScriptManager::Instance()->ExecuteScript(lAux.c_str());
return TRUE;
}
void PlatformGameState::Release()
{
mMusic->Stop();
graphics::RenderManager::Instance()->RemoveMainLight();
logic::World::Instance()->Release();
}
BOOL PlatformGameState::Update()
{
logic::World::Instance()->Update();
//graphics::Light* lMainLight = graphics::RenderManager::Instance()->GetMainLight();
//lMainLight->SetPosition(Vector3D<float32>(20.0f + 25.0f * Math::Cosf(sys::Time::GetCurrentSec() * 0.8f), 8.0f, 8.0f));
if (input::InputManager::Instance()->IsActionDown(ePltatformmerExit))
{
game::MenuState *lGameState = new game::MenuState();
core::Game::Instance()->ChangeGameState(lGameState);
}
return TRUE;
}
void PlatformGameState::FixedUpdate()
{
logic::World::Instance()->FixedUpdate();
}
void PlatformGameState::Render()
{
graphics::RenderManager::Instance()->BeginRender();
logic::World::Instance()->Render();
ui::MenuManager::Instance()->Render();
graphics::RenderManager::Instance()->EndRender();
}
} // namespace game
| 32.060748 | 162 | 0.692756 | DanielParra159 |
6004e96ed0c659d26d4f75e8f40e34665025f6d4 | 8,651 | cpp | C++ | XPowerControl/token_retrieve.cpp | snowpoke/XPowerControl | a5e4493cde4bdc06df30dba69a9460247074fdcd | [
"MIT"
] | 4 | 2021-11-11T17:03:20.000Z | 2022-01-14T18:13:41.000Z | XPowerControl/token_retrieve.cpp | snowpoke/XPowerControl | a5e4493cde4bdc06df30dba69a9460247074fdcd | [
"MIT"
] | 1 | 2022-01-14T00:39:49.000Z | 2022-01-14T00:39:49.000Z | XPowerControl/token_retrieve.cpp | snowpoke/XPowerControl | a5e4493cde4bdc06df30dba69a9460247074fdcd | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "RetrieveTokenDlg.h"
#include "token_retrieve.h"
#include "nlohmann/json.hpp"
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <curl/curl.h>
using namespace std;
HANDLE mitm_start_alt() {
DeleteFile(L"token.txt");
// we create an empty job object that will contain the process
HANDLE job_handle = CreateJobObject(NULL, NULL);
// we set up the job object so that closing the job causes all child processes to be terminated
JOBOBJECT_BASIC_LIMIT_INFORMATION kill_flag_info;
kill_flag_info.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info;
job_info.BasicLimitInformation = kill_flag_info;
SetInformationJobObject(job_handle, JobObjectExtendedLimitInformation, &job_info, sizeof(job_info));
// delete files that contain results from previous mitmdump processes
DeleteFile(L"authorization.txt");
DeleteFile(L"registration_token.txt");
// we start mitmdump
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
CreateProcess(L"mitmdump.exe",
L"mitmdump.exe -s mitm_script.py",
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi);
// we associate the mitmdump with the job we created
AssignProcessToJobObject(job_handle, pi.hProcess);
return job_handle;
}
static int writer(char *data, size_t size, size_t nmemb,
std::string *writerData)
{
if (writerData == NULL)
return 0;
writerData->append(data, size*nmemb);
return static_cast<int>(size * nmemb);
}
wstring access_token_to_iksm(string access_token_t, RetrieveTokenDlg* tokenDlg_t) {
CURL *curl1;
CURL *curl2;
CURLcode res;
wstring ret = L"";
tokenDlg_t->tokenEdit.SetWindowTextW(L"Found authorization key! Retrieving token...");
// we obtain the device registration token
// wait until registration token file is created
while (!boost::filesystem::exists("registration_token.txt")) {
}
string registration_token = "";
try {
ifstream file;
file.open("registration_token.txt");
string line;
string file_text = "";
while (getline(file, line)) {
file_text += line;
}
nlohmann::json j = nlohmann::json::parse(file_text);
registration_token = j["parameter"]["registrationToken"].get<string>();
}
catch (...) {
AfxMessageBox(L"Failed retrieving the registration token. Please try again or retrieve the token manually.");
AfxThrowUserException();
}
tokenDlg_t->tokenEdit.SetWindowTextW(L"Retrieving token... [Registration Token OK]");
// we obtain the WebServiceToken
string gamewebtoken = "";
int attempt_num = 1;
while (gamewebtoken == "" && attempt_num <= 3) {
wstring dlg_text = L"Retrieving token... [Gamewebtoken Attempt #" + to_wstring(attempt_num) + L"]";
tokenDlg_t->tokenEdit.SetWindowTextW(dlg_text.c_str());
attempt_num++;
curl1 = curl_easy_init();
if (curl1) {
struct curl_slist* chunk = NULL;
string req_url = "https://api-lp1.znc.srv.nintendo.net/v2/Game/GetWebServiceToken";
static string buffer;
chunk = curl_slist_append(chunk, "host: api-lp1.znc.srv.nintendo.net");
chunk = curl_slist_append(chunk, "content-type: application/json");
chunk = curl_slist_append(chunk, ("Authorization: Bearer " + access_token_t).c_str());
curl_easy_setopt(curl1, CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(curl1, CURLOPT_URL, req_url.c_str());
curl_easy_setopt(curl1, CURLOPT_WRITEFUNCTION, writer);
curl_easy_setopt(curl1, CURLOPT_WRITEDATA, &buffer);
curl_easy_setopt(curl1, CURLOPT_POST, 1L);
string data = "{\"parameter\": {\"f\": \"abcd\",\"id\": 5741031244955648,\"registrationToken\": \""
+ registration_token
+ "\",\"requestId\": \"abcd\",\"timestamp\": 0 }}";
curl_easy_setopt(curl1, CURLOPT_POSTFIELDS, data.c_str());
try {
res = curl_easy_perform(curl1);
}
catch (...) {
wstring afx_message = L"The program failed to perform the web request. (Attempt " + to_wstring(attempt_num - 1) + L"/3)";
AfxMessageBox(afx_message.c_str());
continue;
}
curl_easy_cleanup(curl1);
curl_slist_free_all(chunk);
log_manually("Sending request to https://api-lp1.znc.srv.nintendo.net/v2/Game/GetWebServiceToken.\n \
Using access token " + access_token_t + "\n \
Using post data " + data + "\n \
Obtained response " + buffer + "\n\n\n");
try {
nlohmann::json j = nlohmann::json::parse(buffer);
gamewebtoken = j["result"]["accessToken"].get<string>();
}
catch (...) {
wstring afx_message = L"Failed to read the token from file. (Attempt " + to_wstring(attempt_num - 1) + L"/3)";
AfxMessageBox(afx_message.c_str());
continue;
}
}
}
if (gamewebtoken == "") {
AfxMessageBox(L"Failed retrieving the gamewebtoken. Please try again or retrieve the token manually.");
AfxThrowUserException();
}
attempt_num = 1;
while (ret == L"" && attempt_num <= 3) {
wstring dlg_text = L"Retrieving token... [Authorization Attempt #" + to_wstring(attempt_num) + L"]";
tokenDlg_t->tokenEdit.SetWindowTextW(dlg_text.c_str());
attempt_num++;
curl2 = curl_easy_init();
if (curl2) {
DeleteFile(L"cookies.txt");
struct curl_slist* chunk = NULL;
string req_url = "https://app.splatoon2.nintendo.net/?lang=en-GB&na_country=DE&na_lang=en-US";
string cookie_path = "cookies.txt";
chunk = curl_slist_append(chunk, "host: app.splatoon2.nintendo.net");
chunk = curl_slist_append(chunk, ("x-gamewebtoken: " + gamewebtoken).c_str());
static string buffer;
curl_easy_setopt(curl2, CURLOPT_COOKIEJAR, cookie_path.c_str());
curl_easy_setopt(curl2, CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(curl2, CURLOPT_URL, req_url.c_str());
curl_easy_setopt(curl2, CURLOPT_WRITEFUNCTION, writer);
curl_easy_setopt(curl2, CURLOPT_WRITEDATA, &buffer);
log_manually("Sending request to https://app.splatoon2.nintendo.net/?lang=en-GB&na_country=DE&na_lang=en-US \n \
Using x-gamewebtoken " + gamewebtoken + "\n\n\n");
try {
res = curl_easy_perform(curl2);
}
catch (...) {
wstring afx_message = L"The program failed to perform the web request. (Attempt " + to_wstring(attempt_num - 1) + L"/3)";
AfxMessageBox(afx_message.c_str());
continue;
}
/* always cleanup */
curl_easy_cleanup(curl2);
/* free the custom headers */
curl_slist_free_all(chunk);
try {
// we now read the information from the cookie file
wifstream file;
file.open(cookie_path);
wstring line;
while (getline(file, line)) {
if (line.size() >= 30 // line must have more characters than length of the token
&& boost::contains(line, "iksm_session")) { // line must contain iksm_session
vector<wstring> elems;
boost::split(elems, line, boost::is_any_of("\t"));
bool token = false;
for (wstring elem : elems) { // check for entry iksm_session, then set next entry as return value
if (token)
ret = elem;
token = (boost::contains(elem, "iksm_session"));
}
}
}
DeleteFile(L"cookies.txt");
}
catch (...) {
wstring afx_message = L"Failed retrieving token information. (Attempt " + to_wstring(attempt_num - 1) + L"/3)";
AfxMessageBox(afx_message.c_str());
continue;
}
}
else {
wstring afx_message = L"Could not open web connection object. (Attempt " + to_wstring(attempt_num - 1) + L"/3)";
AfxMessageBox(afx_message.c_str());
continue;
}
}
if (ret == L"") {
AfxMessageBox(L"The program failed to obtain the authorization token. Please try again or retrieve the token manually.");
AfxThrowUserException();
}
return ret;
}
void kill_mitm(RetrieveTokenDlg* dlg_t) {
CloseHandle(dlg_t->mitm_handle); // we set up the job so that this kills all child processes
dlg_t->mitm_started = false;
}
UINT token_listener(LPVOID pParam) { // checks if token file exists
RetrieveTokenDlg* tokenDlg = (RetrieveTokenDlg*)pParam;
while (true) {
if (boost::filesystem::exists("authorization.txt")) {
ifstream file("authorization.txt");
string authorization_token;
file >> authorization_token;
file.close();
DeleteFile(L"authorization.txt");
tokenDlg->found_token = access_token_to_iksm(authorization_token, tokenDlg);
kill_mitm(tokenDlg);
tokenDlg->tokenEdit.SetWindowTextW(tokenDlg->found_token.c_str());
tokenDlg->tokenEdit.EnableWindow(TRUE);
tokenDlg->ok_btn.EnableWindow(TRUE);
break;
}
}
return 0;
}
void log_manually(string message) {
ofstream file;
file.open("log.txt", ios_base::app);
file << message;
} | 29.525597 | 125 | 0.701075 | snowpoke |
6007181b87a5af1d608f11c956c0577c3c9662d9 | 8,110 | hpp | C++ | src/ssd1306/ssd1306.hpp | embvm-drivers/two-tone-oled | 7c8c52daa573e923e3e4fd5e619d509c33506f11 | [
"MIT"
] | null | null | null | src/ssd1306/ssd1306.hpp | embvm-drivers/two-tone-oled | 7c8c52daa573e923e3e4fd5e619d509c33506f11 | [
"MIT"
] | null | null | null | src/ssd1306/ssd1306.hpp | embvm-drivers/two-tone-oled | 7c8c52daa573e923e3e4fd5e619d509c33506f11 | [
"MIT"
] | null | null | null | // Copyright 2020 Embedded Artistry LLC
// SPDX-License-Identifier: MIT
#ifndef SSD1306_HPP_
#define SSD1306_HPP_
#include <driver/basic_display.hpp>
#include <driver/i2c.hpp>
#include <etl/variant_pool.h>
namespace embdrv
{
inline constexpr uint8_t DEFAULT_SSD1306_I2C_ADDR = 0x3C;
/** Driver for the SSD1306 Display Driver
*
* This implementation only supports I2C, though the part supports SPI and Parallel modes
* To implement that support, please use a state pattern and adjust the i2cWrite function
* to be a more generic write. This single function can be swapped out for the particular
* data mode.
*
* The screen size is hard-coded to be 64 x 48 with an offset of 32. Adjustments
* are needed to make the screen size specification generic.
*
* @ingroup FrameworkDrivers
*/
class ssd1306 final : public embvm::basicDisplay
{
public:
/// Address is 0x3D if DC pin is set to 1
explicit ssd1306(embvm::i2c::master& i2c, uint8_t i2c_addr = DEFAULT_SSD1306_I2C_ADDR)
: i2c_(i2c), i2c_addr_(i2c_addr)
{
// Initialize the display buffer with byte 0x40, indicating that it is a
// Data payload. This is used to transfer the whole screen buffer in a
// Single transaction.
display_buffer_[0] = 0x40; // NOLINT
}
void clear() noexcept final;
void clearAndDisplay() noexcept;
void invert(enum invert inv) noexcept final;
void contrast(uint8_t contrast) noexcept final;
void cursor(coord_t x, coord_t y) noexcept final;
void pixel(coord_t x, coord_t y, color c, mode m) noexcept final;
void line(coord_t x0, coord_t y0, coord_t x1, coord_t y1, color c, mode m) noexcept final;
void rect(coord_t x, coord_t y, uint8_t width, uint8_t height, color c, mode m) noexcept final;
void rectFill(coord_t x, coord_t y, uint8_t width, uint8_t height, color c,
mode m) noexcept final;
void circle(coord_t x, coord_t y, uint8_t radius, color c, mode m) noexcept final;
void circleFill(coord_t x, coord_t y, uint8_t radius, color c, mode m) noexcept final;
void drawChar(coord_t x, coord_t y, uint8_t character, color c, mode m) noexcept final;
void drawBitmap(uint8_t* bitmap) noexcept final;
uint8_t screenWidth() const noexcept final;
uint8_t screenHeight() const noexcept final;
void scrollRight(coord_t start, coord_t stop) noexcept final;
void scrollLeft(coord_t start, coord_t stop) noexcept final;
void scrollVertRight(coord_t start, coord_t stop) noexcept final;
void scrollVertLeft(coord_t start, coord_t stop) noexcept final;
void scrollStop() noexcept final;
void flipVertical(bool flip) noexcept final;
void flipHorizontal(bool flip) noexcept final;
void display() noexcept final;
// TODO: refactor font functions out of this driver
/// Set the font type
/// @param type Index for the font to use
/// @returns the currently selected font.
uint8_t fontType(uint8_t type) noexcept;
/// Get the current font type
/// @returns the currently selected font.
uint8_t fontType() const noexcept
{
return fontType_;
}
/// Get the font width
/// @returns the width of the currently selected font in pixels
uint8_t fontWidth() const noexcept
{
return fontWidth_;
}
/// Get the font height
/// @returns the height of the currently selected font in pixels
uint8_t fontHeight() const noexcept
{
return fontHeight_;
}
/// Get the total number of supported fonts
/// @returns the number of supported fonts
static uint8_t totalFonts() noexcept;
/// Get the starting character for the font
/// @returns the starting ASCII character for the currently selected font
uint8_t fontStartChar() const noexcept
{
return fontStartChar_;
}
/// Get the total number of characters supported by the font
/// @returns the number of characters supported by the currently selected font
uint8_t fontTotalChar() const noexcept
{
return fontTotalChar_;
}
void putchar(uint8_t c) noexcept final;
private:
void start_() noexcept final;
void stop_() noexcept final;
/// Helper function which performs an I2C write
/// @param buffer The transaction buffer.
/// @param size The size of the write.
/// @param cb The callback function to invoke when the write completes.
void i2c_write(const uint8_t* buffer, uint8_t size,
const embvm::i2c::master::cb_t& cb) noexcept;
// RAW LCD functions
/// Clear the display and initialize buffer bytes with the target value
/// @param c The value to initialize the bytes of the screen buffe rwith.
void clear(uint8_t c) noexcept;
/// Send a command to the display driver hardware
/// @param c the command byte.
void command(uint8_t c) noexcept;
/// Send a command with one argument to the display driver hardware
/// @param cmd the command byte.
/// @param arg1 The argument to send with the command byte.
void command(uint8_t cmd, uint8_t arg1) noexcept;
/// Send a command with two arguments to the display driver hardware
/// @param cmd the command byte.
/// @param arg1 The first argument to send with the command byte.
/// @param arg2 The second argumet to send with the command byte.
void command(uint8_t cmd, uint8_t arg1, uint8_t arg2) noexcept;
/// Send a data byte to the display driver hardware
/// @param c The data byte to send to the display.
void data(uint8_t c) noexcept;
/// Set the column address
/// @param add The address of the column.
void setColumnAddress(uint8_t add) noexcept;
/// Set the page address
/// @param add The address of the page.
void setPageAddress(uint8_t add) noexcept;
void drawCharSingleRow(coord_t x, coord_t y, uint8_t character, color c, mode m) noexcept;
void drawCharMultiRow(coord_t x, coord_t y, uint8_t character, color c, mode m) noexcept;
/// Deleted copy constructor - make GCC happy since we have pointers to data members
ssd1306(const ssd1306&) = delete;
/// Deleted copy assignment operator - make GCC happy since we have pointers to data members
const ssd1306& operator=(const ssd1306&) = delete;
/// Deleted move constructor - make GCC happy since we have pointers to data members
ssd1306(ssd1306&&) = delete;
/// Deleted move assignment operator - make GCC happy since we have pointers to data members
ssd1306& operator=(ssd1306&&) = delete;
private:
/// The width of the scren in pixels
static constexpr uint8_t SCREEN_WIDTH = 64;
/// The height of the screen in pixels
static constexpr uint8_t SCREEN_HEIGHT = 48;
/// The size of the screen buffer
/// We divide by 8 because each byte controls the state of 8 pixels.
static constexpr size_t SCREEN_BUFFER_SIZE = ((SCREEN_WIDTH * SCREEN_HEIGHT) / 8);
/// The number of columns offset into the display where the active display area starts.
static constexpr uint8_t COLUMN_OFFSET = 32;
uint8_t fontWidth_ = 0, fontHeight_ = 0, fontType_ = 0, fontStartChar_ = 0, fontTotalChar_ = 0;
uint16_t fontMapWidth_ = 0;
/// X-axies position of the cursor.
uint8_t cursorX_ = 0;
/// Y-axis position of the cursor.
uint8_t cursorY_ = 0;
/// The i2c instance this display driver is attached to
embvm::i2c::master& i2c_;
/// The I2C address for this dispaly
uint8_t i2c_addr_;
/// Array of fonts supported by this driver
static const std::array<const uint8_t*, 2> fonts_;
/// Static memory pool which is used for display I2C transactions.
etl::variant_pool<128, uint8_t, uint16_t, uint32_t> i2c_pool_{};
/** \brief OLED screen buffer.
* Page buffer is required because in SPI and I2C mode, the host cannot read the SSD1306's GDRAM
* of the controller. This page buffer serves as a scratch RAM for graphical functions. All
* drawing function will first be drawn on this page buffer, only upon calling display()
* function will transfer the page buffer to the actual LCD controller's memory.
*
* The additional byte is to represent the data word byte, which allows us to send the entire
* buffer in one shot
*/
uint8_t display_buffer_[SCREEN_BUFFER_SIZE + 1] = {0};
/// Pointer alias to the display_buffer_ which accounts for the single byte reserved for the
/// DATA command value.
uint8_t* const screen_buffer_ = &display_buffer_[1];
};
} // namespace embdrv
#endif // SSD1306_HPP_
| 35.414847 | 97 | 0.744266 | embvm-drivers |
600d4ac22f265afb8ac7ccc32a98b0aca27e1c3c | 3,412 | cpp | C++ | Core/SGConnect/examples/SGConnect_TestProgram.cpp | dic-iit/SenseGlove-API | baad587d4e165d7bfafd7f0c8ee6a1ce8ad651d6 | [
"MIT"
] | null | null | null | Core/SGConnect/examples/SGConnect_TestProgram.cpp | dic-iit/SenseGlove-API | baad587d4e165d7bfafd7f0c8ee6a1ce8ad651d6 | [
"MIT"
] | null | null | null | Core/SGConnect/examples/SGConnect_TestProgram.cpp | dic-iit/SenseGlove-API | baad587d4e165d7bfafd7f0c8ee6a1ce8ad651d6 | [
"MIT"
] | 1 | 2022-03-29T07:53:42.000Z | 2022-03-29T07:53:42.000Z | // Application demonstrating the main funtion(s) of the SGConnect library.
#include <iostream> //output to console
#include "SGConnect.h" //Access SGConnect functions.
int main()
{
std::cout << "Testing " << SGConnect::GetLibraryVersion() << std::endl;
std::cout << "=========================================" << std::endl;
bool scanActive = SGConnect::ScanningActive();
if (!scanActive)
{
std::cout << "We call SGConnect::Init() to startup a background process, which will begin scanning for SenseGlove devices." << std::endl;
int initCode = SGConnect::Init();
if (initCode > 0)
{
std::cout << "Succesfully initialized background process: (InitCode = " << std::to_string(initCode) << ")" << std::endl;
std::cout << "This process will begin connecting to ports that should belong to SenseGlove devices." << std::endl;
std::cout << "It will take a few seconds before the devices appear to the SenseGlove API, especially when using Bluetooth devices." << std::endl;
std::cout << "Below, you will see debug messages appear from the background process. Press return when you are ready to finish" << std::endl;
std::cout << "" << std::endl;
while (std::cin.get() != '\n') {} //Wait for the user to confirm before exiting.
std::cout << "" << std::endl;
//If you have access to SGCoreCpp or SGCoreCs, you can interface with SenseGlove devices
int disposeCode = SGConnect::Dispose();
if (disposeCode > 0)
{
std::cout << "Succesfully cleaned up SGConnect resources: (DisposeCode = " << std::to_string(disposeCode) << ")" << std::endl;
}
else
{
std::cout << "Unable to properly dispose of SGConnect resources: (DisposeCode = " << std::to_string(disposeCode) << ")." << std::endl;
std::cout << "Fortunately, closing this process will cause them to go out of scope and be destroyed either way." << std::endl;
}
}
else
{
std::cout << "Oddly enough, we could not initialize the SGConnect library. (InitCode = " << std::to_string(initCode) << ")" << std::endl;
std::cout << "Please close this program, and try again." << std::endl;
}
}
else
{
std::cout << "A SenseGlove scanning process is already running (ScanState " << std::to_string(SGConnect::ScanningState()) << " > 0)." << std::endl;
std::cout << "Seeing as we've just started up, it can't possibly be this process that did it." << std::endl;
std::cout << "It is safe to call SGConnect::Init() even if this is the case, but no new process will be started." << std::endl;
int initCode = SGConnect::Init();
std::cout << "The SGConnect::Init() will return 0, to let us know no Initialization was done: " << std::to_string(initCode) << std::endl;
std::cout << std::endl;
std::cout << "We can call SGConnect::Dispose() safely, but this will not stop the original process." << std::endl;
int disposeVal = SGConnect::Dispose();
std::cout << "The SGConnect::Dispose() will return 0, to let us know nothing was Disposed of: " << std::to_string(disposeVal) << std::endl;
std::cout << "If you wish to dispose of the already running process, you should call SGConnect::Dispose() from the program that originally called SGConnect::Init()" << std::endl;
}
std::cout << "=========================================" << std::endl;
std::cout << "Done. Press Return to exit." << std::endl;
while (std::cin.get() != '\n') {} //Wait for the user to confirm before exiting.
} | 55.032258 | 180 | 0.650938 | dic-iit |
60104de79c3e0bd1d5a1c84b41e0848d251ef410 | 1,706 | hh | C++ | core/test/multiplexing/engine/hooker.hh | centreon-lab/centreon-broker | b412470204eedc01422bbfd00bcc306dfb3d2ef5 | [
"Apache-2.0"
] | 40 | 2015-03-10T07:55:39.000Z | 2021-06-11T10:13:56.000Z | core/test/multiplexing/engine/hooker.hh | centreon-lab/centreon-broker | b412470204eedc01422bbfd00bcc306dfb3d2ef5 | [
"Apache-2.0"
] | 297 | 2015-04-30T10:02:04.000Z | 2022-03-09T13:31:54.000Z | core/test/multiplexing/engine/hooker.hh | centreon-lab/centreon-broker | b412470204eedc01422bbfd00bcc306dfb3d2ef5 | [
"Apache-2.0"
] | 29 | 2015-08-03T10:04:15.000Z | 2021-11-25T12:21:00.000Z | /*
* Copyright 2011 - 2019 Centreon (https://www.centreon.com/)
*
* 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.
*
* For more information : contact@centreon.com
*
*/
#ifndef HOOKER_HH
#define HOOKER_HH
#include <queue>
#include "com/centreon/broker/multiplexing/hooker.hh"
const std::string HOOKMSG1("my first hooking message (when engine is started)");
const std::string HOOKMSG2(
"my second hooking message (when multiplexing events)");
const std::string HOOKMSG3("my third hooking message (when engine is stopped)");
using namespace com::centreon::broker;
/**
* @class hooker hooker.hh "test/multiplexing/engine/hooker.hh"
* @brief Test hook class.
*
* Simple class that hook events from the multiplexing engine.
*/
class hooker : public multiplexing::hooker {
std::queue<std::shared_ptr<io::data>> _queue;
public:
hooker();
~hooker();
hooker(const hooker&) = delete;
hooker& operator=(const hooker&) = delete;
bool read(std::shared_ptr<io::data>& d, time_t deadline = (time_t)-1) override;
void starting() override;
void stopping() override;
int32_t write(std::shared_ptr<io::data> const& d) override;
int32_t stop() override;
};
#endif // !HOOKER_HH
| 31.018182 | 81 | 0.723916 | centreon-lab |
6010f95b0e95193e76b0b35cc9841e7880a3740f | 1,137 | hpp | C++ | src/3rd party/boost/boost/test/unit_test.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 8 | 2016-01-25T20:18:51.000Z | 2019-03-06T07:00:04.000Z | src/3rd party/boost/boost/test/unit_test.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | null | null | null | src/3rd party/boost/boost/test/unit_test.hpp | OLR-xray/OLR-3.0 | b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611 | [
"Apache-2.0"
] | 3 | 2016-02-14T01:20:43.000Z | 2021-02-03T11:19:11.000Z | // (C) Copyright Gennadiy Rozental 2001-2002.
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.
// See http://www.boost.org for most recent version including documentation.
//
// File : $RCSfile: unit_test.hpp,v $
//
// Version : $Id: unit_test.hpp,v 1.6 2002/11/02 19:31:04 rogeeff Exp $
//
// Description : wrapper include . To be used by end-user
// ***************************************************************************
#ifndef BOOST_UNIT_TEST_HPP
#define BOOST_UNIT_TEST_HPP
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test_suite.hpp>
// ***************************************************************************
// Revision History :
//
// $Log: unit_test.hpp,v $
// Revision 1.6 2002/11/02 19:31:04 rogeeff
// merged into the main trank
//
// ***************************************************************************
#endif // BOOST_UNIT_TEST_HPP
| 34.454545 | 78 | 0.562005 | OLR-xray |
601335bf34dba3f7fc4690f67510c3a971d9dc3e | 1,933 | cpp | C++ | Source/Arnoldi/file_operations.cpp | evstigneevnm/NS3DPeriodic | 094c168f153e36f00ac9103675416ddb9ee6b586 | [
"BSD-3-Clause"
] | null | null | null | Source/Arnoldi/file_operations.cpp | evstigneevnm/NS3DPeriodic | 094c168f153e36f00ac9103675416ddb9ee6b586 | [
"BSD-3-Clause"
] | null | null | null | Source/Arnoldi/file_operations.cpp | evstigneevnm/NS3DPeriodic | 094c168f153e36f00ac9103675416ddb9ee6b586 | [
"BSD-3-Clause"
] | null | null | null | #include "file_operations.h"
void print_vector(const char *f_name, int N, real *vec){
FILE *stream;
stream=fopen(f_name, "w" );
for (int i = 0; i < N; ++i)
{
fprintf(stream, "%.16le\n",(double)vec[i]);
}
fclose(stream);
}
void print_vector(const char *f_name, int N, real complex *vec){
FILE *stream;
stream=fopen(f_name, "w" );
for (int i = 0; i < N; ++i)
{
fprintf(stream, "%.16le+%.16lei\n",(double complex)vec[i]);
}
fclose(stream);
}
void print_matrix(const char *f_name, int Row, int Col, real *matrix){
int N=Col;
FILE *stream;
stream=fopen(f_name, "w" );
for (int i = 0; i<Row; i++)
{
for(int j=0;j<Col;j++)
{
fprintf(stream, "%.16le ",(double) matrix[I2(i,j,Row)]);
}
fprintf(stream, "\n");
}
fclose(stream);
}
void print_matrix(const char *f_name, int Row, int Col, real complex *matrix){
int N=Col;
FILE *stream;
stream=fopen(f_name, "w" );
for (int i = 0; i<Row; i++)
{
for(int j=0;j<Col;j++)
{
//if(cimag(matrix[I2(i,j)])<0.0)
// fprintf(stream, "%.16le%.16leI ",matrix[I2(i,j)]);
//else
fprintf(stream, "%.16le %.16le",(double complex)matrix[I2(i,j,Row)]);
}
fprintf(stream, "\n");
}
fclose(stream);
}
int read_matrix(const char *f_name, int Row, int Col, real *matrix){
FILE *stream;
stream=fopen(f_name, "r" );
if (stream == NULL)
{
return -1;
}
else{
for (int i = 0; i<Row; i++)
{
for(int j=0;j<Col;j++)
{
double val=0;
fscanf(stream, "%le",&val);
matrix[I2(i,j,Row)]=(real)val;
}
}
fclose(stream);
return 0;
}
}
int read_vector(const char *f_name, int N, real *vec){
FILE *stream;
stream=fopen(f_name, "r" );
if (stream == NULL)
{
return -1;
}
else{
for (int i = 0; i<N; i++)
{
double val=0;
fscanf(stream, "%le",&val);
vec[i]=(real)val;
}
fclose(stream);
return 0;
}
}
| 15.844262 | 78 | 0.549405 | evstigneevnm |
60148b4214239e2e40b7308dfc99941db587df6a | 5,315 | cpp | C++ | VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Responding to the appearance of the on-screen keyboard sample (Windows 8)/C++/KeyboardPage.xaml.cpp | alonmm/VCSamples | 6aff0b4902f5027164d593540fcaa6601a0407c3 | [
"MIT"
] | 300 | 2019-05-09T05:32:33.000Z | 2022-03-31T20:23:24.000Z | VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Responding to the appearance of the on-screen keyboard sample (Windows 8)/C++/KeyboardPage.xaml.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 9 | 2016-09-19T18:44:26.000Z | 2018-10-26T10:20:05.000Z | VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Responding to the appearance of the on-screen keyboard sample (Windows 8)/C++/KeyboardPage.xaml.cpp | JaydenChou/VCSamples | 9e1d4475555b76a17a3568369867f1d7b6cc6126 | [
"MIT"
] | 633 | 2019-05-08T07:34:12.000Z | 2022-03-30T04:38:28.000Z | //
// KeyboardPage.xaml.cpp
// Implementation of the KeyboardPage class
//
#include "pch.h"
#include "KeyboardPage.xaml.h"
using namespace KeyboardEventsSampleCPP;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
KeyboardPage::KeyboardPage() : _displacement(0), _viewSize(0), _bottomOfList(0), _resized(false), _shouldResize(ResizeType::NoResize)
{
InitializeComponent();
// Each scrollable area should be large enough to demonstrate scrolling
double listHeight = Window::Current->Bounds.Height * 2;
LeftList->Height = listHeight;
MiddleList->Height = listHeight;
// InputPaneHelper is a custom class that allows keyboard event listeners to
// be attached to individual elements
_inputPaneHelper = ref new InputPaneHelper();
_inputPaneHelper->SubscribeToKeyboard(true);
_inputPaneHelper->AddShowingHandler(CustomHandlingBox, ref new InputPaneShowingHandler(this, &KeyboardPage::CustomKeyboardHandler));
_inputPaneHelper->SetHidingHandler(ref new InputPaneHidingHandler(this, &KeyboardPage::InputPaneHiding));
}
void KeyboardPage::CloseView_Click(Object^ sender, RoutedEventArgs^ e)
{
this->Frame->GoBack();
}
void KeyboardPage::OnNavigatedFrom(NavigationEventArgs^ e)
{
_inputPaneHelper->SubscribeToKeyboard(false);
_inputPaneHelper->RemoveShowingHandler(CustomHandlingBox);
_inputPaneHelper->SetHidingHandler(nullptr);
}
void KeyboardPage::CustomKeyboardHandler(Object^ sender, InputPaneVisibilityEventArgs^ e)
{
// This function animates the middle scroll area up, then resizes the rest of
// the viewport. The order of operations is important to ensure that the user
// doesn't see a blank spot appear behind the keyboard
_viewSize = e->OccludedRect.Y;
// Keep in mind that other elements could be shifting out of your control. The sticky app bar, for example
// will move on its own. You should make sure the input element doesn't get occluded by the bar
_displacement = -e->OccludedRect.Height;
_bottomOfList = MiddleScroller->VerticalOffset + MiddleScroller->ActualHeight;
// Be careful with this property. Once it has been set, the framework will
// do nothing to help you keep the focused element in view.
e->EnsuredFocusedElementInView = true;
ShowingMoveSpline->Value = _displacement;
MoveMiddleOnShowing->Begin();
}
void KeyboardPage::ShowAnimationComplete(Object^ sender, Object^ e)
{
// Once the animation completes, the app is resized
_shouldResize = ResizeType::ResizeFromShow;
Container->SetValue(Grid::HeightProperty, _viewSize);
MiddleTranslate->Y = 0;
}
void KeyboardPage::InputPaneHiding(InputPane^ sender, InputPaneVisibilityEventArgs^ e)
{
if (_displacement != 0.0)
{
MoveMiddleOnShowing->Stop();
// Keep in mind that other elements could be shifting out of your control. The sticky app bar, for example
// will move on its own. You should make sure the input element doesn't get occluded by the bar
_bottomOfList = MiddleScroller->VerticalOffset + MiddleScroller->ActualHeight;
// If the middle area has actually completed resize, then we want to ignore
// the default system behavior
if (_resized)
{
// Be careful with this property. Once it has been set, the framework will not change
// any layouts in response to the keyboard coming up
e->EnsuredFocusedElementInView = true;
}
// If the container has already been resized, it should be sized back to the right size
// Otherwise, there's no need to change the height
//
// This piece of code checks if the height is NaN
double computedHeight = dynamic_cast<IPropertyValue^>(Container->GetValue(Grid::HeightProperty))->GetDouble();
if (computedHeight != computedHeight)
{
MoveMiddleOnHiding->Begin();
}
else
{
_shouldResize = ResizeType::ResizeFromHide;
// Clear the height property in order to return it to the default height defined in XAML
Container->ClearValue(Grid::HeightProperty);
}
}
}
void KeyboardPage::MiddleScroller_SizeChanged(Object^ sender, SizeChangedEventArgs^ e)
{
// Scrolling should occur after the scrollable element has been resized to ensure
// that the items the user was looking at remain in view
if (_shouldResize == ResizeType::ResizeFromShow)
{
_resized = true;
_shouldResize = ResizeType::NoResize;
MiddleScroller->ScrollToVerticalOffset(_bottomOfList - MiddleScroller->ActualHeight);
}
else if (_shouldResize == ResizeType::ResizeFromHide)
{
_shouldResize = ResizeType::NoResize;
MiddleTranslate->Y = _displacement;
MiddleScroller->ScrollToVerticalOffset(_bottomOfList - MiddleScroller->ActualHeight);
_displacement = 0;
_resized = false;
MoveMiddleOnHiding->Begin();
}
}
| 37.964286 | 138 | 0.73095 | alonmm |
6017f3c3e6b3f7e9f26a4c970037089f7cc26724 | 1,995 | cpp | C++ | openmp/cplusplus/src/viz.cpp | rohanvarma16/pcseg | 574b9cd7b42f8aff49f4a9a7baf3a8a2c316a092 | [
"MIT"
] | 23 | 2017-12-06T02:23:52.000Z | 2022-02-13T22:17:11.000Z | openmp/cplusplus/src/viz.cpp | zjsprit/pcseg | 574b9cd7b42f8aff49f4a9a7baf3a8a2c316a092 | [
"MIT"
] | null | null | null | openmp/cplusplus/src/viz.cpp | zjsprit/pcseg | 574b9cd7b42f8aff49f4a9a7baf3a8a2c316a092 | [
"MIT"
] | 11 | 2018-01-02T07:56:09.000Z | 2022-01-12T05:36:43.000Z | #include <iostream>
#include <stdio.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/common/common_headers.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/console/parse.h>
boost::shared_ptr<pcl::visualization::PCLVisualizer> simpleVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud)
{
// --------------------------------------------
// -----Open 3D viewer and add point cloud-----
// --------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
viewer->addPointCloud<pcl::PointXYZ> (cloud, "sample cloud");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "sample cloud");
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
return (viewer);
}
boost::shared_ptr<pcl::visualization::PCLVisualizer> rgbVis (pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud)
{
// --------------------------------------------
// -----Open 3D viewer and add point cloud-----
// --------------------------------------------
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb(cloud);
viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb, "sample cloud");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
return (viewer);
}
void pc_viz (pcl::PointCloud<pcl::PointXYZRGB>::Ptr ptCloud){
boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer;
viewer = rgbVis(ptCloud);
while (!viewer->wasStopped ())
{
viewer->spinOnce (100);
boost::this_thread::sleep (boost::posix_time::microseconds (100000));
}
}
| 37.641509 | 116 | 0.66015 | rohanvarma16 |
6019af95b2f08eba5ea29d6b050d91ccc499a98d | 1,576 | cpp | C++ | typical90/052-DiceProduct/dice-product.cpp | keitaronaruse/AtCoderTraining | 9fb8f0d492be678a788080c96b06c33992cb6db2 | [
"MIT"
] | null | null | null | typical90/052-DiceProduct/dice-product.cpp | keitaronaruse/AtCoderTraining | 9fb8f0d492be678a788080c96b06c33992cb6db2 | [
"MIT"
] | null | null | null | typical90/052-DiceProduct/dice-product.cpp | keitaronaruse/AtCoderTraining | 9fb8f0d492be678a788080c96b06c33992cb6db2 | [
"MIT"
] | null | null | null | /*
052 - Dice Product(★3)
https://atcoder.jp/contests/typical90/tasks/typical90_az
Author: Keitaro Naruse
Date: 2021-12-18, 2022-01-02
MIT License
*/
// # Solution
// - sum1 = ( A11 + A12 + ... + A16 )
// - sum2 = ( A21 + A22 + ... + A26 )
// - sum1 * sum2
// = A11*A21 + A11*A22 + ... + A11*A26
// + A12*A21 + A12*A22 + ... + A12*A26
// + ...
// + A16*A21 + A16*A22 + ... + A16*A26
// - sum1 * sum2 * ... * sumN
#include <iostream>
#include <vector>
// Very large Prime
const long long Large_Prime = 1000000007LL;
const bool Debug = false;
int main()
{
// Initialize
// Constant
const int M = 6;
// Read N
int N = 0;
std::cin >> N;
if( Debug ) {
std::cerr << N << std::endl;
}
// Read Aij and make Si
std::vector< std::vector< int > > A( N, std::vector< int >( M, 0 ) );
std::vector< int > S( N, 0LL );
long long sum = 1LL;
for( int i = 0; i < N; i ++ ) {
for( int j = 0; j < M; j ++) {
std::cin >> A.at( i ).at( j );
S.at( i ) += A.at( i ).at( j );
if( Debug ) {
std::cerr << A.at( i ).at( j ) << " ";
}
}
if( Debug ) {
std::cerr << ": " << S.at( i ) << std::endl;
}
sum *= ( long long ) S.at( i );
sum %= Large_Prime;
}
// Main
// Display results
std::cout << sum << std::endl;
// Finalize
if( Debug ) {
std::cerr << "Normally terminated." << std::endl;
}
return( 0 );
}
| 22.514286 | 73 | 0.434645 | keitaronaruse |
6019b7ca1a2a8c0e38c029fe2e59c74affcc73ea | 4,739 | cpp | C++ | src/leaf-node-cylinder.cpp | nassimeblinlaas/gepetto-viewer | f47dc13f73c5667c66f1c5273aa0740d62fe9240 | [
"BSD-3-Clause"
] | null | null | null | src/leaf-node-cylinder.cpp | nassimeblinlaas/gepetto-viewer | f47dc13f73c5667c66f1c5273aa0740d62fe9240 | [
"BSD-3-Clause"
] | null | null | null | src/leaf-node-cylinder.cpp | nassimeblinlaas/gepetto-viewer | f47dc13f73c5667c66f1c5273aa0740d62fe9240 | [
"BSD-3-Clause"
] | null | null | null | //
// leaf-node-cylinder.cpp
// gepetto-viewer
//
// Created by Justin Carpentier, Mathieu Geisert in November 2014.
// Copyright (c) 2014 LAAS-CNRS. All rights reserved.
//
#include <gepetto/viewer/leaf-node-cylinder.h>
namespace graphics {
/* Declaration of private function members */
void LeafNodeCylinder::init ()
{
/* Create cylinder object */
cylinder_ptr_ = new ::osg::Cylinder ();
/* Set ShapeDrawable */
shape_drawable_ptr_ = new ::osg::ShapeDrawable(cylinder_ptr_);
/* Create Geode for adding ShapeDrawable */
geode_ptr_ = new osg::Geode ();
geode_ptr_->addDrawable (shape_drawable_ptr_);
/* Create PositionAttitudeTransform */
this->asQueue()->addChild (geode_ptr_);
/* Allow transparency */
geode_ptr_->getOrCreateStateSet()->setRenderBinDetails(10, "DepthSortedBin");
geode_ptr_->getOrCreateStateSet()->setMode(GL_BLEND, ::osg::StateAttribute::ON);
}
LeafNodeCylinder::LeafNodeCylinder (const std::string &name, const float &radius, const float &height) :
Node (name)
{
init();
setRadius(radius);
setHeight(height);
setColor(osgVector4(1.,1.,1.,1.));
}
LeafNodeCylinder::LeafNodeCylinder (const std::string &name, const float &radius, const float &height, const osgVector4 &color) :
Node (name)
{
init();
setRadius(radius);
setHeight(height);
setColor(color);
}
LeafNodeCylinder::LeafNodeCylinder (const LeafNodeCylinder& other) :
Node (other)
{
init();
setRadius(other.getRadius());
setHeight(other.getHeight());
setColor(other.getColor());
}
void LeafNodeCylinder::initWeakPtr (LeafNodeCylinderWeakPtr other_weak_ptr)
{
weak_ptr_ = other_weak_ptr;
}
/* End of declaration of private function members */
/* Declaration of protected function members */
LeafNodeCylinderPtr_t LeafNodeCylinder::create (const std::string &name, const float &radius, const float &height)
{
LeafNodeCylinderPtr_t shared_ptr (new LeafNodeCylinder(name, radius, height));
// Add reference to itself
shared_ptr->initWeakPtr (shared_ptr);
return shared_ptr;
}
LeafNodeCylinderPtr_t LeafNodeCylinder::create (const std::string &name, const float &radius, const float &height, const osgVector4 &color)
{
LeafNodeCylinderPtr_t shared_ptr (new LeafNodeCylinder(name, radius, height, color));
// Add reference to itself
shared_ptr->initWeakPtr (shared_ptr);
return shared_ptr;
}
LeafNodeCylinderPtr_t LeafNodeCylinder::createCopy (LeafNodeCylinderPtr_t other)
{
LeafNodeCylinderPtr_t shared_ptr (new LeafNodeCylinder(*other));
// Add reference to itself
shared_ptr->initWeakPtr (shared_ptr);
return shared_ptr;
}
/* End of declaration of protected function members */
/* Declaration of public function members */
LeafNodeCylinderPtr_t LeafNodeCylinder::clone (void) const
{
return LeafNodeCylinder::createCopy(weak_ptr_.lock());
}
LeafNodeCylinderPtr_t LeafNodeCylinder::self (void) const
{
return weak_ptr_.lock ();
}
void LeafNodeCylinder::setRadius (const float& radius)
{
cylinder_ptr_->setRadius(radius);
}
void LeafNodeCylinder::setHeight (const float& height)
{
cylinder_ptr_->setHeight(height);
}
void LeafNodeCylinder::setColor (const osgVector4& color)
{
shape_drawable_ptr_->setColor(color);
}
void LeafNodeCylinder::setTexture(const std::string& image_path)
{
osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D;
texture->setDataVariance(osg::Object::DYNAMIC);
osg::ref_ptr<osg::Image> image = osgDB::readImageFile(image_path);
if (!image)
{
std::cout << " couldn't find texture, quiting." << std::endl;
return;
}
texture->setImage(image);
geode_ptr_->getStateSet()->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
}
LeafNodeCylinder::~LeafNodeCylinder ()
{
/* Proper deletion of all tree scene */
geode_ptr_->removeDrawable(shape_drawable_ptr_);
shape_drawable_ptr_ = NULL;
this->asQueue()->removeChild(geode_ptr_);
geode_ptr_ = NULL;
weak_ptr_.reset();
}
/* End of declaration of public function members */
} /* namespace graphics */
| 29.61875 | 143 | 0.627348 | nassimeblinlaas |
601afe56f19d2d76bbcc3398c9080b454d63c246 | 1,441 | hpp | C++ | src/muxer/async_webm_muxer.hpp | kounoike/hisui | 7dca5cf4fedfdcf9320a1299ed61f16ee6a3a3ce | [
"Apache-2.0"
] | null | null | null | src/muxer/async_webm_muxer.hpp | kounoike/hisui | 7dca5cf4fedfdcf9320a1299ed61f16ee6a3a3ce | [
"Apache-2.0"
] | null | null | null | src/muxer/async_webm_muxer.hpp | kounoike/hisui | 7dca5cf4fedfdcf9320a1299ed61f16ee6a3a3ce | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <memory>
#include <vector>
#include "config.hpp"
#include "metadata.hpp"
#include "muxer/muxer.hpp"
#include "webm/output/context.hpp"
namespace hisui {
struct Frame;
}
namespace hisui::muxer {
struct AsyncWebMMuxerParameters {
const std::vector<hisui::ArchiveItem>& audio_archive_items;
const std::vector<hisui::ArchiveItem>& normal_archives;
const std::vector<hisui::ArchiveItem>& preferred_archives;
const double duration;
};
struct AsyncWebMMuxerParametersForLayout {
const std::vector<hisui::ArchiveItem>& audio_archive_items;
const std::shared_ptr<VideoProducer>& video_producer;
const double duration;
};
class AsyncWebMMuxer : public Muxer {
public:
AsyncWebMMuxer(const hisui::Config&, const AsyncWebMMuxerParameters&);
AsyncWebMMuxer(const hisui::Config&,
const AsyncWebMMuxerParametersForLayout&);
void setUp() override;
void run() override;
void cleanUp() override;
private:
void muxFinalize() override;
void appendAudio(hisui::Frame) override;
void appendVideo(hisui::Frame) override;
std::unique_ptr<hisui::webm::output::Context> m_context;
bool has_preferred;
hisui::Config m_config;
std::vector<hisui::ArchiveItem> m_audio_archives;
std::vector<hisui::ArchiveItem> m_normal_archives;
std::vector<hisui::ArchiveItem> m_preferred_archives;
double m_duration;
std::size_t m_normal_archive_size;
};
} // namespace hisui::muxer
| 24.423729 | 72 | 0.754337 | kounoike |
e743b74123793aa76809f07861c8e23d68a367cb | 733 | cpp | C++ | CodeForces/Rating 1200/982A.Row.cpp | GouravKhunger/Competetive-Programming | 0c50807242233c267c1a170150a88bd8b16ceb05 | [
"MIT"
] | 1 | 2020-11-23T11:47:01.000Z | 2020-11-23T11:47:01.000Z | CodeForces/Rating 1200/982A.Row.cpp | GouravKhunger/Competetive-Programming | 0c50807242233c267c1a170150a88bd8b16ceb05 | [
"MIT"
] | null | null | null | CodeForces/Rating 1200/982A.Row.cpp | GouravKhunger/Competetive-Programming | 0c50807242233c267c1a170150a88bd8b16ceb05 | [
"MIT"
] | null | null | null | // https://codeforces.com/problemset/problem/982/A
// Row
// File Creation Date: 2-Dec-2020
// Author: Gourav(https://github.com/GouravKhunger)
#include <bits/stdc++.h>
using namespace std;
#define FIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int main() {
FIO;
int t;
cin>>t;
string n;
cin>>n;
auto one = n.find("11");
auto zero = n.find("000");
if(one!=string::npos||zero!=string::npos){
cout<<"NO";
} else {
if(n=="0")cout<<"NO";
else if(n=="1") cout<<"YES";
else if(n.substr(n.length()-2, n.length()-1)=="00")cout<<"NO";
else if(n.substr(0, 2)=="00")cout<<"NO";
else cout << "YES";
}
return 0;
} | 25.275862 | 71 | 0.527967 | GouravKhunger |
e7454bbf6d0a7a84493d557527012dd560140a1a | 3,219 | hpp | C++ | include/gridtools/stencil_composition/level.hpp | mbianco/gridtools | 1abef09881a31495a3d02a15d3fe21620c6dde98 | [
"BSD-3-Clause"
] | null | null | null | include/gridtools/stencil_composition/level.hpp | mbianco/gridtools | 1abef09881a31495a3d02a15d3fe21620c6dde98 | [
"BSD-3-Clause"
] | null | null | null | include/gridtools/stencil_composition/level.hpp | mbianco/gridtools | 1abef09881a31495a3d02a15d3fe21620c6dde98 | [
"BSD-3-Clause"
] | 1 | 2019-06-14T10:35:50.000Z | 2019-06-14T10:35:50.000Z | /*
* GridTools
*
* Copyright (c) 2014-2019, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
#include <type_traits>
#include "../common/defs.hpp"
#include "../meta/macros.hpp"
namespace gridtools {
namespace _impl {
constexpr int_t calc_level_index(uint_t splitter, int_t offset, int_t limit) {
return limit * (2 * (int_t)splitter + 1) + offset - (offset >= 0);
}
constexpr int_t get_splitter_from_index(int_t index, int_t limit) { return index / (2 * limit); }
constexpr int_t get_offset_from_index(int_t index, int_t limit) {
return index % (2 * limit) - limit + (index % (2 * limit) >= limit);
}
} // namespace _impl
/**
* @struct Level
* Structure defining an axis position relative to a splitter
*/
template <uint_t Splitter, int_t Offset, int_t OffsetLimit>
struct level {
// check offset and splitter value ranges
// (note that non negative splitter values simplify the index computation)
GT_STATIC_ASSERT(Splitter >= 0 && Offset != 0, "check offset and splitter value ranges \n\
(note that non negative splitter values simplify the index computation)");
GT_STATIC_ASSERT(-OffsetLimit <= Offset && Offset <= OffsetLimit, "check offset and splitter value ranges \n\
(note that non negative splitter values simplify the index computation)");
// define splitter, level offset and offset limit
static constexpr uint_t splitter = Splitter;
static constexpr int_t offset = Offset;
static constexpr int_t offset_limit = OffsetLimit;
using type = level;
};
/**
* @struct is_level
* Trait returning true it the template parameter is a level
*/
template <class>
struct is_level : std::false_type {};
template <uint_t Splitter, int_t Offset, int_t OffsetLimit>
struct is_level<level<Splitter, Offset, OffsetLimit>> : std::true_type {};
template <int_t Value, int_t OffsetLimit>
struct level_index {
static constexpr int_t value = Value;
static constexpr int_t offset_limit = OffsetLimit;
using type = level_index;
using next = level_index<Value + 1, OffsetLimit>;
using prior = level_index<Value - 1, OffsetLimit>;
};
template <class>
struct is_level_index : std::false_type {};
template <int_t Index, int_t OffsetLimit>
struct is_level_index<level_index<Index, OffsetLimit>> : std::true_type {};
template <class Level>
GT_META_DEFINE_ALIAS(level_to_index,
level_index,
(_impl::calc_level_index(Level::splitter, Level::offset, Level::offset_limit), Level::offset_limit));
/**
* @struct index_to_level
* Meta function converting a unique index back into a level
*/
template <class Index>
GT_META_DEFINE_ALIAS(index_to_level,
level,
(_impl::get_splitter_from_index(Index::value, Index::offset_limit),
_impl::get_offset_from_index(Index::value, Index::offset_limit),
Index::offset_limit));
} // namespace gridtools
| 35.373626 | 117 | 0.664181 | mbianco |
e7487d067cf6a536c32587a63bb291888da663e4 | 1,231 | cpp | C++ | ThrowThingsTemplate/Vixen/source/vgraphics/vix_glcamera3d.cpp | eric-fonseca/Throw-Things-at-Monsters | c92d9cd4e244d4ddb54b74e8508cba2b6408abb7 | [
"MIT"
] | null | null | null | ThrowThingsTemplate/Vixen/source/vgraphics/vix_glcamera3d.cpp | eric-fonseca/Throw-Things-at-Monsters | c92d9cd4e244d4ddb54b74e8508cba2b6408abb7 | [
"MIT"
] | null | null | null | ThrowThingsTemplate/Vixen/source/vgraphics/vix_glcamera3d.cpp | eric-fonseca/Throw-Things-at-Monsters | c92d9cd4e244d4ddb54b74e8508cba2b6408abb7 | [
"MIT"
] | null | null | null | #include <vix_glcamera3d.h>
namespace Vixen {
GLCamera3D::GLCamera3D()
: m_aspect(0.0f),
m_fov(0.0f),
m_znear(1.0f),
m_zfar(1000.0f),
m_position(0.0f),
m_target(0.0f, 0.0f, -1.0f),
m_up(0.0f, 1.0f, 0.0f)
{
}
void GLCamera3D::SetPerspective(float aspect, float fov, float znear, float zfar)
{
/*should probably check for stupid fov ranges*/
m_aspect = aspect;
m_fov = fov;
m_znear = znear;
m_zfar = zfar;
m_projection = glm::perspective(m_fov, m_aspect, m_znear, m_zfar);
}
void GLCamera3D::SetView(const Vec3& pos, const Vec3& target, const Vec3& up)
{
m_position = pos;
m_target = target;
m_up = up;
m_view = glm::lookAt(m_position, m_target, m_up);
}
void GLCamera3D::Move(C3D_DIRECTION cam_dir)
{
switch (cam_dir)
{
case Vixen::C3D_DIRECTION::UP:
break;
case Vixen::C3D_DIRECTION::DOWN:
break;
case Vixen::C3D_DIRECTION::LEFT:
break;
case Vixen::C3D_DIRECTION::RIGHT:
break;
case Vixen::C3D_DIRECTION::FORWARD:
break;
case Vixen::C3D_DIRECTION::BACKWARD:
break;
default:
break;
}
}
const Mat4& GLCamera3D::Projection() const
{
return m_projection;
}
const Mat4& GLCamera3D::View() const
{
return m_view;
}
} | 18.373134 | 82 | 0.662063 | eric-fonseca |
e74d07804d273033c242b5c9b5f1adbc42f55740 | 471 | hpp | C++ | Source/Engine/src/include/SceneData/Background.hpp | DatZach/Swift | b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7 | [
"MIT"
] | null | null | null | Source/Engine/src/include/SceneData/Background.hpp | DatZach/Swift | b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7 | [
"MIT"
] | null | null | null | Source/Engine/src/include/SceneData/Background.hpp | DatZach/Swift | b0c6f9c87e8c8dfe8a19dedc4dd57081fa5cdef7 | [
"MIT"
] | 1 | 2021-10-30T20:43:01.000Z | 2021-10-30T20:43:01.000Z | /*
* background.hpp
* Scene Data Background
*/
#ifndef __SCENE_DATA_BACKGROUND_HPP
#define __SCENE_DATA_BACKGROUND_HPP
#include <string>
#include <Video/Color.hpp>
#include <SceneData/Section.hpp>
#define SD_TAG_BACKGROUND SD_TAG_VALUE('B', 'K', 'G', 'D')
namespace SceneData
{
class Background : public ISection
{
public:
Video::Color color;
std::string textureName;
public:
Background();
virtual void Read(Util::Stream* stream);
};
}
#endif
| 15.193548 | 60 | 0.713376 | DatZach |
e750b7de03729d87d1f6a7cb78f4d7274901b8ee | 2,380 | cpp | C++ | CogEye/App/src/CogQueue.cpp | Bounty556/CogEye | c4f678cad9542f7d595510849779ffb46f26e016 | [
"Apache-2.0"
] | null | null | null | CogEye/App/src/CogQueue.cpp | Bounty556/CogEye | c4f678cad9542f7d595510849779ffb46f26e016 | [
"Apache-2.0"
] | null | null | null | CogEye/App/src/CogQueue.cpp | Bounty556/CogEye | c4f678cad9542f7d595510849779ffb46f26e016 | [
"Apache-2.0"
] | null | null | null | #include "CogQueue.h"
#include <UI/UISprite.h>
CogQueue::CogQueue(Soul::FontManager& fonts, Soul::TextureManager& textures, u32 smallCogs, u32 medCogs, u32 largeCogs) :
m_UI(),
m_Listener()
{
m_CogsLeft[0] = smallCogs;
m_CogsLeft[1] = medCogs;
m_CogsLeft[2] = largeCogs;
m_CogText[0] = PARTITION(Soul::UILabel, Soul::String::IntToString(smallCogs).GetCString(), *fonts.RequestFont("res/Fonts/m5x7.ttf"));
m_CogText[1] = PARTITION(Soul::UILabel, Soul::String::IntToString(medCogs).GetCString(), *fonts.RequestFont("res/Fonts/m5x7.ttf"));
m_CogText[2] = PARTITION(Soul::UILabel, Soul::String::IntToString(largeCogs).GetCString(), *fonts.RequestFont("res/Fonts/m5x7.ttf"));
Soul::UISprite* small = PARTITION(Soul::UISprite, *textures.RequestTexture("res/Sprites/SmallCog1.png"), 64, 64);
Soul::UISprite* medium = PARTITION(Soul::UISprite, *textures.RequestTexture("res/Sprites/MediumCog1.png"), 64, 64);
Soul::UISprite* large = PARTITION(Soul::UISprite, *textures.RequestTexture("res/Sprites/LargeCog1.png"), 64, 64);
m_CogText[0]->setPosition(50, 25);
small->setPosition(75, 25);
m_CogText[1]->setPosition(150, 25);
medium->setPosition(175, 25);
m_CogText[2]->setPosition(250, 25);
large->setPosition(275, 25);
m_UI.AddUIComponent(m_CogText[0]);
m_UI.AddUIComponent(m_CogText[1]);
m_UI.AddUIComponent(m_CogText[2]);
m_UI.AddUIComponent(small);
m_UI.AddUIComponent(medium);
m_UI.AddUIComponent(large);
m_Listener.Subscribe("PlacedCog",
[&](void* data)
{
u32 size = *(Cog::Size*)data;
m_CogsLeft[size]--;
m_CogText[size]->SetText(Soul::String::IntToString(m_CogsLeft[size]).GetCString());
Soul::MemoryManager::FreeMemory((Cog::Size*)data);
});
}
CogQueue::CogQueue(CogQueue&& other) noexcept :
m_UI(std::move(other.m_UI))
{
for (u32 i = 0; i < 3; i++)
{
m_CogsLeft[i] = other.m_CogsLeft[i];
m_CogText[i] = other.m_CogText[i];
other.m_CogText[i] = nullptr;
}
}
CogQueue& CogQueue::operator=(CogQueue&& other) noexcept
{
m_UI = std::move(other.m_UI);
for (u32 i = 0; i < 3; i++)
{
m_CogsLeft[i] = other.m_CogsLeft[i];
m_CogText[i] = other.m_CogText[i];
other.m_CogText[i] = nullptr;
}
return *this;
}
void CogQueue::Update(f32 dt)
{
m_UI.Update(dt);
}
void CogQueue::Draw(sf::RenderStates states) const
{
m_UI.Draw(states);
}
bool CogQueue::CanPlace(Cog::Size cogSize)
{
return m_CogsLeft[(u32)cogSize] > 0;
} | 29.75 | 134 | 0.706303 | Bounty556 |
e7535025071ac0e1457f54d03f844c224dbc716f | 3,881 | cpp | C++ | 03_FreeRTOS/user/RCC.cpp | AVilezhaninov/NUCLEO-H753ZI | cc60a653814becfee3dce07f3f8ef6adba7698a0 | [
"MIT"
] | null | null | null | 03_FreeRTOS/user/RCC.cpp | AVilezhaninov/NUCLEO-H753ZI | cc60a653814becfee3dce07f3f8ef6adba7698a0 | [
"MIT"
] | null | null | null | 03_FreeRTOS/user/RCC.cpp | AVilezhaninov/NUCLEO-H753ZI | cc60a653814becfee3dce07f3f8ef6adba7698a0 | [
"MIT"
] | null | null | null | #include "user\RCC.h"
namespace rcc {
/******************************************************************************/
/* Private definitions ********************************************************/
/******************************************************************************/
#define DIVN1 480u
#define DIVP1 2u
#define DIVQ1 2u
#define DIVR1 2u
#define HSE_STARTUP_TIMEOUT 0x05000u
/******************************************************************************/
/* Exported functions *********************************************************/
/******************************************************************************/
void InitSystemClock() {
uint32_t StartUpCounter = 0u;
uint32_t HSEStatus = 0u;
/* Select voltage scaling 1 */
PWR->D3CR |= PWR_D3CR_VOS;
/* Enable overdrive */
SYSCFG->PWRCR |= SYSCFG_PWRCR_ODEN;
/* Wait till Vos ready */
while ((PWR->D3CR & PWR_D3CR_VOSRDY) != PWR_D3CR_VOSRDY) {
;
}
/* Enable HSE */
RCC->CR |= RCC_CR_HSEON;
/* Wait till HSE is ready and if timeout is reached exit */
while ((HSEStatus == 0u) && (StartUpCounter < HSE_STARTUP_TIMEOUT)) {
HSEStatus = RCC->CR & RCC_CR_HSERDY;
++StartUpCounter;
}
if (HSEStatus == RCC_CR_HSERDY) {
/* Set prescaler for PLL1 */
RCC->PLLCKSELR &= ~RCC_PLLCKSELR_DIVM1;
RCC->PLLCKSELR |= RCC_PLLCKSELR_DIVM1_2;
/* Select HSE as PLL clock */
RCC->PLLCKSELR |= RCC_PLLCKSELR_PLLSRC_HSE;
/* Set PLL dividers */
RCC->PLL1DIVR = DIVN1 - 1u;
RCC->PLL1DIVR |= (DIVP1 - 1u) << RCC_PLL1DIVR_P1_Pos;
RCC->PLL1DIVR |= (DIVQ1 - 1u) << RCC_PLL1DIVR_Q1_Pos;
RCC->PLL1DIVR |= (DIVR1 - 1u) << RCC_PLL1DIVR_R1_Pos;
/* Enable PLL divider output */
RCC->PLLCFGR |= RCC_PLLCFGR_DIVP1EN;
/* Enable PLL1 */
RCC->CR |= RCC_CR_PLL1ON;
/* Wait till PLL1 is ready */
while ((RCC->CR & RCC_CR_PLLRDY) == 0u) {
;
}
/* Set flash latency */
FLASH->ACR &= ~FLASH_ACR_LATENCY;
FLASH->ACR |= FLASH_ACR_LATENCY_4WS;
/* Set D1 domain AHB prescaler */
RCC->D1CFGR |= RCC_D1CFGR_HPRE_DIV2;
/* Set D1 domain APB3 prescaler */
RCC->D1CFGR |= RCC_D1CFGR_D1PPRE_DIV2;
/* Set D2 domain APB1 prescaler */
RCC->D2CFGR |= RCC_D2CFGR_D2PPRE1_DIV2;
/* Set D2 domain APB2 prescaler */
RCC->D2CFGR |= RCC_D2CFGR_D2PPRE2_DIV2;
/* Set D3 domain APB4 prescaler */
RCC->D3CFGR |= RCC_D3CFGR_D3PPRE_DIV2;
/* Select PLL1 as system clock source */
RCC->CFGR |= RCC_CFGR_SW_PLL1;
/* Wait till PLL1 is used as system clock source */
while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL1) {
;
}
SystemCoreClockUpdate();
} else {
/* If HSE fails to start-up, the application will have wrong clock
configuration. User can add here some code to deal with this error */
while (1) {
;
}
}
}
/**
* Get SYSCLK frequency
* @return SYSCLK frequency
*/
uint32_t GetSysclkFrequency() {
return SystemCoreClock;
}
/**
* Get HCLK frequency
* @return HCLK frequency
*/
uint32_t GetHclkFrequency() {
return GetSysclkFrequency() >>
((D1CorePrescTable[(RCC->D1CFGR & RCC_D1CFGR_HPRE) >>
RCC_D1CFGR_HPRE_Pos]) & 0x1FU);
}
/**
* Get PCLK1 frequency
* @return PCLK1 frequency
*/
uint32_t GetPclk1Frequency() {
return GetHclkFrequency() >>
((D1CorePrescTable[(RCC->D2CFGR & RCC_D2CFGR_D2PPRE1) >>
RCC_D2CFGR_D2PPRE1_Pos]) & 0x1FU);
}
/**
* Get PCLK2 frequency
* @return PCLK2 frequency
*/
uint32_t GetPclk2Frequency() {
return GetHclkFrequency() >>
((D1CorePrescTable[(RCC->D2CFGR & RCC_D2CFGR_D2PPRE2) >>
RCC_D2CFGR_D2PPRE2_Pos]) & 0x1FU);
}
/**
* Blocking delay
* @param delay
*/
void StupidDelay(volatile uint32_t delay) {
while (delay-- > 0u) {
;
}
}
} /* namespace rcc */
| 26.222973 | 80 | 0.55965 | AVilezhaninov |
e7546c697244d3940b24b00b6e0d9faf5b6f670c | 1,188 | cpp | C++ | Aurora-lwip-sgx/Enclave/smx/randombytes.cpp | Maxul/Aurora | c4315574f85b04f8575e7ff14bc251317b9ca5db | [
"MIT"
] | 8 | 2020-03-16T06:34:49.000Z | 2021-12-06T01:50:54.000Z | Aurora-lwip-sgx/Enclave/smx/randombytes.cpp | Maxul/Aurora | c4315574f85b04f8575e7ff14bc251317b9ca5db | [
"MIT"
] | null | null | null | Aurora-lwip-sgx/Enclave/smx/randombytes.cpp | Maxul/Aurora | c4315574f85b04f8575e7ff14bc251317b9ca5db | [
"MIT"
] | 1 | 2021-12-06T01:50:56.000Z | 2021-12-06T01:50:56.000Z | #include <stdint.h>
#include <stdlib.h>
#include <sgx_trts.h>
#include "core.h"
#include "randombytes.h"
#include "utils.h"
#define RDRAND_RETRY_LOOPS 10
static inline uint8_t rdrand_32(uint32_t *rand)
{
uint8_t carry;
__asm__ __volatile__(
".byte 0x0f; .byte 0xc7; .byte 0xf0; setc %1"
: "=a" (*rand), "=qm" (carry));
return carry;
}
int get_random_number_32(uint32_t *rand)
{
int i;
/* Perform a loop call until RDRAND succeeds or returns failure. */
for (i = 0; i < RDRAND_RETRY_LOOPS; i++) {
if (rdrand_32(rand))
return 0;
}
return -1;
}
void
randombytes_buf(void * const buf, const size_t size)
{
unsigned char *p = (unsigned char *) buf;
sgx_read_rand(p, size);
}
uint32_t
randombytes_uniform(const uint32_t upper_bound)
{
uint32_t min;
uint32_t r;
if (upper_bound < 2) {
return 0;
}
min = (1U + ~upper_bound) % upper_bound; /* = 2**32 mod upper_bound */
do {
//r = randombytes_random();
get_random_number_32(&r);
} while (r < min);
/* r is now clamped to a set whose size mod upper_bound == 0
* the worst case (2**31+1) requires ~ 2 attempts */
return r % upper_bound;
}
| 19.47541 | 74 | 0.63468 | Maxul |
e7579709126b41001fd74c4614acd937040ae635 | 6,565 | cpp | C++ | src/moveitPlugin/arm_action_server.cpp | jpmerc/perception3d | f0eef9271afdf9b9100448b88ae1921a97bbba88 | [
"BSD-3-Clause"
] | null | null | null | src/moveitPlugin/arm_action_server.cpp | jpmerc/perception3d | f0eef9271afdf9b9100448b88ae1921a97bbba88 | [
"BSD-3-Clause"
] | null | null | null | src/moveitPlugin/arm_action_server.cpp | jpmerc/perception3d | f0eef9271afdf9b9100448b88ae1921a97bbba88 | [
"BSD-3-Clause"
] | null | null | null | #include <ros/ros.h>
#include <actionlib/server/simple_action_server.h>
#include <control_msgs/FollowJointTrajectoryAction.h>
#include <control_msgs/JointTolerance.h>
//#include <jaco_msgs/JointVelocity.h>
//#include <jaco_msgs/JointAngles.h>
//#include <jaco_msgs/ArmJointAnglesAction.h>
#include <trajectory_msgs/JointTrajectoryPoint.h>
#include <actionlib/client/simple_action_client.h>
#include <angles/angles.h>
ros::Publisher pub;
ros::Publisher pubTest;
float PI = 3.14159265358979323846;
/** \addtogroup container_ops_grp
* @{ */
/** Modifies the given angle to translate it into the [0,2pi[ range.
* \note Take care of not instancing this template for integer numbers, since it only works for float, double and long double.
* \sa wrapToPi, wrapTo2Pi, unwrap2PiSequence
*/
template <class T>
inline void wrapTo2PiInPlace(T &a)
{
bool was_neg = a<0;
a = fmod(a, static_cast<T>(2.0*PI) );
if (was_neg) a+=static_cast<T>(2.0*PI);
}
/** Modifies the given angle to translate it into the [0,2pi[ range.
* \note Take care of not instancing this template for integer numbers, since it only works for float, double and long double.
* \sa wrapToPi, wrapTo2Pi, unwrap2PiSequence
*/
template <class T>
inline T wrapTo2Pi(T a)
{
wrapTo2PiInPlace(a);
return a;
}
/** Modifies the given angle to translate it into the ]-pi,pi] range.
* \note Take care of not instancing this template for integer numbers, since it only works for float, double and long double.
* \sa wrapTo2Pi, wrapToPiInPlace, unwrap2PiSequence
*/
template <class T>
inline T wrapToPi(T a)
{
return wrapTo2Pi( a + static_cast<T>(PI) )-static_cast<T>(PI);
}
void callBackVelocity(const control_msgs::FollowJointTrajectoryGoalConstPtr& p_input, actionlib::SimpleActionServer<control_msgs::FollowJointTrajectoryAction>* p_server)
{
std::cout << "Message received" << std::endl;
std::vector<std::string> jointVector(p_input->trajectory.joint_names);
std::vector<trajectory_msgs::JointTrajectoryPoint> pointVector(p_input->trajectory.points);
//debug////////////////////////////////////////////////////////
for(int i = 0; i < jointVector.size(); i++)
{
std::cout << jointVector[i] << std::endl;
}
std::cout << "JointTrajectorySize == " << pointVector.size() << std::endl;
//////////////////////////////////////////////////////////////////
ros::Duration memDuration(0);
for(int i = 0; i < pointVector.size(); i++)
{
jaco_msgs::JointVelocity sendedMessage;
std::vector<double> velocitiesVec(p_input->trajectory.points[i].velocities);
//debug/////////////////////////////
for(int j = 0; j < velocitiesVec.size(); j++)
{
std::cout << "velocities : " << velocitiesVec[j] << std::endl;
}
std::cout << "Duration : " << p_input->trajectory.points[i].time_from_start << std::endl;
////////////////////////////////////////////////////////////////////////////////////////////
ros::Duration duration = p_input->trajectory.points[i].time_from_start;
ros::Duration diff = (duration - memDuration);
memDuration = p_input->trajectory.points[i].time_from_start;
ros::Time timeToSend = ros::Time::now();
timeToSend += diff;
std::cout << "TimeToSend == " << timeToSend << std::endl;
std::cout << "Diff ==" << diff << std::endl;
sendedMessage.joint1 = (velocitiesVec[0] * 180)/PI;
sendedMessage.joint2 = (velocitiesVec[1] * 180)/PI;
sendedMessage.joint3 = (velocitiesVec[2] * 180)/PI;
sendedMessage.joint4 = (velocitiesVec[3] * 180)/PI;
sendedMessage.joint5 = (velocitiesVec[4] * 180)/PI;
sendedMessage.joint6 = (velocitiesVec[5] * 180)/PI;
while(ros::Time::now() < timeToSend)
{
pubTest.publish(sendedMessage);
pub.publish(sendedMessage);
}
}
//might send it earlier
std::vector<double> position((p_input->trajectory.points[(pointVector.size())-1]).positions);
for(int i = 0; i < position.size(); i++)
{
std::cout << "Position [" << i << "] == " << position[i] << std::endl;
}
control_msgs::FollowJointTrajectoryResult result;
p_server->setSucceeded(result);
}
void callBackAngles(const control_msgs::FollowJointTrajectoryGoalConstPtr& p_input, actionlib::SimpleActionServer<control_msgs::FollowJointTrajectoryAction>* p_server)
{
actionlib::SimpleActionClient<jaco_msgs::ArmJointAnglesAction> ac("/jaco_arm_driver/joint_angles/arm_joint_angles", true);
std::vector<trajectory_msgs::JointTrajectoryPoint> pointVector(p_input->trajectory.points);
std::cout << "THE SIZE OF THE TRAJECTORY IS " << pointVector.size() << " POINTS" << std::endl;
for(int i = 0; i < pointVector.size(); i++)
{
std::vector<double> position(p_input->trajectory.points[i].positions);
jaco_msgs::ArmJointAnglesGoal sendPosition;
sendPosition.angles.joint1 = position[0];
sendPosition.angles.joint2 = position[1];
sendPosition.angles.joint3 = position[2];
sendPosition.angles.joint4 = position[3];
sendPosition.angles.joint5 = position[4];
sendPosition.angles.joint6 = position[5];
ac.sendGoal(sendPosition);
//debug
std::cout << "Position1 == " << position[0] << std::endl;
std::cout << "Position2 == " << position[1] << std::endl;
std::cout << "Position3 == " << position[2] << std::endl;
std::cout << "Position4 == " << position[3] << std::endl;
std::cout << "Position5 == " << position[4] << std::endl;
std::cout << "Position6 == " << position[5] << std::endl;
std::cout << "===============================" << std::endl;
/////////////////////////////////////////////////////////////
ac.waitForResult(ros::Duration(1.0));
}
control_msgs::FollowJointTrajectoryResult result;
p_server->setSucceeded(result);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "arm_controller");
ros::NodeHandle nh;
pub = nh.advertise<jaco_msgs::JointVelocity>("jaco_arm_driver/in/joint_velocity",1);
pubTest = nh.advertise<jaco_msgs::JointVelocity>("/jaco_arm_driver/in/joint_velocity_test",1);
actionlib::SimpleActionServer<control_msgs::FollowJointTrajectoryAction>as(nh, "arm/arm_joint_angles",boost::bind(&callBackAngles,_1, &as),false);
as.start();
while(ros::ok())
{
ros::spin();
}
return 0;
}
| 34.73545 | 169 | 0.621325 | jpmerc |
e758d0344fcfddfb9d6950db440615cc1b820b6f | 5,948 | cpp | C++ | plugin_III/game_III/CGlass.cpp | gta-chaos-mod/plugin-sdk | e3bf176337774a2afc797a47825f81adde78e899 | [
"Zlib"
] | 368 | 2015-01-01T21:42:00.000Z | 2022-03-29T06:22:22.000Z | plugin_III/game_III/CGlass.cpp | SteepCheat/plugin-sdk | a17c5d933cb8b06e4959b370092828a6a7aa00ef | [
"Zlib"
] | 89 | 2016-05-08T06:42:36.000Z | 2022-03-29T06:49:09.000Z | plugin_III/game_III/CGlass.cpp | SteepCheat/plugin-sdk | a17c5d933cb8b06e4959b370092828a6a7aa00ef | [
"Zlib"
] | 179 | 2015-02-03T23:41:17.000Z | 2022-03-26T08:27:16.000Z | /*
Plugin-SDK (Grand Theft Auto 3) source file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "CGlass.h"
PLUGIN_SOURCE_FILE
PLUGIN_VARIABLE CFallingGlassPane(&CGlass::aGlassPanes)[45] = *reinterpret_cast<CFallingGlassPane(*)[45]>(GLOBAL_ADDRESS_BY_VERSION(0x6EE480, 0x6EE480, 0x6FE5C0));
PLUGIN_VARIABLE CEntity *(&CGlass::apEntitiesToBeRendered)[32] = *reinterpret_cast<CEntity *(*)[32]>(GLOBAL_ADDRESS_BY_VERSION(0x6FA8E0, 0x6FA8E0, 0x70AA20));
PLUGIN_VARIABLE unsigned int &CGlass::NumGlassEntities = *reinterpret_cast<unsigned int *>(GLOBAL_ADDRESS_BY_VERSION(0x885B5C, 0x885B0C, 0x895C4C));
int addrof(CGlass::AskForObjectToBeRenderedInGlass) = ADDRESS_BY_VERSION(0x5033F0, 0x5034D0, 0x503460);
int gaddrof(CGlass::AskForObjectToBeRenderedInGlass) = GLOBAL_ADDRESS_BY_VERSION(0x5033F0, 0x5034D0, 0x503460);
void CGlass::AskForObjectToBeRenderedInGlass(CEntity *entity) {
plugin::CallDynGlobal<CEntity *>(gaddrof(CGlass::AskForObjectToBeRenderedInGlass), entity);
}
int addrof(CGlass::CalcAlphaWithNormal) = ADDRESS_BY_VERSION(0x503C90, 0x503D70, 0x503D00);
int gaddrof(CGlass::CalcAlphaWithNormal) = GLOBAL_ADDRESS_BY_VERSION(0x503C90, 0x503D70, 0x503D00);
int CGlass::CalcAlphaWithNormal(CVector *normal) {
return plugin::CallAndReturnDynGlobal<int, CVector *>(gaddrof(CGlass::CalcAlphaWithNormal), normal);
}
int addrof(CGlass::FindFreePane) = ADDRESS_BY_VERSION(0x502490, 0x502570, 0x502500);
int gaddrof(CGlass::FindFreePane) = GLOBAL_ADDRESS_BY_VERSION(0x502490, 0x502570, 0x502500);
CFallingGlassPane *CGlass::FindFreePane() {
return plugin::CallAndReturnDynGlobal<CFallingGlassPane *>(gaddrof(CGlass::FindFreePane));
}
int addrof(CGlass::GeneratePanesForWindow) = ADDRESS_BY_VERSION(0x502AC0, 0x502BA0, 0x502B30);
int gaddrof(CGlass::GeneratePanesForWindow) = GLOBAL_ADDRESS_BY_VERSION(0x502AC0, 0x502BA0, 0x502B30);
void CGlass::GeneratePanesForWindow(unsigned int type, CVector pos, CVector at, CVector right, CVector speed, CVector point, float moveSpeed, bool cracked, bool explosion) {
plugin::CallDynGlobal<unsigned int, CVector, CVector, CVector, CVector, CVector, float, bool, bool>(gaddrof(CGlass::GeneratePanesForWindow), type, pos, at, right, speed, point, moveSpeed, cracked, explosion);
}
int addrof(CGlass::Init) = ADDRESS_BY_VERSION(0x501F20, 0x502000, 0x501F90);
int gaddrof(CGlass::Init) = GLOBAL_ADDRESS_BY_VERSION(0x501F20, 0x502000, 0x501F90);
void CGlass::Init() {
plugin::CallDynGlobal(gaddrof(CGlass::Init));
}
int addrof(CGlass::Render) = ADDRESS_BY_VERSION(0x502350, 0x502430, 0x5023C0);
int gaddrof(CGlass::Render) = GLOBAL_ADDRESS_BY_VERSION(0x502350, 0x502430, 0x5023C0);
void CGlass::Render() {
plugin::CallDynGlobal(gaddrof(CGlass::Render));
}
int addrof(CGlass::RenderEntityInGlass) = ADDRESS_BY_VERSION(0x503420, 0x503500, 0x503490);
int gaddrof(CGlass::RenderEntityInGlass) = GLOBAL_ADDRESS_BY_VERSION(0x503420, 0x503500, 0x503490);
void CGlass::RenderEntityInGlass(CEntity *entity) {
plugin::CallDynGlobal<CEntity *>(gaddrof(CGlass::RenderEntityInGlass), entity);
}
int addrof(CGlass::RenderHiLightPolys) = ADDRESS_BY_VERSION(0x503D60, 0x503E40, 0x503DD0);
int gaddrof(CGlass::RenderHiLightPolys) = GLOBAL_ADDRESS_BY_VERSION(0x503D60, 0x503E40, 0x503DD0);
void CGlass::RenderHiLightPolys() {
plugin::CallDynGlobal(gaddrof(CGlass::RenderHiLightPolys));
}
int addrof(CGlass::RenderReflectionPolys) = ADDRESS_BY_VERSION(0x503E70, 0x503F50, 0x503EE0);
int gaddrof(CGlass::RenderReflectionPolys) = GLOBAL_ADDRESS_BY_VERSION(0x503E70, 0x503F50, 0x503EE0);
void CGlass::RenderReflectionPolys() {
plugin::CallDynGlobal(gaddrof(CGlass::RenderReflectionPolys));
}
int addrof(CGlass::RenderShatteredPolys) = ADDRESS_BY_VERSION(0x503DE0, 0x503EC0, 0x503E50);
int gaddrof(CGlass::RenderShatteredPolys) = GLOBAL_ADDRESS_BY_VERSION(0x503DE0, 0x503EC0, 0x503E50);
void CGlass::RenderShatteredPolys() {
plugin::CallDynGlobal(gaddrof(CGlass::RenderShatteredPolys));
}
int addrof(CGlass::Update) = ADDRESS_BY_VERSION(0x502050, 0x502130, 0x5020C0);
int gaddrof(CGlass::Update) = GLOBAL_ADDRESS_BY_VERSION(0x502050, 0x502130, 0x5020C0);
void CGlass::Update() {
plugin::CallDynGlobal(gaddrof(CGlass::Update));
}
int addrof(CGlass::WasGlassHitByBullet) = ADDRESS_BY_VERSION(0x504670, 0x504750, 0x5046E0);
int gaddrof(CGlass::WasGlassHitByBullet) = GLOBAL_ADDRESS_BY_VERSION(0x504670, 0x504750, 0x5046E0);
void CGlass::WasGlassHitByBullet(CEntity *entity, CVector point) {
plugin::CallDynGlobal<CEntity *, CVector>(gaddrof(CGlass::WasGlassHitByBullet), entity, point);
}
int addrof(CGlass::WindowRespondsToCollision) = ADDRESS_BY_VERSION(0x503F10, 0x503FF0, 0x503F80);
int gaddrof(CGlass::WindowRespondsToCollision) = GLOBAL_ADDRESS_BY_VERSION(0x503F10, 0x503FF0, 0x503F80);
void CGlass::WindowRespondsToCollision(CEntity *entity, float amount, CVector speed, CVector point, bool explosion) {
plugin::CallDynGlobal<CEntity *, float, CVector, CVector, bool>(gaddrof(CGlass::WindowRespondsToCollision), entity, amount, speed, point, explosion);
}
int addrof(CGlass::WindowRespondsToExplosion) = ADDRESS_BY_VERSION(0x504790, 0x504870, 0x504800);
int gaddrof(CGlass::WindowRespondsToExplosion) = GLOBAL_ADDRESS_BY_VERSION(0x504790, 0x504870, 0x504800);
void CGlass::WindowRespondsToExplosion(CEntity *entity, CVector point) {
plugin::CallDynGlobal<CEntity *, CVector>(gaddrof(CGlass::WindowRespondsToExplosion), entity, point);
}
int addrof(CGlass::WindowRespondsToSoftCollision) = ADDRESS_BY_VERSION(0x504630, 0x504710, 0x5046A0);
int gaddrof(CGlass::WindowRespondsToSoftCollision) = GLOBAL_ADDRESS_BY_VERSION(0x504630, 0x504710, 0x5046A0);
void CGlass::WindowRespondsToSoftCollision(CEntity *entity, float amount) {
plugin::CallDynGlobal<CEntity *, float>(gaddrof(CGlass::WindowRespondsToSoftCollision), entity, amount);
}
| 49.983193 | 212 | 0.797747 | gta-chaos-mod |
e76181e4c071ec31021d0a0d333358ff1149421a | 8,998 | hpp | C++ | include/oneapi/mkl/rng/detail/engine_impl.hpp | andrewtbarker/oneMKL | 722f6c51b528a2bc09bf549b1097f7d8fdc37826 | [
"Apache-2.0"
] | null | null | null | include/oneapi/mkl/rng/detail/engine_impl.hpp | andrewtbarker/oneMKL | 722f6c51b528a2bc09bf549b1097f7d8fdc37826 | [
"Apache-2.0"
] | null | null | null | include/oneapi/mkl/rng/detail/engine_impl.hpp | andrewtbarker/oneMKL | 722f6c51b528a2bc09bf549b1097f7d8fdc37826 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright 2020-2021 Intel Corporation
*
* 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.
*
*
* SPDX-License-Identifier: Apache-2.0
*******************************************************************************/
#ifndef _ONEMKL_RNG_ENGINE_IMPL_HPP_
#define _ONEMKL_RNG_ENGINE_IMPL_HPP_
#include <cstdint>
#if __has_include(<sycl/sycl.hpp>)
#include <sycl/sycl.hpp>
#else
#include <CL/sycl.hpp>
#endif
#include "oneapi/mkl/detail/export.hpp"
#include "oneapi/mkl/detail/get_device_id.hpp"
#include "oneapi/mkl/rng/distributions.hpp"
#include "oneapi/mkl/types.hpp"
namespace oneapi {
namespace mkl {
namespace rng {
namespace detail {
class engine_impl {
public:
engine_impl(sycl::queue queue) : queue_(queue) {}
engine_impl(const engine_impl& other) : queue_(other.queue_) {}
// Buffers API
virtual void generate(const uniform<float, uniform_method::standard>& distr, std::int64_t n,
sycl::buffer<float, 1>& r) = 0;
virtual void generate(const uniform<double, uniform_method::standard>& distr, std::int64_t n,
sycl::buffer<double, 1>& r) = 0;
virtual void generate(const uniform<std::int32_t, uniform_method::standard>& distr,
std::int64_t n, sycl::buffer<std::int32_t, 1>& r) = 0;
virtual void generate(const uniform<float, uniform_method::accurate>& distr, std::int64_t n,
sycl::buffer<float, 1>& r) = 0;
virtual void generate(const uniform<double, uniform_method::accurate>& distr, std::int64_t n,
sycl::buffer<double, 1>& r) = 0;
virtual void generate(const gaussian<float, gaussian_method::box_muller2>& distr,
std::int64_t n, sycl::buffer<float, 1>& r) = 0;
virtual void generate(const gaussian<double, gaussian_method::box_muller2>& distr,
std::int64_t n, sycl::buffer<double, 1>& r) = 0;
virtual void generate(const gaussian<float, gaussian_method::icdf>& distr, std::int64_t n,
sycl::buffer<float, 1>& r) = 0;
virtual void generate(const gaussian<double, gaussian_method::icdf>& distr, std::int64_t n,
sycl::buffer<double, 1>& r) = 0;
virtual void generate(const lognormal<float, lognormal_method::box_muller2>& distr,
std::int64_t n, sycl::buffer<float, 1>& r) = 0;
virtual void generate(const lognormal<double, lognormal_method::box_muller2>& distr,
std::int64_t n, sycl::buffer<double, 1>& r) = 0;
virtual void generate(const lognormal<float, lognormal_method::icdf>& distr, std::int64_t n,
sycl::buffer<float, 1>& r) = 0;
virtual void generate(const lognormal<double, lognormal_method::icdf>& distr, std::int64_t n,
sycl::buffer<double, 1>& r) = 0;
virtual void generate(const bernoulli<std::int32_t, bernoulli_method::icdf>& distr,
std::int64_t n, sycl::buffer<std::int32_t, 1>& r) = 0;
virtual void generate(const bernoulli<std::uint32_t, bernoulli_method::icdf>& distr,
std::int64_t n, sycl::buffer<std::uint32_t, 1>& r) = 0;
virtual void generate(const poisson<std::int32_t, poisson_method::gaussian_icdf_based>& distr,
std::int64_t n, sycl::buffer<std::int32_t, 1>& r) = 0;
virtual void generate(const poisson<std::uint32_t, poisson_method::gaussian_icdf_based>& distr,
std::int64_t n, sycl::buffer<std::uint32_t, 1>& r) = 0;
virtual void generate(const bits<std::uint32_t>& distr, std::int64_t n,
sycl::buffer<std::uint32_t, 1>& r) = 0;
// USM APIs
virtual sycl::event generate(const uniform<float, uniform_method::standard>& distr,
std::int64_t n, float* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const uniform<double, uniform_method::standard>& distr,
std::int64_t n, double* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const uniform<std::int32_t, uniform_method::standard>& distr,
std::int64_t n, std::int32_t* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const uniform<float, uniform_method::accurate>& distr,
std::int64_t n, float* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const uniform<double, uniform_method::accurate>& distr,
std::int64_t n, double* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const gaussian<float, gaussian_method::box_muller2>& distr,
std::int64_t n, float* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const gaussian<double, gaussian_method::box_muller2>& distr,
std::int64_t n, double* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const gaussian<float, gaussian_method::icdf>& distr,
std::int64_t n, float* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const gaussian<double, gaussian_method::icdf>& distr,
std::int64_t n, double* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const lognormal<float, lognormal_method::box_muller2>& distr,
std::int64_t n, float* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const lognormal<double, lognormal_method::box_muller2>& distr,
std::int64_t n, double* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const lognormal<float, lognormal_method::icdf>& distr,
std::int64_t n, float* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const lognormal<double, lognormal_method::icdf>& distr,
std::int64_t n, double* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const bernoulli<std::int32_t, bernoulli_method::icdf>& distr,
std::int64_t n, std::int32_t* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const bernoulli<std::uint32_t, bernoulli_method::icdf>& distr,
std::int64_t n, std::uint32_t* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(
const poisson<std::int32_t, poisson_method::gaussian_icdf_based>& distr, std::int64_t n,
std::int32_t* r, const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(
const poisson<std::uint32_t, poisson_method::gaussian_icdf_based>& distr, std::int64_t n,
std::uint32_t* r, const std::vector<sycl::event>& dependencies) = 0;
virtual sycl::event generate(const bits<std::uint32_t>& distr, std::int64_t n, std::uint32_t* r,
const std::vector<sycl::event>& dependencies) = 0;
virtual engine_impl* copy_state() = 0;
virtual void skip_ahead(std::uint64_t num_to_skip) = 0;
virtual void skip_ahead(std::initializer_list<std::uint64_t> num_to_skip) = 0;
virtual void leapfrog(std::uint64_t idx, std::uint64_t stride) = 0;
virtual ~engine_impl() {}
sycl::queue& get_queue() {
return queue_;
}
protected:
sycl::queue queue_;
};
} // namespace detail
} // namespace rng
} // namespace mkl
} // namespace oneapi
#endif //_ONEMKL_RNG_ENGINE_IMPL_HPP_
| 45.444444 | 100 | 0.589575 | andrewtbarker |
e76bd96ac07b3e42ccc24462b7460967a2050df3 | 29,040 | cpp | C++ | scenes/avion.cpp | nissmar/Paper_Plane_VCL | 04c51d57cac6772ffa7b39008ba4fc33d6a24610 | [
"MIT"
] | null | null | null | scenes/avion.cpp | nissmar/Paper_Plane_VCL | 04c51d57cac6772ffa7b39008ba4fc33d6a24610 | [
"MIT"
] | null | null | null | scenes/avion.cpp | nissmar/Paper_Plane_VCL | 04c51d57cac6772ffa7b39008ba4fc33d6a24610 | [
"MIT"
] | 1 | 2020-05-21T16:02:51.000Z | 2020-05-21T16:02:51.000Z | #include "avion.hpp"
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifdef SCENE_AVION
using namespace vcl;
static void set_gui(timer_basic& timer, plane_physics& pphy, camera_physics& cphy);
//avion
void init_phy_cam(plane_physics& pphy, camera_physics& cphy);
void physic_model(plane_physics& pphy, camera_physics& cphy, float dt);
vcl::hierarchy_mesh_drawable create_plane();
mesh create_propeller();
//arbres
float evaluate_terrain_z(float u, float v);
mesh create_terrain();
mesh create_cylinder(vec3 p2, vec3 p1);
mesh create_tree(std::vector<vcl::vec3>& branches_pos);
//NEW
bool collision(plane_physics& pphy, std::vector<vcl::vec3>& tree_position, std::vector<vcl::vec3> branches_pos);
vec3 evaluate_terrain(float u, float v);
mesh create_tree_foliage();
std::vector<vcl::vec3> branch_tip(vec3 p, float height, int nbBranch, int steps);
//mesh create_tree_foliage(float radius, float height, float z_offset);
std::vector<vcl::vec3> update_tree_position();
//skybox
mesh create_skybox();
void scene_model::setup_data(std::map<std::string, GLuint>& shaders, scene_structure& scene, gui_structure&)
{
//initialisation de la caméra et du modèle physique
init_phy_cam(pphy, cphy);
cphy.draw_skybox = true;
cphy.draw_tree_texture = false;
scene.camera.perspective.z_far = 2000.0f;
scene.camera.translation = cphy.p;
scene.camera.orientation = cphy.r;
//creation de l'avion
plane = create_plane();
plane.set_shader_for_all_elements(shaders["mesh"]);
plane_texture_id = create_texture_gpu(image_load_png("scenes/textures/plane.png"));
propeller = create_propeller();
prop_active = false;
//creation terrain
terrain = create_terrain();
terrain.uniform.shading.specular = 0.0f; // non-specular terrain material
texture_id = create_texture_gpu(image_load_png("scenes/textures/grass.png"));
//création des arbres
tree_position = update_tree_position();
trunk = create_tree(branches_pos);
trunk.uniform.color = { 0.38f, 0.2f, 0.07f };
trunk.uniform.shading.specular = 0.0f;
trunk.uniform.transform.rotation = rotation_from_axis_angle_mat3({ 1, 0, 0 }, -M_PI / 2);
trunk_texture_id = create_texture_gpu(image_load_png("scenes/textures/trunk.png"));
foliage = create_tree_foliage();
foliage.uniform.color = { 1.0f, 1.0f, 1.0f };
foliage.uniform.shading.specular = 0.0f;
foliage.uniform.shading.diffuse = 0.3f;
foliage.uniform.shading.ambiant = 0.4f;
foliage.uniform.transform.rotation = rotation_from_axis_angle_mat3({ 1, 0, 0 }, -M_PI / 2);
foliage_texture_id = create_texture_gpu(image_load_png("scenes/textures/leaves.png"));
//creation de la skybox
skybox = create_skybox();
skybox.uniform.shading.specular = 0.0f;
skybox.uniform.shading.diffuse = 0.0f;
skybox.uniform.shading.ambiant = 1.0f;
skybox_texture_id = create_texture_gpu(image_load_png("scenes/textures/skybox.png"));
timer.stop();
//création des objectifs
score = 0;
tore = mesh_drawable(mesh_primitive_torus(1.5f, 0.5f));
tore_current_i = 0;
tore.uniform.color = { 1.0f, 1.0f,0.0f };
tore_position = { evaluate_terrain(0.58f,rand_interval(0.49f,0.51f)) };
tore_position[0][1] += 15.0f;
tore_rotation = { M_PI / 2.0f };
float x;
float y;
float r = 10.0f;
for (int i = 1; i < 100; i++) {
vcl::vec3 pos;
bool searching = true;
while (searching) {
searching = false;
x = rand_interval(0.2f, 0.8f);
y = rand_interval(0.2f, 0.8f);
pos = evaluate_terrain(x, y);
if ((tore_position[i - 1].x - pos.x) * (tore_position[i - 1].x - pos.x) + (tore_position[i - 1].y - pos.y) * (tore_position[i - 1].y - pos.y) < r * r) {
searching = true;
}
}
tore_position.push_back(pos);
tore_position[i][1] += 10.0f + 10 * rand_interval(0, 1);
tore_rotation.push_back(rand_interval(0, M_PI));
}
}
void scene_model::frame_draw(std::map<std::string, GLuint>& shaders, scene_structure& scene, gui_structure&)
{
const float t = timer.t;
//matrices pour le dessin
mat3 const Symmetry = { 1, 0, 0, 0, 1, 0, 0, 0, -1 };
mat3 const R_side = mat3::identity();
mat3 const R_flapR = rotation_from_axis_angle_mat3({ 0, 0, 1 }, -pphy.alphaR);
mat3 const R_flapL = rotation_from_axis_angle_mat3({ 0, 0, 1 }, -pphy.alphaL);
vec3 const flap_t = { 0, 0.12f, 0 }; //changer avec height
mat4 const TotR = mat4::from_translation(flap_t) * mat4::from_mat3(R_flapR) * mat4::from_translation(-flap_t);
mat4 const TotL = mat4::from_translation(flap_t) * mat4::from_mat3(R_flapL) * mat4::from_translation(-flap_t);
//pour le pli
plane["sideR"].transform.rotation = R_side;
plane["sideL"].transform.rotation = Symmetry * R_side;
//pour les ailerons
plane["flapR"].transform.rotation = TotR.mat3();
plane["flapR"].transform.translation = TotR.vec3();
plane["flapL"].transform.rotation = TotL.mat3();
plane["flapL"].transform.translation = TotL.vec3();
//pour la physique
float dt = 0;
if (last_t > 0)
{
dt = t - last_t;
}
const int steps = 4; //plusieurs étapes sont simulées pour une animation plus fluide
for (int i = 0; i < steps; i++) {
physic_model(pphy, cphy, dt / steps);
}
if (collision(pphy, tree_position, branches_pos)) {
timer.stop();
}
else {
plane["body"].transform.translation = pphy.p;
plane["body"].transform.rotation = pphy.r;
}
timer.update();
set_gui(timer, pphy, cphy);
plane.update_local_to_global_coordinates();
//dessin de l'avion
glBindTexture(GL_TEXTURE_2D, plane_texture_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
draw(plane, scene.camera);
last_t = t;
if (prop_active) {
float speed = 20.0f;
propeller.uniform.transform.translation = pphy.p + pphy.r * flap_t;
mat4 Totprop = mat4::from_mat3(pphy.r) * mat4::from_mat3(rotation_from_axis_angle_mat3({ 1, 0, 0 }, speed * t));
propeller.uniform.transform.rotation = Totprop.mat3();
draw(propeller, scene.camera, shaders["mesh"]);
Totprop = mat4::from_mat3(pphy.r) * mat4::from_mat3(rotation_from_axis_angle_mat3({ 1, 0, 0 }, speed * t + M_PI / 2));
propeller.uniform.transform.rotation = Totprop.mat3();
draw(propeller, scene.camera, shaders["mesh"]);
}
//Pour le terrain
glEnable(GL_POLYGON_OFFSET_FILL); // avoids z-fighting when displaying wireframe
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glPolygonOffset(1.0, 1.0);
draw(terrain, scene.camera, shaders["mesh"]);
//skybox
if (cphy.draw_skybox) {
glEnable(GL_POLYGON_OFFSET_FILL); // avoids z-fighting when displaying wireframe
glBindTexture(GL_TEXTURE_2D, skybox_texture_id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT);
draw(skybox, scene.camera, shaders["mesh"]);
}
glBindTexture(GL_TEXTURE_2D, scene.texture_white);
//pour les arbres
if (cphy.draw_tree_texture) {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBindTexture(GL_TEXTURE_2D, trunk_texture_id);
for (vec3 pi : tree_position) {
trunk.uniform.color = { 0.92f, 0.7f, 0.5f };
trunk.uniform.transform.translation = pi;
draw(trunk, scene.camera, shaders["mesh"]);
}
glBindTexture(GL_TEXTURE_2D, foliage_texture_id);
glDepthMask(false);
for (vec3 pi : tree_position) {
foliage.uniform.transform.translation = pi;
draw(foliage, scene.camera, shaders["mesh"]);
}
glDepthMask(true);
}
else {
for (vec3 pi : tree_position)
{
glBindTexture(GL_TEXTURE_2D, scene.texture_white);
trunk.uniform.color = { 0.38f, 0.2f, 0.07f };
trunk.uniform.transform.translation = pi;
draw(trunk, scene.camera, shaders["mesh"]);
}
}
glDepthMask(true);
glBindTexture(GL_TEXTURE_2D, scene.texture_white);
//Pour la caméra
if (cphy.type == "follow") {
scene.camera.translation = cphy.p;
scene.camera.orientation = cphy.r;
}
if (cphy.type == "fixed") {
scene.camera.translation = cphy.p0;
double vert_rot = 0.0f;
if (abs(pphy.p[0]) > 0.000001) {
vert_rot = atan(pphy.p[1] / std::sqrt((pphy.p[2] - 2.0f) * (pphy.p[2] - 2.0f) + (pphy.p[0] - 50.0f) * (pphy.p[0] - 50.0f)));
}
double hor_rot = 0.0f;
if (abs(pphy.p[2] - 2.0f) > 0.000001) {
if ((pphy.p[2] - 2.0f) < 0) {
hor_rot = atan((pphy.p[0] - 50.0f) / (pphy.p[2] - 2.0f));
}
else {
hor_rot = M_PI + atan((pphy.p[0] - 50.0f) / (pphy.p[2] - 2.0f));
}
}
vec3 dir = { 1.0f,0,0 };
scene.camera.orientation = rotation_from_axis_angle_mat3({ 0, 1, 0 }, hor_rot);
scene.camera.orientation = rotation_from_axis_angle_mat3(scene.camera.orientation * dir, vert_rot) * scene.camera.orientation;
}
//pour l'objectif
tore.uniform.transform.translation = tore_position[tore_current_i];
tore.uniform.transform.scaling = 1.0f;
tore.uniform.transform.rotation = rotation_from_axis_angle_mat3({ 0,1.0f,0 }, t) * rotation_from_axis_angle_mat3({ 0, 1, 0 }, tore_rotation[tore_current_i]);
draw(tore, scene.camera, shaders["mesh"]);
if (norm(tore_position[tore_current_i] - pphy.p) < 2.0f) {
tore_current_i++;
score++;
if (tore_current_i >= tore_position.size()) tore_current_i = 0;
}
//pour le score
vcl::vec3 tr;
vcl::vec3 norm = { 0,1.0f,0 };
tore.uniform.transform.rotation = rotation_from_axis_angle_mat3(scene.camera.orientation * norm, t) * scene.camera.orientation;
tore.uniform.transform.scaling = 0.01f;
for (int j = 0; j < score; j++) {
int number = 30.0f;
tr = { 1.0f + (j % number) / 50.0f,1.0f - ((j / number - (j / number) % 1)) / 30.0f,0 };
tore.uniform.transform.translation = -scene.camera.translation + scene.camera.orientation * tr;
draw(tore, scene.camera, shaders["mesh"]);
}
skybox.uniform.transform.translation = -scene.camera.translation;
}
void scene_model::keyboard_input(scene_structure&, GLFWwindow*, int key, int, int action, int) {
if (key == 32) {
if (action == 0) {
if (timer.update() > 0.000001f) {
timer.stop();
}
else {
timer.start();
}
}
}
else if (key == 66) {
if (action == 1) {
pphy.boost = 0.2f;
prop_active = true;
}
else if (action == 0) {
pphy.boost = 0.0f;
prop_active = false;
}
}
else if (key == 257) {
init_phy_cam(pphy, cphy);
}
else {
std::cout << key << " pressed" << std::endl;
}
}
void scene_model::mouse_move(scene_structure&, GLFWwindow* window) {
const vec2 cursor = glfw_cursor_coordinates_window(window);
float vert = 3.14f / 2 * cursor.y * cursor.y * cursor.y;
float hor = (cursor.x) * (cursor.x) * (cursor.x);
pphy.alphaL = vert + hor;
pphy.alphaR = vert - hor;
}
/** Part specific GUI drawing */
static void set_gui(timer_basic& timer, plane_physics& pphy, camera_physics& cphy)
{
// Can set the speed of the animation
if (ImGui::Button("Camera Position")) {
if (cphy.type == "follow") {
cphy.type = "fixed";
}
else {
cphy.type = "follow";
}
}
float scale_min = 0.05f;
float scale_max = 2.0f;
ImGui::SliderScalar("Time scale", ImGuiDataType_Float, &timer.scale, &scale_min, &scale_max, "%.2f s");
ImGui::Text(" ");
ImGui::Text("Quality settings: ");
ImGui::Checkbox("Skybox", &cphy.draw_skybox); ImGui::SameLine();
ImGui::Checkbox("Tree foliage", &cphy.draw_tree_texture);
ImGui::Text(" ");
// Start and stop animation
ImGui::Text("Animation: ");
if (ImGui::Button("Start")) {
timer.start();
}
ImGui::SameLine();
if (ImGui::Button("Stop")) {
timer.stop();
}
ImGui::SameLine();
if (ImGui::Button("Reset")) {
init_phy_cam(pphy, cphy);
}
}
void init_phy_cam(plane_physics& pphy, camera_physics& cphy)
{
float yaw = 0;
float pitch = 3.14f / 8;
//Initialisation du modèle physique
pphy.alphaL = 3.14f / 8;
pphy.alphaR = 3.14f / 8;
pphy.boost = 0.0f;
pphy.p = { 50.0f, 0, 0 };
pphy.v = { 5.0f, 0.0f, 0 };
pphy.w = { 0, 0, 0 };
pphy.r = rotation_from_axis_angle_mat3({ 0, 0, 1 }, pitch) * rotation_from_axis_angle_mat3({ 0, 1, 0 }, yaw);
//Initialisation de la caméra
cphy.p0 = { -50.0f, 0, -2.0f };
cphy.p = { -52.0f, 0, 0 };
cphy.r = rotation_from_axis_angle_mat3({ 0, 1, 0 }, yaw - M_PI / 2);
cphy.type = "follow";
}
vec3 frott(vec3 p, float c)
{
return { -c * p.x * abs(p.x), -c * p.y * abs(p.y), -c * p.z * abs(p.z) };
}
void physic_model(plane_physics& pphy, camera_physics& cphy, float dt)
{
//variables
const float m = 0.05f; //masse : ne pas trop changer
const float I = 0.01f; //moment d'inertie
const float aero_coeff = 1.0f; //"portance"
const float thrust_coeff = pphy.boost; //poussée
const float drag_coeff = 0.01f; //coeff de frottements
const float M_wing = 1.0f; //coefficient du moment des ailes
const float flap_wing_ratio = 0.3f; //rapport entre le coeff des flaps et des ailes
const float rot_drag = 0.8f;
const vec3 gravity = { 0, -9.81f, 0 };
//vecteurs utiles
const vec3 global_x = { 1.0f, 0, 0 };
const vec3 global_y = { 0, 1.0f, 0 };
const vec3 global_z = { 0, 0, 1.0f };
const vec3 lateral = pphy.r * global_z; //vecteur latéral
const vec3 normal = pphy.r * global_y; //vecteur normal
const vec3 direction = pphy.r * global_x; //vecteur de direction
float penetration = dot(-pphy.v, normal); //"rebond" de l'air sur l'aile
//rotation
const vec3 Righting = M_wing * cross(direction, pphy.v); //moment du vent sur les ailes
const vec3 Flaps = M_wing * flap_wing_ratio * cross(pphy.v, rotation_from_axis_angle_mat3(lateral, (pphy.alphaR + pphy.alphaL) / 2.0f) * direction); //moment des flaps
const vec3 FlapsRot = M_wing * flap_wing_ratio * dot(pphy.v, (-pphy.alphaR + pphy.alphaL) * direction) * direction; //moment des flaps
const vec3 RDrag = frott(pphy.w, rot_drag);
const vec3 Mt = Righting + Flaps + FlapsRot + RDrag;
pphy.w += dt * Mt / I;
pphy.r = rotation_from_axis_angle_mat3(global_y, pphy.w[1] * dt) * rotation_from_axis_angle_mat3(global_x, pphy.w[0] * dt) * rotation_from_axis_angle_mat3(global_z, pphy.w[2] * dt) * pphy.r;
//translation
const vec3 Weight = m * gravity;
const vec3 Aero = aero_coeff * penetration * normal;
const vec3 Thrust = (thrust_coeff - drag_coeff * drag_coeff * drag_coeff * norm(pphy.v) * norm(pphy.v) * norm(pphy.v)) * direction;
const vec3 Ft = Weight + Aero + Thrust;
pphy.v += dt * Ft / m;
pphy.p += pphy.v * dt;
//camera
cphy.p = -pphy.p + direction * 2;
cphy.r = rotation_from_axis_angle_mat3(global_z, pphy.w[2] * dt) * cphy.r;
cphy.r = rotation_from_axis_angle_mat3(global_y, pphy.w[1] * dt) * cphy.r;
cphy.r = rotation_from_axis_angle_mat3(global_x, pphy.w[0] * dt) * cphy.r;
}
bool collision(plane_physics& pphy, std::vector<vcl::vec3>& tree_position, std::vector<vcl::vec3> branches_pos) {
float u = pphy.p[0] / 1000 + 0.5f;
float v = pphy.p[2] / 1000 + 0.5f;
if (pphy.p[1] - evaluate_terrain_z(u, v) < 0.1f) {
return true;
}
float r0 = 30.0f;
float r1;
vec3 branch;
vec3 link;
float scal;
mat3 rot = rotation_from_axis_angle_mat3({ 1, 0, 0 }, -M_PI / 2);
for (vec3 pi : tree_position)
{
if (norm(pi - pphy.p) < r0) {
for (std::vector<int>::size_type i = 0; i < branches_pos.size(); i += 2) {
r1 = 1.0f * exp(-branches_pos[i].z * branches_pos[i + 1].z / 100);
branch = rot * (branches_pos[i + 1] - branches_pos[i]);
link = pphy.p - (rot * branches_pos[i] + pi);
scal = dot(link, branch) / norm(branch);
if (scal > 0 && scal < norm(branch)) {
if ((norm(link) * norm(link) - scal * scal) < r1 * r1) {
return true;
}
}
}
return false; //on ne peut être proche que d'un arbre à la fois
}
}
return false;
}
mesh create_propeller() {
const float L = 0.2f;
const float l = 0.02f;
const float back = 0.3f;
vec3 p0 = { back, -L / 2, -l / 2 };
vec3 p1 = { back, -L / 2, l / 2 };
vec3 p2 = { back, L / 2, l / 2 };
vec3 p3 = { back, L / 2, -l / 2 };
return mesh_primitive_quad(p0, p1, p2, p3);
}
vcl::hierarchy_mesh_drawable create_plane()
{
const float height = 0.12f;
const float diffuse = 0.5f;
const float wing_back = 0.18f;
vcl::hierarchy_mesh_drawable planem;
mesh_drawable body;
planem.add(body, "body");
vec3 p0 = { 0, 0, 0 };
vec3 p1 = { 0.3f, 0.07f, 0 };
vec3 p2 = { 0.3f, height, 0.01f };
vec3 p3 = { 0, height, 0.03f };
vec3 p4 = { 0, height, wing_back };
vec3 p5 = { 0.3f, height, 0.06f };
vec3 p6 = { -0.06, height, 0.05f };
vec3 p7 = { -0.06, height, wing_back - 0.05f };
mesh_drawable sideR = mesh_drawable(mesh_primitive_quad(p0, p1, p2, p3));
sideR.uniform.shading.ambiant = diffuse;
planem.add(sideR, "sideR", "body");
planem.add(sideR, "sideL", "body");
mesh_drawable wing = mesh_drawable(mesh_primitive_quad(p2, p3, p4, p5));
wing.uniform.shading.ambiant = diffuse;
planem.add(wing, "wingR", "sideR");
planem.add(wing, "wingL", "sideL");
mesh_drawable flap = mesh_drawable(mesh_primitive_quad(p4, p3, p6, p7));
flap.uniform.shading.ambiant = diffuse;
planem.add(flap, "flapL", "wingL");
planem.add(flap, "flapR", "wingR");
return planem;
}
// Evaluate height of the terrain for any (u,v) \in [0,1]
float evaluate_terrain_z(float u, float v)
{
// get gui parameters
const float z0 = -20;
const float scaling = 10.0f;
const int octave = 5;
const float persistency = 0.2;
const float height = 10;
// Evaluate Perlin noise
const float noise = perlin(scaling * u, scaling * v, octave, persistency);
return height * noise + z0;
}
vec3 evaluate_terrain(float u, float v)
{
const float terrain_size = 1000;
const float x = terrain_size * (u - 0.5f); // u = x/terrain_size + 0.5f
const float y = terrain_size * (v - 0.5f);
const float z = evaluate_terrain_z(u, v);
return { x, z, y };
}
mesh create_terrain()
{
// Number of samples of the terrain is N x N
const size_t N = 150;
mesh terrain; // temporary terrain storage (CPU only)
terrain.position.resize(N * N);
terrain.texture_uv.resize(N * N);
// Fill terrain geometry
for (size_t ku = 0; ku < N; ++ku)
{
for (size_t kv = 0; kv < N; ++kv)
{
// Compute local parametric coordinates (u,v) \in [0,1]
const float u = ku / (N - 1.0f);
const float v = kv / (N - 1.0f);
// Compute coordinates
terrain.position[kv + N * ku] = evaluate_terrain(u, v);
//terrain.texture_uv[kv + N * ku] = vec2({ 1.0f*ku ,1.0f *kv });
terrain.texture_uv[kv + N * ku] = vec2({ 0.2f * ku, 0.2f * kv });
}
}
const unsigned int Ns = N;
for (unsigned int ku = 0; ku < Ns - 1; ++ku)
{
for (unsigned int kv = 0; kv < Ns - 1; ++kv)
{
const unsigned int idx = kv + N * ku; // current vertex offset
const uint3 triangle_1 = { idx + 1, idx + 1 + Ns, idx };
const uint3 triangle_2 = { idx + 1 + Ns, idx + Ns, idx };
terrain.connectivity.push_back(triangle_1);
terrain.connectivity.push_back(triangle_2);
}
}
return terrain;
}
mesh create_cylinder(vec3 p1, vec3 p2)
{
mesh m;
mesh q;
// Number of samples
const size_t N = 30;
float r1 = 1.0f * exp(-p1.z * p1.z / 100);
float r2 = 1.0f * exp(-p2.z * p2.z / 100);
// Geometry
for (size_t k = 0; k < N; ++k)
{
const float u = 1 / float(N);
const vec3 c1 = { std::cos(2 * 3.14f * u * k), std::sin(2 * 3.14f * u * k), 0.0f };
const vec3 c2 = { std::cos(2 * 3.14f * u * (k + 1)), std::sin(2 * 3.14f * u * (k + 1)), 0.0f };
q = mesh_primitive_quad(r1 * c1 + p1, r1 * c2 + p1, r2 * c2 + p2, r2 * c1 + p2);
q.texture_uv = { { u * k,0.0f }, { u * (k + 1),0.0f }, { u * (k + 1),1.0f }, { u * k,1.0f } };
m.push_back(q);
}
return m;
}
std::vector<vcl::vec3> branch_tip(vec3 p, float height, int nbBranch, int steps)
{
std::vector<vcl::vec3> listp;
std::vector<vcl::vec3> suite;
if (steps == 1)
{
for (int i = 0; i < nbBranch; i++)
{
listp.push_back(p);
float angle = (i*1.0f/nbBranch) + (rand() % 20 - 10.0f) / 360.0f;
float h = (height / 1.618f);
float r = pow(height * height - h * h, 0.5);
float angle2 = (rand() % 180) / 360.0f;
vec3 p2 = p + vec3{ r * std::cos(2 * 3.14f * angle), r * std::sin(2 * 3.14f * angle), h * (0.5f + 0.7f * std::sin(2 * 3.14f * angle2)) };
listp.push_back(p2);
}
return listp;
}
for (int i = 0; i < nbBranch; i++)
{
listp.push_back(p);
float angle = (i*1.0f/nbBranch) + (rand() % 20 - 10.0f) / 360.0f;
float h = height / 1.618f;
float r = pow(height * height - h * h, 0.5);
float angle2 = (rand() % 180) / 360.0f;
vec3 p2 = p + vec3{ r * std::cos(2 * 3.14f * angle), r * std::sin(2 * 3.14f * angle), h * (0.5f + 0.7f * std::sin(2 * 3.14f * angle2)) };
listp.push_back(p2);
suite.push_back(p2);
}
for (vec3 pit : suite)
{
std::vector<vcl::vec3> l = branch_tip(pit, height / 1.618f, nbBranch, steps - 1);
for (vec3 pit2 : l)
{
listp.push_back(pit2);
}
}
return listp;
}
mesh create_tree(std::vector<vcl::vec3>& branches_pos)
{
mesh m;
int steps = 2;
int nbBranch = 4;
float height = 6.0f;
vec3 p1 = vec3(0, 0, 0);
vec3 p2 = vec3(0, 0, height);
m.push_back(create_cylinder(p1, p2));
branches_pos.push_back(p1);
branches_pos.push_back(p2);
srand(195);
std::vector<vcl::vec3> listp = branch_tip(p2, height, nbBranch, steps);
for (unsigned long i = 0; i < listp.size() - 1;)
{
m.push_back(create_cylinder(listp.at(i), listp.at(i + 1)));
branches_pos.push_back(listp.at(i));
branches_pos.push_back(listp.at(i + 1));
i = i + 2;
}
return m;
}
mesh create_tree_foliage()
{
mesh m;
int steps = 2;
int nbBranch = 4;
float height = 6.0f;
int N = 4;
vec3 p = vec3(0, 0, height);
srand(195);
std::vector<vcl::vec3> listp = branch_tip(p, height, nbBranch, steps);
vec3 p1 = { 2.0f, 2.0f, 0.0f };
vec3 p2 = { 2.0f, -2.0f, 0.0f };
vec3 p3 = { -2.0f, -2.0f, 0.0f };
vec3 p4 = { -2.0f, 2.0f, 0.0f };
for (unsigned long i = 0; i < listp.size() - 1;)
{
vec3 l = listp.at(i) - listp.at(i + 1);
for (int n = 0; n < N; n++)
{
float u = (1.0f * n) / N;
mat3 R = rotation_from_axis_angle_mat3({ 0, 0, 1 }, (rand() % 360) / 360.0f) * rotation_from_axis_angle_mat3({ 1, 0, 0 }, (rand() % 360) / 360.0f);
mesh quad = mesh_primitive_quad(listp.at(i + 1) + u * l + R * p1, listp.at(i + 1) + u * l + R * p2, listp.at(i + 1) + u * l + R * p3, listp.at(i + 1) + u * l + R * p4);
m.push_back(quad);
R = R * rotation_from_axis_angle_mat3(listp.at(i + 1) + u * l + R * p1 - (listp.at(i + 1) + u * l + R * p4), M_PI / 2);
quad = mesh_primitive_quad(listp.at(i + 1) + u * l + R * p1, listp.at(i + 1) + u * l + R * p2, listp.at(i + 1) + u * l + R * p3, listp.at(i + 1) + u * l + R * p4);
m.push_back(quad);
}
i = i + 2;
}
return m;
}
std::vector<vcl::vec3> update_tree_position()
{
std::cout << "Updating tree position..."<<std::endl;
int nbgroupes = 23;
int arbrespargroupe = 5;
float dgroup = 30.0f;
float darbres = 5.0f;
std::vector<vcl::vec3> pos;
std::vector<vcl::vec2> groups;
int i = 0;
while (i < nbgroupes) {
float u = rand_interval(0, 1.0f);
float v = rand_interval(0, 1.0f);
vec3 ptest = evaluate_terrain(u, v);
int test = 1;
for (vec3 p : pos)
{
if( (ptest.x-p.x)* (ptest.x - p.x) + (ptest.y - p.y)* (ptest.y - p.y) < dgroup*dgroup)
{
test = 0;
break;
}
}
if (test == 1)
{
pos.push_back(ptest);
groups.push_back({ u, v });
i = i + 1;
}
}
srand(3818);
for (vec2 c : groups) {
int i = 0;
while (i < arbrespargroupe) {
const float u = c.x + (rand_interval(0, 0.08f) - 0.04f);
const float v = c.y + (rand_interval(0, 0.08f) - 0.04f);
int test = 1;
for (vec3 p : pos)
{
vec3 ptest = evaluate_terrain(u, v);
if ((ptest.x - p.x) * (ptest.x - p.x) + (ptest.y - p.y) * (ptest.y - p.y) < darbres * darbres)
{
test = 0;
break;
}
}
if (test == 1)
{
pos.push_back(evaluate_terrain(u, v));
i = i + 1;
}
}
}
std::cout << " [OK]" << std::endl;
return pos;
}
mesh create_skybox() {
mesh skybox;
float size = 1000.0f;
vec3 p0 = { -size / 2,-size / 2,-size / 2 };
vec3 p1 = { size / 2,-size / 2,-size / 2 };
vec3 p2 = { size / 2,-size / 2,size / 2 };
vec3 p3 = { -size / 2,-size / 2,size / 2 };
vec3 p4 = { -size / 2,size / 2,-size / 2 };
vec3 p5 = { size / 2,size / 2,-size / 2 };
vec3 p6 = { size / 2,size / 2,size / 2 };
vec3 p7 = { -size / 2,size / 2,size / 2 };
mesh side1 = mesh_primitive_quad(p5, p4, p0, p1);
side1.texture_uv = { {0.25f,1.0f / 3.0f},{0.0f,1.0f / 3.0f},{0.0f,2.0f / 3.0f},{0.25f,2.0f / 3.0f} };
skybox.push_back(side1);
mesh side2 = mesh_primitive_quad(p6, p5, p1, p2);
side2.texture_uv = { {0.5f,1.0f / 3.0f},{0.25f,1.0f / 3.0f},{0.25f,2.0f / 3.0f},{0.5f,2.0f / 3.0f} };
skybox.push_back(side2);
mesh side3 = mesh_primitive_quad(p7, p6, p2, p3);
side3.texture_uv = { {0.75f,1.0f / 3.0f},{0.5f,1.0f / 3.0f},{0.5f,2.0f / 3.0f},{0.75f,2.0f / 3.0f} };
skybox.push_back(side3);
mesh side4 = mesh_primitive_quad(p4, p7, p3, p0);
side4.texture_uv = { {1.0f,1.0f / 3.0f},{0.75f,1.0f / 3.0f},{0.75f,2.0f / 3.0f},{1.0f,2.0f / 3.0f} };
skybox.push_back(side4);
mesh side5 = mesh_primitive_quad(p5, p6, p7, p4);
side5.texture_uv = { {0.25f,1.0f / 3.0f},{0.5f,1.0f / 3.0f},{0.5f,0.0f},{0.25f,0.0f} };
skybox.push_back(side5);
return skybox;
}
#endif | 33.806752 | 195 | 0.55489 | nissmar |
e76f03073a0f9994d498e442e6fb15306d5b1d46 | 8,472 | cpp | C++ | SDL_Guide 03 Image Loading & Rendering/main.cpp | xeek-pro/SDL_Guide | 16c9fbff4dd246b73e984ab4149e94ef418e532a | [
"MIT"
] | 3 | 2020-07-13T04:49:27.000Z | 2020-07-24T21:27:43.000Z | SDL_Guide 03 Image Loading & Rendering/main.cpp | xeek-pro/sdl_guide | 16c9fbff4dd246b73e984ab4149e94ef418e532a | [
"MIT"
] | null | null | null | SDL_Guide 03 Image Loading & Rendering/main.cpp | xeek-pro/sdl_guide | 16c9fbff4dd246b73e984ab4149e94ef418e532a | [
"MIT"
] | 1 | 2021-07-13T13:48:18.000Z | 2021-07-13T13:48:18.000Z | #include <SDL.h>
#include <iostream>
#include <sstream>
#include <string>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h" // https://github.com/nothings/stb/blob/master/stb_image.h
int main(int argc, char* argv[])
{
std::string app_title = "SDL_Guide 03: Image Loading & Rendering";
int display_width = 1024;
int display_height = 768;
std::stringstream error;
SDL_Window* main_window = NULL;
SDL_Renderer* renderer = NULL;
std::string image_path = "../assets/green-chameleon-01.png";
SDL_Texture* image_texture = NULL;
SDL_Rect image_rect = { 0, 0 };
try {
// CONFIGURE LOGGING:
// -----------------------------------------------------------------------------------------------------------------
// Set this so that all logged messages show in the console
SDL_LogSetAllPriority(SDL_LOG_PRIORITY_VERBOSE);
// INITIALIZATION:
// -----------------------------------------------------------------------------------------------------------------
// Initialize SDL and create a window and renderer
SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Initializing SDL...");
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) < 0) {
error << "Failed to initialize SDL: " << SDL_GetError();
throw(std::exception(error.str().c_str()));
}
SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Creating main window...");
if ((main_window = SDL_CreateWindow(
app_title.c_str(),
SDL_WINDOWPOS_CENTERED, // Use Centered Top Coordinate
SDL_WINDOWPOS_CENTERED, // Use Centered Left Coordinate
display_width, display_height, // Width & Height
0 // Flags (Window is implicitly shown if SDL_WINDOW_HIDDEN is not set)
)) == 0) {
error << "Failed to create a window: " << SDL_GetError();
throw(std::exception(error.str().c_str()));
}
SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Creating renderer...");
if ((renderer = SDL_CreateRenderer(main_window, -1, SDL_RENDERER_ACCELERATED)) == 0) {
error << "Failed to create the renderer: " << SDL_GetError();
throw(std::exception(error.str().c_str()));
}
// LOAD ASSETS & CREATE TEXTURES:
// -----------------------------------------------------------------------------------------------------------------
// I'm using stb_image to load various image formats, which is available here:
// https://github.com/nothings/stb/blob/master/stb_image.h
int orig_format; // What format was the file in? stbi_load requires this, but we do not need this information
int depth = 32; // Each pixel has 4 channels and each channel is a byte (so 8 bits X 4 channels)
int channels = STBI_rgb_alpha; // 4 channels
//int pitch = channels * image_rect.w; // Pitch is the width of an entire row in bytes, so multiply image width by number of channels
SDL_Log("Loading image from '%s'", image_path.c_str());
unsigned char* data = stbi_load(image_path.c_str(), &image_rect.w, &image_rect.h, &orig_format, channels);
if (data == NULL) {
error << "Loading image failed: " << stbi_failure_reason();
throw(std::exception(error.str().c_str()));
}
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
Uint32 rmask = 0xff000000, gmask = 0x00ff0000, bmask = 0x0000ff00, amask = 0x000000ff;
#else // little endian, like x86, and typical desktop processors
Uint32 rmask = 0x000000ff, gmask = 0x0000ff00, bmask = 0x00ff0000, amask = 0xff000000;
#endif
SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Creating surface for image...");
SDL_Surface* image_surface = SDL_CreateRGBSurfaceFrom(
data, // The pixel buffer as loaded from stbi_load
image_rect.w, image_rect.h, // Width and height of the image
depth, // Depth is the number of bits per pixel
channels * image_rect.w, // Pitch is the number of bytes per image row
rmask, gmask, bmask, amask // So SDL knows which order the channels are in per 32-bits
);
if (image_surface == NULL) {
stbi_image_free(data); // Free the pixel buffer so that it doesn't leak after failing to create the surface
error << "Creating image surface failed: " << SDL_GetError();
throw(std::exception(error.str().c_str()));
}
SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Creating texture for image and freeing surface...");
image_texture = SDL_CreateTextureFromSurface(renderer, image_surface);
SDL_FreeSurface(image_surface); // Free the surface because it's no longer needed after a texture is created
stbi_image_free(data); // Free the pixel buffer becausae SDL_FreeSurface doesn't do this for us
if (image_texture == NULL) {
error << "Creating image texture failed: " << SDL_GetError();
throw(std::exception(error.str().c_str()));
}
// PRIMARY & EVENT LOOP:
// -----------------------------------------------------------------------------------------------------------------
// There are two loops (one nested into the other). If the event queue isn't emptied entirely for every frame
// then events can get backed up in the queue and begin to lag, causing undesired effects
bool should_quit = false; // Used so the game-loop can end naturally
SDL_Event event = { 0 }; // Create the event struct here so that it's not recreated repeatedly in the loop
SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Game loop starting...");
while (!should_quit) {
// We'll discuss events later, but without the event loop, some platforms may not render or display a window
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
should_quit = 1;
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
should_quit = 1;
break;
}
break;
}
}
// RENDERING:
// -----------------------------------------------------------------------------------------------------------------
// Clear the background:
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_RenderClear(renderer);
// Render the loaded image:
SDL_RenderCopy(renderer, image_texture,
NULL, // Use the entire image for the source rect
NULL // Stretch the image onto the entire display
);
// Show what was previously rendered to the back buffer:
SDL_RenderPresent(renderer);
// Note: After a call to SDL_RenderPresent, if no textures had been rendered, with verbose logging turned on, it's
// normal for the following error to show in the console:
// SDL failed to get a vertex buffer for this Direct3D 9 rendering batch!
// This is only seen when batching is supported, which right now is most likely only with Windows + Direct3D 9
}
}
catch (std::exception ex) {
// This is a simple way to show a message box, if main_window failed to create this will still work
// since main_window will be NULL (the message box will just not have a parent):
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, app_title.c_str(), ex.what(), main_window);
// Output the error to the console, if you have one
SDL_LogError(SDL_LOG_CATEGORY_ERROR, ex.what());
}
// CLEAN-UP & SHUTDOWN:
// -----------------------------------------------------------------------------------------------------------------
SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Freeing resources");
if (image_texture) SDL_DestroyTexture(image_texture);
if (renderer) SDL_DestroyRenderer(renderer);
if (main_window) SDL_DestroyWindow(main_window);
SDL_Quit();
SDL_Log("Shutdown");
return 0;
} | 50.428571 | 144 | 0.561851 | xeek-pro |
e7725820b336f5c2d2dcccdc4b86929b54c3b06f | 6,350 | cpp | C++ | src/plugin.cpp | mattcomeback/samp-plugin-crashdetect | 4bd4052ff8001e1b30875aceaf06b49f51479a07 | [
"BSD-2-Clause"
] | null | null | null | src/plugin.cpp | mattcomeback/samp-plugin-crashdetect | 4bd4052ff8001e1b30875aceaf06b49f51479a07 | [
"BSD-2-Clause"
] | 1 | 2018-07-14T14:10:19.000Z | 2018-07-14T18:05:34.000Z | src/plugin.cpp | Zeex/crashdetect | 4bd4052ff8001e1b30875aceaf06b49f51479a07 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2011-2021 Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <functional>
#include <string>
#ifdef _WIN32
#include <windows.h>
#else
#include <stdio.h>
#endif
#include <subhook.h>
#include "amxpathfinder.h"
#include "crashdetect.h"
#include "fileutils.h"
#include "logprintf.h"
#include "natives.h"
#include "options.h"
#include "os.h"
#include "plugincommon.h"
#include "pluginversion.h"
#include "stringutils.h"
namespace {
std::vector<std::function<void()>> unload_callbacks;
subhook::Hook exec_hook;
subhook::Hook open_file_hook;
std::string last_opened_amx_file_name;
#ifdef _WIN32
HANDLE WINAPI CreateFileAHook(
LPCSTR lpFileName,
DWORD dwDesiredAccess,
DWORD dwShareMode,
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes,
HANDLE hTemplateFile)
{
subhook::ScopedHookRemove _(&open_file_hook);
const char *ext = fileutils::GetFileExtensionPtr(lpFileName);
if (ext != nullptr && stringutils::CompareIgnoreCase(ext, "amx") == 0) {
last_opened_amx_file_name = lpFileName;
}
return CreateFileA(
lpFileName,
dwDesiredAccess,
dwShareMode,
lpSecurityAttributes,
dwCreationDisposition,
dwFlagsAndAttributes,
hTemplateFile);
}
#else
FILE *FopenHook(const char *filename, const char *mode) {
subhook::ScopedHookRemove _(&open_file_hook);
const char *ext = fileutils::GetFileExtensionPtr(filename);
if (ext != nullptr && stringutils::CompareIgnoreCase(ext, "amx") == 0) {
last_opened_amx_file_name = filename;
}
return fopen(filename, mode);
}
#endif
int AMXAPI OnDebugHook(AMX *amx) {
return CrashDetect::GetHandler(amx)->OnDebugHook();
}
int AMXAPI OnCallback(AMX *amx, cell index, cell *result, cell *params) {
CrashDetect *handler = CrashDetect::GetHandler(amx);
return handler->OnCallback(index, result, params);
}
int AMXAPI OnExec(AMX *amx, cell *retval, int index) {
if (amx->flags & AMX_FLAG_BROWSE) {
return amx_Exec(amx, retval, index);
}
CrashDetect *handler = CrashDetect::GetHandler(amx);
if (handler == nullptr) {
return amx_Exec(amx, retval, index);
}
return handler->OnExec(retval, index);
}
int AMXAPI OnExecError(AMX *amx, cell index, cell *retval, int error) {
CrashDetect *handler = CrashDetect::GetHandler(amx);
return handler->OnExecError(index, retval, error);
}
int AMXAPI OnLongCallRequest(AMX *amx, int option, int value) {
CrashDetect *handler = CrashDetect::GetHandler(amx);
return handler->OnLongCallRequest(option, value);
}
} // anonymous namespace
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
void **exports = reinterpret_cast<void**>(ppData[PLUGIN_DATA_AMX_EXPORTS]);
::logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
void *amx_Exec_ptr = exports[PLUGIN_AMX_EXPORT_Exec];
void *amx_Exec_sub = subhook::ReadHookDst(amx_Exec_ptr);
if (amx_Exec_sub == nullptr) {
exec_hook.Install(amx_Exec_ptr, (void*)OnExec);
unload_callbacks.push_back([]() {
exec_hook.Remove();
});
} else {
std::string module =
fileutils::GetFileName(os::GetModuleName(amx_Exec_sub));
if (!module.empty()) {
logprintf(" CrashDetect must be loaded before '%s'", module.c_str());
}
return false;
}
#if _WIN32
open_file_hook.Install((void*)CreateFileA, (void*)CreateFileAHook);
#else
open_file_hook.Install((void*)fopen, (void*)FopenHook);
#endif
unload_callbacks.push_back([]() {
open_file_hook.Remove();
});
AMXPathFinder::shared().AddSearchPath("gamemodes");
AMXPathFinder::shared().AddSearchPath("filterscripts");
const char *amx_path_var = getenv("AMX_PATH");
if (amx_path_var != nullptr) {
stringutils::SplitString(
amx_path_var,
fileutils::kNativePathListSepChar,
std::bind1st(std::mem_fun(&AMXPathFinder::AddSearchPath),
&AMXPathFinder::shared()));
}
os::SetCrashHandler(CrashDetect::OnCrash);
os::SetInterruptHandler(CrashDetect::OnInterrupt);
CrashDetect::PluginLoad();
logprintf(" CrashDetect plugin " PLUGIN_VERSION_STRING);
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
CrashDetect::PluginUnload();
for (auto &callback : unload_callbacks) {
callback();
}
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
if (!last_opened_amx_file_name.empty()) {
AMXPathFinder::shared().AddKnownFile(amx, last_opened_amx_file_name);
}
CrashDetect *handler = CrashDetect::CreateHandler(amx);
handler->Load();
amx_SetDebugHook(amx, OnDebugHook);
amx_SetCallback(amx, OnCallback);
static AMX_EXT_HOOKS ext_hooks = {
OnExecError,
OnLongCallRequest
};
amx_SetExtHooks(amx, &ext_hooks);
RegisterNatives(amx);
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
CrashDetect::GetHandler(amx)->Unload();
CrashDetect::DestroyHandler(amx);
return AMX_ERR_NONE;
}
| 30.676329 | 79 | 0.725984 | mattcomeback |
e772893fc5df04ff6ece99cb16228f16145e700a | 17,450 | cpp | C++ | src/windows/iosystem_win32.cpp | kfrolov/netcoredbg | 84f51b95d0eb4a087ce2a068d4474895e44e3f97 | [
"MIT"
] | null | null | null | src/windows/iosystem_win32.cpp | kfrolov/netcoredbg | 84f51b95d0eb4a087ce2a068d4474895e44e3f97 | [
"MIT"
] | null | null | null | src/windows/iosystem_win32.cpp | kfrolov/netcoredbg | 84f51b95d0eb4a087ce2a068d4474895e44e3f97 | [
"MIT"
] | null | null | null | // Copyright (C) 2020 Samsung Electronics Co., Ltd.
// See the LICENSE file in the project root for more information.
/// \file iosystem_win32.cpp This file contains windows-specific definitions of
/// IOSystem class members (see iosystem.h).
#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#include <ws2tcpip.h>
#include <afunix.h>
#include <stdexcept>
#include <new>
#include <memory>
#include <atomic>
#include <string.h>
#include <assert.h>
#include "iosystem.h"
#include "limits.h"
// short alias for full class name
namespace { typedef netcoredbg::IOSystemTraits<netcoredbg::Win32PlatformTag> Class; }
namespace
{
class Win32Exception : public std::runtime_error
{
struct Msg
{
mutable char buf[2 * LINE_MAX];
};
static const char* getmsg(const char *prefix, DWORD error, const Msg& msg = Msg())
{
int len = prefix ? snprintf(msg.buf, sizeof(msg.buf), "%s: ", prefix) : 0;
if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
msg.buf + len, sizeof(msg.buf) - len, NULL))
{
return msg.buf;
}
snprintf(msg.buf + len, sizeof(msg.buf) - len, "error %#x", error);
return msg.buf;
}
public:
/// Specify Win32 error code and, optionally, error message prefix.
Win32Exception(DWORD error, const char* prefix = nullptr) : std::runtime_error(getmsg(prefix, error)) {}
/// Specify error message prefix (optionally). Win32 error code will be obtained via call to GetLastError().
Win32Exception(const char *prefix = nullptr) : Win32Exception(prefix, GetLastError()) {}
/// Specify explicitly error message prefix and error code.
Win32Exception(const char *prefix, DWORD error) : Win32Exception(error, prefix) {}
};
struct Initializer
{
Initializer()
{
WSADATA wsa;
int wsa_error = WSAStartup(MAKEWORD(2, 2), &wsa);
if (wsa_error != 0)
throw Win32Exception("WSAStartup failed", wsa_error);
}
~Initializer()
{
WSACleanup();
}
};
static Initializer initializer;
#if 0
// assuming domain=AF_UNIX, type=SOCK_STREAM, protocol=0
int wsa_socketpair(int domain, int type, int protocol, SOCKET sv[2])
{
SOCKET serv = ::socket(domain, type, protocol);
if (serv == INVALID_SOCKET)
throw Win32Exception("can't create socket", WSAGetLastError());
// TODO
char name[] = "netcoredbg";
size_t namelen = sizeof(name)-1;
SOCKADDR_UN sa;
sa.sun_family = domain;
assert(namelen <= sizeof(sa.sun_path));
memcpy(sa.sun_path, name, namelen);
if (::bind(serv, (struct sockaddr*)&sa, sizeof(sa)) == SOCKET_ERROR)
{
auto err = WSAGetLastError();
::closesocket(serv);
throw Win32Exception("can't bind socket", err);
}
u_long mode = 1;
if (::ioctlsocket(serv, FIONBIO, &mode) == SOCKET_ERROR)
{
auto err = WSAGetLastError();
::closesocket(serv);
throw Win32Exception("ioctlsocket(FIONBIO)", err);
}
if (::listen(serv, 1) == SOCKET_ERROR && WSAGetLastError() != WSAEINPROGRESS)
{
auto err = WSAGetLastError();
::closesocket(serv);
throw Win32Exception("ioctlsocket(FIONBIO)", err);
}
SOCKET conn = ::socket(domain, type, protocol);
if (conn == INVALID_SOCKET)
{
auto err = WSAGetLastError();
::closesocket(serv);
throw Win32Exception("can't create socket", err);
}
sa.sun_family = domain;
memcpy(sa.sun_path, name, namelen);
if (::connect(conn, (struct sockaddr*)&sa, sizeof(sa)) == SOCKET_ERROR)
{
auto err = WSAGetLastError();
::closesocket(serv);
::closesocket(conn);
throw Win32Exception("can't bind socket", err);
}
mode = 0;
if (::ioctlsocket(serv, FIONBIO, &mode) == SOCKET_ERROR)
{
auto err = WSAGetLastError();
::closesocket(serv);
::closesocket(conn);
throw Win32Exception("ioctlsocket(FIONBIO)", err);
}
SOCKET newsock = ::accept(serv, NULL, NULL);
if (newsock == INVALID_SOCKET)
{
auto err = WSAGetLastError();
::closesocket(serv);
::closesocket(conn);
throw Win32Exception("accept on socket", err);
}
::closesocket(serv);
sv[0] = newsock, sv[1] = conn;
return 0;
}
#endif
}
// Function should create unnamed pipe and return two file handles
// (reading and writing pipe ends) or return empty file handles if pipe can't be created.
std::pair<Class::FileHandle, Class::FileHandle> Class::unnamed_pipe()
{
#if 0
SOCKET sv[2];
if (wsa_socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0)
return {FileHandle(), FileHandle()};
#endif
static const size_t PipeSize = 32 * LINE_MAX;
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
HANDLE reading_fd, writing_fd;
static std::atomic<long> pipe_num;
char pipe_name[MAX_PATH + 1];
snprintf(pipe_name, sizeof(pipe_name), "\\\\.\\Pipe\\Win32Pipes.%08x.%08x",
GetCurrentProcessId(), pipe_num++);
reading_fd = CreateNamedPipeA(pipe_name,
PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE | PIPE_WAIT,
1, // number of pipes
PipeSize, PipeSize,
0, // 50ms default timeout
&saAttr);
if (reading_fd == INVALID_HANDLE_VALUE)
{
perror("CreateNamedPipeA");
return { FileHandle(), FileHandle() };
}
writing_fd = CreateFileA(pipe_name,
GENERIC_WRITE,
0, // no sharing
&saAttr,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
NULL);
if (writing_fd == INVALID_HANDLE_VALUE)
{
auto err = GetLastError();
::CloseHandle(writing_fd);
fprintf(stderr, "CreateFile pipe error: %#x\n", err);
return { FileHandle(), FileHandle() };
}
if (!SetHandleInformation(writing_fd, HANDLE_FLAG_INHERIT, 0))
{
fprintf(stderr, "SetHandleInformation failed!\n");
return { FileHandle(), FileHandle() };
}
if (!SetHandleInformation(reading_fd, HANDLE_FLAG_INHERIT, 0))
{
fprintf(stderr, "SetHandleInformation failed!\n");
return { FileHandle(), FileHandle() };
}
return { FileHandle(reading_fd), FileHandle(writing_fd) };
}
// Function creates listening TCP socket on given port, waits, accepts single
// connection, and return file descriptor related to the accepted connection.
// In case of error, empty file handle will be returned.
Class::FileHandle Class::listen_socket(unsigned port)
{
assert(port > 0 && port < 65536);
SOCKET newsockfd;
int clilen;
struct sockaddr_in serv_addr, cli_addr;
SOCKET sockFd = ::socket(AF_INET, SOCK_STREAM, 0);
if (sockFd == INVALID_SOCKET)
{
fprintf(stderr, "can't create socket: %#x\n", WSAGetLastError());
return {};
}
BOOL enable = 1;
if (::setsockopt(sockFd, SOL_SOCKET, SO_REUSEADDR, (const char *)&enable, sizeof(BOOL)) == SOCKET_ERROR)
{
::closesocket(sockFd);
fprintf(stderr, "setsockopt failed\n");
return {};
}
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port);
if (::bind(sockFd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == SOCKET_ERROR)
{
::closesocket(sockFd);
fprintf(stderr, "can't bind to specified port!\n");
return {};
}
::listen(sockFd, 1);
clilen = sizeof(cli_addr);
newsockfd = ::accept(sockFd, (struct sockaddr*)&cli_addr, &clilen);
::closesocket(sockFd);
if (newsockfd == INVALID_SOCKET)
{
fprintf(stderr, "can't accept connection\n");
return {};
}
return FileHandle(newsockfd);
}
// Function enables or disables inheritance of file handle for child processes.
Class::IOResult Class::set_inherit(const FileHandle& fh, bool inherit)
{
DWORD flags;
if (!GetHandleInformation(fh.handle, &flags))
return {IOResult::Error};
if (inherit)
flags |= HANDLE_FLAG_INHERIT;
else
flags &= ~HANDLE_FLAG_INHERIT;
if (!SetHandleInformation(fh.handle, HANDLE_FLAG_INHERIT, flags))
return {IOResult::Error};
return {IOResult::Success};
}
// Function perform reading from the file: it may read up to `count' bytes to `buf'.
Class::IOResult Class::read(const FileHandle& fh, void *buf, size_t count)
{
DWORD dwRead = 0;
OVERLAPPED ov = {};
if (! ReadFile(fh.handle, buf, (DWORD)count, &dwRead, &ov))
return { (GetLastError() == ERROR_IO_PENDING ? IOResult::Pending : IOResult::Error), dwRead };
else
return { (dwRead == 0 ? IOResult::Eof : IOResult::Success), dwRead };
}
// Function perform writing to the file: it may write up to `count' byte from `buf'.
Class::IOResult Class::write(const FileHandle& fh, const void *buf, size_t count)
{
// see https://stackoverflow.com/questions/43939424/writefile-with-windows-sockets-returns-invalid-parameter-error
DWORD dwWritten = 0;
OVERLAPPED ov = {};
if (! WriteFile(fh.handle, buf, (DWORD)count, &dwWritten, &ov))
return { (GetLastError() == ERROR_IO_PENDING ? IOResult::Pending : IOResult::Error), dwWritten };
else
return { IOResult::Success, dwWritten };
}
Class::AsyncHandle Class::async_read(const FileHandle& fh, void *buf, size_t count)
{
if (fh.handle == INVALID_HANDLE_VALUE)
return {};
AsyncHandle result;
result.handle = fh.handle;
result.overlapped.reset(new OVERLAPPED);
memset(result.overlapped.get(), 0, sizeof(OVERLAPPED));
result.overlapped->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (result.overlapped->hEvent == INVALID_HANDLE_VALUE)
return {};
if (! ReadFile(fh.handle, buf, (DWORD)count, nullptr, result.overlapped.get()))
{
if (GetLastError() != ERROR_IO_PENDING)
return {};
}
return result;
}
Class::AsyncHandle Class::async_write(const FileHandle& fh, const void *buf, size_t count)
{
if (fh.handle == INVALID_HANDLE_VALUE)
return {};
AsyncHandle result;
result.handle = fh.handle;
result.overlapped.reset(new OVERLAPPED);
memset(result.overlapped.get(), 0, sizeof(OVERLAPPED));
result.overlapped->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
if (result.overlapped->hEvent == INVALID_HANDLE_VALUE)
return {};
if (! WriteFile(fh.handle, buf, (DWORD)count, nullptr, result.overlapped.get()))
{
if (GetLastError() != ERROR_IO_PENDING)
return {};
}
return result;
}
bool Class::async_wait(IOSystem::AsyncHandleIterator begin, IOSystem::AsyncHandleIterator end, std::chrono::milliseconds timeout)
{
// count number of active handles
unsigned count = 0;
for (auto it = begin; it != end; ++it)
if (*it) ++count;
// allocate memory for events array
HANDLE *events = static_cast<HANDLE*>(alloca(count * sizeof(HANDLE)));
unsigned n = 0;
for (auto it = begin; it != end; ++it)
{
if (*it)
events[n++] = it->handle.overlapped->hEvent;
}
assert(n == count);
DWORD result = WaitForMultipleObjects(count, events, FALSE, DWORD(timeout.count()));
return result != WAIT_FAILED && result != WAIT_TIMEOUT;
}
Class::IOResult Class::async_cancel(AsyncHandle& h)
{
if (!h)
return {IOResult::Error};
if (!CloseHandle(h.overlapped->hEvent))
perror("CloseHandle(event) error");
IOResult result;
if (!CancelIoEx(h.handle, h.overlapped.get()))
result = {IOResult::Error};
else
result = {IOResult::Success};
h = AsyncHandle();
return result;
}
Class::IOResult Class::async_result(AsyncHandle& h)
{
if (!h)
return {IOResult::Error};
DWORD bytes;
bool finished = GetOverlappedResult(h.handle, h.overlapped.get(), &bytes, FALSE);
if (!finished)
{
DWORD error = GetLastError();
if (error == ERROR_IO_INCOMPLETE)
return {IOResult::Pending};
}
if (!CloseHandle(h.overlapped->hEvent))
perror("CloseHandle(event) error");
h = AsyncHandle();
return finished ? IOResult{IOResult::Success, bytes} : IOResult{IOResult::Error};
}
// Function closes the file represented by file handle.
Class::IOResult Class::close(const FileHandle& fh)
{
assert(fh);
if (fh.type == FileHandle::Socket)
return { ::closesocket((SOCKET)fh.handle) == 0 ? IOResult::Success : IOResult::Error };
else
return { ::CloseHandle(fh.handle) ? IOResult::Success : IOResult::Error };
}
// Function allows non-blocking IO on files, it is similar with select(2) system call on Unix.
// Arguments includes: pointers to three sets of file handles (for reading, for writing, and for
// exceptions), and timeout value, in milliseconds. Any pointer might have NULL value if some set
// isn't specified.
// Function returns -1 on error, 0 on timeout or number of ready to read/write file handles.
// If function returns value greater than zero, at least one of the sets, passed in arguments,
// is not empty and contains file handles ready to read/write/etc...
// This function returns triplet of currently selected standard files.
Class::IOSystem::StdFiles Class::get_std_files()
{
using Handles = std::tuple<IOSystem::FileHandle, IOSystem::FileHandle, IOSystem::FileHandle>;
/*thread_local*/ static alignas(alignof(Handles)) char mem[sizeof(Handles)]; // TODO
Handles& handles = *new (mem) Handles {
FileHandle(GetStdHandle(STD_INPUT_HANDLE)),
FileHandle(GetStdHandle(STD_OUTPUT_HANDLE)),
FileHandle(GetStdHandle(STD_ERROR_HANDLE))
};
return { std::get<IOSystem::Stdin>(handles),
std::get<IOSystem::Stdout>(handles),
std::get<IOSystem::Stderr>(handles) };
}
// StdIOSwap class allows to substitute set of standard IO files with one provided to constructor.
// Substitution exists only during life time of StsIOSwap instance.
Class::StdIOSwap::StdIOSwap(const StdFiles& files)
{
const static unsigned NFD = std::tuple_size<StdFiles>::value;
static const DWORD std_handles[NFD] = {STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE};
static const int open_flags[NFD] = {_O_RDONLY | _O_BINARY, _O_BINARY, _O_BINARY};
const int open_fds[NFD] = {_fileno(stdin), _fileno(stdout), _fileno(stderr)};
const FileHandle new_handles[NFD] = {
std::get<IOSystem::Stdin>(files).handle,
std::get<IOSystem::Stdout>(files).handle,
std::get<IOSystem::Stderr>(files).handle };
fflush(stdout);
fflush(stderr);
for (unsigned n = 0; n < NFD; n++)
{
if (new_handles[n].type != FileHandle::FileOrPipe)
throw std::runtime_error("can't use socket handle for stdin/stdout/stderr");
}
for (unsigned n = 0; n < NFD; n++)
{
m_orig_handle[n] = GetStdHandle(std_handles[n]);
if (m_orig_handle[n] == INVALID_HANDLE_VALUE)
{
char msg[256];
snprintf(msg, sizeof(msg), "GetStdHandle(%#x): error", std_handles[n]);
throw std::runtime_error(msg);
}
if (!SetHandleInformation(new_handles[n].handle, HANDLE_FLAG_INHERIT, 1))
fprintf(stderr, "SetHandleInformation failed!\n");
if (!SetStdHandle(std_handles[n], new_handles[n].handle))
{
char msg[256];
snprintf(msg, sizeof(msg), "SetStdHandle(%#x, %p): error", std_handles[n], new_handles[n].handle);
throw std::runtime_error(msg);
}
int fd = _open_osfhandle(reinterpret_cast<intptr_t>(new_handles[n].handle), open_flags[n]);
if (fd == -1)
throw Win32Exception("_open_osfhandle");
m_orig_fd[n] = _dup(open_fds[n]);
if (m_orig_fd[n] == -1)
throw Win32Exception("_dup");
if (_dup2(fd, open_fds[n]) == -1)
throw Win32Exception("_dup2");
close(fd);
}
}
Class::StdIOSwap::~StdIOSwap()
{
const static unsigned NFD = std::tuple_size<StdFiles>::value;
static const DWORD std_handles[NFD] = {STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE};
const int open_fds[NFD] = {_fileno(stdin), _fileno(stdout), _fileno(stderr)};
fflush(stdout);
fflush(stderr);
for (unsigned n = 0; n < NFD; n++)
{
if (!SetStdHandle(std_handles[n], m_orig_handle[n]))
{
abort();
}
_dup2(m_orig_fd[n], open_fds[n]);
close(m_orig_fd[n]);
}
}
#endif // WIN32
| 31.90128 | 129 | 0.618166 | kfrolov |
e7730d74ff4bf71713040b668f595157af49f731 | 325 | cpp | C++ | test/incrementalTest/tasks/legacy_namespace/tasklegacynamespacea.cpp | JamesMBallard/qmake-unity | cf5006a83e7fb1bbd173a9506771693a673d387f | [
"MIT"
] | 16 | 2019-05-23T08:10:39.000Z | 2021-12-21T11:20:37.000Z | test/incrementalTest/tasks/legacy_namespace/tasklegacynamespacea.cpp | JamesMBallard/qmake-unity | cf5006a83e7fb1bbd173a9506771693a673d387f | [
"MIT"
] | null | null | null | test/incrementalTest/tasks/legacy_namespace/tasklegacynamespacea.cpp | JamesMBallard/qmake-unity | cf5006a83e7fb1bbd173a9506771693a673d387f | [
"MIT"
] | 2 | 2019-05-23T18:37:43.000Z | 2021-08-24T21:29:40.000Z | #include "tasklegacynamespacea.h"
#include "factory.h"
#include <QDebug>
using namespace LegacyNamespaceA;
REGISTER_CLASS(TaskLegacyNamespaceA)
void TaskLegacyNamespaceA::Exec()
{
qDebug() << metaObject()->className() << ", namespace " << NamespaceName();
}
QString LegacyNamespaceA::NamespaceName() { return "A"; }
| 20.3125 | 79 | 0.732308 | JamesMBallard |
e7769f9453db407449a7908a8235f33db40e876c | 3,749 | cpp | C++ | backends/graphs/parsers.cpp | hesingh/emit-struct | 5002445545178cfeefe78220186a5d8a3081eea3 | [
"Apache-2.0"
] | 22 | 2020-08-03T18:28:39.000Z | 2021-09-27T00:25:26.000Z | backends/graphs/parsers.cpp | hesingh/emit-struct | 5002445545178cfeefe78220186a5d8a3081eea3 | [
"Apache-2.0"
] | 8 | 2019-03-03T20:26:46.000Z | 2019-04-26T16:16:16.000Z | backends/graphs/parsers.cpp | hesingh/emit-struct | 5002445545178cfeefe78220186a5d8a3081eea3 | [
"Apache-2.0"
] | 5 | 2020-08-20T02:53:31.000Z | 2021-04-13T23:43:12.000Z | /*
* Copyright (c) 2017 VMware Inc. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*
* 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 "frontends/common/resolveReferences/referenceMap.h"
#include "frontends/p4/toP4/toP4.h"
#include "lib/nullstream.h"
#include "parsers.h"
namespace graphs {
static cstring toString(const IR::Expression* expression) {
std::stringstream ss;
P4::ToP4 toP4(&ss, false);
toP4.setListTerm("(", ")");
expression->apply(toP4);
return cstring(ss.str());
}
void ParserGraphs::postorder(const IR::P4Parser *parser) {
auto path = Util::PathName(graphsDir).join(parser->name + ".dot");
LOG2("Writing parser graph " << parser->name);
auto out = openFile(path.toString(), false);
if (out == nullptr) {
::error("Failed to open file %1%", path.toString());
return;
}
(*out) << "digraph " << parser->name << "{" << std::endl;
for (auto state : states[parser]) {
cstring label = state->name;
if (state->selectExpression != nullptr &&
state->selectExpression->is<IR::SelectExpression>()) {
label += "\n" + toString(
state->selectExpression->to<IR::SelectExpression>()->select);
}
(*out) << state->name.name << " [shape=rectangle,label=\"" <<
label << "\"]" << std::endl;
}
for (auto edge : transitions[parser]) {
*out << edge->sourceState->name.name << " -> " << edge->destState->name.name <<
" [label=\"" << edge->label << "\"]" << std::endl;
}
*out << "}" << std::endl;
}
void ParserGraphs::postorder(const IR::ParserState* state) {
auto parser = findContext<IR::P4Parser>();
CHECK_NULL(parser);
states[parser].push_back(state);
}
void ParserGraphs::postorder(const IR::PathExpression* expression) {
auto state = findContext<IR::ParserState>();
if (state != nullptr) {
auto parser = findContext<IR::P4Parser>();
CHECK_NULL(parser);
auto decl = refMap->getDeclaration(expression->path);
if (decl != nullptr && decl->is<IR::ParserState>()) {
auto sc = findContext<IR::SelectCase>();
cstring label;
if (sc == nullptr) {
label = "always";
} else {
label = toString(sc->keyset);
}
transitions[parser].push_back(
new TransitionEdge(state, decl->to<IR::ParserState>(), label));
}
}
}
void ParserGraphs::postorder(const IR::SelectExpression* expression) {
// transition (..) { ... } may imply a transition to
// "reject" - if none of the cases matches.
for (auto c : expression->selectCases) {
if (c->keyset->is<IR::DefaultExpression>())
// If we have a default case this will always match
return;
}
auto state = findContext<IR::ParserState>();
auto parser = findContext<IR::P4Parser>();
CHECK_NULL(state);
CHECK_NULL(parser);
auto reject = parser->getDeclByName(IR::ParserState::reject);
CHECK_NULL(reject);
transitions[parser].push_back(
new TransitionEdge(state, reject->to<IR::ParserState>(), "fallthrough"));
}
} // namespace graphs
| 35.367925 | 87 | 0.612163 | hesingh |
e77c09b2864b2912994d8cc3873b25da9258c655 | 4,515 | cpp | C++ | src/DiffEq/Beta/MixNumberFractionBetaCoeffPolicy.cpp | franjgonzalez/Quinoa | 411eb8815e92618c563881b784e287e2dd916f89 | [
"RSA-MD"
] | null | null | null | src/DiffEq/Beta/MixNumberFractionBetaCoeffPolicy.cpp | franjgonzalez/Quinoa | 411eb8815e92618c563881b784e287e2dd916f89 | [
"RSA-MD"
] | null | null | null | src/DiffEq/Beta/MixNumberFractionBetaCoeffPolicy.cpp | franjgonzalez/Quinoa | 411eb8815e92618c563881b784e287e2dd916f89 | [
"RSA-MD"
] | null | null | null | // *****************************************************************************
/*!
\file src/DiffEq/Beta/MixNumberFractionBetaCoeffPolicy.cpp
\copyright 2012-2015 J. Bakosi,
2016-2018 Los Alamos National Security, LLC.,
2019 Triad National Security, LLC.
All rights reserved. See the LICENSE file for details.
\brief Mass-fraction beta SDE coefficients policies
\details This file defines coefficients policy classes for the mass-fraction
beta SDE, defined in DiffEq/Beta/MixNumberFractionBeta.h. For
general requirements on mixture number-fraction beta SDE
coefficients policy classes see the header file.
*/
// *****************************************************************************
#include "MixNumberFractionBetaCoeffPolicy.hpp"
walker::MixNumFracBetaCoeffDecay::MixNumFracBetaCoeffDecay(
ncomp_t ncomp,
const std::vector< kw::sde_bprime::info::expect::type >& bprime_,
const std::vector< kw::sde_S::info::expect::type >& S_,
const std::vector< kw::sde_kappaprime::info::expect::type >& kprime_,
const std::vector< kw::sde_rho2::info::expect::type >& rho2_,
const std::vector< kw::sde_rcomma::info::expect::type >& rcomma_,
std::vector< kw::sde_bprime::info::expect::type >& bprime,
std::vector< kw::sde_S::info::expect::type >& S,
std::vector< kw::sde_kappaprime::info::expect::type >& kprime,
std::vector< kw::sde_rho2::info::expect::type >& rho2,
std::vector< kw::sde_rcomma::info::expect::type >& rcomma,
std::vector< kw::sde_b::info::expect::type >& b,
std::vector< kw::sde_kappa::info::expect::type >& k )
// *****************************************************************************
// Constructor: initialize coefficients
//! \param[in] ncomp Number of scalar components in this SDE system
//! \param[in] bprime_ Vector used to initialize coefficient vector bprime
//! \param[in] S_ Vector used to initialize coefficient vector S
//! \param[in] kprime_ Vector used to initialize coefficient vector kprime
//! \param[in] rho2_ Vector used to initialize coefficient vector rho2
//! \param[in] rcomma_ Vector used to initialize coefficient vector rcomma
//! \param[in,out] bprime Coefficient vector to be initialized
//! \param[in,out] S Coefficient vector to be initialized
//! \param[in,out] kprime Coefficient vector to be initialized
//! \param[in,out] rho2 Coefficient vector to be initialized
//! \param[in,out] rcomma Coefficient vector to be initialized
//! \param[in,out] b Coefficient vector to be initialized
//! \param[in,out] k Coefficient vector to be initialized
// *****************************************************************************
{
ErrChk( bprime_.size() == ncomp,
"Wrong number of mix number-fraction beta SDE parameters 'b''");
ErrChk( S_.size() == ncomp,
"Wrong number of mix number-fraction beta SDE parameters 'S'");
ErrChk( kprime_.size() == ncomp,
"Wrong number of mix number-fraction beta SDE parameters 'kappa''");
ErrChk( rho2_.size() == ncomp,
"Wrong number of mix number-fraction beta SDE parameters 'rho2'");
ErrChk( rcomma_.size() == ncomp,
"Wrong number of mix number-fraction beta SDE parameters 'rcomma'");
bprime = bprime_;
S = S_;
kprime = kprime_;
rho2 = rho2_;
rcomma = rcomma_;
b.resize( bprime.size() );
k.resize( kprime.size() );
}
void
walker::MixNumFracBetaCoeffDecay::update(
char depvar,
ncomp_t ncomp,
const std::map< tk::ctr::Product, tk::real >& moments,
const std::vector< kw::sde_bprime::info::expect::type >& bprime,
const std::vector< kw::sde_kappaprime::info::expect::type >& kprime,
std::vector< kw::sde_b::info::expect::type >& b,
std::vector< kw::sde_kappa::info::expect::type >& k ) const
// *****************************************************************************
// Update coefficients
//! \details This where the mix number-fraction beta SDE is made consistent
//! with the no-mix and fully mixed limits by specifying the SDE
//! coefficients, b and kappa as functions of b' and kappa'.
// *****************************************************************************
{
for (ncomp_t c=0; c<ncomp; ++c) {
tk::real m = tk::ctr::lookup( tk::ctr::mean(depvar,c), moments );
tk::real v = tk::ctr::lookup( tk::ctr::variance(depvar,c), moments );
if (m<1.0e-8 || m>1.0-1.0e-8) m = 0.5;
if (v<1.0e-8 || v>1.0-1.0e-8) v = 0.5;
b[c] = bprime[c] * (1.0 - v / m / ( 1.0 - m ));
k[c] = kprime[c] * v;
}
}
| 46.071429 | 80 | 0.609302 | franjgonzalez |
e784d5471a0b3b67eec5f4c866591677d95c504c | 2,633 | hpp | C++ | tests/unit/math/rect.test.hpp | purpurina-engine/purpurina-frwk | 1df6fc2768f346fd47fd5cc3dd05daa59dea3726 | [
"MIT"
] | null | null | null | tests/unit/math/rect.test.hpp | purpurina-engine/purpurina-frwk | 1df6fc2768f346fd47fd5cc3dd05daa59dea3726 | [
"MIT"
] | null | null | null | tests/unit/math/rect.test.hpp | purpurina-engine/purpurina-frwk | 1df6fc2768f346fd47fd5cc3dd05daa59dea3726 | [
"MIT"
] | null | null | null |
#include <doctest.h>
#include <ct/math/detail/trect.hpp>
typedef ct::trect<ct::f32> rect;
typedef ct::trect<ct::i32> recti;
TEST_CASE("math/rect") {
SUBCASE("default constructors") {
rect rect0;
CHECK(rect0.x == 0.f);
CHECK(rect0.y == 0.f);
CHECK(rect0.width == 0.f);
CHECK(rect0.height == 0.f);
rect rect1(32.f, 128.f, 640.f, 480.f);
CHECK(rect1.x == 32.f);
CHECK(rect1.y == 128.f);
CHECK(rect1.width == 640.f);
CHECK(rect1.height == 480.f);
rect rect2(ct::tvec2<ct::f32>(48, -64), ct::tvec2<ct::f32>(1024, 2048));
CHECK(rect2.x == 48.f);
CHECK(rect2.y == -64.f);
CHECK(rect2.width == 1024.f);
CHECK(rect2.height == 2048.f);
};
SUBCASE("copy constructors") {
rect rect0(32.f, 128.f, 640.f, 480.f);
auto rect1(rect0);
CHECK(rect0.x == rect1.x);
CHECK(rect0.y == rect1.y);
CHECK(rect0.width == rect1.width);
CHECK(rect0.height == rect1.height);
rect rect2(32.f, 128.f, 640.f, 480.f);
auto rect3(MOV(rect2));
CHECK(rect2.x == rect3.x);
CHECK(rect2.y == rect3.y);
CHECK(rect2.width == rect3.width);
CHECK(rect2.height == rect3.height);
};
SUBCASE("array subscriptors: []") {
recti rect0(80, 128, 176, 224);
CHECK(rect0[0] == 80);
CHECK(rect0[1] == 128);
CHECK(rect0[2] == 176);
CHECK(rect0[3] == 224);
#ifdef CT_ASSERT_ENABLED
CHECK_THROWS(rect0[4] == 272);
#endif
}
SUBCASE("top left and bottom right") {
recti rect0(2048, -1024, 100, 100);
CHECK(rect0.top_left() == ct::tvec2<ct::i32>(2048, -1024));
CHECK(rect0.bottom_right() == ct::tvec2<ct::i32>(2148, -924));
}
SUBCASE("center") {
recti rect0(-96, 96, 512, 480);
CHECK(rect0.center() == ct::tvec2<ct::i32>(160, 336));
}
SUBCASE("contains") {
recti rect0(48, 640, 240, 160);
CHECK(rect0.contains(rect0.center()));
CHECK(rect0.contains(ct::tvec2<ct::i32>(100, 700)) == true);
CHECK(rect0.contains(ct::tvec2<ct::i32>(168, 639)) == false); // top
CHECK(rect0.contains(ct::tvec2<ct::i32>(168, 800)) == false); // bottom
CHECK(rect0.contains(ct::tvec2<ct::i32>(47, 720)) == false); // left
CHECK(rect0.contains(ct::tvec2<ct::i32>(288, 720)) == false); // right
CHECK(rect0.contains(ct::tvec2<ct::i32>(290, 800)) == false);
}
SUBCASE("intersects") {
recti rect0(-16, -16, 160, 160);
recti rect1(0, 0, 64, 64);
rect1.position = rect0.top_left();
rect1.x -= 176;
CHECK(rect0.intersects(rect1)); // bottom right
rect1.y += 160;
CHECK(rect0.intersects(rect1)); // top right
rect1.position = rect0.bottom_right();
rect1.x -= 32;
CHECK(rect0.intersects(rect1)); // top left
rect1.y -= 176;
CHECK(rect0.intersects(rect1)); // bottom left
}
}
| 26.867347 | 74 | 0.620965 | purpurina-engine |
e787bfbdb4fc243dc6edfe3b841d6cd684a735aa | 2,464 | hpp | C++ | src/nchip8/gui.hpp | ocanty/nchip8 | 05735e1d1273afccccf0b3cc84a620cf360a388b | [
"MIT"
] | 5 | 2019-01-08T17:55:12.000Z | 2021-05-02T07:47:08.000Z | src/nchip8/gui.hpp | ocanty/nchip8 | 05735e1d1273afccccf0b3cc84a620cf360a388b | [
"MIT"
] | null | null | null | src/nchip8/gui.hpp | ocanty/nchip8 | 05735e1d1273afccccf0b3cc84a620cf360a388b | [
"MIT"
] | 1 | 2019-03-02T12:18:08.000Z | 2019-03-02T12:18:08.000Z | //
// Created by ocanty on 26/09/18.
//
#ifndef CHIP8_NCURSES_GUI_HPP
#define CHIP8_NCURSES_GUI_HPP
#include <curses.h>
#include <sstream>
#include <vector>
#include <memory>
#include <unordered_map>
#include "cpu_daemon.hpp"
namespace nchip8
{
class gui
{
public:
//! @brief Constructor
//!
//! @param cpu shared_ptr to the cpu_daemon
//! that the GUI will display the screen, disassembly & status of
gui(std::shared_ptr<cpu_daemon>& cpu);
virtual ~gui();
//! @brief Start the GUI logic thread, this will block input and the main thread!
void loop();
private:
std::shared_ptr<cpu_daemon> m_cpu_daemon;
//! Main window width
int m_window_w = 0;
//! Main window height
int m_window_h = 0;
//! Pointers to the ncurses windows
std::shared_ptr<::WINDOW> m_window = nullptr;
std::shared_ptr<::WINDOW> m_screen_window = nullptr;
std::shared_ptr<::WINDOW> m_log_window = nullptr;
std::shared_ptr<::WINDOW> m_reg_window = nullptr;
//! @brief Rebuilds window when a size change is detected
void update_windows_on_resize();
//! The local, gui log (the one drawn by the gui)
std::vector<std::string> m_gui_log;
//! @brief Checks if data has been written to the global log,
//! pushes it to m_gui_log and redraws the window
void update_log_on_global_log_change();
//! @brief Draws log from m_gui_log
void update_log_window();
//! @brief Updates the screen if the gui is attached to a cpu_daemon
void update_screen_window();
//! @brief Update the register preview window, showing all the values of the CPU registers
void update_reg_window();
//! @brief Redraw's all the windows to the current terminal height and width
void rebuild_windows();
//! @brief Update keys
void update_keys();
//! @brief Map what ncurses chracters to what keypad key
static const std::unordered_map<int, std::uint8_t> key_mapping;
//! @brief The current keys that have been pressed
//! @details Because ncurses only tells us the current key that is pushed
//! and we want to have multi-key input into the cpu
//! we assign each pushed key a score of 100 that is decremented at 60Hz
//! when this reaches 0 the key is considered no longer pushed
std::unordered_map<int, std::uint8_t> m_keys;
};
}
#endif //CHIP8_NCURSES_GUI_HPP
| 27.685393 | 95 | 0.669237 | ocanty |
e788ed7666b15a8c7f5a5a6f3388160651f7f517 | 822 | cpp | C++ | foundation/cpp/1_basics_of_programming/1_getting_started/4_print_all_prime_till_N.cpp | vikaskbm/pepcoding | fb39b6dd62f4e5b76f75e12f2b222e2adb4854c1 | [
"MIT"
] | 2 | 2021-03-16T08:56:46.000Z | 2021-03-17T05:37:21.000Z | foundation/cpp/1_basics_of_programming/1_getting_started/4_print_all_prime_till_N.cpp | vikaskbm/pepcoding | fb39b6dd62f4e5b76f75e12f2b222e2adb4854c1 | [
"MIT"
] | null | null | null | foundation/cpp/1_basics_of_programming/1_getting_started/4_print_all_prime_till_N.cpp | vikaskbm/pepcoding | fb39b6dd62f4e5b76f75e12f2b222e2adb4854c1 | [
"MIT"
] | null | null | null | // Print All Primes Till N
// 1. You've to print all prime numbers between a range.
// 2. Take as input "low", the lower limit of range.
// 3. Take as input "high", the higher limit of range.
// 4. For the range print all the primes numbers between low and high (both included).
#include <iostream>
using namespace std;
bool is_prime(int num) {
bool prime = true;
for(int i = 2; i*i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
void print_prime(long int low, long int high) {
bool prime;
while(low <= high) {
prime = is_prime(low);
if (prime)
cout << low << endl;
low++;
}
}
int main(int argc, char **argv){
long int low, high;
cin >> low >> high;
print_prime(low, high);
return 0;
} | 22.833333 | 86 | 0.568127 | vikaskbm |
e789048757007522202c9026ec4b0ecec30e46a2 | 314 | cpp | C++ | Choinon8.cpp | huynhminhtruong/learningcourses | 7df63773abf3e56bb4a5367fe08c7afa91b2e474 | [
"MIT"
] | null | null | null | Choinon8.cpp | huynhminhtruong/learningcourses | 7df63773abf3e56bb4a5367fe08c7afa91b2e474 | [
"MIT"
] | null | null | null | Choinon8.cpp | huynhminhtruong/learningcourses | 7df63773abf3e56bb4a5367fe08c7afa91b2e474 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int isMin(int a, int b) {
if (a < b) {
return a;
}
return b;
}
int main() {
int a, b, c, r;
cin >> a >> b >> c;
if (isMin(a, b) - a == 0) {
r = b;
} else {
r = a;
}
cout << isMin(isMin(a, b), c) << " " << isMin(a, b) << " " << r << endl;
return 0;
}
| 11.62963 | 73 | 0.449045 | huynhminhtruong |
e78d448e3c899b49c4ec887e0e3e65ee1cf86981 | 11,732 | cpp | C++ | src/framework/graphics/drawpool.cpp | Mrpox/otclient | 2df4c8c6c87ab3d0cbeedf62091690837e14f2eb | [
"MIT"
] | null | null | null | src/framework/graphics/drawpool.cpp | Mrpox/otclient | 2df4c8c6c87ab3d0cbeedf62091690837e14f2eb | [
"MIT"
] | null | null | null | src/framework/graphics/drawpool.cpp | Mrpox/otclient | 2df4c8c6c87ab3d0cbeedf62091690837e14f2eb | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2010-2020 OTClient <https://github.com/edubart/otclient>
*
* 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 "drawpool.h"
#include "declarations.h"
#include <framework/core/declarations.h>
#include <framework/graphics/framebuffermanager.h>
#include <framework/graphics/graphics.h>
#include "painter.h"
const static std::hash<size_t> HASH_INT;
const static std::hash<float> HASH_FLOAT;
DrawPool g_drawPool;
void DrawPool::init()
{
n_unknowPool = g_drawPool.createPool(PoolType::UNKNOW);
use(n_unknowPool);
}
void DrawPool::terminate()
{
m_currentPool = nullptr;
for(int8 i = -1; ++i <= PoolType::UNKNOW;)
m_pools[i] = nullptr;
}
PoolFramedPtr DrawPool::createPoolF(const PoolType type)
{
auto pool = std::make_shared<FramedPool>();
pool->m_framebuffer = g_framebuffers.createFrameBuffer(true);
if(type == PoolType::MAP) pool->m_framebuffer->disableBlend();
else if(type == PoolType::LIGHT) pool->m_framebuffer->setCompositionMode(Painter::CompositionMode_Light);
m_pools[type] = pool;
return pool;
}
void DrawPool::add(const Painter::PainterState& state, const Pool::DrawMethod& method, const Painter::DrawMode drawMode)
{
updateHash(state, method);
auto& list = m_currentPool->m_objects;
if(m_forceGrouping) {
auto& groupList = m_currentPool->m_objects;
const uint16 startIndex = m_currentPool->m_indexToStartSearching ? m_currentPool->m_indexToStartSearching - 1 : 0;
const auto itFind = std::find_if(m_currentPool->m_objects.begin() + startIndex, m_currentPool->m_objects.end(), [state]
(const Pool::DrawObject& action) { return action.state == state; });
if(itFind != groupList.end()) {
(*itFind).drawMethods.push_back(method);
} else {
list.push_back(Pool::DrawObject{ state, Painter::DrawMode::Triangles, {method} });
}
return;
}
if(!list.empty()) {
auto& prevObj = list.back();
const bool sameState = prevObj.state == state;
if(!method.dest.isNull()) {
// Look for identical or opaque textures that are greater than or
// equal to the size of the previous texture, if so, remove it from the list so they don't get drawn.
for(auto itm = prevObj.drawMethods.begin(); itm != prevObj.drawMethods.end(); ++itm) {
auto& prevMtd = *itm;
if(prevMtd.dest == method.dest &&
((sameState && prevMtd.rects.second == method.rects.second) || (state.texture->isOpaque() && prevObj.state.texture->canSuperimposed()))) {
prevObj.drawMethods.erase(itm);
break;
}
}
}
if(sameState) {
prevObj.drawMode = Painter::DrawMode::Triangles;
prevObj.drawMethods.push_back(method);
return;
}
}
list.push_back(Pool::DrawObject{ state, drawMode, {method} });
}
void DrawPool::draw()
{
// Pre Draw
for(const auto& pool : m_pools) {
if(!pool->isEnabled() || !pool->hasFrameBuffer()) continue;
const auto& pf = pool->toFramedPool();
if(pf->hasModification(true) && !pool->m_objects.empty()) {
pf->m_framebuffer->bind();
for(auto& obj : pool->m_objects)
drawObject(obj);
pf->m_framebuffer->release();
}
}
// Draw
for(const auto& pool : m_pools) {
if(!pool->isEnabled()) continue;
if(pool->hasFrameBuffer()) {
const auto pf = pool->toFramedPool();
g_painter->saveAndResetState();
if(pf->m_beforeDraw) pf->m_beforeDraw();
pf->m_framebuffer->draw(pf->m_dest, pf->m_src);
if(pf->m_afterDraw) pf->m_afterDraw();
g_painter->restoreSavedState();
} else for(auto& obj : pool->m_objects)
drawObject(obj);
pool->m_objects.clear();
}
}
void DrawPool::drawObject(Pool::DrawObject& obj)
{
if(obj.action) {
obj.action();
return;
}
if(obj.drawMethods.empty()) return;
g_painter->executeState(obj.state);
if(obj.state.texture) {
obj.state.texture->create();
g_painter->setTexture(obj.state.texture.get());
}
for(const auto& method : obj.drawMethods) {
if(method.type == Pool::DrawMethodType::BOUNDING_RECT) {
m_coordsbuffer.addBoudingRect(method.rects.first, method.intValue);
} else if(method.type == Pool::DrawMethodType::RECT) {
if(obj.drawMode == Painter::DrawMode::Triangles)
m_coordsbuffer.addRect(method.rects.first, method.rects.second);
else
m_coordsbuffer.addQuad(method.rects.first, method.rects.second);
} else if(method.type == Pool::DrawMethodType::TRIANGLE) {
m_coordsbuffer.addTriangle(std::get<0>(method.points), std::get<1>(method.points), std::get<2>(method.points));
} else if(method.type == Pool::DrawMethodType::UPSIDEDOWN_RECT) {
if(obj.drawMode == Painter::DrawMode::Triangles)
m_coordsbuffer.addUpsideDownRect(method.rects.first, method.rects.second);
else
m_coordsbuffer.addUpsideDownQuad(method.rects.first, method.rects.second);
} else if(method.type == Pool::DrawMethodType::REPEATED_RECT) {
m_coordsbuffer.addRepeatedRects(method.rects.first, method.rects.second);
}
}
g_painter->drawCoords(m_coordsbuffer, obj.drawMode);
m_coordsbuffer.clear();
}
void DrawPool::addTexturedRect(const Rect& dest, const TexturePtr& texture, const Color color)
{
addTexturedRect(dest, texture, Rect(Point(), texture->getSize()), color);
}
void DrawPool::addTexturedRect(const Rect& dest, const TexturePtr& texture, const Rect& src, const Color color, const Point& originalDest)
{
if(dest.isEmpty() || src.isEmpty())
return;
Pool::DrawMethod method{
Pool::DrawMethodType::RECT,
std::make_pair(dest, src),
{},
originalDest
};
auto state = generateState();
state.color = color;
state.texture = texture;
add(state, method, Painter::DrawMode::TriangleStrip);
}
void DrawPool::addUpsideDownTexturedRect(const Rect& dest, const TexturePtr& texture, const Rect& src, const Color color)
{
if(dest.isEmpty() || src.isEmpty())
return;
Pool::DrawMethod method{ Pool::DrawMethodType::UPSIDEDOWN_RECT, std::make_pair(dest, src) };
auto state = generateState();
state.color = color;
state.texture = texture;
add(state, method, Painter::DrawMode::TriangleStrip);
}
void DrawPool::addTexturedRepeatedRect(const Rect& dest, const TexturePtr& texture, const Rect& src, const Color color)
{
if(dest.isEmpty() || src.isEmpty())
return;
Pool::DrawMethod method{ Pool::DrawMethodType::REPEATED_RECT,std::make_pair(dest, src) };
auto state = generateState();
state.color = color;
state.texture = texture;
add(state, method);
}
void DrawPool::addFilledRect(const Rect& dest, const Color color)
{
if(dest.isEmpty())
return;
Pool::DrawMethod method{ Pool::DrawMethodType::RECT,std::make_pair(dest, Rect()) };
auto state = generateState();
state.color = color;
add(state, method);
}
void DrawPool::addFilledTriangle(const Point& a, const Point& b, const Point& c, const Color color)
{
if(a == b || a == c || b == c)
return;
Pool::DrawMethod method{ Pool::DrawMethodType::TRIANGLE, {}, std::make_tuple(a, b, c) };
auto state = generateState();
state.color = color;
add(state, method);
}
void DrawPool::addBoundingRect(const Rect& dest, const Color color, int innerLineWidth)
{
if(dest.isEmpty() || innerLineWidth == 0)
return;
Pool::DrawMethod method{
Pool::DrawMethodType::BOUNDING_RECT,
std::make_pair(dest, Rect()),
{},{},
(uint16)innerLineWidth
};
auto state = generateState();
state.color = color;
add(state, method);
}
void DrawPool::addAction(std::function<void()> action)
{
m_currentPool->m_objects.push_back(Pool::DrawObject{ {}, Painter::DrawMode::None, {}, action });
}
Painter::PainterState DrawPool::generateState()
{
Painter::PainterState state = g_painter->getCurrentState();
state.clipRect = m_currentPool->m_state.clipRect;
state.compositionMode = m_currentPool->m_state.compositionMode;
state.opacity = m_currentPool->m_state.opacity;
state.alphaWriting = m_currentPool->m_state.alphaWriting;
state.shaderProgram = m_currentPool->m_state.shaderProgram;
return state;
}
void DrawPool::use(const PoolPtr& pool)
{
m_forceGrouping = false;
m_currentPool = pool ? pool : n_unknowPool;
m_currentPool->resetState();
if(m_currentPool->hasFrameBuffer()) {
poolFramed()->resetCurrentStatus();
}
}
void DrawPool::use(const PoolFramedPtr& pool, const Rect& dest, const Rect& src)
{
use(pool);
pool->m_dest = dest;
pool->m_src = src;
pool->m_state.alphaWriting = false;
}
void DrawPool::updateHash(const Painter::PainterState& state, const Pool::DrawMethod& method)
{
if(!m_currentPool->hasFrameBuffer()) return;
size_t hash = 0;
if(state.texture) {
// TODO: use uniqueID id when applying multithreading, not forgetting that in the APNG texture, the id changes every frame.
boost::hash_combine(hash, HASH_INT(state.texture->getId()));
}
if(state.opacity < 1.f)
boost::hash_combine(hash, HASH_FLOAT(state.opacity));
if(state.color != Color::white)
boost::hash_combine(hash, HASH_INT(state.color.rgba()));
if(state.compositionMode != Painter::CompositionMode_Normal)
boost::hash_combine(hash, HASH_INT(state.compositionMode));
if(state.shaderProgram)
poolFramed()->m_autoUpdate = true;
if(state.clipRect.isValid()) boost::hash_combine(hash, state.clipRect.hash());
if(method.rects.first.isValid()) boost::hash_combine(hash, method.rects.first.hash());
if(method.rects.second.isValid()) boost::hash_combine(hash, method.rects.second.hash());
const auto& a = std::get<0>(method.points),
b = std::get<1>(method.points),
c = std::get<2>(method.points);
if(!a.isNull()) boost::hash_combine(hash, a.hash());
if(!b.isNull()) boost::hash_combine(hash, b.hash());
if(!c.isNull()) boost::hash_combine(hash, c.hash());
if(method.intValue) boost::hash_combine(hash, HASH_INT(method.intValue));
if(method.hash) boost::hash_combine(hash, method.hash);
boost::hash_combine(poolFramed()->m_status.second, hash);
}
| 32.862745 | 157 | 0.65658 | Mrpox |
e79285db69f4ad768afe21bbec32498678f7f1d3 | 23,569 | hpp | C++ | libraries/chain/include/golos/chain/steem_objects.hpp | 1aerostorm/golos | 06105e960537347bee7c4657e0b63c85adfff26f | [
"MIT"
] | null | null | null | libraries/chain/include/golos/chain/steem_objects.hpp | 1aerostorm/golos | 06105e960537347bee7c4657e0b63c85adfff26f | [
"MIT"
] | null | null | null | libraries/chain/include/golos/chain/steem_objects.hpp | 1aerostorm/golos | 06105e960537347bee7c4657e0b63c85adfff26f | [
"MIT"
] | null | null | null | #pragma once
#include <golos/protocol/authority.hpp>
#include <golos/protocol/steem_operations.hpp>
#include <golos/chain/steem_object_types.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/interprocess/containers/flat_set.hpp>
namespace golos {
namespace chain {
namespace bip = boost::interprocess;
using golos::protocol::asset;
using golos::protocol::price;
using golos::protocol::asset_symbol_type;
/**
* This object is used to track pending requests to convert sbd to steem
*/
class convert_request_object
: public object<convert_request_object_type, convert_request_object> {
public:
template<typename Constructor, typename Allocator>
convert_request_object(Constructor &&c, allocator <Allocator> a) {
c(*this);
}
convert_request_object() {
}
id_type id;
account_name_type owner;
uint32_t requestid = 0; ///< id set by owner, the owner,requestid pair must be unique
asset amount;
time_point_sec conversion_date; ///< at this time the feed_history_median_price * amount
};
class escrow_object : public object<escrow_object_type, escrow_object> {
public:
template<typename Constructor, typename Allocator>
escrow_object(Constructor &&c, allocator <Allocator> a) {
c(*this);
}
escrow_object() {
}
id_type id;
uint32_t escrow_id = 20;
account_name_type from;
account_name_type to;
account_name_type agent;
time_point_sec ratification_deadline;
time_point_sec escrow_expiration;
asset sbd_balance;
asset steem_balance;
asset pending_fee;
bool to_approved = false;
bool agent_approved = false;
bool disputed = false;
bool is_approved() const {
return to_approved && agent_approved;
}
};
class savings_withdraw_object
: public object<savings_withdraw_object_type, savings_withdraw_object> {
savings_withdraw_object() = delete;
public:
template<typename Constructor, typename Allocator>
savings_withdraw_object(Constructor &&c, allocator <Allocator> a)
:memo(a) {
c(*this);
}
id_type id;
account_name_type from;
account_name_type to;
shared_string memo;
uint32_t request_id = 0;
asset amount;
time_point_sec complete;
};
/**
* If last_update is greater than 1 week, then volume gets reset to 0
*
* When a user is a maker, their volume increases
* When a user is a taker, their volume decreases
*
* Every 1000 blocks, the account that has the highest volume_weight() is paid the maximum of
* 1000 STEEM or 1000 * virtual_supply / (100*blocks_per_year) aka 10 * virtual_supply / blocks_per_year
*
* After being paid volume gets reset to 0
*/
class liquidity_reward_balance_object
: public object<liquidity_reward_balance_object_type, liquidity_reward_balance_object> {
public:
template<typename Constructor, typename Allocator>
liquidity_reward_balance_object(Constructor &&c, allocator <Allocator> a) {
c(*this);
}
liquidity_reward_balance_object() {
}
id_type id;
account_id_type owner;
int64_t steem_volume = 0;
int64_t sbd_volume = 0;
uint128_t weight = 0;
time_point_sec last_update = fc::time_point_sec::min(); /// used to decay negative liquidity balances. block num
/// this is the sort index
uint128_t volume_weight() const {
return steem_volume * sbd_volume * is_positive();
}
uint128_t min_volume_weight() const {
return std::min(steem_volume, sbd_volume) * is_positive();
}
void update_weight(bool hf9) {
weight = hf9 ? min_volume_weight() : volume_weight();
}
inline int is_positive() const {
return (steem_volume > 0 && sbd_volume > 0) ? 1 : 0;
}
};
/**
* This object gets updated once per hour, on the hour
*/
class feed_history_object
: public object<feed_history_object_type, feed_history_object> {
feed_history_object() = delete;
public:
template<typename Constructor, typename Allocator>
feed_history_object(Constructor &&c, allocator <Allocator> a)
:price_history(a.get_segment_manager()) {
c(*this);
}
id_type id;
price current_median_history; ///< the current median of the price history, used as the base for convert operations
price witness_median_history; ///< the current median of the price history not limited with min_price (raw median from witnesses)
boost::interprocess::deque <price, allocator<price>> price_history; ///< tracks this last week of median_feed one per hour
};
/**
* @brief an offer to sell a amount of a asset at a specified exchange rate by a certain time
* @ingroup object
* @ingroup protocol
* @ingroup market
*
* This limit_order_objects are indexed by @ref expiration and is automatically deleted on the first block after expiration.
*/
class limit_order_object
: public object<limit_order_object_type, limit_order_object> {
public:
template<typename Constructor, typename Allocator>
limit_order_object(Constructor &&c, allocator <Allocator> a) {
c(*this);
}
limit_order_object() {
}
id_type id;
time_point_sec created;
time_point_sec expiration;
account_name_type seller;
uint32_t orderid = 0;
share_type for_sale; ///< asset id is sell_price.base.symbol
price sell_price;
pair <asset_symbol_type, asset_symbol_type> get_market() const {
return sell_price.base.symbol < sell_price.quote.symbol ?
std::make_pair(sell_price.base.symbol, sell_price.quote.symbol)
:
std::make_pair(sell_price.quote.symbol, sell_price.base.symbol);
}
asset amount_for_sale() const {
return asset(for_sale, sell_price.base.symbol);
}
asset amount_to_receive() const {
return amount_for_sale() * sell_price;
}
};
/**
* @breif a route to send withdrawn vesting shares.
*/
class withdraw_vesting_route_object
: public object<withdraw_vesting_route_object_type, withdraw_vesting_route_object> {
public:
template<typename Constructor, typename Allocator>
withdraw_vesting_route_object(Constructor &&c, allocator <Allocator> a) {
c(*this);
}
withdraw_vesting_route_object() {
}
id_type id;
account_id_type from_account;
account_id_type to_account;
uint16_t percent = 0;
bool auto_vest = false;
};
class decline_voting_rights_request_object
: public object<decline_voting_rights_request_object_type, decline_voting_rights_request_object> {
public:
template<typename Constructor, typename Allocator>
decline_voting_rights_request_object(Constructor &&c, allocator <Allocator> a) {
c(*this);
}
decline_voting_rights_request_object() {
}
id_type id;
account_id_type account;
time_point_sec effective_date;
};
class donate_object: public object<donate_object_type, donate_object> {
public:
donate_object() = delete;
template<typename Constructor, typename Allocator>
donate_object(Constructor&& c, allocator<Allocator> a) : target(a) {
c(*this);
}
id_type id;
account_name_type app;
uint16_t version;
shared_string target;
};
class asset_object: public object<asset_object_type, asset_object> {
public:
asset_object() = delete;
template<typename Constructor, typename Allocator>
asset_object(Constructor&& c, allocator<Allocator> a) : symbols_whitelist(a), json_metadata(a) {
c(*this);
}
id_type id;
account_name_type creator;
asset max_supply;
asset supply;
bool allow_fee = false;
bool allow_override_transfer = false;
time_point_sec created;
time_point_sec modified;
using symbol_allocator_type = allocator<asset_symbol_type>;
using symbol_set_type = bip::flat_set<asset_symbol_type, std::less<asset_symbol_type>, symbol_allocator_type>;
symbol_set_type symbols_whitelist;
uint16_t fee_percent = 0;
shared_string json_metadata;
asset_symbol_type symbol() const {
return supply.symbol;
}
std::string symbol_name() const {
return supply.symbol_name();
}
bool whitelists(asset_symbol_type symbol) const {
return !symbols_whitelist.size() || symbols_whitelist.count(symbol);
}
};
struct by_price;
struct by_expiration;
struct by_account;
typedef multi_index_container <
limit_order_object,
indexed_by<
ordered_unique < tag <
by_id>, member<limit_order_object, limit_order_id_type, &limit_order_object::id>>,
ordered_non_unique <tag<by_expiration>, member<limit_order_object, time_point_sec, &limit_order_object::expiration>>,
ordered_unique <tag<by_price>,
composite_key<limit_order_object,
member <
limit_order_object, price, &limit_order_object::sell_price>,
member<limit_order_object, limit_order_id_type, &limit_order_object::id>
>,
composite_key_compare <std::greater<price>, std::less<limit_order_id_type>>
>,
ordered_unique <tag<by_account>,
composite_key<limit_order_object,
member <
limit_order_object, account_name_type, &limit_order_object::seller>,
member<limit_order_object, uint32_t, &limit_order_object::orderid>
>
>
>,
allocator <limit_order_object>
>
limit_order_index;
struct by_owner;
struct by_conversion_date;
typedef multi_index_container <
convert_request_object,
indexed_by<
ordered_unique < tag <
by_id>, member<convert_request_object, convert_request_id_type, &convert_request_object::id>>,
ordered_unique <tag<by_conversion_date>,
composite_key<convert_request_object,
member <
convert_request_object, time_point_sec, &convert_request_object::conversion_date>,
member<convert_request_object, convert_request_id_type, &convert_request_object::id>
>
>,
ordered_unique <tag<by_owner>,
composite_key<convert_request_object,
member <
convert_request_object, account_name_type, &convert_request_object::owner>,
member<convert_request_object, uint32_t, &convert_request_object::requestid>
>
>
>,
allocator <convert_request_object>
>
convert_request_index;
struct by_owner;
struct by_volume_weight;
typedef multi_index_container <
liquidity_reward_balance_object,
indexed_by<
ordered_unique < tag <
by_id>, member<liquidity_reward_balance_object, liquidity_reward_balance_id_type, &liquidity_reward_balance_object::id>>,
ordered_unique <tag<by_owner>, member<liquidity_reward_balance_object, account_id_type, &liquidity_reward_balance_object::owner>>,
ordered_unique <tag<by_volume_weight>,
composite_key<liquidity_reward_balance_object,
member <
liquidity_reward_balance_object, fc::uint128_t, &liquidity_reward_balance_object::weight>,
member<liquidity_reward_balance_object, account_id_type, &liquidity_reward_balance_object::owner>
>,
composite_key_compare <std::greater<fc::uint128_t>, std::less<account_id_type>>
>
>,
allocator <liquidity_reward_balance_object>
>
liquidity_reward_balance_index;
typedef multi_index_container <
feed_history_object,
indexed_by<
ordered_unique < tag <
by_id>, member<feed_history_object, feed_history_id_type, &feed_history_object::id>>
>,
allocator <feed_history_object>
>
feed_history_index;
struct by_withdraw_route;
struct by_destination;
typedef multi_index_container <
withdraw_vesting_route_object,
indexed_by<
ordered_unique < tag <
by_id>, member<withdraw_vesting_route_object, withdraw_vesting_route_id_type, &withdraw_vesting_route_object::id>>,
ordered_unique <tag<by_withdraw_route>,
composite_key<withdraw_vesting_route_object,
member <
withdraw_vesting_route_object, account_id_type, &withdraw_vesting_route_object::from_account>,
member<withdraw_vesting_route_object, account_id_type, &withdraw_vesting_route_object::to_account>
>,
composite_key_compare <std::less<account_id_type>, std::less<account_id_type>>
>,
ordered_unique <tag<by_destination>,
composite_key<withdraw_vesting_route_object,
member <
withdraw_vesting_route_object, account_id_type, &withdraw_vesting_route_object::to_account>,
member<withdraw_vesting_route_object, withdraw_vesting_route_id_type, &withdraw_vesting_route_object::id>
>
>
>,
allocator <withdraw_vesting_route_object>
>
withdraw_vesting_route_index;
struct by_from_id;
struct by_to;
struct by_agent;
struct by_ratification_deadline;
struct by_sbd_balance;
typedef multi_index_container <
escrow_object,
indexed_by<
ordered_unique < tag <
by_id>, member<escrow_object, escrow_id_type, &escrow_object::id>>,
ordered_unique <tag<by_from_id>,
composite_key<escrow_object,
member <
escrow_object, account_name_type, &escrow_object::from>,
member<escrow_object, uint32_t, &escrow_object::escrow_id>
>
>,
ordered_unique <tag<by_to>,
composite_key<escrow_object,
member < escrow_object, account_name_type, &escrow_object::to>,
member<escrow_object, escrow_id_type, &escrow_object::id>
>
>,
ordered_unique <tag<by_agent>,
composite_key<escrow_object,
member <
escrow_object, account_name_type, &escrow_object::agent>,
member<escrow_object, escrow_id_type, &escrow_object::id>
>
>,
ordered_unique <tag<by_ratification_deadline>,
composite_key<escrow_object,
const_mem_fun <
escrow_object, bool, &escrow_object::is_approved>,
member<escrow_object, time_point_sec, &escrow_object::ratification_deadline>,
member<escrow_object, escrow_id_type, &escrow_object::id>
>,
composite_key_compare <std::less<bool>, std::less<time_point_sec>, std::less<escrow_id_type>>
>,
ordered_unique <tag<by_sbd_balance>,
composite_key<escrow_object,
member < escrow_object, asset, &escrow_object::sbd_balance>,
member<escrow_object, escrow_id_type, &escrow_object::id>
>,
composite_key_compare <std::greater<asset>, std::less<escrow_id_type>>
>
>,
allocator <escrow_object>
>
escrow_index;
struct by_from_rid;
struct by_to_complete;
struct by_complete_from_rid;
typedef multi_index_container <
savings_withdraw_object,
indexed_by<
ordered_unique < tag <
by_id>, member<savings_withdraw_object, savings_withdraw_id_type, &savings_withdraw_object::id>>,
ordered_unique <tag<by_from_rid>,
composite_key<savings_withdraw_object,
member <
savings_withdraw_object, account_name_type, &savings_withdraw_object::from>,
member<savings_withdraw_object, uint32_t, &savings_withdraw_object::request_id>
>
>,
ordered_unique <tag<by_to_complete>,
composite_key<savings_withdraw_object,
member <
savings_withdraw_object, account_name_type, &savings_withdraw_object::to>,
member<savings_withdraw_object, time_point_sec, &savings_withdraw_object::complete>,
member<savings_withdraw_object, savings_withdraw_id_type, &savings_withdraw_object::id>
>
>,
ordered_unique <tag<by_complete_from_rid>,
composite_key<savings_withdraw_object,
member <
savings_withdraw_object, time_point_sec, &savings_withdraw_object::complete>,
member<savings_withdraw_object, account_name_type, &savings_withdraw_object::from>,
member<savings_withdraw_object, uint32_t, &savings_withdraw_object::request_id>
>
>
>,
allocator <savings_withdraw_object>
>
savings_withdraw_index;
struct by_account;
struct by_effective_date;
typedef multi_index_container <
decline_voting_rights_request_object,
indexed_by<
ordered_unique < tag <
by_id>, member<decline_voting_rights_request_object, decline_voting_rights_request_id_type, &decline_voting_rights_request_object::id>>,
ordered_unique <tag<by_account>,
member<decline_voting_rights_request_object, account_id_type, &decline_voting_rights_request_object::account>
>,
ordered_unique <tag<by_effective_date>,
composite_key<decline_voting_rights_request_object,
member <
decline_voting_rights_request_object, time_point_sec, &decline_voting_rights_request_object::effective_date>,
member<decline_voting_rights_request_object, account_id_type, &decline_voting_rights_request_object::account>
>,
composite_key_compare <std::less<time_point_sec>, std::less<account_id_type>>
>
>,
allocator <decline_voting_rights_request_object>
>
decline_voting_rights_request_index;
struct by_app_version;
using donate_index = multi_index_container<
donate_object,
indexed_by<
ordered_unique<tag<by_id>, member<donate_object, donate_object_id_type, &donate_object::id>>,
ordered_non_unique<tag<by_app_version>, composite_key<donate_object,
member<donate_object, account_name_type, &donate_object::app>,
member<donate_object, uint16_t, &donate_object::version>
>>>,
allocator<donate_object>>;
struct by_creator_symbol_name;
struct by_symbol;
struct by_symbol_name;
using asset_index = multi_index_container<
asset_object,
indexed_by<
ordered_unique<tag<by_id>,
member<asset_object, asset_object_id_type, &asset_object::id>
>,
ordered_unique<tag<by_creator_symbol_name>, composite_key<asset_object,
member<asset_object, account_name_type, &asset_object::creator>,
const_mem_fun<asset_object, std::string, &asset_object::symbol_name>
>>,
ordered_unique<tag<by_symbol>,
const_mem_fun<asset_object, asset_symbol_type, &asset_object::symbol>
>,
ordered_unique<tag<by_symbol_name>,
const_mem_fun<asset_object, std::string, &asset_object::symbol_name>
>
>, allocator<asset_object>>;
}
} // golos::chain
#include <golos/chain/comment_object.hpp>
#include <golos/chain/account_object.hpp>
FC_REFLECT((golos::chain::limit_order_object),
(id)(created)(expiration)(seller)(orderid)(for_sale)(sell_price))
CHAINBASE_SET_INDEX_TYPE(golos::chain::limit_order_object, golos::chain::limit_order_index)
FC_REFLECT((golos::chain::feed_history_object),
(id)(current_median_history)(witness_median_history)(price_history))
CHAINBASE_SET_INDEX_TYPE(golos::chain::feed_history_object, golos::chain::feed_history_index)
FC_REFLECT((golos::chain::convert_request_object),
(id)(owner)(requestid)(amount)(conversion_date))
CHAINBASE_SET_INDEX_TYPE(golos::chain::convert_request_object, golos::chain::convert_request_index)
FC_REFLECT((golos::chain::liquidity_reward_balance_object),
(id)(owner)(steem_volume)(sbd_volume)(weight)(last_update))
CHAINBASE_SET_INDEX_TYPE(golos::chain::liquidity_reward_balance_object, golos::chain::liquidity_reward_balance_index)
FC_REFLECT((golos::chain::withdraw_vesting_route_object),
(id)(from_account)(to_account)(percent)(auto_vest))
CHAINBASE_SET_INDEX_TYPE(golos::chain::withdraw_vesting_route_object, golos::chain::withdraw_vesting_route_index)
FC_REFLECT((golos::chain::savings_withdraw_object),
(id)(from)(to)(memo)(request_id)(amount)(complete))
CHAINBASE_SET_INDEX_TYPE(golos::chain::savings_withdraw_object, golos::chain::savings_withdraw_index)
FC_REFLECT((golos::chain::escrow_object),
(id)(escrow_id)(from)(to)(agent)
(ratification_deadline)(escrow_expiration)
(sbd_balance)(steem_balance)(pending_fee)
(to_approved)(agent_approved)(disputed))
CHAINBASE_SET_INDEX_TYPE(golos::chain::escrow_object, golos::chain::escrow_index)
FC_REFLECT((golos::chain::decline_voting_rights_request_object),
(id)(account)(effective_date))
CHAINBASE_SET_INDEX_TYPE(golos::chain::decline_voting_rights_request_object, golos::chain::decline_voting_rights_request_index)
CHAINBASE_SET_INDEX_TYPE(golos::chain::donate_object, golos::chain::donate_index)
CHAINBASE_SET_INDEX_TYPE(golos::chain::asset_object, golos::chain::asset_index)
| 38.701149 | 152 | 0.630532 | 1aerostorm |
e79701c6c68a0f5ffb35063a0458e989eea949b5 | 5,602 | cpp | C++ | src/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/pybind11_cross_module_tests.cpp | matchRos/simulation_multirobots | 286c5add84d521ad371b2c8961dea872c34e7da2 | [
"BSD-2-Clause"
] | 15 | 2020-04-17T17:25:47.000Z | 2022-02-02T09:28:56.000Z | src/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/pybind11_cross_module_tests.cpp | matchRos/simulation_multirobots | 286c5add84d521ad371b2c8961dea872c34e7da2 | [
"BSD-2-Clause"
] | 84 | 2020-04-29T17:22:04.000Z | 2022-02-14T12:24:59.000Z | src/orocos_kinematics_dynamics/python_orocos_kdl/pybind11/tests/pybind11_cross_module_tests.cpp | matchRos/simulation_multirobots | 286c5add84d521ad371b2c8961dea872c34e7da2 | [
"BSD-2-Clause"
] | 2 | 2021-03-02T04:15:05.000Z | 2022-01-15T11:59:22.000Z | /*
tests/pybind11_cross_module_tests.cpp -- contains tests that require multiple modules
Copyright (c) 2017 Jason Rhinelander <jason@imaginary.ca>
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
*/
#include "pybind11_tests.h"
#include "local_bindings.h"
#include "test_exceptions.h"
#include <pybind11/stl_bind.h>
#include <numeric>
#include <utility>
PYBIND11_MODULE(pybind11_cross_module_tests, m) {
m.doc() = "pybind11 cross-module test module";
// test_local_bindings.py tests:
//
// Definitions here are tested by importing both this module and the
// relevant pybind11_tests submodule from a test_whatever.py
// test_load_external
bind_local<ExternalType1>(m, "ExternalType1", py::module_local());
bind_local<ExternalType2>(m, "ExternalType2", py::module_local());
// test_exceptions.py
m.def("raise_runtime_error", []() { PyErr_SetString(PyExc_RuntimeError, "My runtime error"); throw py::error_already_set(); });
m.def("raise_value_error", []() { PyErr_SetString(PyExc_ValueError, "My value error"); throw py::error_already_set(); });
m.def("throw_pybind_value_error", []() { throw py::value_error("pybind11 value error"); });
m.def("throw_pybind_type_error", []() { throw py::type_error("pybind11 type error"); });
m.def("throw_stop_iteration", []() { throw py::stop_iteration(); });
py::register_exception_translator([](std::exception_ptr p) {
try {
if (p) std::rethrow_exception(p);
} catch (const shared_exception &e) {
PyErr_SetString(PyExc_KeyError, e.what());
}
});
// test_local_bindings.py
// Local to both:
bind_local<LocalType, 1>(m, "LocalType", py::module_local())
.def("get2", [](LocalType &t) { return t.i + 2; })
;
// Can only be called with our python type:
m.def("local_value", [](LocalType &l) { return l.i; });
// test_nonlocal_failure
// This registration will fail (global registration when LocalFail is already registered
// globally in the main test module):
m.def("register_nonlocal", [m]() {
bind_local<NonLocalType, 0>(m, "NonLocalType");
});
// test_stl_bind_local
// stl_bind.h binders defaults to py::module_local if the types are local or converting:
py::bind_vector<LocalVec>(m, "LocalVec");
py::bind_map<LocalMap>(m, "LocalMap");
// test_stl_bind_global
// and global if the type (or one of the types, for the map) is global (so these will fail,
// assuming pybind11_tests is already loaded):
m.def("register_nonlocal_vec", [m]() {
py::bind_vector<NonLocalVec>(m, "NonLocalVec");
});
m.def("register_nonlocal_map", [m]() {
py::bind_map<NonLocalMap>(m, "NonLocalMap");
});
// The default can, however, be overridden to global using `py::module_local()` or
// `py::module_local(false)`.
// Explicitly made local:
py::bind_vector<NonLocalVec2>(m, "NonLocalVec2", py::module_local());
// Explicitly made global (and so will fail to bind):
m.def("register_nonlocal_map2", [m]() {
py::bind_map<NonLocalMap2>(m, "NonLocalMap2", py::module_local(false));
});
// test_mixed_local_global
// We try this both with the global type registered first and vice versa (the order shouldn't
// matter).
m.def("register_mixed_global_local", [m]() {
bind_local<MixedGlobalLocal, 200>(m, "MixedGlobalLocal", py::module_local());
});
m.def("register_mixed_local_global", [m]() {
bind_local<MixedLocalGlobal, 2000>(m, "MixedLocalGlobal", py::module_local(false));
});
m.def("get_mixed_gl", [](int i) { return MixedGlobalLocal(i); });
m.def("get_mixed_lg", [](int i) { return MixedLocalGlobal(i); });
// test_internal_locals_differ
m.def("local_cpp_types_addr", []() { return (uintptr_t) &py::detail::registered_local_types_cpp(); });
// test_stl_caster_vs_stl_bind
py::bind_vector<std::vector<int>>(m, "VectorInt");
m.def("load_vector_via_binding", [](std::vector<int> &v) {
return std::accumulate(v.begin(), v.end(), 0);
});
// test_cross_module_calls
m.def("return_self", [](LocalVec *v) { return v; });
m.def("return_copy", [](const LocalVec &v) { return LocalVec(v); });
class Dog : public pets::Pet {
public:
Dog(std::string name) : Pet(std::move(name)) {}
};
py::class_<pets::Pet>(m, "Pet", py::module_local())
.def("name", &pets::Pet::name);
// Binding for local extending class:
py::class_<Dog, pets::Pet>(m, "Dog")
.def(py::init<std::string>());
m.def("pet_name", [](pets::Pet &p) { return p.name(); });
py::class_<MixGL>(m, "MixGL", py::module_local()).def(py::init<int>());
m.def("get_gl_value", [](MixGL &o) { return o.i + 100; });
py::class_<MixGL2>(m, "MixGL2", py::module_local()).def(py::init<int>());
// test_vector_bool
// We can't test both stl.h and stl_bind.h conversions of `std::vector<bool>` within
// the same module (it would be an ODR violation). Therefore `bind_vector` of `bool`
// is defined here and tested in `test_stl_binders.py`.
py::bind_vector<std::vector<bool>>(m, "VectorBool");
// test_missing_header_message
// The main module already includes stl.h, but we need to test the error message
// which appears when this header is missing.
m.def("missing_header_arg", [](const std::vector<float> &) {});
m.def("missing_header_return", []() { return std::vector<float>(); });
}
| 40.594203 | 131 | 0.650303 | matchRos |
e7973b06cb60cec789733ecb028636b04ea10f0c | 693 | cpp | C++ | src/constraint/DefaultTestableOutcome.cpp | usc-csci-545/aikido | afd8b203c17cb0b05d7db436f8bffbbe2111a75a | [
"BSD-3-Clause"
] | null | null | null | src/constraint/DefaultTestableOutcome.cpp | usc-csci-545/aikido | afd8b203c17cb0b05d7db436f8bffbbe2111a75a | [
"BSD-3-Clause"
] | null | null | null | src/constraint/DefaultTestableOutcome.cpp | usc-csci-545/aikido | afd8b203c17cb0b05d7db436f8bffbbe2111a75a | [
"BSD-3-Clause"
] | null | null | null | #include <aikido/constraint/DefaultTestableOutcome.hpp>
namespace aikido {
namespace constraint {
//==============================================================================
bool DefaultTestableOutcome::isSatisfied() const
{
return mSatisfiedFlag;
}
//==============================================================================
std::string DefaultTestableOutcome::toString() const
{
if (mSatisfiedFlag)
return "true";
return "false";
}
//==============================================================================
void DefaultTestableOutcome::setSatisfiedFlag(bool satisfiedFlag)
{
mSatisfiedFlag = satisfiedFlag;
}
} // namespace constraint
} // namespace aikido
| 23.896552 | 80 | 0.497835 | usc-csci-545 |
e79b2729f263c7f0728590d71f85e51c27469101 | 7,003 | cpp | C++ | src/uMOOSArduinoLib/NetUtil/tcpblockio.cpp | mandad/moos-ivp-manda | 6bc81d14aba7c537b7932d6135eed7a5b39c3c52 | [
"MIT"
] | 9 | 2016-02-25T03:25:53.000Z | 2022-03-27T09:47:50.000Z | src/uMOOSArduinoLib/NetUtil/tcpblockio.cpp | mandad/moos-ivp-manda | 6bc81d14aba7c537b7932d6135eed7a5b39c3c52 | [
"MIT"
] | null | null | null | src/uMOOSArduinoLib/NetUtil/tcpblockio.cpp | mandad/moos-ivp-manda | 6bc81d14aba7c537b7932d6135eed7a5b39c3c52 | [
"MIT"
] | 4 | 2016-06-02T17:42:42.000Z | 2021-12-15T09:37:55.000Z | /* tcpblockio.c - a set of functions that define a block i/o interface to TCP.
* These functions encapsulate all the steps needed to:
* - read and write blocks of a specified size
* - open clients and listeners
* must be linked with -lnsl and -lsocket on solaris
*/
#define _POSIX_C_SOURCE 200809L
#define _ISOC99_SOURCE
#define _XOPEN_SOURCE 700
#define __EXTENSIONS__
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
#include <errno.h>
#include <sys/param.h>
#include <netdb.h>
#include "tcpblockio.h"
#define LISTENING_DEPTH 3
/* Returns after all nbytes characters from buffer have been written to fd.
* Will return sooner if an error is encountered.
* Value returned is actual number of bytes written, or -errno if hit an error.
*/
int
writeblock(int fd, void *buffer, int nbytes)
{
int n; /* number of bytes actually sent in one write*/
int offset; /* total number of bytes sent so far */
char *bufptr; /* pointer to next byte to send */
for (offset = 0, bufptr = (char *)buffer; offset < nbytes; offset += n) {
if ((n = send(fd, bufptr, nbytes-offset, 0)) < 0) {
if (errno == EINTR)
n = 0; /* interrupted by signal, keep going */
else {
if (offset == 0)
offset = -errno;
perror("send to socket");
break;
}
} else {
bufptr += n; /* point at byte following last sent */
}
}
return offset; /* return total number of bytes actually sent*/
} /* writeblock */
/* Returns after all nbytes characters have been read into buffer from fd.
* Will return sooner if an end of file is encountered.
* Value returned is actual number of bytes read, or -errno if hit an error.
*/
int readblock(int fd, void *buffer, int nbytes)
{
int n; /* number of bytes actually received in read */
int offset; /* total number of bytes received so far */
char *bufptr; /* pointer to next byte to read into */
for (offset = 0, bufptr = (char *)buffer; offset < nbytes; offset += n) {
if ((n = recv(fd, bufptr, nbytes-offset, 0)) < 0) {
if (errno == EINTR)
n = 0; /* interrupted by signal, keep going */
else {
if (offset == 0)
offset = -errno;
perror("recv from socket");
break;
}
} else if( n == 0 ) {
break; /* end of file on receive */
} else {
bufptr += n; /* point at byte following last read */
}
}
return offset; /* return total number of bytes actually read */
} /* readblock */
/* Opens a new TCP socket to server on node server_node, port server_port.
* Returns in server_addr the server's IPv4 address structure,
* and in client_addr the client's IPv4 address structure.
* Returns an fd that is connected to the server, or -1 on an error.
*/
int openclient(char *server_port, char *server_node,
struct sockaddr *server_addr,
struct sockaddr *client_addr)
{
int fd, err;
socklen_t len;
char local_node[MAXHOSTNAMELEN];
struct addrinfo *aptr, hints;
/* get internet name of the local host node on which we are running */
if (gethostname(local_node, MAXHOSTNAMELEN) < 0) {
perror("openclient gethostname");
return -1;
}
/* set up the name of the remote host node for the server */
if (server_node == NULL)
server_node = local_node; /* default to local node */
/* get structure for remote host node on which server resides */
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if ((err = getaddrinfo(server_node, server_port, &hints, &aptr))) {
fprintf(stderr, "%s port %s: %s\n", server_node, server_port,
gai_strerror(err));
return -1;
}
/* open an internet tcp socket for client to connect on */
if ((fd = socket(aptr->ai_family, aptr->ai_socktype, 0)) < 0) {
perror("openclient socket");
freeaddrinfo(aptr);
return -1;
}
/* connect this socket to the server's Internet address */
if (connect(fd, aptr->ai_addr, aptr->ai_addrlen) < 0 ) {
perror("openclient connect");
close(fd);
freeaddrinfo(aptr);
return -1;
}
if (client_addr) {
/* caller wants local port number assigned to this client */
len = sizeof(struct sockaddr);
if (getsockname(fd, client_addr, &len) < 0 ) {
perror("client getsockname");
close(fd);
freeaddrinfo(aptr);
return -1;
}
if (server_addr != NULL)
/* caller wants server addess info returned */
memcpy(server_addr, aptr->ai_addr, aptr->ai_addrlen);
}
/* we are now successfully connected to a remote server */
freeaddrinfo(aptr);
return fd; /* return fd of connected socket */
} /* openclient */
/* Opens a new TCP socket for the listener at interface listen_name,
* port listen_port. Returns in listen_addr the listener's internet
* address structure. The listener is NOT connected to a client on return.
* Returns an fd that is a "listening post" on which to make connections.
*/
int
openlistener(char *listen_port, char *listen_name,
struct sockaddr *listen_address)
{
int fd, err;
socklen_t len;
struct addrinfo *aptr, hints;
char *host_name, *host_port;
if (listen_name == NULL)
host_name = (char *)std::string("0.0.0.0").c_str(); /* all available interfaces */
else
host_name = listen_name;
if (listen_port == NULL)
host_port = (char *)std::string("0").c_str(); /* let system assign a port */
else
host_port = listen_port;
/* get structure for local interface listener is to use */
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ((err = getaddrinfo(host_name, listen_port, &hints, &aptr))) {
fprintf(stderr, "%s: %s port %s\n", host_name, host_port,
gai_strerror(err));
return -1;
}
/* open an internet tcp socket for listener to listen on */
if ((fd = socket(aptr->ai_family, aptr->ai_socktype, 0)) < 0) {
perror("openlistener socket");
freeaddrinfo(aptr);
return -1;
}
/* bind this socket to the listener's Internet address */
if (bind(fd, aptr->ai_addr, aptr->ai_addrlen) < 0) {
perror("openlistener bind");
close(fd);
freeaddrinfo(aptr);
return -1;
}
/* set up listening backlog for connect requests from clients */
if (listen(fd, LISTENING_DEPTH) < 0) {
perror("openlistener listen");
close(fd);
freeaddrinfo(aptr);
return -1;
}
if (listen_address) {
/* caller wants local port number assigned to this listener */
len = sizeof(struct sockaddr);
if (getsockname(fd, listen_address, &len) < 0 ){
perror("openlistener getsockname");
close(fd);
freeaddrinfo(aptr);
return -1;
}
}
/* we are now successfully established as a listener */
freeaddrinfo(aptr);
return fd; /* return fd of listening socket */
} /* openlistener */
/* vi: set autoindent tabstop=8 shiftwidth=8 : */
| 30.986726 | 89 | 0.648865 | mandad |
e7a1e5ffa070b8adec7e1ce8c972268aaaad3a45 | 778 | cpp | C++ | pulsar/util/Mangle.cpp | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | pulsar/util/Mangle.cpp | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | pulsar/util/Mangle.cpp | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | /*! \file
*
* \brief Mangling/Demangling helpers (source)
* \author Benjamin Pritchard (ben@bennyp.org)
*/
#include <cxxabi.h>
#include "pulsar/util/Mangle.hpp"
namespace pulsar{
std::string demangle_cpp(const char * typestr)
{
// taken from https://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html
int status;
char * realname;
// by default, return typestr, unless the
// demangling fails. Should it ever?
std::string ret(typestr);
realname = abi::__cxa_demangle(typestr, NULL, NULL, &status);
if(status == 0)
ret = std::string(realname);
free(realname);
return ret;
}
std::string demangle_cpp(const std::string & typestr)
{
return demangle_cpp(typestr.c_str());
}
} // close namespace pulsar
| 18.97561 | 85 | 0.664524 | pulsar-chem |
e7a1e75a6190370a596c247d9280f0e87289ebb0 | 426 | cc | C++ | P1-Introduction/P42042.cc | srmeeseeks/PRO1-jutge-FIB | 3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1 | [
"MIT"
] | null | null | null | P1-Introduction/P42042.cc | srmeeseeks/PRO1-jutge-FIB | 3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1 | [
"MIT"
] | null | null | null | P1-Introduction/P42042.cc | srmeeseeks/PRO1-jutge-FIB | 3af3d28c77ff14a5dbff20b1b5ddc4178462d8a1 | [
"MIT"
] | null | null | null | //Classificació de caràcters (1)
#include <iostream>
using namespace std;
int main() {
char c;
cin >> c;
if (c >= 'A' and c <= 'Z') cout << "majuscula";
else cout << "minuscula";
cout << endl;
if (c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u' or c == 'A' or
c == 'E' or c == 'I' or c == 'O' or c == 'U') cout << "vocal";
else cout << "consonant";
cout << endl;
}
| 23.666667 | 80 | 0.455399 | srmeeseeks |
e7a32d80887bdb61105720ef8702a3e7e2637109 | 168 | cpp | C++ | GameEngine/src/GameEngine/Renderer/RenderCommand.cpp | josh-teichro/game-engine | be016e1a5d58b01255093bb08926969706f3e69a | [
"Apache-2.0"
] | null | null | null | GameEngine/src/GameEngine/Renderer/RenderCommand.cpp | josh-teichro/game-engine | be016e1a5d58b01255093bb08926969706f3e69a | [
"Apache-2.0"
] | null | null | null | GameEngine/src/GameEngine/Renderer/RenderCommand.cpp | josh-teichro/game-engine | be016e1a5d58b01255093bb08926969706f3e69a | [
"Apache-2.0"
] | null | null | null | #include "gepch.h"
#include "GameEngine/Renderer/RenderCommand.h"
namespace GameEngine {
Scope<RendererAPI> RenderCommand::s_RendererAPI = RendererAPI::Create();
} | 18.666667 | 73 | 0.77381 | josh-teichro |
e7a478ec621ec8190b9ab35c27f9a0b20b3d5db7 | 10,632 | cxx | C++ | AD/ADrec/AliADDecision.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | null | null | null | AD/ADrec/AliADDecision.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 2 | 2016-11-25T08:40:56.000Z | 2019-10-11T12:29:29.000Z | AD/ADrec/AliADDecision.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | null | null | null | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-------------------------------------------
// Class : AliADDecision
//
// Fill up the trigger mask word.
//
#include <Riostream.h>
#include <TGeoManager.h>
#include <TGeoMatrix.h>
#include <TGeoPhysicalNode.h>
#include <TF1.h>
#include <TMath.h>
#include <AliGeomManager.h>
#include "AliLog.h"
#include "AliADDecision.h"
#include "AliADConst.h"
#include "AliADCalibData.h"
#include "AliESDAD.h"
#include "AliADReconstructor.h"
//______________________________________________________________________
ClassImp(AliADDecision)
//______________________________________________________________________
AliADDecision::AliADDecision()
:TObject(),
fADADist(0),
fADCDist(0),
fRecoParam(NULL),
fEarlyHitCutShape(NULL)
{
// Default constructor
//AD has two layers, filling average
Float_t zADA = (TMath::Abs(GetZPosition("AD/ADA1")) + TMath::Abs(GetZPosition("AD/ADA2")))/2;
Float_t zADC = (TMath::Abs(GetZPosition("AD/ADC1")) + TMath::Abs(GetZPosition("AD/ADC2")))/2;
// distance in time units from nominal vertex to AD
fADADist = zADA/TMath::Ccgs()*1e9;
fADCDist = zADC/TMath::Ccgs()*1e9;
//fADADist = 56.6958892608299081;
//fADCDist = 65.1917667655268360;
fEarlyHitCutShape = new TF1("fEarlyHitCutShape", " [0]+(x>[2])*[1]*(x-[2])**2");
}
//______________________________________________________________________
AliADDecision::~AliADDecision()
{
// d-tor
delete fEarlyHitCutShape;
}
//________________________________________________________________________________
Double_t AliADDecision::GetZPosition(const char* symname)
{
// Get the global z coordinate of the given AD alignable volume
//
Double_t *tr;
TGeoPNEntry *pne = gGeoManager->GetAlignableEntry(symname);
if (!pne) {
AliFatalClass(Form("TGeoPNEntry with symbolic name %s does not exist!",symname));
return 0;
}
TGeoPhysicalNode *pnode = pne->GetPhysicalNode();
if(pnode){
TGeoHMatrix* hm = pnode->GetMatrix();
tr = hm->GetTranslation();
}else{
const char* path = pne->GetTitle();
if(!gGeoManager->cd(path)){
AliFatalClass(Form("Volume path %s not valid!",path));
return 0;
}
tr = gGeoManager->GetCurrentMatrix()->GetTranslation();
}
return tr[2];
}
//________________________________________________________________________________
void AliADDecision::FillDecisions(AliESDAD *esdAD)
{
// Fill up offline trigger decisions
// using the TDC data (already corrected for
// slewing and misalignment between channels)
esdAD->SetBit(AliESDAD::kDecisionFilled,kTRUE);
esdAD->SetBit(AliESDAD::kTriggerBitsFilled,kTRUE);
// loop over AD channels
Double_t timeADA =0., timeADC = 0.;
Double_t weightADA =0., weightADC = 0.;
UInt_t ntimeADA=0, ntimeADC=0;
UInt_t itimeADA[8], itimeADC[8];
//Compute average time with basic method(charge weighted average)
Double_t timeBasicADA=0, timeBasicADC=0;
Double_t weightBasicADA =0., weightBasicADC = 0.;
UInt_t ntimeBasicADA=0, ntimeBasicADC=0;
UInt_t itimeBasicADA[8], itimeBasicADC[8];
for (Int_t i = 0; i < 16; ++i) {
Float_t adc = esdAD->GetAdc(i);
if (adc > GetRecoParam()->GetAdcThresHold()) {
Float_t time = esdAD->GetTime(i);
if(time > (AliADReconstructor::kInvalidTime+1.e-6)){
Float_t timeErr = 1;
if (adc>1) timeErr = 1/adc;
if (i<8) {
itimeBasicADC[ntimeBasicADC] = i;
ntimeBasicADC++;
timeBasicADC += time/(timeErr*timeErr);
weightBasicADC += 1./(timeErr*timeErr);
}
else{
itimeBasicADA[ntimeBasicADA] = i-8;
ntimeBasicADA++;
timeBasicADA += time/(timeErr*timeErr);
weightBasicADA += 1./(timeErr*timeErr);
}
}
}
} // end of loop over channels
if(weightBasicADA > 1) timeBasicADA /= weightBasicADA;
else timeBasicADA = -1024.;
if(weightBasicADC > 1) timeBasicADC /= weightBasicADC;
else timeBasicADC = -1024.;
//Robust time: Pad coincidence and early hit removal
Double_t timeRobustADA=0, timeRobustADC=0;
Double_t weightRobustADA =0., weightRobustADC = 0.;
UInt_t ntimeRobustADA=0, ntimeRobustADC=0;
UInt_t itimeRobustADA[8], itimeRobustADC[8];
fEarlyHitCutShape->SetParameter(0,GetRecoParam()->GetMaxResid());
fEarlyHitCutShape->SetParameter(1,GetRecoParam()->GetResidRise());
//C-side
fEarlyHitCutShape->SetParameter(2,2*fADCDist - 10);
for (Int_t i = 0; i < 4; ++i) {
Float_t adc1 = esdAD->GetAdc(i);
Float_t adc2 = esdAD->GetAdc(i+4);
if (adc1 > GetRecoParam()->GetAdcThresHold() && adc2 > GetRecoParam()->GetAdcThresHold()) {
Float_t time1 = esdAD->GetTime(i);
Float_t time2 = esdAD->GetTime(i+4);
if(time1 > (AliADReconstructor::kInvalidTime+1.e-6) && time2 > (AliADReconstructor::kInvalidTime+1.e-6)){
Float_t timeErr1 = 1/adc1;
Float_t timeErr2 = 1/adc2;
Float_t timeDiff = TMath::Abs(time1-time2);
Float_t timeSum = time1+time2;
Float_t earlyHitCut = 1000;
if(TMath::Abs(timeSum - 2*fADCDist) < 20) earlyHitCut = fEarlyHitCutShape->Eval(timeSum);
if(timeDiff < earlyHitCut){
itimeRobustADC[ntimeRobustADC] = i;
ntimeRobustADC++;
timeRobustADC += time1/(timeErr1*timeErr1);
weightRobustADC += 1./(timeErr1*timeErr1);
itimeRobustADC[ntimeRobustADC] = i+4;
ntimeRobustADC++;
timeRobustADC += time2/(timeErr2*timeErr2);
weightRobustADC += 1./(timeErr2*timeErr2);
}
}
}
}
//A-side
fEarlyHitCutShape->SetParameter(2,2*fADADist - 10);
for (Int_t i = 8; i < 12; ++i) {
Float_t adc1 = esdAD->GetAdc(i);
Float_t adc2 = esdAD->GetAdc(i+4);
if (adc1 > GetRecoParam()->GetAdcThresHold() && adc2 > GetRecoParam()->GetAdcThresHold()) {
Float_t time1 = esdAD->GetTime(i);
Float_t time2 = esdAD->GetTime(i+4);
if(time1 > (AliADReconstructor::kInvalidTime+1.e-6) && time2 > (AliADReconstructor::kInvalidTime+1.e-6)){
Float_t timeErr1 = 1/adc1;
Float_t timeErr2 = 1/adc2;
Float_t timeDiff = TMath::Abs(time1-time2);
Float_t timeSum = time1+time2;
Float_t earlyHitCut = 1000;
if(TMath::Abs(timeSum - 2*fADADist) < 20) earlyHitCut = fEarlyHitCutShape->Eval(timeSum);
if(timeDiff < earlyHitCut){
itimeRobustADA[ntimeRobustADA] = i-8;
ntimeRobustADA++;
timeRobustADA += time1/(timeErr1*timeErr1);
weightRobustADA += 1./(timeErr1*timeErr1);
itimeRobustADA[ntimeRobustADA] = i-4;
ntimeRobustADA++;
timeRobustADA += time2/(timeErr2*timeErr2);
weightRobustADA += 1./(timeErr2*timeErr2);
}
}
}
}
if(weightRobustADA > 1) timeRobustADA /= weightRobustADA;
else timeRobustADA = -1024.;
if(weightRobustADC > 1) timeRobustADC /= weightRobustADC;
else timeRobustADC = -1024.;
/*/Use basic time for decisions
timeADA = timeBasicADA; timeADC = timeBasicADC;
weightADA = weightBasicADA; weightADC = weightBasicADC;
ntimeADA = ntimeBasicADA; ntimeADC = ntimeBasicADC;
for(Int_t i=0; i<8; ++i){itimeADA[i] = itimeBasicADA[i]; itimeADC[i] = itimeBasicADC[i];}/*/
//Use Robust time for decisions
esdAD->SetBit(AliESDAD::kRobustMeanTime,kTRUE);
timeADA = timeRobustADA; timeADC = timeRobustADC;
weightADA = weightRobustADA; weightADC = weightRobustADC;
ntimeADA = ntimeRobustADA; ntimeADC = ntimeRobustADC;
for(Int_t i=0; i<8; ++i){itimeADA[i] = itimeRobustADA[i]; itimeADC[i] = itimeRobustADC[i];}
esdAD->SetADATime(timeADA);
esdAD->SetADCTime(timeADC);
esdAD->SetADATimeError((weightADA > 1) ? (1./TMath::Sqrt(weightADA)) : 666);
esdAD->SetADCTimeError((weightADC > 1) ? (1./TMath::Sqrt(weightADC)) : 666);
esdAD->SetADADecision(AliESDAD::kADEmpty);
esdAD->SetADCDecision(AliESDAD::kADEmpty);
if (timeADA > (fADADist + GetRecoParam()->GetTimeWindowBBALow()) &&
timeADA < (fADADist + GetRecoParam()->GetTimeWindowBBAUp()))
esdAD->SetADADecision(AliESDAD::kADBB);
else if (timeADA > (-fADADist + GetRecoParam()->GetTimeWindowBGALow()) &&
timeADA < (-fADADist + GetRecoParam()->GetTimeWindowBGAUp()))
esdAD->SetADADecision(AliESDAD::kADBG);
else if (timeADA > (AliADReconstructor::kInvalidTime + 1e-6))
esdAD->SetADADecision(AliESDAD::kADFake);
if (timeADC > (fADCDist + GetRecoParam()->GetTimeWindowBBCLow()) &&
timeADC < (fADCDist + GetRecoParam()->GetTimeWindowBBCUp()))
esdAD->SetADCDecision(AliESDAD::kADBB);
else if (timeADC > (-fADCDist + GetRecoParam()->GetTimeWindowBGCLow()) &&
timeADC < (-fADCDist + GetRecoParam()->GetTimeWindowBGCUp()))
esdAD->SetADCDecision(AliESDAD::kADBG);
else if (timeADC > (AliADReconstructor::kInvalidTime + 1e-6))
esdAD->SetADCDecision(AliESDAD::kADFake);
UInt_t aBBtriggerADA = 0; // bit mask for Beam-Beam trigger in ADA
UInt_t aBGtriggerADA = 0; // bit mask for Beam-Gas trigger in ADA
UInt_t aBBtriggerADC = 0; // bit mask for Beam-Beam trigger in ADC
UInt_t aBGtriggerADC = 0; // bit mask for Beam-Gas trigger in ADC
for(Int_t i = 0; i < ntimeADA; ++i) {
if (esdAD->GetADADecision() == AliESDAD::kADBB)
aBBtriggerADA |= (1 << (itimeADA[i]));
else if (esdAD->GetADADecision() == AliESDAD::kADBG)
aBGtriggerADA |= (1 << (itimeADA[i]));
}
for(Int_t i = 0; i < ntimeADC; ++i) {
if (esdAD->GetADCDecision() == AliESDAD::kADBB)
aBBtriggerADC |= (1 << (itimeADC[i]));
else if (esdAD->GetADCDecision() == AliESDAD::kADBG)
aBGtriggerADC |= (1 << (itimeADC[i]));
}
esdAD->SetBBtriggerADA(aBBtriggerADA);
esdAD->SetBGtriggerADA(aBGtriggerADA);
esdAD->SetBBtriggerADC(aBBtriggerADC);
esdAD->SetBGtriggerADC(aBGtriggerADC);
}
| 35.918919 | 106 | 0.663469 | AllaMaevskaya |
e7a9922d223075b89e6e1363c58fa1e98a059e4f | 484 | hpp | C++ | OGL TLM on GPU/Mesh/PlaneMesh.hpp | bobvodka/TransmissionLineMatrixTheoryOnGPU | 6db9eb97c7af88969a8bec102e8c55dec48ed8e9 | [
"MIT"
] | null | null | null | OGL TLM on GPU/Mesh/PlaneMesh.hpp | bobvodka/TransmissionLineMatrixTheoryOnGPU | 6db9eb97c7af88969a8bec102e8c55dec48ed8e9 | [
"MIT"
] | null | null | null | OGL TLM on GPU/Mesh/PlaneMesh.hpp | bobvodka/TransmissionLineMatrixTheoryOnGPU | 6db9eb97c7af88969a8bec102e8c55dec48ed8e9 | [
"MIT"
] | null | null | null | /************************************************************************/
/* Plane implementation of the Base interface */
/* */
/************************************************************************/
#ifndef TLM_PLANEMEHS_HPP
#define TLM_PLANEMEHS_HPP
#include "IMesh.hpp"
namespace Mesh
{
class PlaneMesh : public IMesh
{
public:
PlaneMesh(int size, float scale = 1.0f);
void generateMesh();
protected:
private:
};
}
#endif | 24.2 | 74 | 0.429752 | bobvodka |
e7ab13af6430551112ffc00a4a11a2b3fbe1c0c6 | 2,750 | cc | C++ | server/modules/filter/cache/test/keycheck.cc | mariadb-corporation/MaxScale | e18ccc287d7714165479992f5214aacc7486048d | [
"BSD-3-Clause"
] | 1,157 | 2015-01-06T15:44:47.000Z | 2022-03-28T02:52:37.000Z | server/modules/filter/cache/test/keycheck.cc | mariadb-corporation/MaxScale | e18ccc287d7714165479992f5214aacc7486048d | [
"BSD-3-Clause"
] | 80 | 2015-02-13T11:49:05.000Z | 2022-01-17T09:00:11.000Z | server/modules/filter/cache/test/keycheck.cc | mariadb-corporation/MaxScale | e18ccc287d7714165479992f5214aacc7486048d | [
"BSD-3-Clause"
] | 361 | 2015-01-14T03:01:00.000Z | 2022-03-28T00:14:04.000Z | /*
* Copyright (c) 2016 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2025-10-11
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#include <fstream>
#include <map>
#include <maxbase/log.hh>
#include "../../../../../query_classifier/test/testreader.hh"
#include "../cache_storage_api.hh"
#include "../cache.hh"
using namespace std;
namespace
{
using StatementsByKeys = unordered_multimap<CacheKey, string>;
GWBUF* create_gwbuf(const string& s)
{
size_t len = s.length();
size_t payload_len = len + 1;
size_t gwbuf_len = MYSQL_HEADER_LEN + payload_len;
GWBUF* gwbuf = gwbuf_alloc(gwbuf_len);
*((unsigned char*)((char*)GWBUF_DATA(gwbuf))) = payload_len;
*((unsigned char*)((char*)GWBUF_DATA(gwbuf) + 1)) = (payload_len >> 8);
*((unsigned char*)((char*)GWBUF_DATA(gwbuf) + 2)) = (payload_len >> 16);
*((unsigned char*)((char*)GWBUF_DATA(gwbuf) + 3)) = 0x00;
*((unsigned char*)((char*)GWBUF_DATA(gwbuf) + 4)) = 0x03;
memcpy((char*)GWBUF_DATA(gwbuf) + 5, s.c_str(), len);
return gwbuf;
}
void run(StatementsByKeys& stats, istream& in)
{
mxs::TestReader reader(in);
string stmt;
while (reader.get_statement(stmt) == mxs::TestReader::RESULT_STMT)
{
GWBUF* pStmt = create_gwbuf(stmt);
CacheKey key;
Cache::get_default_key(nullptr, pStmt, &key);
gwbuf_free(pStmt);
auto range = stats.equal_range(key);
if (range.first != stats.end())
{
bool header_printed = false;
for (auto it = range.first; it != range.second; ++it)
{
if (stmt != it->second)
{
if (!header_printed)
{
cout << "Statement: " << stmt << " clashes with:\n";
header_printed = true;
}
cout << " " << it->second << endl;
}
}
if (header_printed)
{
cout << endl;
}
}
stats.emplace(key, stmt);
}
}
void run(StatementsByKeys& stats, int argc, char** argv)
{
for (int i = 0; i < argc; i++)
{
cout << argv[i] << endl;
ifstream in(argv[i]);
run(stats, in);
}
}
}
int main(int argc, char** argv)
{
mxb::Log log;
StatementsByKeys stats;
if (argc != 1)
{
run(stats, argc - 1, argv + 1);
}
else
{
run(stats, cin);
}
return 0;
}
| 23.504274 | 76 | 0.549818 | mariadb-corporation |
e7aba3f304fc7b6bd45061dc507d3cfbdc498932 | 5,860 | cpp | C++ | src/net/NetClient.cpp | levyhoo/netwb | 2d00398ca5b8cd69e94e986822b98733b3780d57 | [
"Apache-2.0"
] | null | null | null | src/net/NetClient.cpp | levyhoo/netwb | 2d00398ca5b8cd69e94e986822b98733b3780d57 | [
"Apache-2.0"
] | null | null | null | src/net/NetClient.cpp | levyhoo/netwb | 2d00398ca5b8cd69e94e986822b98733b3780d57 | [
"Apache-2.0"
] | null | null | null | #include "common/Stdafx.h"
#include "net/NetClient.h"
#include "stream.h"
#include "net/ProxyHelper.h"
#include "net/NetSocket.h"
using namespace net;
NetClient::NetClient(io_service& ioservice, string serverIp, unsigned short serverPort) : m_ioservice(ioservice), m_reconnectTimer(ioservice)
{
m_serverIp = serverIp;
m_serverPort = serverPort;
}
NetClient::~NetClient()
{
}
r_int32 NetClient::start(bool async)
{
if (async)
{
m_ioservice.post(boost::bind(&NetClient::startConnectAsync, shared_from_this()));
}
else
{
startConnectSync();
}
return 1;
}
r_int32 NetClient::stop()
{
boost::system::error_code error;
m_reconnectTimer.cancel(error);
m_ioservice.post(boost::bind(&NetClient::removeAllConnections, shared_from_this()));
return 1;
}
r_int32 NetClient::sendData(ByteArray& data, r_int32 len, bool async)
{
r_int32 ret = 1;
if (m_connection.get() != NULL)
{
ret = m_connection->sendData(data, len, async) ? 1 : 0;
}
return ret;
}
r_int32 NetClient::sendData(const char* data, r_int32 len, bool async)
{
ByteArray vdata(len);
memcpy(&vdata[0], data, len);
return sendData(vdata, len, async);
}
size_t NetClient::recvDataSync(char* buf, size_t len)
{
return m_connection->recvDataSync(buf, len);
}
bool NetClient::isConnected()
{
bool ret = false;
if (m_connection.get() != NULL)
ret = m_connection->isConnected();
return ret;
}
void NetClient::startConnectSync()
{
if (isConnected())
{
return;
}
try
{
m_connection = createConnection();
if (NULL == m_connection)
{
boost::system::error_code error = boost::asio::error::service_not_found;
m_ioservice.post(boost::bind(&NetClient::onConnectionError, shared_from_this(), error, m_connection));
} else {
m_connection->setNetManager(shared_from_this());
boost::system::error_code error;
m_connection->connect(m_proxyInfo, m_serverIp, m_serverPort, error);
if (!error)
{
addConnection(m_connection);
m_connection->start();
} else {
onConnectionError(error, m_connection);
}
}
}
catch (const boost::system::error_code& error)
{
onConnectionError(error, m_connection);
}
catch (...)
{
boost::system::error_code error = boost::asio::error::ssl_errors();
onConnectionError(error, m_connection);
}
}
void NetClient::startConnectAsync()
{
if (isConnected())
{
return;
}
//判断是否启用了代理
try
{
m_connection = createConnection();
if (NULL == m_connection)
{
boost::system::error_code error = boost::asio::error::service_not_found;
m_ioservice.post(boost::bind(&NetClient::onConnectionError, shared_from_this(), error, m_connection));
} else {
m_connection->setNetManager(shared_from_this());
m_connection->async_connect(m_proxyInfo, m_serverIp, m_serverPort, boost::bind(&NetClient::handleConnect, shared_from_this(), boost::asio::placeholders::error, m_connection));
}
}
catch (const boost::system::error_code& error)
{
m_ioservice.post(boost::bind(&NetClient::onConnectionError, shared_from_this(), error, m_connection));
}
catch (...)
{
boost::system::error_code error = boost::asio::error::ssl_errors();
m_ioservice.post(boost::bind(&NetClient::onConnectionError, shared_from_this(), error, m_connection));
}
}
void NetClient::handleConnect(const boost::system::error_code& err, boost::shared_ptr<NetConnection> connection)
{
if (!err)
{
try
{
tcp::endpoint endpoint = connection->getSocket().remote_endpoint();
connection->m_peerIp = endpoint.address().to_string();
connection->m_peerPort = endpoint.port();
string str = endpoint.address().to_string();
// 检测自成交, 如果自成交, 网络断开
tcp::endpoint localEndpoint = connection->getSocket().local_endpoint();
string localstr = endpoint.address().to_string();
if (endpoint == localEndpoint)
{
connection->close();
onConnectionError(err, connection);
}
}
catch (...)
{
}
addConnection(connection);
connection->start();
} else {
onConnectionError(err, connection);
}
}
void NetClient::onConnectionMade(boost::shared_ptr<NetConnection> connection)
{
}
void NetClient::onConnectionError(const boost::system::error_code& err, boost::shared_ptr<NetConnection> connection)
{
reconnect(NET_RECONNECT_INTERVAL);
}
void NetClient::onPackageReceived(const NetPackageHeader& header, const unsigned char* contentP, const size_t& contentLen, boost::shared_ptr<NetConnection> connection)
{
}
void NetClient::onDataSend(r_int32 len, boost::shared_ptr<NetConnection> connection)
{
}
NetConnectionPtr NetClient::createConnection()
{
StrandPtr strand(new boost::asio::strand(m_ioservice));
SocketPtr socket = NetSocket::makeComonSocket(strand);
NetConnectionPtr connection = boost::shared_ptr<NetConnection>(new NetConnection(strand, socket));
return connection;
}
void NetClient::onReconnectTimer(const boost::system::error_code& error)
{
if (!error)
{
startConnectAsync();
}
}
void NetClient::setProxy( const ProxyInfo proxyInfo )
{
m_proxyInfo = proxyInfo;
}
void NetClient::reconnect(int seconds)
{
m_reconnectTimer.expires_from_now(boost::posix_time::seconds(seconds));
m_reconnectTimer.async_wait(boost::bind(&NetClient::onReconnectTimer, shared_from_this(), _1));
} | 26.278027 | 191 | 0.642491 | levyhoo |
e7aeb938fcc9ef3d757463ed1053f5c83aae420f | 12,418 | cpp | C++ | test_conformance/gles/main.cpp | gwawiork/OpenCL-CTS | de6c3db41ba3dfc345321afe2612d0d99a16c7f3 | [
"Apache-2.0"
] | 1 | 2020-06-05T04:01:03.000Z | 2020-06-05T04:01:03.000Z | test_conformance/gles/main.cpp | gwawiork/OpenCL-CTS | de6c3db41ba3dfc345321afe2612d0d99a16c7f3 | [
"Apache-2.0"
] | null | null | null | test_conformance/gles/main.cpp | gwawiork/OpenCL-CTS | de6c3db41ba3dfc345321afe2612d0d99a16c7f3 | [
"Apache-2.0"
] | 3 | 2020-10-26T02:53:08.000Z | 2021-02-12T14:59:41.000Z | //
// Copyright (c) 2017 The Khronos Group Inc.
//
// 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 <stdio.h>
#include <stdlib.h>
#if !defined(_WIN32)
#include <stdbool.h>
#endif
#include <math.h>
#include <string.h>
#if !defined (__APPLE__)
#include <CL/cl.h>
#endif
#include "procs.h"
#include "../../test_common/gles/setup.h"
#include "../../test_common/harness/testHarness.h"
#if !defined(_WIN32)
#include <unistd.h>
#endif
static cl_context sCurrentContext = NULL;
#define TEST_FN_REDIRECT( fn ) redirect_##fn
#define TEST_FN_REDIRECTOR( fn ) \
int redirect_##fn(cl_device_id device, cl_context context, cl_command_queue queue, int numElements ) \
{ \
int error; \
clCommandQueueWrapper realQueue = clCreateCommandQueue( sCurrentContext, device, 0, &error ); \
test_error( error, "Unable to create command queue" ); \
return fn( device, sCurrentContext, realQueue, numElements ); \
}
TEST_FN_REDIRECTOR( test_buffers )
TEST_FN_REDIRECTOR( test_buffers_getinfo )
TEST_FN_REDIRECTOR( test_images_read )
TEST_FN_REDIRECTOR( test_images_2D_getinfo )
TEST_FN_REDIRECTOR( test_images_read_cube )
TEST_FN_REDIRECTOR( test_images_cube_getinfo )
TEST_FN_REDIRECTOR( test_images_read_3D )
TEST_FN_REDIRECTOR( test_images_3D_getinfo )
TEST_FN_REDIRECTOR( test_images_write )
TEST_FN_REDIRECTOR( test_images_write_cube )
TEST_FN_REDIRECTOR( test_renderbuffer_read )
TEST_FN_REDIRECTOR( test_renderbuffer_write )
TEST_FN_REDIRECTOR( test_renderbuffer_getinfo )
#ifndef GL_ES_VERSION_2_0
TEST_FN_REDIRECTOR( test_fence_sync )
#endif
basefn basefn_list[] = {
TEST_FN_REDIRECT( test_buffers ),
TEST_FN_REDIRECT( test_buffers_getinfo ),
TEST_FN_REDIRECT( test_images_read ),
TEST_FN_REDIRECT( test_images_2D_getinfo ),
TEST_FN_REDIRECT( test_images_read_cube ),
TEST_FN_REDIRECT( test_images_cube_getinfo ),
TEST_FN_REDIRECT( test_images_read_3D ),
TEST_FN_REDIRECT( test_images_3D_getinfo ),
TEST_FN_REDIRECT( test_images_write ),
TEST_FN_REDIRECT( test_images_write_cube ),
TEST_FN_REDIRECT( test_renderbuffer_read ),
TEST_FN_REDIRECT( test_renderbuffer_write ),
TEST_FN_REDIRECT( test_renderbuffer_getinfo )
};
#ifndef GL_ES_VERSION_2_0
basefn basefn_list32[] = {
TEST_FN_REDIRECT( test_fence_sync )
};
#endif
const char *basefn_names[] = {
"buffers",
"buffers_getinfo",
"images_read",
"images_2D_getinfo",
"images_read_cube",
"images_cube_getinfo",
"images_read_3D",
"images_3D_getinfo",
"images_write",
"images_write_cube",
"renderbuffer_read",
"renderbuffer_write",
"renderbuffer_getinfo",
"all"
};
const char *basefn_names32[] = {
"fence_sync",
"all"
};
ct_assert((sizeof(basefn_names) / sizeof(basefn_names[0]) - 1) == (sizeof(basefn_list) / sizeof(basefn_list[0])));
int num_fns = sizeof(basefn_names) / sizeof(char *);
int num_fns32 = sizeof(basefn_names32) / sizeof(char *);
int main(int argc, const char *argv[])
{
int error = 0;
cl_platform_id platform_id = NULL;
/* To keep it simple, use a static allocation of 32 argv pointers.
argc is not expected to go beyond 32 */
const char* argv_tmp[32] = {0};
int argc_tmp = 0;
test_start();
cl_device_type requestedDeviceType = CL_DEVICE_TYPE_DEFAULT;
for(int z = 1; z < argc; ++z)
{//for
if(strcmp( argv[ z ], "-list" ) == 0 )
{
log_info( "Available 2.x tests:\n" );
for( int i = 0; i < num_fns - 1; i++ )
log_info( "\t%s\n", basefn_names[ i ] );
log_info( "Available 3.2 tests:\n" );
for( int i = 0; i < num_fns32 - 1; i++ )
log_info( "\t%s\n", basefn_names32[ i ] );
log_info( "Note: Any 3.2 test names must follow 2.1 test names on the command line." );
log_info( "Use environment variables to specify desired device." );
test_finish();
return 0;
}
/* support requested device type */
if(!strcmp(argv[z], "CL_DEVICE_TYPE_GPU"))
{
printf("Requested device type is CL_DEVICE_TYPE_GPU\n");
requestedDeviceType = CL_DEVICE_TYPE_GPU;
}
else
if(!strcmp(argv[z], "CL_DEVICE_TYPE_CPU"))
{
printf("Requested device type is CL_DEVICE_TYPE_CPU\n");
log_info("Invalid CL device type. GL tests can only run on a GPU device.\n");
test_finish();
return 0;
}
}//for
// Check to see if any 2.x or 3.2 test names were specified on the command line.
unsigned first_32_testname = 0;
for (int j=1; (j<argc) && (!first_32_testname); ++j)
for (int i=0;i<num_fns32-1;++i)
if (strcmp(basefn_names32[i],argv[j])==0) {
first_32_testname = j;
break;
}
// Create the environment for the test.
GLEnvironment *glEnv = GLEnvironment::Instance();
// Check if any devices of the requested type support CL/GL interop.
int supported = glEnv->SupportsCLGLInterop( requestedDeviceType );
if( supported == 0 ) {
log_info("Test not run because GL-CL interop is not supported for any devices of the requested type.\n");
test_finish();
error = 0;
goto cleanup;
} else if ( supported == -1 ) {
log_error("Failed to determine if CL-GL interop is supported.\n");
test_finish();
error = -1;
goto cleanup;
}
// OpenGL tests for non-3.2 ////////////////////////////////////////////////////////
if ((argc == 1) || (first_32_testname != 1)) {
// At least one device supports CL-GL interop, so init the test.
if( glEnv->Init( &argc, (char **)argv, CL_FALSE ) ) {
log_error("Failed to initialize the GL environment for this test.\n");
test_finish();
error = -1;
goto cleanup;
}
// Create a context to use and then grab a device (or devices) from it
sCurrentContext = glEnv->CreateCLContext();
if( sCurrentContext == NULL )
{
log_error( "ERROR: Unable to obtain CL context from GL\n" );
test_finish();
error = -1;
goto cleanup;
}
size_t numDevices = 0;
cl_device_id deviceIDs[ 16 ];
error = clGetContextInfo( sCurrentContext, CL_CONTEXT_DEVICES, 0, NULL, &numDevices);
if( error != CL_SUCCESS )
{
print_error( error, "Unable to get device count from context" );
test_finish();
error = -1;
goto cleanup;
}
numDevices /= sizeof(cl_device_id);
if (numDevices < 1) {
log_error("No devices found.\n");
test_finish();
error = -1;
goto cleanup;
}
error = clGetContextInfo( sCurrentContext, CL_CONTEXT_DEVICES, sizeof( deviceIDs ), deviceIDs, NULL);
if( error != CL_SUCCESS ) {
print_error( error, "Unable to get device list from context" );
test_finish();
error = -1;
goto cleanup;
}
// Execute tests.
int argc_ = (first_32_testname) ? first_32_testname : argc;
for( size_t i = 0; i < numDevices; i++ ) {
log_info( "\nTesting OpenGL 2.x\n" );
if( printDeviceHeader( deviceIDs[ i ] ) != CL_SUCCESS ) {
test_finish();
error = -1;
goto cleanup;
}
error = clGetDeviceInfo(deviceIDs[ i ],
CL_DEVICE_PLATFORM,
sizeof(platform_id),
&platform_id,
NULL);
if(error)
{
goto cleanup;
}
error = init_clgl_ext(platform_id);
if (error < 0)
{
goto cleanup;
}
/* parseAndCallCommandLineTests considers every command line argument
as a test name. This results in the test failing because of considering
args such as 'CL_DEVICE_TYPE_GPU' as test names unless
the actual test name happens to be the first argument.
Instead of changing the behaviour of parseAndCallCommandLineTests
modify the arguments passed to it so as to not affect other tests.
*/
int w = 1;
argc_tmp= argc_;
for(int k = 1; k < argc; k++)
{
if( (strcmp(argv[k], "full") == 0) ||
(strcmp(argv[k], "CL_DEVICE_TYPE_CPU") == 0) ||
(strcmp(argv[k], "CL_DEVICE_TYPE_GPU") == 0))
{
argc_tmp--;
continue;
}
else
{
argv_tmp[w++] = argv[k];
}
}
// Note: don't use the entire harness, because we have a different way of obtaining the device (via the context)
error = parseAndCallCommandLineTests( argc_tmp, argv_tmp, deviceIDs[ i ], num_fns, basefn_list, basefn_names, true, 0, 1024 );
if( error != 0 )
break;
}
// Clean-up.
// We move this to a common cleanup step to make sure that things will be released properly before the test exit
goto cleanup;
// clReleaseContext( sCurrentContext );
// delete glEnv;
}
// OpenGL 3.2 tests. ////////////////////////////////////////////////////////
if ((argc==1) || first_32_testname) {
// At least one device supports CL-GL interop, so init the test.
if( glEnv->Init( &argc, (char **)argv, CL_TRUE ) ) {
log_error("Failed to initialize the GL environment for this test.\n");
test_finish();
error = -1;
goto cleanup;
}
// Create a context to use and then grab a device (or devices) from it
sCurrentContext = glEnv->CreateCLContext();
if( sCurrentContext == NULL ) {
log_error( "ERROR: Unable to obtain CL context from GL\n" );
test_finish();
error = -1;
goto cleanup;
}
size_t numDevices = 0;
cl_device_id deviceIDs[ 16 ];
error = clGetContextInfo( sCurrentContext, CL_CONTEXT_DEVICES, 0, NULL, &numDevices);
if( error != CL_SUCCESS ) {
print_error( error, "Unable to get device count from context" );
test_finish();
error = -1;
goto cleanup;
}
numDevices /= sizeof(cl_device_id);
if (numDevices < 1) {
log_error("No devices found.\n");
test_finish();
error = -1;
goto cleanup;
}
error = clGetContextInfo( sCurrentContext, CL_CONTEXT_DEVICES, sizeof( deviceIDs ), deviceIDs, NULL);
if( error != CL_SUCCESS ) {
print_error( error, "Unable to get device list from context" );
test_finish();
error = -1;
goto cleanup;
}
int argc_ = (first_32_testname) ? 1 + (argc - first_32_testname) : argc;
const char** argv_ = (first_32_testname) ? &argv[first_32_testname-1] : argv;
// Execute the tests.
for( size_t i = 0; i < numDevices; i++ ) {
log_info( "\nTesting OpenGL 3.2\n" );
if( printDeviceHeader( deviceIDs[ i ] ) != CL_SUCCESS ) {
test_finish();
error = -1;
goto cleanup;
}
#ifdef GL_ES_VERSION_2_0
log_info("Cannot test OpenGL 3.2! This test was built for OpenGL ES 2.0\n");
test_finish();
error = -1;
goto cleanup;
#else
// Note: don't use the entire harness, because we have a different way of obtaining the device (via the context)
error = parseAndCallCommandLineTests( argc_, argv_, deviceIDs[ i ], num_fns32, basefn_list32, basefn_names32, true, 0, 1024 );
if( error != 0 )
break;
#endif
}
// Converge on a common cleanup to make sure that things will be released properly before the test exit
goto cleanup;
}
// cleanup CL/GL/EGL environment properly when the test exit.
// This change does not affect any functionality of the test
// Intentional falling through
cleanup:
// Cleanup EGL
glEnv->terminate_egl_display();
// Always make sure that OpenCL context is released properly when the test exit
if(sCurrentContext)
{
clReleaseContext( sCurrentContext );
sCurrentContext = NULL;
}
delete glEnv;
return error;
} | 30.890547 | 134 | 0.629167 | gwawiork |
e7b01259b8c76a98b0edb2aaa5785ccb0fd30d45 | 704 | hpp | C++ | include/RED4ext/Scripting/Natives/Generated/audio/VehicleEngageMovingFasterInterpolationData.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 42 | 2020-12-25T08:33:00.000Z | 2022-03-22T14:47:07.000Z | include/RED4ext/Scripting/Natives/Generated/audio/VehicleEngageMovingFasterInterpolationData.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 38 | 2020-12-28T22:36:06.000Z | 2022-02-16T11:25:47.000Z | include/RED4ext/Scripting/Natives/Generated/audio/VehicleEngageMovingFasterInterpolationData.hpp | jackhumbert/RED4ext.SDK | 2c55eccb83beabbbe02abae7945af8efce638fca | [
"MIT"
] | 20 | 2020-12-28T22:17:38.000Z | 2022-03-22T17:19:01.000Z | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/Natives/Generated/audio/ESoundCurveType.hpp>
namespace RED4ext
{
namespace audio {
struct VehicleEngageMovingFasterInterpolationData
{
static constexpr const char* NAME = "audioVehicleEngageMovingFasterInterpolationData";
static constexpr const char* ALIAS = NAME;
audio::ESoundCurveType enterCurveType; // 00
float enterCurveTime; // 04
audio::ESoundCurveType exitCurveType; // 08
float exitCurveTime; // 0C
};
RED4EXT_ASSERT_SIZE(VehicleEngageMovingFasterInterpolationData, 0x10);
} // namespace audio
} // namespace RED4ext
| 28.16 | 90 | 0.776989 | jackhumbert |
e7b141d56b570e9418e21a39f1a0b23dd24bdbbd | 354 | hh | C++ | deps.win32/include/live555/BasicUsageEnvironment_version.hh | wongdu/refGaming-anywhere | 471f23ff402f9b31e743062d897a05b6a672ba5c | [
"BSD-3-Clause"
] | null | null | null | deps.win32/include/live555/BasicUsageEnvironment_version.hh | wongdu/refGaming-anywhere | 471f23ff402f9b31e743062d897a05b6a672ba5c | [
"BSD-3-Clause"
] | null | null | null | deps.win32/include/live555/BasicUsageEnvironment_version.hh | wongdu/refGaming-anywhere | 471f23ff402f9b31e743062d897a05b6a672ba5c | [
"BSD-3-Clause"
] | null | null | null | // Version information for the "BasicUsageEnvironment" library
// Copyright (c) 1996-2020 Live Networks, Inc. All rights reserved.
#ifndef _BASICUSAGEENVIRONMENT_VERSION_HH
#define _BASICUSAGEENVIRONMENT_VERSION_HH
#define BASICUSAGEENVIRONMENT_LIBRARY_VERSION_STRING "2020.03.06"
#define BASICUSAGEENVIRONMENT_LIBRARY_VERSION_INT 1583452800
#endif
| 32.181818 | 68 | 0.847458 | wongdu |
e7b22032610b875bd680726c975c4256f498069c | 3,451 | cpp | C++ | src/http.cpp | nodenative/nodenative | cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3 | [
"MIT"
] | 16 | 2016-03-16T22:16:18.000Z | 2021-04-05T04:46:38.000Z | src/http.cpp | nodenative/nodenative | cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3 | [
"MIT"
] | 11 | 2016-03-16T22:02:26.000Z | 2021-04-04T02:20:51.000Z | src/http.cpp | nodenative/nodenative | cf988c9399e0793b1b8c29a8ffd09e910d1a0cb3 | [
"MIT"
] | 5 | 2016-03-22T14:03:34.000Z | 2021-01-06T18:08:46.000Z | #include "native/http.hpp"
#include <cctype>
#include <iomanip>
#include <sstream>
#include <string>
namespace {
int hexValue(const char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
}
return -1;
}
int hexPairValue(const char c1, const char c2) {
int v1 = hexValue(c1);
int v2 = hexValue(c2);
if (v1 >= 0 && v2 >= 0) {
return (v1 << 4) + v2;
}
return -1;
}
} /* namespace */
namespace native {
namespace http {
std::string encodeUrl(const std::string &url,
const bool skipPercentSequence /*=false*/,
const std::string &allowedChars,
const std::string &valueAllowedChars) {
// A good example of encode/decode URL is
// https://chromium.googlesource.com/external/libjingle/chrome-sandbox/+/master/talk/base/urlencode.cc
std::ostringstream escaped;
escaped.fill('0');
escaped << std::hex;
unsigned int i = 0, n = url.size();
while (i < n) {
// Keep alphanumeric and other accepted characters intact
std::string::value_type c = url[i];
if (std::isalnum(c) || valueAllowedChars.find(c) != std::string::npos ||
allowedChars.find(c) != std::string::npos) {
escaped << c;
} else if (skipPercentSequence && c == '%' && i + 2 < n) {
int value = hexPairValue(url[i + 1], url[i + 2]);
if (value >= 0) {
escaped << c << url[i + 1] << url[i + 2];
i += 2;
}
} else {
// Any other characters are percent-encoded
escaped << std::uppercase;
escaped << '%' << std::setw(2) << int((unsigned char)c);
escaped << std::nouppercase;
}
++i;
}
return escaped.str();
}
std::string decodeUrl(const std::string &url, const bool spaceAsPlus) {
std::string result;
result.reserve(url.size());
unsigned int i = 0, n = url.size();
while (i < n) {
std::string::value_type c = url[i];
switch (c) {
case '+':
result += (spaceAsPlus ? ' ' : c);
break;
case '%':
if (i + 2 < n) {
int value = hexPairValue(url[i + 1], url[i + 2]);
if (value >= 0) {
result += (char)value;
i += 2;
} else {
result += '?';
}
} else {
result += '?';
}
break;
default:
result += c;
break;
}
++i;
}
return result;
}
Future<std::shared_ptr<ClientResponse>> request(std::shared_ptr<Loop> iLoop,
const std::string &method,
const std::string &host,
const int port,
const std::string &path) {
std::shared_ptr<ClientRequest> req = ClientRequest::Create(iLoop, method, host, port, path);
return req->end();
}
Future<std::shared_ptr<ClientResponse>> get(std::shared_ptr<Loop> iLoop, const std::string &uri) {
std::shared_ptr<ClientRequest> req = ClientRequest::Create(iLoop, "GET", uri);
return req->end();
}
Future<std::shared_ptr<ClientResponse>>
get(std::shared_ptr<Loop> iLoop, const std::string &host, const int port, const std::string &path) {
std::shared_ptr<ClientRequest> req = ClientRequest::Create(iLoop, "GET", host, port, path);
return req->end();
}
} /* namespace http */
} /* namespace native */
| 26.546154 | 104 | 0.534338 | nodenative |
e7b695eaadbd1fc90e9aea7ca3b0acd28a852b1d | 1,219 | cpp | C++ | examples/hotplug.cpp | damercer/libsmu | 6f141ea37a0778299ad1771cc9385fef14010bc0 | [
"BSD-3-Clause"
] | null | null | null | examples/hotplug.cpp | damercer/libsmu | 6f141ea37a0778299ad1771cc9385fef14010bc0 | [
"BSD-3-Clause"
] | null | null | null | examples/hotplug.cpp | damercer/libsmu | 6f141ea37a0778299ad1771cc9385fef14010bc0 | [
"BSD-3-Clause"
] | null | null | null | // Simple example demonstrating hotplug support.
#include <chrono>
#include <iostream>
#include <thread>
#include <libsmu/libsmu.hpp>
using std::cout;
using std::cerr;
using std::endl;
using namespace smu;
int main(int argc, char **argv)
{
// Create session object and add all compatible devices them to the
// session. Note that this currently doesn't handle returned errors.
Session* session = new Session();
session->add_all();
// Register hotplug detach callback handler.
session->hotplug_detach([=](Device* device, void* data){
session->cancel();
if (!session->remove(device, true)) {
printf("device detached: %s: serial %s: fw %s: hw %s\n",
device->info()->label, device->m_serial.c_str(),
device->m_fwver.c_str(), device->m_hwver.c_str());
}
});
// Register hotplug attach callback handler.
session->hotplug_attach([=](Device* device, void* data){
if (!session->add(device)) {
printf("device attached: %s: serial %s: fw %s: hw %s\n",
device->info()->label, device->m_serial.c_str(),
device->m_fwver.c_str(), device->m_hwver.c_str());
}
});
cout << "waiting for hotplug events..." << endl;
while (true)
std::this_thread::sleep_for(std::chrono::seconds(1));
}
| 27.088889 | 69 | 0.675964 | damercer |
e7b90fb45bdc1b73b77b4341ad155c32cd3273e5 | 3,937 | cpp | C++ | test/core/image_view/dynamic_step.cpp | sdebionne/gil-reformated | 7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2 | [
"BSL-1.0"
] | null | null | null | test/core/image_view/dynamic_step.cpp | sdebionne/gil-reformated | 7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2 | [
"BSL-1.0"
] | null | null | null | test/core/image_view/dynamic_step.cpp | sdebionne/gil-reformated | 7065d600d7f84d9ef2ed4df9862c596ff7e8a8c2 | [
"BSL-1.0"
] | null | null | null | //
// Copyright 2019 Mateusz Loskot <mateusz at loskot dot net>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
#include <boost/gil/dynamic_step.hpp>
#include <boost/gil/image_view.hpp>
#include <boost/gil/typedefs.hpp>
namespace gil = boost::gil;
template <typename View> void test() {
static_assert(
gil::view_is_basic<typename gil::dynamic_x_step_type<View>::type>::value,
"view does not model HasDynamicXStepTypeConcept");
static_assert(
gil::view_is_basic<typename gil::dynamic_y_step_type<View>::type>::value,
"view does not model HasDynamicYStepTypeConcept");
}
int main() {
test<gil::gray8_view_t>();
test<gil::gray8_step_view_t>();
test<gil::gray8c_view_t>();
test<gil::gray8c_step_view_t>();
test<gil::gray16_view_t>();
test<gil::gray16_step_view_t>();
test<gil::gray16c_view_t>();
test<gil::gray16c_step_view_t>();
test<gil::gray32_view_t>();
test<gil::gray32_step_view_t>();
test<gil::gray32c_view_t>();
test<gil::gray32c_step_view_t>();
test<gil::gray32f_view_t>();
test<gil::gray32f_step_view_t>();
test<gil::abgr8_view_t>();
test<gil::abgr8_step_view_t>();
test<gil::abgr16_view_t>();
test<gil::abgr16_step_view_t>();
test<gil::abgr32_view_t>();
test<gil::abgr32_step_view_t>();
test<gil::abgr32f_view_t>();
test<gil::abgr32f_step_view_t>();
test<gil::argb8_view_t>();
test<gil::argb8_step_view_t>();
test<gil::argb16_view_t>();
test<gil::argb16_step_view_t>();
test<gil::argb32_view_t>();
test<gil::argb32_step_view_t>();
test<gil::argb32f_view_t>();
test<gil::argb32f_step_view_t>();
test<gil::bgr8_view_t>();
test<gil::bgr8_step_view_t>();
test<gil::bgr16_view_t>();
test<gil::bgr16_step_view_t>();
test<gil::bgr32_view_t>();
test<gil::bgr32_step_view_t>();
test<gil::bgr32f_view_t>();
test<gil::bgr32f_step_view_t>();
test<gil::bgra8_view_t>();
test<gil::bgra8_step_view_t>();
test<gil::bgra16_view_t>();
test<gil::bgra16_step_view_t>();
test<gil::bgra32_view_t>();
test<gil::bgra32_step_view_t>();
test<gil::bgra32f_view_t>();
test<gil::bgra32f_step_view_t>();
test<gil::rgb8_view_t>();
test<gil::rgb8_step_view_t>();
test<gil::rgb8_planar_view_t>();
test<gil::rgb8_planar_step_view_t>();
test<gil::rgb16_view_t>();
test<gil::rgb16_step_view_t>();
test<gil::rgb16_planar_view_t>();
test<gil::rgb16_planar_step_view_t>();
test<gil::rgb32_view_t>();
test<gil::rgb32_step_view_t>();
test<gil::rgb32_planar_view_t>();
test<gil::rgb32_planar_step_view_t>();
test<gil::rgb32f_view_t>();
test<gil::rgb32f_step_view_t>();
test<gil::rgb32f_planar_view_t>();
test<gil::rgb32f_planar_step_view_t>();
test<gil::rgba8_view_t>();
test<gil::rgba8_step_view_t>();
test<gil::rgba8_planar_view_t>();
test<gil::rgba8_planar_step_view_t>();
test<gil::rgba16_view_t>();
test<gil::rgba16_step_view_t>();
test<gil::rgba16_planar_view_t>();
test<gil::rgba16_planar_step_view_t>();
test<gil::rgba32_view_t>();
test<gil::rgba32_step_view_t>();
test<gil::rgba32_planar_view_t>();
test<gil::rgba32_planar_step_view_t>();
test<gil::rgba32f_view_t>();
test<gil::rgba32f_step_view_t>();
test<gil::rgba32f_planar_view_t>();
test<gil::rgba32f_planar_step_view_t>();
test<gil::cmyk8_view_t>();
test<gil::cmyk8_step_view_t>();
test<gil::cmyk8_planar_view_t>();
test<gil::cmyk8_planar_step_view_t>();
test<gil::cmyk16_view_t>();
test<gil::cmyk16_step_view_t>();
test<gil::cmyk16_planar_view_t>();
test<gil::cmyk16_planar_step_view_t>();
test<gil::cmyk32_view_t>();
test<gil::cmyk32_step_view_t>();
test<gil::cmyk32_planar_view_t>();
test<gil::cmyk32_planar_step_view_t>();
test<gil::cmyk32f_view_t>();
test<gil::cmyk32f_step_view_t>();
test<gil::cmyk32f_planar_view_t>();
test<gil::cmyk32f_planar_step_view_t>();
}
| 31 | 79 | 0.709931 | sdebionne |
e7b987be450ccccd164443e0f0cdfee7f4d16395 | 3,305 | cpp | C++ | Nov-9-Comp-Code/First_Comp/src/main.cpp | TonyCha3713/VEX_Robotics_TowerTakeOver | 92c0dc4349ee4c7112a41f641a0335cfec87cd50 | [
"MIT"
] | null | null | null | Nov-9-Comp-Code/First_Comp/src/main.cpp | TonyCha3713/VEX_Robotics_TowerTakeOver | 92c0dc4349ee4c7112a41f641a0335cfec87cd50 | [
"MIT"
] | null | null | null | Nov-9-Comp-Code/First_Comp/src/main.cpp | TonyCha3713/VEX_Robotics_TowerTakeOver | 92c0dc4349ee4c7112a41f641a0335cfec87cd50 | [
"MIT"
] | null | null | null | #include "main.h"
/**
* A callback function for LLEMU's center button.
*
* When this callback is fired, it will toggle line 2 of the LCD text between
* "I was pressed!" and nothing.
*/
/**
* Runs initialization code. This occurs as soon as the program is started.
*
* All other competition modes are blocked by initialize; it is recommended
* to keep execution time for this mode under a few seconds.
*/
void initialize() {
Intake1.set_brake_mode(E_MOTOR_BRAKE_HOLD);
Intake2.set_brake_mode(E_MOTOR_BRAKE_HOLD);
}
/**
* Runs while the robot is in the disabled state of Field Management System or
* the VEX Competition Switch, following either autonomous or opcontrol. When
* the robot is enabled, this task will exit.
*/
void disabled() {}
/**
* Runs after initialize(), and before autonomous when connected to the Field
* Management System or the VEX Competition Switch. This is intended for
* competition-specific initialization routines, such as an autonomous selector
* on the LCD.
*
* This task will exit when the robot is enabled and autonomous or opcontrol
* starts.
*/
//int autonCount = 0;
void lcdScroll() {
if(autonCount < 0)
autonCount = 0;
else if(autonCount > 3)
autonCount = 0;
switch(autonCount) {
case 0:
lcd::set_text(1, "one cube safety");
break;
case 1:
lcd::set_text(1, "red small zone 5");
break;
case 2:
lcd::set_text(1, "blue zone 5");
break;
default:
lcd::set_text(1, "how did you mess up");
break;
}
}
void on_left_pressed() {
autonCount--;
lcdScroll();
}
void on_center_pressed() {
autonCount = autonCount;
lcd::shutdown();
}
void on_right_pressed() {
autonCount++;
lcdScroll();
}
void competition_initialize() {
lcd::initialize();
lcd::set_text(0, "Choose auton");
lcdScroll();
lcd::register_btn0_cb(on_left_pressed);
lcd::register_btn1_cb(on_center_pressed);
lcd::register_btn2_cb(on_right_pressed);
}
void autonomous() {
/*if(autonCount == 0)
oneCubeSafety();
else if(autonCount == 1)
redSmallZone5();
else if(autonCount == 2)
blueSmallZone5();*/
//oneCubeSafety();
redSmallZone5();
}
/**
* Runs the operator control code. This function will be started in its own task
* with the default priority and stack size whenever the robot is enabled via
* the Field Management System or the VEX Competition Switch in the operator
* control mode.
*
* If no competition control is connected, this function will run immediately
* following initialize().
*
* If the robot is disabled or communications is lost, the
* operator control task will be stopped. Re-enabling the robot will restart the
* task, not resume it from where it left off.
*/
void opcontrol() {
Intake1.set_brake_mode(E_MOTOR_BRAKE_HOLD);
Intake2.set_brake_mode(E_MOTOR_BRAKE_HOLD);
while (true) {
runLeftBase(master.get_analog(E_CONTROLLER_ANALOG_LEFT_Y) * .7);
runRightBase(master.get_analog(E_CONTROLLER_ANALOG_RIGHT_Y) * .7);
if(master.get_digital(E_CONTROLLER_DIGITAL_R1))
runIntake(115);
else if(master.get_digital(E_CONTROLLER_DIGITAL_R2))
runIntake(-115);
else
runIntake(0);
if(master.get_digital(E_CONTROLLER_DIGITAL_L1))
runTray(100);
else if(master.get_digital(E_CONTROLLER_DIGITAL_L2))
runTray(-115);
else
runTray(0);
}
} | 22.636986 | 80 | 0.71528 | TonyCha3713 |
e7c09f65c8b98be297245ff3ad44b2ca65434ec1 | 3,719 | cc | C++ | src/meili/map_matcher_factory.cc | sinabakh/valhalla | 4f93590bca142330ae0ce34e6a614144aef57254 | [
"MIT"
] | 1 | 2019-10-25T06:16:27.000Z | 2019-10-25T06:16:27.000Z | src/meili/map_matcher_factory.cc | sinabakh/valhalla | 4f93590bca142330ae0ce34e6a614144aef57254 | [
"MIT"
] | null | null | null | src/meili/map_matcher_factory.cc | sinabakh/valhalla | 4f93590bca142330ae0ce34e6a614144aef57254 | [
"MIT"
] | 1 | 2019-10-25T06:16:29.000Z | 2019-10-25T06:16:29.000Z | #include <string>
#include "baldr/graphreader.h"
#include "baldr/tilehierarchy.h"
#include "sif/autocost.h"
#include "sif/bicyclecost.h"
#include "sif/costconstants.h"
#include "sif/motorscootercost.h"
#include "sif/pedestriancost.h"
#include "meili/candidate_search.h"
#include "meili/map_matcher.h"
#include "meili/map_matcher_factory.h"
namespace {
inline float local_tile_size() {
const auto& tiles = valhalla::baldr::TileHierarchy::levels().rbegin()->second.tiles;
return tiles.TileSize();
}
} // namespace
namespace valhalla {
namespace meili {
MapMatcherFactory::MapMatcherFactory(const boost::property_tree::ptree& root,
const std::shared_ptr<baldr::GraphReader>& graph_reader)
: config_(root.get_child("meili")), graphreader_(graph_reader),
max_grid_cache_size_(root.get<float>("meili.grid.cache_size")) {
if (!graphreader_)
graphreader_.reset(new baldr::GraphReader(root.get_child("mjolnir")));
candidatequery_.reset(
new CandidateGridQuery(*graphreader_, local_tile_size() / root.get<size_t>("meili.grid.size"),
local_tile_size() / root.get<size_t>("meili.grid.size")));
cost_factory_.RegisterStandardCostingModels();
}
MapMatcherFactory::~MapMatcherFactory() {
}
MapMatcher* MapMatcherFactory::Create(const odin::Costing costing,
const odin::DirectionsOptions& options) {
// Merge any customizable options with the config defaults
const auto& config = MergeConfig(options);
valhalla::sif::cost_ptr_t cost = cost_factory_.Create(costing, options);
valhalla::sif::TravelMode mode = cost->travel_mode();
mode_costing_[static_cast<uint32_t>(mode)] = cost;
// TODO investigate exception safety
return new MapMatcher(config, *graphreader_, *candidatequery_, mode_costing_, mode);
}
MapMatcher* MapMatcherFactory::Create(const odin::DirectionsOptions& options) {
return Create(options.costing(), options);
}
boost::property_tree::ptree MapMatcherFactory::MergeConfig(const odin::DirectionsOptions& options) {
// Copy the default child config
auto config = config_.get_child("default");
// Get a list of customizable options
std::unordered_set<std::string> customizable;
for (const auto& item : config_.get_child("customizable")) {
customizable.insert(item.second.get_value<std::string>());
}
// Check for overrides of matcher related directions options. Override these values in config.
// TODO - there are several options listed as customizable that are not documented
// in the interface...either add them and document or remove them from config?
if (options.search_radius() && customizable.find("search_radius") != customizable.end()) {
config.put<float>("search_radius", options.search_radius());
}
if (options.turn_penalty_factor() &&
customizable.find("turn_penalty_factor") != customizable.end()) {
config.put<float>("turn_penalty_factor", options.turn_penalty_factor());
}
if (options.gps_accuracy() && customizable.find("gps_accuracy") != customizable.end()) {
config.put<float>("gps_accuracy", options.gps_accuracy());
}
if (options.breakage_distance() && customizable.find("breakage_distance") != customizable.end()) {
config.put<float>("breakage_distance", options.breakage_distance());
}
// Give it back
return config;
}
void MapMatcherFactory::ClearFullCache() {
if (graphreader_->OverCommitted()) {
graphreader_->Clear();
}
if (candidatequery_->size() > max_grid_cache_size_) {
candidatequery_->Clear();
}
}
void MapMatcherFactory::ClearCache() {
graphreader_->Clear();
candidatequery_->Clear();
}
} // namespace meili
} // namespace valhalla
| 34.119266 | 100 | 0.718204 | sinabakh |
e7c2e151246bad859eb05e25aed02268fcb166ac | 9,091 | cpp | C++ | android-project/jni/libtesseract/src/ccmain/recogtraining.cpp | pixelsquare/tesseract-ocr-unity | f5f16c3d77cb4898f3fa96aed4abd82817de39fd | [
"MIT"
] | 6 | 2019-08-22T11:42:27.000Z | 2021-12-24T09:23:23.000Z | android-project/jni/libtesseract/src/ccmain/recogtraining.cpp | pixelsquare/tesseract-ocr-unity | f5f16c3d77cb4898f3fa96aed4abd82817de39fd | [
"MIT"
] | 1 | 2018-11-30T15:53:24.000Z | 2020-01-23T16:46:24.000Z | android-project/jni/libtesseract/src/ccmain/recogtraining.cpp | pixelsquare/tesseract-ocr-unity | f5f16c3d77cb4898f3fa96aed4abd82817de39fd | [
"MIT"
] | 3 | 2019-05-30T04:13:56.000Z | 2021-12-24T09:23:26.000Z | ///////////////////////////////////////////////////////////////////////
// File: recogtraining.cpp
// Description: Functions for ambiguity and parameter training.
// Author: Daria Antonova
//
// (C) Copyright 2009, Google Inc.
// 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 "tesseractclass.h"
#include "boxread.h"
#include "control.h"
#include "host.h" // for NearlyEqual
#include "ratngs.h"
#ifndef DISABLED_LEGACY_ENGINE
# include "reject.h"
#endif
#include "stopper.h"
namespace tesseract {
const int16_t kMaxBoxEdgeDiff = 2;
// Sets flags necessary for recognition in the training mode.
// Opens and returns the pointer to the output file.
FILE *Tesseract::init_recog_training(const char *filename) {
if (tessedit_ambigs_training) {
tessedit_tess_adaption_mode.set_value(0); // turn off adaption
tessedit_enable_doc_dict.set_value(false); // turn off document dictionary
// Explore all segmentations.
getDict().stopper_no_acceptable_choices.set_value(true);
}
std::string output_fname = filename;
const char *lastdot = strrchr(output_fname.c_str(), '.');
if (lastdot != nullptr) {
output_fname[lastdot - output_fname.c_str()] = '\0';
}
output_fname += ".txt";
FILE *output_file = fopen(output_fname.c_str(), "a+");
if (output_file == nullptr) {
tprintf("Error: Could not open file %s\n", output_fname.c_str());
ASSERT_HOST(output_file);
}
return output_file;
}
// Copies the bounding box from page_res_it->word() to the given TBOX.
static bool read_t(PAGE_RES_IT *page_res_it, TBOX *tbox) {
while (page_res_it->block() != nullptr && page_res_it->word() == nullptr) {
page_res_it->forward();
}
if (page_res_it->word() != nullptr) {
*tbox = page_res_it->word()->word->bounding_box();
// If tbox->left() is negative, the training image has vertical text and
// all the coordinates of bounding boxes of page_res are rotated by 90
// degrees in a counterclockwise direction. We need to rotate the TBOX back
// in order to compare with the TBOXes of box files.
if (tbox->left() < 0) {
tbox->rotate(FCOORD(0.0, -1.0));
}
return true;
} else {
return false;
}
}
// This function takes tif/box pair of files and runs recognition on the image,
// while making sure that the word bounds that tesseract identified roughly
// match to those specified by the input box file. For each word (ngram in a
// single bounding box from the input box file) it outputs the ocred result,
// the correct label, rating and certainty.
void Tesseract::recog_training_segmented(const char *filename, PAGE_RES *page_res,
volatile ETEXT_DESC *monitor, FILE *output_file) {
std::string box_fname = filename;
const char *lastdot = strrchr(box_fname.c_str(), '.');
if (lastdot != nullptr) {
box_fname[lastdot - box_fname.c_str()] = '\0';
}
box_fname += ".box";
// ReadNextBox() will close box_file
FILE *box_file = fopen(box_fname.c_str(), "r");
if (box_file == nullptr) {
tprintf("Error: Could not open file %s\n", box_fname.c_str());
ASSERT_HOST(box_file);
}
PAGE_RES_IT page_res_it;
page_res_it.page_res = page_res;
page_res_it.restart_page();
std::string label;
// Process all the words on this page.
TBOX tbox; // tesseract-identified box
TBOX bbox; // box from the box file
bool keep_going;
int line_number = 0;
int examined_words = 0;
do {
keep_going = read_t(&page_res_it, &tbox);
keep_going &= ReadNextBox(applybox_page, &line_number, box_file, label, &bbox);
// Align bottom left points of the TBOXes.
while (keep_going && !NearlyEqual<int>(tbox.bottom(), bbox.bottom(), kMaxBoxEdgeDiff)) {
if (bbox.bottom() < tbox.bottom()) {
page_res_it.forward();
keep_going = read_t(&page_res_it, &tbox);
} else {
keep_going = ReadNextBox(applybox_page, &line_number, box_file, label, &bbox);
}
}
while (keep_going && !NearlyEqual<int>(tbox.left(), bbox.left(), kMaxBoxEdgeDiff)) {
if (bbox.left() > tbox.left()) {
page_res_it.forward();
keep_going = read_t(&page_res_it, &tbox);
} else {
keep_going = ReadNextBox(applybox_page, &line_number, box_file, label, &bbox);
}
}
// OCR the word if top right points of the TBOXes are similar.
if (keep_going && NearlyEqual<int>(tbox.right(), bbox.right(), kMaxBoxEdgeDiff) &&
NearlyEqual<int>(tbox.top(), bbox.top(), kMaxBoxEdgeDiff)) {
ambigs_classify_and_output(label.c_str(), &page_res_it, output_file);
examined_words++;
}
page_res_it.forward();
} while (keep_going);
// Set up scripts on all of the words that did not get sent to
// ambigs_classify_and_output. They all should have, but if all the
// werd_res's don't get uch_sets, tesseract will crash when you try
// to iterate over them. :-(
int total_words = 0;
for (page_res_it.restart_page(); page_res_it.block() != nullptr; page_res_it.forward()) {
if (page_res_it.word()) {
if (page_res_it.word()->uch_set == nullptr) {
page_res_it.word()->SetupFake(unicharset);
}
total_words++;
}
}
if (examined_words < 0.85 * total_words) {
tprintf(
"TODO(antonova): clean up recog_training_segmented; "
" It examined only a small fraction of the ambigs image.\n");
}
tprintf("recog_training_segmented: examined %d / %d words.\n", examined_words, total_words);
}
// Helper prints the given set of blob choices.
static void PrintPath(int length, const BLOB_CHOICE **blob_choices, const UNICHARSET &unicharset,
const char *label, FILE *output_file) {
float rating = 0.0f;
float certainty = 0.0f;
for (int i = 0; i < length; ++i) {
const BLOB_CHOICE *blob_choice = blob_choices[i];
fprintf(output_file, "%s", unicharset.id_to_unichar(blob_choice->unichar_id()));
rating += blob_choice->rating();
if (certainty > blob_choice->certainty()) {
certainty = blob_choice->certainty();
}
}
fprintf(output_file, "\t%s\t%.4f\t%.4f\n", label, rating, certainty);
}
// Helper recursively prints all paths through the ratings matrix, starting
// at column col.
static void PrintMatrixPaths(int col, int dim, const MATRIX &ratings, int length,
const BLOB_CHOICE **blob_choices, const UNICHARSET &unicharset,
const char *label, FILE *output_file) {
for (int row = col; row < dim && row - col < ratings.bandwidth(); ++row) {
if (ratings.get(col, row) != NOT_CLASSIFIED) {
BLOB_CHOICE_IT bc_it(ratings.get(col, row));
for (bc_it.mark_cycle_pt(); !bc_it.cycled_list(); bc_it.forward()) {
blob_choices[length] = bc_it.data();
if (row + 1 < dim) {
PrintMatrixPaths(row + 1, dim, ratings, length + 1, blob_choices, unicharset, label,
output_file);
} else {
PrintPath(length + 1, blob_choices, unicharset, label, output_file);
}
}
}
}
}
// Runs classify_word_pass1() on the current word. Outputs Tesseract's
// raw choice as a result of the classification. For words labeled with a
// single unichar also outputs all alternatives from blob_choices of the
// best choice.
void Tesseract::ambigs_classify_and_output(const char *label, PAGE_RES_IT *pr_it,
FILE *output_file) {
// Classify word.
fflush(stdout);
WordData word_data(*pr_it);
SetupWordPassN(1, &word_data);
classify_word_and_language(1, pr_it, &word_data);
WERD_RES *werd_res = word_data.word;
WERD_CHOICE *best_choice = werd_res->best_choice;
ASSERT_HOST(best_choice != nullptr);
// Compute the number of unichars in the label.
std::vector<UNICHAR_ID> encoding;
if (!unicharset.encode_string(label, true, &encoding, nullptr, nullptr)) {
tprintf("Not outputting illegal unichar %s\n", label);
return;
}
// Dump all paths through the ratings matrix (which is normally small).
int dim = werd_res->ratings->dimension();
const auto **blob_choices = new const BLOB_CHOICE *[dim];
PrintMatrixPaths(0, dim, *werd_res->ratings, 0, blob_choices, unicharset, label, output_file);
delete[] blob_choices;
}
} // namespace tesseract
| 39.69869 | 98 | 0.647344 | pixelsquare |
b10d104abeba0880c1e6d84cbc75634fc900eb3a | 2,178 | cpp | C++ | libs/units/example/tutorial.cpp | zyiacas/boost-doc-zh | 689e5a3a0a4dbead1a960f7b039e3decda54aa2c | [
"BSL-1.0"
] | 11 | 2015-07-12T13:04:52.000Z | 2021-05-30T23:23:46.000Z | libs/units/example/tutorial.cpp | boost-cmake/vintage | dcfb7da3177134eddaee6789d6f582259cb0d6ee | [
"BSL-1.0"
] | null | null | null | libs/units/example/tutorial.cpp | boost-cmake/vintage | dcfb7da3177134eddaee6789d6f582259cb0d6ee | [
"BSL-1.0"
] | 3 | 2015-12-23T01:51:57.000Z | 2019-08-25T04:58:32.000Z | // Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
/**
\file
\brief tutorial.cpp
\detailed
Basic tutorial using si units.
Output:
@verbatim
//[tutorial_output
F = 2 N
dx = 2 m
E = 4 J
V = (12.5,0) V
I = (3,4) A
Z = (1.5,-2) Ohm
I*Z = (12.5,0) V
I*Z == V? true
//]
@endverbatim
**/
//[tutorial_code
#include <complex>
#include <iostream>
#include <boost/typeof/std/complex.hpp>
#include <boost/units/systems/si/energy.hpp>
#include <boost/units/systems/si/force.hpp>
#include <boost/units/systems/si/length.hpp>
#include <boost/units/systems/si/electric_potential.hpp>
#include <boost/units/systems/si/current.hpp>
#include <boost/units/systems/si/resistance.hpp>
#include <boost/units/systems/si/io.hpp>
using namespace boost::units;
using namespace boost::units::si;
quantity<energy>
work(const quantity<force>& F,const quantity<length>& dx)
{
return F*dx;
}
int main()
{
/// test calcuation of work
quantity<force> F(2.0*newton);
quantity<length> dx(2.0*meter);
quantity<energy> E(work(F,dx));
std::cout << "F = " << F << std::endl
<< "dx = " << dx << std::endl
<< "E = " << E << std::endl
<< std::endl;
/// check complex quantities
typedef std::complex<double> complex_type;
quantity<electric_potential,complex_type> v = complex_type(12.5,0.0)*volts;
quantity<current,complex_type> i = complex_type(3.0,4.0)*amperes;
quantity<resistance,complex_type> z = complex_type(1.5,-2.0)*ohms;
std::cout << "V = " << v << std::endl
<< "I = " << i << std::endl
<< "Z = " << z << std::endl
<< "I*Z = " << i*z << std::endl
<< "I*Z == V? " << std::boolalpha << (i*z == v) << std::endl
<< std::endl;
return 0;
}
//]
| 24.47191 | 80 | 0.598255 | zyiacas |
b10d2cb094f15d118417f04a05cdd14bd85f729a | 832 | cpp | C++ | Exams/bcp-2022-02/PBQ1.cpp | dbilovd/compeng-sem1-cpp | 136c89ec63b65e4bc7fba07a45f29dc0c9de56e6 | [
"Apache-2.0"
] | 1 | 2018-12-03T10:06:06.000Z | 2018-12-03T10:06:06.000Z | Exams/bcp-2022-02/PBQ1.cpp | dbilovd/compeng-sem1-cpp | 136c89ec63b65e4bc7fba07a45f29dc0c9de56e6 | [
"Apache-2.0"
] | null | null | null | Exams/bcp-2022-02/PBQ1.cpp | dbilovd/compeng-sem1-cpp | 136c89ec63b65e4bc7fba07a45f29dc0c9de56e6 | [
"Apache-2.0"
] | 1 | 2018-12-03T10:23:55.000Z | 2018-12-03T10:23:55.000Z | #include<iostream>
using namespace std;
int addFiveNumbers ()
{
double results = 0;
for (int i = 0; i < 5; i++)
{
double currentNumber;
cout << "Enter a number:\n";
cin >> currentNumber;
results += (double) currentNumber;
}
cout << "The result is: " + to_string(results) + "\n";
return 0;
}
int addNNumbers()
{
int numOfNumbers;
cout << "Enter the number of numbers you want to calculate: ";
cin >> numOfNumbers;
double results = 0;
for (int i = 0; i < numOfNumbers; i++)
{
double currentNumber;
cout << "Enter a number: ";
cin >> currentNumber;
results += (double) currentNumber;
}
cout << "The sum of all " + to_string(numOfNumbers) + " numbers is: " + to_string(results) + "\n";
return 0;
}
int main()
{
// addFiveNumbers();
addNNumbers();
return 0;
}
| 17.702128 | 100 | 0.602163 | dbilovd |
b10ff608257821c5b4cfe8496c1a5f5917fbb108 | 571 | cpp | C++ | program9/program9/Source.cpp | hurnhu/Academic-C-Code-Examples | 2dbab12888fc7f87b997daf7df4127a1ffd81b44 | [
"MIT"
] | null | null | null | program9/program9/Source.cpp | hurnhu/Academic-C-Code-Examples | 2dbab12888fc7f87b997daf7df4127a1ffd81b44 | [
"MIT"
] | null | null | null | program9/program9/Source.cpp | hurnhu/Academic-C-Code-Examples | 2dbab12888fc7f87b997daf7df4127a1ffd81b44 | [
"MIT"
] | null | null | null | //Author: michael lapan
//assignment: program9
/*
*this program reads two files, loads both into BST
*and then allows the user to search for a user on a certin date
*/
#include <fstream>
#include <iostream>
using namespace std;
#include "wrap.h"
int main()
{
//vars to hold user input.
int custID = 0;
string date;
wrap BST;
cout << "what is the customers id?" << endl;
cin >> custID;
cout << "the date to look up for the person? (format must be DD/MM/YYY)" << endl;
cin >> date;
//find this custID on this date
BST.find(custID, date);
system("pause");
} | 20.392857 | 82 | 0.676007 | hurnhu |
b110cee854f2750143ec0a482a471191a6a117ce | 167 | hpp | C++ | include/MemeEditor/ImGui.hpp | Gurman8r/CppSandbox | a0f1cf0ade69ecaba4d167c0611a620914155e53 | [
"MIT"
] | null | null | null | include/MemeEditor/ImGui.hpp | Gurman8r/CppSandbox | a0f1cf0ade69ecaba4d167c0611a620914155e53 | [
"MIT"
] | null | null | null | include/MemeEditor/ImGui.hpp | Gurman8r/CppSandbox | a0f1cf0ade69ecaba4d167c0611a620914155e53 | [
"MIT"
] | null | null | null | #ifndef _ML_IMGUI_HPP_
#define _ML_IMGUI_HPP_
#include <imgui/imgui.h>
#include <imgui/imgui_internal.h>
#include <imgui/imgui_impl_ml.hpp>
#endif // !_ML_IMGUI_HPP_ | 20.875 | 34 | 0.790419 | Gurman8r |
b113279b41355c1596d28a4bb777921d1a8575a4 | 8,562 | cpp | C++ | perf/sort_patterns.cpp | memsharded/range-v3 | 30a4dc8ef723a6db95d80f6bba3d6d5e9af0eadd | [
"MIT"
] | null | null | null | perf/sort_patterns.cpp | memsharded/range-v3 | 30a4dc8ef723a6db95d80f6bba3d6d5e9af0eadd | [
"MIT"
] | null | null | null | perf/sort_patterns.cpp | memsharded/range-v3 | 30a4dc8ef723a6db95d80f6bba3d6d5e9af0eadd | [
"MIT"
] | 1 | 2021-10-02T08:03:49.000Z | 2021-10-02T08:03:49.000Z | /// \file
// Range v3 library
//
// Copyright Eric Niebler 2013-2015
// Copyright Gonzalo Brito Gadeschi 2015
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/ericniebler/range-v3
//
#include <range/v3/detail/config.hpp>
#if RANGES_CXX_RETURN_TYPE_DEDUCTION >= RANGES_CXX_RETURN_TYPE_DEDUCTION_14 && \
RANGES_CXX_GENERIC_LAMBDAS >= RANGES_CXX_GENERIC_LAMBDAS_14
#include <iostream>
#include <iomanip>
#include <vector>
#include <random>
#include <functional>
#include <climits>
#include <chrono>
#include <algorithm>
#include <range/v3/all.hpp>
RANGES_DIAGNOSTIC_IGNORE_GLOBAL_CONSTRUCTORS
RANGES_DIAGNOSTIC_IGNORE_SIGN_CONVERSION
namespace
{
/// Creates an geometric infinite sequence starting at 1 where the
/// successor is multiplied by \p V
auto geometric_sequence(std::size_t V) {
std::size_t N = 1;
return ranges::view::generate([N, V]() mutable {
auto old = N;
N *= V;
return old;
});
}
/// Creates an geometric infinite sequence starting at 1 where the
/// successor is multiplied by \p V
auto geometric_sequence_n(std::size_t V, std::size_t limit) {
return geometric_sequence(V) |
ranges::view::take_while([limit](std::size_t n) { return n <= limit; });
}
/// Random uniform integer sequence
struct random_uniform_integer_sequence {
std::default_random_engine gen;
std::uniform_int_distribution<> dist;
auto operator()(std::size_t) {
return ranges::view::generate([&]{ return dist(gen); });
}
static std::string name() { return "random_uniform_integer_sequence"; }
};
struct ascending_integer_sequence {
auto operator()(std::size_t) { return ranges::view::ints(1); }
static std::string name() { return "ascending_integer_sequence"; }
};
struct descending_integer_sequence {
auto operator()(std::size_t) {
return ranges::view::iota(0ll, std::numeric_limits<long long>::max()) |
ranges::view::reverse;
}
static std::string name() { return "descending_integer_sequence"; }
};
auto even = [](auto i) { return i % 2 == 0; };
auto odd = [](auto i) { return !even(i); };
struct even_odd_integer_sequence {
static std::string name() { return "even_odd_integer_sequence"; }
auto operator()(std::size_t n) {
return ranges::view::concat(ranges::view::ints(std::size_t{0}, n) | ranges::view::filter(even),
ranges::view::ints(std::size_t{0}, n) | ranges::view::filter(odd));
}
};
struct organ_pipe_integer_sequence {
static std::string name() { return "organ_pipe_integer_sequence"; }
auto operator()(std::size_t n) {
return ranges::view::concat(ranges::view::ints(std::size_t{0}, n/2),
ranges::view::ints(std::size_t{0}, n/2 + 1)
| ranges::view::reverse);
}
};
template<typename Seq>
void print(Seq seq, std::size_t n) {
std::cout << "sequence: " << seq.name() << '\n';
RANGES_FOR(auto i, seq(n) | ranges::view::take(n)) {
std::cout << i << '\n';
}
}
/// Returns the duration of a computation
using clock_t = std::chrono::high_resolution_clock;
using duration_t = clock_t::duration;
template<typename Computation>
auto duration(Computation &&c) {
auto time = []{ return clock_t::now(); };
const auto start = time();
c();
return time() - start;
}
template<typename Duration>
auto to_millis(Duration d) {
return std::chrono::duration_cast<std::chrono::milliseconds>(d).count();
}
template<typename Durations> auto compute_mean(Durations &&durations) {
using D = ranges::range_value_type_t<Durations>;
D total = ranges::accumulate(durations, D{}, ranges::plus{}, ranges::convert_to<D>{});
return total / ranges::size(durations);
}
template<typename Durations> auto compute_stddev(Durations &&durations) {
using D = ranges::range_value_type_t<Durations>;
using Rep = typename D::rep;
const auto mean = compute_mean(durations);
const auto stddev = ranges::accumulate(
durations | ranges::view::transform([=](auto i) {
auto const delta = (i - mean).count();
return delta * delta;
}), Rep{}, ranges::plus{}, ranges::convert_to<Rep>{});
return D{static_cast<typename D::rep>(std::sqrt(stddev / ranges::size(durations)))};
}
struct benchmark {
struct result_t {
duration_t mean_t;
duration_t max_t;
duration_t min_t;
std::size_t size;
duration_t deviation;
};
std::vector<result_t> results;
template<typename Computation, typename Sizes>
benchmark(Computation &&c, Sizes &&sizes, double target_deviation = 0.25,
std::size_t max_iters = 100, std::size_t min_iters = 5) {
RANGES_FOR(auto size, sizes) {
std::vector<duration_t> durations;
duration_t deviation;
duration_t mean_duration;
std::size_t iter;
for (iter = 0; iter < max_iters; ++iter) {
c.init(size);
durations.emplace_back(duration(c));
mean_duration = compute_mean(durations);
if (++iter == max_iters) {
break;
}
if (iter >= min_iters) {
deviation = compute_stddev(durations);
if (deviation < target_deviation * mean_duration)
break;
}
}
auto minmax = ranges::minmax(durations);
results.emplace_back(
result_t{mean_duration, minmax.second, minmax.first, size, deviation});
std::cerr << "size: " << size << " iter: " << iter
<< " dev: " << to_millis(deviation)
<< " mean: " << to_millis(mean_duration)
<< " max: " << to_millis(minmax.second)
<< " min: " << to_millis(minmax.first) << '\n';
}
}
};
template<typename Seq, typename Comp>
struct computation_on_sequence {
Seq seq;
Comp comp;
std::vector<ranges::range_value_type_t<decltype(seq(std::size_t{}))>> data;
computation_on_sequence(Seq s, Comp c, std::size_t max_size)
: seq(std::move(s)), comp(std::move(c)) {
data.reserve(max_size);
}
void init(std::size_t size) {
data.resize(size);
ranges::copy(seq(size) | ranges::view::take(size), ranges::begin(data));
}
void operator()() { comp(data); }
};
template<typename Seq, typename Comp>
auto make_computation_on_sequence(Seq s, Comp c, std::size_t max_size) {
return computation_on_sequence<Seq, Comp>(std::move(s), std::move(c),
max_size);
}
template<typename Seq> void benchmark_sort(Seq &&seq, std::size_t max_size) {
auto ranges_sort_comp =
make_computation_on_sequence(seq, ranges::sort, max_size);
auto std_sort_comp = make_computation_on_sequence(
seq, [](auto &&v) { std::sort(std::begin(v), std::end(v)); }, max_size);
auto ranges_sort_benchmark =
benchmark(ranges_sort_comp, geometric_sequence_n(2, max_size));
auto std_sort_benchmark =
benchmark(std_sort_comp, geometric_sequence_n(2, max_size));
using std::setw;
std::cout << '#'
<< "pattern: " << seq.name() << '\n';
std::cout << '#' << setw(19) << 'N' << setw(20) << "ranges::sort" << setw(20)
<< "std::sort"
<< '\n';
RANGES_FOR(auto p, ranges::view::zip(ranges_sort_benchmark.results,
std_sort_benchmark.results)) {
auto rs = p.first;
auto ss = p.second;
std::cout << setw(20) << rs.size << setw(20) << to_millis(rs.mean_t)
<< setw(20) << to_millis(ss.mean_t) << '\n';
}
}
} // unnamed namespace
int main() {
constexpr std::size_t max_size = 2000000;
print(random_uniform_integer_sequence(), 20);
print(ascending_integer_sequence(), 20);
print(descending_integer_sequence(), 20);
print(even_odd_integer_sequence(), 20);
print(organ_pipe_integer_sequence(), 20);
benchmark_sort(random_uniform_integer_sequence(), max_size);
benchmark_sort(ascending_integer_sequence(), max_size);
benchmark_sort(descending_integer_sequence(), max_size);
benchmark_sort(organ_pipe_integer_sequence(), max_size);
}
#else
#pragma message("sort_patterns requires C++14 return type deduction and generic lambdas")
int main() {}
#endif
| 33.315175 | 101 | 0.629292 | memsharded |
b11c5ec8a59a1b8f7fcf6723bc7c9ca17ef11600 | 2,130 | cpp | C++ | aspirant_application/Context.Editor.NewRoom.cpp | playdeezgames/Aspirant | a907475fefb58d766a103324e65317613831561b | [
"MIT"
] | null | null | null | aspirant_application/Context.Editor.NewRoom.cpp | playdeezgames/Aspirant | a907475fefb58d766a103324e65317613831561b | [
"MIT"
] | null | null | null | aspirant_application/Context.Editor.NewRoom.cpp | playdeezgames/Aspirant | a907475fefb58d766a103324e65317613831561b | [
"MIT"
] | null | null | null | #include "Context.Editor.NewRoom.h"
#include "Game.Descriptors.h"
#include <vector>
#include "Common.Finisher.h"
#include "Game.Object.Common.h"
namespace context::editor::NewRoom
{
const std::string DEFAULT_ROOM_NAME = "<replace me>";
const size_t DEFAULT_ROOM_COLUMNS = 10;
const size_t DEFAULT_ROOM_ROWS = 10;
const size_t MINIMUM_COLUMNS = 1;
const size_t MINIMUM_ROWS = 1;
const size_t DELTA_COLUMNS = 1;
const size_t DELTA_ROWS = 1;
static std::string newRoomName = "";
static size_t newRoomColumns = 0;
static size_t newRoomRows = 0;
static std::vector<std::string> terrains;
static size_t terrainIndex;
void Reset()
{
newRoomName = DEFAULT_ROOM_NAME;
newRoomColumns = DEFAULT_ROOM_COLUMNS;
newRoomRows = DEFAULT_ROOM_ROWS;
}
const std::string& GetName()
{
return newRoomName;
}
void AppendName(const std::string& text)
{
if (text == "\b")
{
if (!newRoomName.empty())
{
newRoomName.pop_back();
}
}
else
{
newRoomName += text;
}
}
void ClearName()
{
newRoomName = "";
}
size_t GetColumns()
{
return newRoomColumns;
}
void IncrementColumns()
{
newRoomColumns+=DELTA_COLUMNS;
}
void DecrementColumns()
{
newRoomColumns = (newRoomColumns <= MINIMUM_COLUMNS) ? (MINIMUM_COLUMNS) : (newRoomColumns - DELTA_COLUMNS);
}
size_t GetRows()
{
return newRoomRows;
}
void IncrementRows()
{
newRoomRows+=DELTA_ROWS;
}
void DecrementRows()
{
newRoomRows = (newRoomRows <= MINIMUM_ROWS) ? (MINIMUM_ROWS) : (newRoomRows - DELTA_ROWS);
}
void Start()
{
terrains.clear();
auto identifiers = game::Descriptors::GetIdentifiers();
for (auto& identifier : identifiers)
{
auto descriptor = game::Descriptors::Get(identifier);
nlohmann::json model;
if (descriptor.CanCover(std::optional<game::object::Common>()))
{
terrains.push_back(identifier);
}
}
}
const std::string GetTerrain()
{
return terrains[terrainIndex];
}
void NextTerrain()
{
terrainIndex = (terrainIndex + 1) % terrains.size();
}
void PreviousTerrain()
{
terrainIndex = (terrainIndex + terrains.size() - 1) % terrains.size();
}
}
| 18.684211 | 110 | 0.688263 | playdeezgames |
b11ca6a084503cd41e4b54966586d42f08c9504b | 72 | cpp | C++ | for python/auto.cpp | aerolalit/Auto-Testing-Python-Programs | dd49ab266c9f0fd8e34278f68f8af017711942e3 | [
"MIT"
] | 4 | 2019-10-03T21:16:51.000Z | 2019-10-04T01:28:08.000Z | for python/auto.cpp | aerolalit/Auto-Testing | dd49ab266c9f0fd8e34278f68f8af017711942e3 | [
"MIT"
] | null | null | null | for python/auto.cpp | aerolalit/Auto-Testing | dd49ab266c9f0fd8e34278f68f8af017711942e3 | [
"MIT"
] | null | null | null | #include <stdlib.h>
int main(){
system("bash auto.sh");
return 0;
}
| 9 | 24 | 0.611111 | aerolalit |
b1223c7357635c357b5606d3457e3a6b0d8f9c9f | 3,712 | hpp | C++ | source/Expected.hpp | CyberSys/vaultmp | 341d62202eb47c5f8795c3b93391fd799c6a4ca8 | [
"MIT"
] | 67 | 2015-01-08T10:40:31.000Z | 2022-03-29T21:16:51.000Z | source/Expected.hpp | CyberSys/vaultmp | 341d62202eb47c5f8795c3b93391fd799c6a4ca8 | [
"MIT"
] | 20 | 2015-01-05T21:04:05.000Z | 2018-04-15T11:50:37.000Z | source/Expected.hpp | CyberSys/vaultmp | 341d62202eb47c5f8795c3b93391fd799c6a4ca8 | [
"MIT"
] | 60 | 2015-02-17T00:12:11.000Z | 2021-08-21T22:16:58.000Z | #ifndef EXPECTED_H
#define EXPECTED_H
#include "vaultmp.hpp"
#include "VaultException.hpp"
/**
* \brief http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2012-Andrei-Alexandrescu-Systematic-Error-Handling-in-C
*/
template<typename T>
class Expected
{
private:
union
{
T value;
std::exception_ptr exception;
};
bool valid;
public:
Expected() : value(), valid(true) {}
Expected(const T& value) : value(value), valid(true) {}
Expected(T&& value) : value(std::move(value)), valid(true) {}
Expected(const Expected& expected) : valid(expected.valid)
{
if (valid)
new(&value) T(expected.value);
else
new(&exception) std::exception_ptr(expected.exception);
}
Expected(Expected&& expected) : valid(expected.valid)
{
if (valid)
new(&value) T(std::move(expected.value));
else
new(&exception) std::exception_ptr(std::move(expected.exception));
}
Expected& operator=(const Expected& expected)
{
Expected tmp(expected);
tmp.swap(*this);
return *this;
}
Expected(const VaultException& exception) : exception(std::make_exception_ptr(exception)), valid(false) {}
~Expected()
{
using std::exception_ptr;
if (valid)
value.~T();
else
exception.~exception_ptr();
}
void swap(Expected& expected)
{
if (valid)
{
if (expected.valid)
{
using std::swap;
swap(value, expected.value);
}
else
{
using std::exception_ptr;
auto t = std::move(expected.exception);
expected.exception.~exception_ptr();
new(&expected.value) T(std::move(value));
value.~T();
new(&exception) exception_ptr(std::move(t));
std::swap(valid, expected.valid);
}
}
else
{
if (expected.valid)
expected.swap(*this);
else
exception.swap(expected.exception);
}
}
T& get()
{
if (this->operator bool())
return value;
else
{
if (valid)
throw VaultException("Expected<T> failed: operator bool returned false").stacktrace();
try
{
std::rethrow_exception(exception);
}
catch (VaultException& exception)
{
exception.stacktrace();
throw;
}
}
}
template<typename U>
struct result_star_operator
{
template<typename Q> static decltype(Q().operator*()) test(decltype(&Q::operator*));
template<typename> static void test(...);
typedef decltype(test<U>(0)) type;
};
template<typename U>
struct result_pointer_operator
{
template<typename Q> static decltype(Q().operator->()) test(decltype(&Q::operator->));
template<typename> static void test(...);
typedef decltype(test<U>(0)) type;
};
template<typename U> typename std::enable_if<std::is_class<U>::value, bool>::type bool_operator() const { return valid && value.operator bool(); }
template<typename U> typename std::enable_if<!std::is_class<U>::value, bool>::type bool_operator() const { return valid; }
explicit operator bool() const { return bool_operator<T>(); }
template<typename U> typename std::enable_if<std::is_class<U>::value, typename result_star_operator<U>::type>::type star_operator(U& u) { return u.operator*(); }
template<typename U> typename std::enable_if<!std::is_class<U>::value, U&>::type star_operator(U& u) { return u; }
auto operator*() { return star_operator<T>(get()); }
template<typename U> typename std::enable_if<std::is_class<U>::value, typename result_pointer_operator<U>::type>::type pointer_operator(U& u) { return u.operator->(); }
template<typename U> typename std::enable_if<!std::is_class<U>::value && std::is_pointer<U>::value, U>::type pointer_operator(U& u) { return u; }
auto operator->() { return pointer_operator<T>(get()); }
};
#endif
| 26.705036 | 170 | 0.658405 | CyberSys |
b12306a388689a36c34321782d6f893044cb4346 | 1,754 | hpp | C++ | lib/grid/concrete_domain_index.hpp | mdavezac/bempp | bc573062405bda107d1514e40b6153a8350d5ab5 | [
"BSL-1.0"
] | null | null | null | lib/grid/concrete_domain_index.hpp | mdavezac/bempp | bc573062405bda107d1514e40b6153a8350d5ab5 | [
"BSL-1.0"
] | null | null | null | lib/grid/concrete_domain_index.hpp | mdavezac/bempp | bc573062405bda107d1514e40b6153a8350d5ab5 | [
"BSL-1.0"
] | null | null | null | // Copyright (C) 2011-2012 by the BEM++ Authors
//
// 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.
#ifndef bempp_concrete_domain_index_hpp
#define bempp_concrete_domain_index_hpp
#include "domain_index.hpp"
#include "concrete_index_set.hpp"
namespace Bempp {
template <typename DuneGrid> class ConcreteDomainIndex : public DomainIndex {
public:
ConcreteDomainIndex(const DuneGrid &grid,
const std::vector<int> &elementIndexToPhysicalEntity)
: DomainIndex(std::unique_ptr<IndexSet>(
new ConcreteIndexSet<typename DuneGrid::LevelGridView>(
&grid.levelIndexSet(0))),
elementIndexToPhysicalEntity) {}
};
} // namespace
#endif
| 41.761905 | 80 | 0.734892 | mdavezac |
b124f967865c5a926cc8cac6d7d1b463dd88ab16 | 14,225 | cpp | C++ | libraries/disp/plots/imagesc.cpp | MagCPP/mne-cpp | 05f634a8401b20226bd719254a5da227e67a379b | [
"BSD-3-Clause"
] | null | null | null | libraries/disp/plots/imagesc.cpp | MagCPP/mne-cpp | 05f634a8401b20226bd719254a5da227e67a379b | [
"BSD-3-Clause"
] | null | null | null | libraries/disp/plots/imagesc.cpp | MagCPP/mne-cpp | 05f634a8401b20226bd719254a5da227e67a379b | [
"BSD-3-Clause"
] | null | null | null | //=============================================================================================================
/**
* @file imagesc.cpp
* @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
* Daniel Strohmeier <daniel.strohmeier@tu-ilmenau.de>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>;
* @version 1.0
* @date June, 2013
*
* @section LICENSE
*
* Copyright (C) 2013, Christoph Dinh and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief Definition of the ImageSc class.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "imagesc.h"
#include "helpers/colormap.h"
//*************************************************************************************************************
//=============================================================================================================
// Qt INCLUDES
//=============================================================================================================
#include <QPainter>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace DISPLIB;
using namespace Eigen;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
ImageSc::ImageSc(QWidget *parent)
: Graph(parent)
, m_pPixmapData(NULL)
, m_pPixmapColorbar(NULL)
{
init();
}
//*************************************************************************************************************
ImageSc::ImageSc(MatrixXd &p_dMat, QWidget *parent)
: Graph(parent)
, m_pPixmapData(NULL)
, m_pPixmapColorbar(NULL)
{
init();
updateData(p_dMat);
}
//*************************************************************************************************************
ImageSc::ImageSc(MatrixXf &p_fMat, QWidget *parent)
: Graph(parent)
, m_pPixmapData(NULL)
, m_pPixmapColorbar(NULL)
{
init();
updateData(p_fMat);
}
//*************************************************************************************************************
ImageSc::ImageSc(MatrixXi &p_iMat, QWidget *parent)
: Graph(parent)
, m_pPixmapData(NULL)
, m_pPixmapColorbar(NULL)
{
init();
updateData(p_iMat);
}
//*************************************************************************************************************
ImageSc::~ImageSc()
{
if(m_pPixmapData)
delete m_pPixmapData;
if(m_pPixmapColorbar)
delete m_pPixmapColorbar;
}
//*************************************************************************************************************
void ImageSc::init()
{
//Colormap
pColorMapper = ColorMap::valueToColor;
m_sColorMap = "Hot";
//Parent init
Graph::init();
m_iBorderTopBottom = 20;
m_iBorderLeftRight = 60;
//Colorbar
m_bColorbar = true;
m_qFontColorbar.setPixelSize(10);
m_qPenColorbar = QPen(Qt::black);
m_iColorbarWidth = 12;
m_iColorbarSteps = 7;//>= 2!!
m_iColorbarGradSteps = 200;
}
//*************************************************************************************************************
void ImageSc::updateData(MatrixXd &p_dMat)
{
if(p_dMat.rows() > 0 && p_dMat.cols() > 0)
{
m_dMinValue = p_dMat.minCoeff();
m_dMaxValue = p_dMat.maxCoeff();
// -- data --
m_matCentNormData = p_dMat;
double minValue = m_matCentNormData.minCoeff();
m_matCentNormData.array() -= minValue;
double maxValue = m_matCentNormData.maxCoeff();
m_matCentNormData.array() /= maxValue;
updateMaps();
}
}
//*************************************************************************************************************
void ImageSc::updateData(MatrixXf &p_fMat)
{
MatrixXd t_dMat = p_fMat.cast<double>();
updateData(t_dMat);
}
//*************************************************************************************************************
void ImageSc::updateData(MatrixXi &p_iMat)
{
MatrixXd t_dMat = p_iMat.cast<double>();
updateData(t_dMat);
}
//*************************************************************************************************************
void ImageSc::updateMaps()
{
if(m_pPixmapData)
{
delete m_pPixmapData;
m_pPixmapData = NULL;
}
if(m_pPixmapColorbar)
{
delete m_pPixmapColorbar;
m_pPixmapColorbar = NULL;
}
if(m_matCentNormData.rows() > 0 && m_matCentNormData.cols() > 0)
{
// --Data--
qint32 x = m_matCentNormData.cols();
qint32 y = m_matCentNormData.rows();
qint32 i, j;
QImage t_qImageData(x, y, QImage::Format_RGB32);
for(i = 0; i < x; ++i)
for(j = 0; j < y; ++j)
t_qImageData.setPixel(i, j, pColorMapper(m_matCentNormData(j,i), m_sColorMap));
m_pPixmapData = new QPixmap(QPixmap::fromImage(t_qImageData));
// --Colorbar--
QImage t_qImageColorbar(1, m_iColorbarGradSteps, QImage::Format_RGB32);
double t_dQuantile = 1.0/((double)m_iColorbarGradSteps-1);
for(j = 0; j < m_iColorbarGradSteps; ++j)
{
QRgb t_qRgb = pColorMapper(t_dQuantile*((double)(m_iColorbarGradSteps-1-j))*1.0, m_sColorMap);
t_qImageColorbar.setPixel(0, j, t_qRgb);
}
m_pPixmapColorbar = new QPixmap(QPixmap::fromImage(t_qImageColorbar));
// --Scale Values--
m_qVecScaleValues.clear();
double scale = pow(10, floor(log(m_dMaxValue-m_dMinValue)/log(10.0)));
//Zero Based Scale?
if(m_dMaxValue > 0 && m_dMinValue < 0)
{
double quantum = floor((((m_dMaxValue-m_dMinValue)/scale)/(m_iColorbarSteps-1))*10.0)*(scale/10.0);
double start = 0;
while(m_dMinValue < (start - quantum))
start -= quantum;
//Create Steps
m_qVecScaleValues.push_back(start);
for(qint32 i = 1; i < m_iColorbarSteps-1; ++i)
m_qVecScaleValues.push_back(m_qVecScaleValues[i-1]+quantum);
}
else
{
double quantum = floor((((m_dMaxValue-m_dMinValue)/scale)/(m_iColorbarSteps-1))*10.0)*(scale/10.0);
double start = floor(((m_dMaxValue-m_dMinValue)/2.0 + m_dMinValue)/scale)*scale;
while(m_dMinValue < (start - quantum))
start -= quantum;
//Create Steps
m_qVecScaleValues.push_back(start);
for(qint32 i = 1; i < m_iColorbarSteps-1; ++i)
m_qVecScaleValues.push_back(m_qVecScaleValues[i-1]+quantum);
}
update();
}
}
//*************************************************************************************************************
void ImageSc::setColorMap(const QString &p_sColorMap)
{
m_sColorMap = p_sColorMap;
updateMaps();
}
//*************************************************************************************************************
void ImageSc::paintEvent(QPaintEvent * event)
{
Q_UNUSED(event);
QPainter painter(this);
if (m_pPixmapData)
{
QPoint t_qPointTopLeft(0,0);
// -- Data --
QSize t_qSizePixmapData = m_qSizeWidget;
t_qSizePixmapData.setHeight(t_qSizePixmapData.height()-m_iBorderTopBottom*2);
t_qSizePixmapData.setWidth(t_qSizePixmapData.width()-m_iBorderLeftRight*2);
// Scale data
QPixmap t_qPixmapScaledData = m_pPixmapData->scaled(t_qSizePixmapData, Qt::IgnoreAspectRatio);//Qt::KeepAspectRatio);
// Calculate data position
t_qPointTopLeft.setX((m_qSizeWidget.width()-t_qPixmapScaledData.width())/2);
t_qPointTopLeft.setY((m_qSizeWidget.height()-t_qPixmapScaledData.height())/2);
//Draw data
painter.drawPixmap(t_qPointTopLeft,t_qPixmapScaledData);
//Draw border
painter.drawRect(t_qPointTopLeft.x()-1, t_qPointTopLeft.y()-1, t_qPixmapScaledData.width()+1, t_qPixmapScaledData.height()+1);
// -- Colorbar --
if(m_bColorbar && m_pPixmapColorbar && m_qVecScaleValues.size() >= 2)
{
QSize t_qSizePixmapColorbar = m_qSizeWidget;
t_qSizePixmapColorbar.setWidth(m_iColorbarWidth);
t_qSizePixmapColorbar.setHeight(t_qPixmapScaledData.height());
// Scale colorbar
QPixmap t_qPixmapScaledColorbar = m_pPixmapColorbar->scaled(t_qSizePixmapColorbar, Qt::IgnoreAspectRatio);
// Calculate colorbar position
t_qPointTopLeft.setY(t_qPointTopLeft.y());
t_qPointTopLeft.setX(t_qPointTopLeft.x() + t_qPixmapScaledData.width() + m_iBorderLeftRight/3);
//Draw colorbar
painter.drawPixmap(t_qPointTopLeft,t_qPixmapScaledColorbar);
//Draw border
painter.drawRect(t_qPointTopLeft.x()-1, t_qPointTopLeft.y()-1, m_iColorbarWidth+1, t_qPixmapScaledData.height()+1);
// -- Scale --
painter.setPen(m_qPenColorbar);
painter.setFont(m_qFontColorbar);
qint32 x = t_qPointTopLeft.x()+ m_iColorbarWidth + m_qFontColorbar.pixelSize()/2;
qint32 x_markLeft = x - m_iColorbarWidth - m_qFontColorbar.pixelSize()/2;
qint32 x_markRight = x_markLeft + m_iColorbarWidth;
// max
painter.save();
qint32 y_max = t_qPointTopLeft.y() - m_qFontColorbar.pixelSize()/2;
painter.translate(x, y_max-1);
painter.drawText(QRect(0, 0, 100, 12), Qt::AlignLeft, QString::number(m_dMaxValue));
painter.restore();
//draw max marks
qint32 y_max_mark = y_max + m_qFontColorbar.pixelSize()/2;
painter.drawLine(x_markLeft,y_max_mark,x_markLeft+2,y_max_mark);
painter.drawLine(x_markRight-3,y_max_mark,x_markRight-1,y_max_mark);
// min
painter.save();
qint32 y_min = t_qPointTopLeft.y() + t_qSizePixmapColorbar.height()-1 - m_qFontColorbar.pixelSize()/2;
painter.translate(x, y_min-1);
painter.drawText(QRect(0, 0, 100, 12), Qt::AlignLeft, QString::number(m_dMinValue));
painter.restore();
//draw min marks
qint32 y_min_mark = y_min + m_qFontColorbar.pixelSize()/2;
painter.drawLine(x_markLeft,y_min_mark,x_markLeft+2,y_min_mark);
painter.drawLine(x_markRight-3,y_min_mark,x_markRight-1,y_min_mark);
//Scale values
qint32 y_dist = y_min - y_max;
double minPercent = (m_qVecScaleValues[0]- m_dMinValue)/(m_dMaxValue-m_dMinValue);
double distPercent = (m_qVecScaleValues[1]-m_qVecScaleValues[0])/(m_dMaxValue-m_dMinValue);
qint32 y_current = y_min - (minPercent*y_dist);
qint32 y_current_mark;
//draw scale
for(qint32 i = 0; i < m_qVecScaleValues.size(); ++i)
{
painter.save();
painter.translate(x, y_current-1);
painter.drawText(QRect(0, 0, 100, 12), Qt::AlignLeft, QString::number(m_qVecScaleValues[i]));
painter.restore();
//draw marks
y_current_mark = y_current + m_qFontColorbar.pixelSize()/2;
painter.drawLine(x_markLeft,y_current_mark,x_markLeft+2,y_current_mark);
painter.drawLine(x_markRight-3,y_current_mark,x_markRight-1,y_current_mark);
//update y_current
y_current -= distPercent*y_dist;
}
}
//Draw title & axes
Graph::drawLabels(t_qPixmapScaledData.width(), t_qPixmapScaledData.height());
}
}
| 38.445946 | 135 | 0.506573 | MagCPP |
b1253235548a7f2582bf992212f074994a19274e | 527 | cpp | C++ | src/noflash.cpp | danielkrupinski/csgo-champion | 25874f21c005ea3da1b35812e928e5b01d625c37 | [
"MIT"
] | 21 | 2018-03-30T20:28:32.000Z | 2022-03-05T16:18:21.000Z | src/noflash.cpp | danielkrupinski/csgo-champion | 25874f21c005ea3da1b35812e928e5b01d625c37 | [
"MIT"
] | 2 | 2018-04-12T21:20:44.000Z | 2018-12-04T14:52:59.000Z | src/noflash.cpp | danielkrupinski/csgo-champion | 25874f21c005ea3da1b35812e928e5b01d625c37 | [
"MIT"
] | 3 | 2018-05-14T01:36:36.000Z | 2020-04-29T14:17:05.000Z | #include "noflash.h"
NoFlash::NoFlash(remote::Handle* csgo, remote::MapModuleMemoryRegion* client)
{
if(!csgo || !client)
return;
if(!csgo->NoFlashEnabled)
return;
csgo->Read((void*) csgo->m_addressOfLocalPlayer, &localPlayer, sizeof(long));
if(!localPlayer)
return;
csgo->Read((void*) (localPlayer + 0xABD4), &m_flFlashMaxAlpha, sizeof(m_flFlashMaxAlpha));
if(m_flFlashMaxAlpha == 255.0f && m_flFlashMaxAlpha != NoFlashAlpha)
csgo->Write((void*) (localPlayer + 0xABD4), &NoFlashAlpha, sizeof(float));
}
| 25.095238 | 91 | 0.711575 | danielkrupinski |
b127ae51dba4bcfebab75cc7694d3fee6a25e032 | 3,070 | cpp | C++ | src/tools/modbus_qt_serialport.cpp | paopaol/modbus | 558036099f3c41c03c1b8658bc26c9adfa271c48 | [
"MIT"
] | 3 | 2020-02-11T03:47:42.000Z | 2022-01-21T03:10:09.000Z | src/tools/modbus_qt_serialport.cpp | paopaol/modbus | 558036099f3c41c03c1b8658bc26c9adfa271c48 | [
"MIT"
] | null | null | null | src/tools/modbus_qt_serialport.cpp | paopaol/modbus | 558036099f3c41c03c1b8658bc26c9adfa271c48 | [
"MIT"
] | 1 | 2022-01-21T03:10:11.000Z | 2022-01-21T03:10:11.000Z | #include <QtSerialPort/QSerialPort>
#include <modbus/tools/modbus_client.h>
namespace modbus {
class QtSerialPort : public AbstractIoDevice {
Q_OBJECT
public:
explicit QtSerialPort(QObject *parent = nullptr) : AbstractIoDevice(parent) {
setupEnvironment();
}
~QtSerialPort() override = default;
bool
setBaudRate(qint32 baudRate,
QSerialPort::Directions directions = QSerialPort::AllDirections) {
return serialPort_.setBaudRate(baudRate, directions);
}
bool setDataBits(QSerialPort::DataBits dataBits) {
return serialPort_.setDataBits(dataBits);
}
bool setParity(QSerialPort::Parity parity) {
return serialPort_.setParity(parity);
}
bool setStopBits(QSerialPort::StopBits stopBits) {
return serialPort_.setStopBits(stopBits);
}
void setPortName(const QString &name) { serialPort_.setPortName(name); }
std::string name() override { return serialPort_.portName().toStdString(); }
void open() override {
bool success = serialPort_.open(QIODevice::ReadWrite);
if (!success) {
return;
}
emit opened();
}
void close() override {
if (serialPort_.isOpen()) {
serialPort_.close();
return;
}
emit closed();
}
void write(const char *data, size_t size) override {
serialPort_.write(data, size);
}
QByteArray readAll() override { return serialPort_.readAll(); }
void clear() override { serialPort_.clear(); }
private:
void setupEnvironment() {
connect(&serialPort_, &QSerialPort::aboutToClose, this,
[&]() { emit closed(); });
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 1))
connect(&serialPort_,
static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(
&QSerialPort::error),
this, [&](QSerialPort::SerialPortError err) {
#else
connect(&serialPort_, &QSerialPort::errorOccurred, this,
[&](QSerialPort::SerialPortError err) {
#endif
if (err == QSerialPort::SerialPortError::NoError) {
emit error("");
return;
}
emit error(serialPort_.errorString());
});
connect(&serialPort_, &QSerialPort::bytesWritten, this,
&QtSerialPort::bytesWritten);
connect(&serialPort_, &QSerialPort::readyRead, this,
&QtSerialPort::readyRead);
}
QSerialPort serialPort_;
};
QModbusClient *
newQtSerialClient(const QString &serialName, QSerialPort::BaudRate baudRate,
QSerialPort::DataBits dataBits, QSerialPort::Parity parity,
QSerialPort::StopBits stopBits, QObject *parent) {
QtSerialPort *port = new QtSerialPort(parent);
port->setBaudRate(baudRate);
port->setDataBits(dataBits);
port->setParity(parity);
port->setStopBits(stopBits);
port->setPortName(serialName);
QModbusClient *client = new QModbusClient(port, parent);
return client;
}
#include "modbus_qt_serialport.moc"
} // namespace modbus
| 29.519231 | 81 | 0.643974 | paopaol |
b12f8a141966b9742981dad33a8dbc78af318416 | 7,308 | cpp | C++ | test/unit/reactor/math/ArithmeticTest.cpp | reactor-engine/reactor-math | 599b7074a8f4a5e620f49dea8dd5e36f22cf79a3 | [
"CC0-1.0"
] | null | null | null | test/unit/reactor/math/ArithmeticTest.cpp | reactor-engine/reactor-math | 599b7074a8f4a5e620f49dea8dd5e36f22cf79a3 | [
"CC0-1.0"
] | null | null | null | test/unit/reactor/math/ArithmeticTest.cpp | reactor-engine/reactor-math | 599b7074a8f4a5e620f49dea8dd5e36f22cf79a3 | [
"CC0-1.0"
] | null | null | null | #include "catch.hpp"
#include "reactor/common/type/types.hpp"
#include "reactor/math/Arithmetic.hpp"
using namespace reactor::common::type;
using namespace reactor::math;
TEST_CASE("Arithmetic abs-operation is correct", "[Arithmetic.abs]") {
int attempts[][2] = {{0, 0}, {1, 1}, {-1, 1}, {-25, 25}, {-120, 120}, {1024, 1024}, {-0, 0}};
for (auto &occur : attempts) {
if (occur[0] >= 0) {
if (occur[0] <= 256) {
REQUIRE( Arithmetic<uint8>::abs(occur[0]) == occur[1] );
REQUIRE( Arithmetic<byte>::abs(occur[0]) == occur[1] );
}
REQUIRE( Arithmetic<uint16>::abs(occur[0]) == occur[1] );
REQUIRE( Arithmetic<uint32>::abs(occur[0]) == occur[1] );
REQUIRE( Arithmetic<uint64>::abs(occur[0]) == occur[1] );
REQUIRE( Arithmetic<uint>::abs(occur[0]) == occur[1] );
}
if (occur[0] <= 128) {
REQUIRE( Arithmetic<int8>::abs(occur[0]) == occur[1] );
}
REQUIRE( Arithmetic<int16>::abs(occur[0]) == occur[1] );
REQUIRE( Arithmetic<int32>::abs(occur[0]) == occur[1] );
REQUIRE( Arithmetic<int64>::abs(occur[0]) == occur[1] );
REQUIRE( Arithmetic<float32>::abs(occur[0]) == occur[1] );
REQUIRE( Arithmetic<float64>::abs(occur[0]) == occur[1] );
REQUIRE( Arithmetic<real>::abs(occur[0]) == occur[1] );
REQUIRE( Arithmetic<integer>::abs(occur[0]) == occur[1] );
}
REQUIRE( Arithmetic<float32>::abs(-2.25f) == 2.25f );
REQUIRE( Arithmetic<float64>::abs(-2.25) == 2.25 );
}
TEST_CASE("Arithmetic sqr-operation is correct", "[Arithmetic.sqr]") {
int attempts[][2] = {{32, 1024}, {15, 225}, {11, 121}, {2, 4}, {1, 1}, {0, 0}};
for (auto &occur : attempts) {
if (occur[1] <= 256) {
if (occur[1] <= 128) {
REQUIRE( Arithmetic<int8>::sqr(occur[0]) == occur[1] );
}
REQUIRE( Arithmetic<uint8>::sqr(occur[0]) == occur[1] );
REQUIRE( Arithmetic<byte>::sqr(occur[0]) == occur[1] );
}
REQUIRE( Arithmetic<int16>::sqr(occur[0]) == occur[1] );
REQUIRE( Arithmetic<int32>::sqr(occur[0]) == occur[1] );
REQUIRE( Arithmetic<int64>::sqr(occur[0]) == occur[1] );
REQUIRE( Arithmetic<uint16>::sqr(occur[0]) == occur[1] );
REQUIRE( Arithmetic<uint32>::sqr(occur[0]) == occur[1] );
REQUIRE( Arithmetic<uint64>::sqr(occur[0]) == occur[1] );
REQUIRE( Arithmetic<float32>::sqr(occur[0]) == occur[1] );
REQUIRE( Arithmetic<float64>::sqr(occur[0]) == occur[1] );
REQUIRE( Arithmetic<real>::sqr(occur[0]) == occur[1] );
REQUIRE( Arithmetic<uint>::sqr(occur[0]) == occur[1] );
REQUIRE( Arithmetic<integer>::sqr(occur[0]) == occur[1] );
}
REQUIRE( Arithmetic<float32>::sqr(1.5f) == 2.25f );
REQUIRE( Arithmetic<float64>::sqr(1.5) == 2.25 );
}
TEST_CASE("Arithmetic sqrt-operation is correct", "[Arithmetic.sqrt]") {
int attempts[][2] = {{1024, 32}, {225, 15}, {121, 11}, {4, 2}, {1, 1}, {0, 0}};
for (auto &occur : attempts) {
if (occur[0] <= 256) {
if (occur[0] <= 128) {
REQUIRE( Arithmetic<int8>::sqrt(occur[0]) == occur[1] );
}
REQUIRE( Arithmetic<uint8>::sqrt(occur[0]) == occur[1] );
REQUIRE( Arithmetic<byte>::sqrt(occur[0]) == occur[1] );
}
REQUIRE( Arithmetic<int16>::sqrt(occur[0]) == occur[1] );
REQUIRE( Arithmetic<int32>::sqrt(occur[0]) == occur[1] );
REQUIRE( Arithmetic<int64>::sqrt(occur[0]) == occur[1] );
REQUIRE( Arithmetic<uint16>::sqrt(occur[0]) == occur[1] );
REQUIRE( Arithmetic<uint32>::sqrt(occur[0]) == occur[1] );
REQUIRE( Arithmetic<uint64>::sqrt(occur[0]) == occur[1] );
REQUIRE( Arithmetic<float32>::sqrt(occur[0]) == occur[1] );
REQUIRE( Arithmetic<float64>::sqrt(occur[0]) == occur[1] );
REQUIRE( Arithmetic<real>::sqrt(occur[0]) == occur[1] );
REQUIRE( Arithmetic<uint>::sqrt(occur[0]) == occur[1] );
REQUIRE( Arithmetic<integer>::sqrt(occur[0]) == occur[1] );
}
REQUIRE( Arithmetic<float32>::sqrt(2.25f) == 1.5f );
REQUIRE( Arithmetic<float64>::sqrt(2.25) == 1.5 );
}
TEST_CASE("Arithmetic min-operation is correct", "[Arithmetic.min]") {
int attempts[][3] = {{100, 32, 32}, {15, 25, 15}, {0, 11, 0}, {4, -2, -2}, {-1, 1, -1}, {-5, 0, -5}, {7, 7, 7}, {-10, -13, -13}};
for (auto &occur : attempts) {
if (occur[0] >= 0 && occur[1] >= 0) {
REQUIRE( Arithmetic<uint8>::min(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<uint16>::min(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<uint32>::min(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<uint64>::min(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<byte>::min(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<uint>::min(occur[0], occur[1]) == occur[2] );
}
REQUIRE( Arithmetic<int8>::min(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<int16>::min(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<int32>::min(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<int64>::min(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<float32>::min(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<float64>::min(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<real>::min(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<integer>::min(occur[0], occur[1]) == occur[2] );
}
REQUIRE( Arithmetic<float32>::min(2.25f, 1.01f) == 1.01f );
REQUIRE( Arithmetic<float64>::min(2.25, -0.01) == -0.01 );
}
TEST_CASE("Arithmetic max-operation is correct", "[Arithmetic.max]") {
int attempts[][3] = {{100, 32, 100}, {15, 25, 25}, {0, 11, 11}, {4, -2, 4}, {-1, 1, 1}, {-5, 0, 0}, {7, 7, 7}, {-10, -13, -10}};
for (auto &occur : attempts) {
if (occur[0] >= 0 && occur[1] >= 0) {
REQUIRE( Arithmetic<uint8>::max(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<uint16>::max(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<uint32>::max(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<uint64>::max(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<byte>::max(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<uint>::max(occur[0], occur[1]) == occur[2] );
}
REQUIRE( Arithmetic<int8>::max(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<int16>::max(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<int32>::max(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<int64>::max(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<float32>::max(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<float64>::max(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<real>::max(occur[0], occur[1]) == occur[2] );
REQUIRE( Arithmetic<integer>::max(occur[0], occur[1]) == occur[2] );
}
REQUIRE( Arithmetic<float32>::max(2.25f, 1.01f) == 2.25f );
REQUIRE( Arithmetic<float64>::max(2.25, -0.01) == 2.25 );
} | 44.024096 | 133 | 0.541735 | reactor-engine |
b12fa0181df2b05eb8d7823c9acfc1454cb5a766 | 19,879 | cpp | C++ | kits/rosie/rosie_demo.cpp | HebiRobotics/hebi-cpp-examples | db01c9b957b3c97885d452d8b72f9919ba6c48c4 | [
"Apache-2.0"
] | 7 | 2018-03-31T06:52:08.000Z | 2022-02-24T21:27:09.000Z | kits/rosie/rosie_demo.cpp | HebiRobotics/hebi-cpp-examples | db01c9b957b3c97885d452d8b72f9919ba6c48c4 | [
"Apache-2.0"
] | 34 | 2018-06-03T17:28:08.000Z | 2021-05-29T01:15:25.000Z | kits/rosie/rosie_demo.cpp | HebiRobotics/hebi-cpp-examples | db01c9b957b3c97885d452d8b72f9919ba6c48c4 | [
"Apache-2.0"
] | 9 | 2018-02-08T22:50:58.000Z | 2021-03-30T08:07:35.000Z | #define PI 3.141592653592
#include <iostream>
#include <chrono>
#include <thread>
#include <iomanip>
#include "util/grav_comp.hpp"
#include "util/vector_utils.h"
#include "lookup.hpp"
#include "group_feedback.hpp"
#include "group_command.hpp"
#include "robot_model.hpp"
#include "trajectory.hpp"
using namespace hebi;
void getTrajectoryCommand(std::shared_ptr<hebi::trajectory::Trajectory> traj,GroupCommand& cmd,
std::vector<uint32_t> indices, double t, Eigen::VectorXd* pos=nullptr,
Eigen::VectorXd* vel=nullptr, Eigen::VectorXd* acc=nullptr) {
auto len = indices.size();
Eigen::VectorXd position(len);
Eigen::VectorXd velocity(len);
Eigen::VectorXd acceleration(len);
traj->getState(t, &position, &velocity, &acceleration);
hebi::util::setPositionScattered(cmd, indices, position);
hebi::util::setVelocityScattered(cmd, indices, velocity);
if(pos!=nullptr)
*pos = position;
if(vel!=nullptr)
*vel = velocity;
if(acc!=nullptr)
*acc = acceleration;
}
int main() {
const std::unique_ptr<robot_model::RobotModel> arm_model = robot_model::RobotModel::loadHRDF("hrdf/6-dof_arm_w_gripper.hrdf");
const std::vector<std::string> arm_module_names = {"Base","Shoulder", "Elbow", "Wrist1", "Wrist2", "Wrist3"};
const std::vector<std::string> arm_gripper_module_name = {"Spool"};
const double arm_shoulder_joint_comp = 0;
const Eigen::VectorXd arm_effort_offset = (Eigen::VectorXd(6) << 0, arm_shoulder_joint_comp, 0,0,0,0).finished();
const double arm_gripper_open_effort = 1;
const double arm_gripper_close_effort = -5;
const Eigen::VectorXd arm_ik_seed_pos = (Eigen::VectorXd(6) << 0,1,2.5,1.5,-1.5,1).finished();
const double arm_min_traj_duration = .5;
const double base_wheel_radius = .15/2.0;
const double base_wheel_base = 0.470;
const double base_max_lin_speed = 0.6;
const double base_max_rot_speed = base_max_lin_speed*(base_wheel_base/2.0);
const Eigen::Matrix4d base_chassis_com = (Eigen::Matrix4d() << 1,0,0,0, 0,1,0,0, 0,0,1, base_wheel_radius +.005, 0,0,0,1).finished();
const double base_chassis_mass = 12.0;
const double base_chassis_inertia_zz = .5*base_chassis_mass*base_wheel_base*base_wheel_base*.25;
const std::vector<std::string> base_wheel_module_names = {"_Wheel1","_Wheel2","_Wheel3"};
const uint32_t base_num_wheels = 3;
const std::vector<Eigen::Matrix4d> base_wheel_base_frames =
{(Eigen::Matrix4d() <<
1,0,0,base_wheel_base/2.0*cos(-60*PI/180.0),
0,1,0,base_wheel_base/2.0*sin(-60*PI/180.0),
0,0,1,base_wheel_radius,
0,0,0,1).finished(),
(Eigen::Matrix4d() <<
1,0,0,base_wheel_base/2.0*cos(60*PI/180.0),
0,1,0,base_wheel_base/2.0*sin(60*PI/180.0),
0,0,1,base_wheel_radius,
0,0,0,1).finished(),
(Eigen::Matrix4d() <<
1,0,0,base_wheel_base/2.0*cos(180*PI/180.0),
0,1,0,base_wheel_base/2.0*cos(180*PI/180.0),
0,0,1,base_wheel_radius,
0,0,0,1).finished()};
double a1 = -60*PI/180;
double a2 = 60*PI/180;
double a3 = 180*PI/180;
const Eigen::Matrix3d base_wheel_transform =
(Eigen::MatrixXd(3,3) <<
sin(a1), -cos(a1), 2/base_wheel_base,
sin(a2), -cos(a2), 2/base_wheel_base/2,
sin(a3), -cos(a3), 2/base_wheel_base/2).finished();
const Eigen::Matrix3d base_wheel_velocity_matrix = base_wheel_transform / base_wheel_radius;
const Eigen::Matrix3d base_wheel_effort_matrix = base_wheel_transform * base_wheel_radius;
const double base_ramp_time = .33;
Lookup lookup;
// % Optional step to limit the lookup to a set of interfaces or modules
// % HebiLookup.setLookupAddresses('10.10.10.255');
bool enable_logging = true;
//
// %%
// %%%%%%%%%%%%%%%%%%%%%
// % Setup Mobile Base %
// %%%%%%%%%%%%%%%%%%%%%
//
// % Maps XYZ chassis velocities to wheel velocities
Eigen::MatrixXd chassis_mass_matrix(3,3);
chassis_mass_matrix << base_chassis_mass,0,0, 0,base_chassis_mass,0, 0,0,base_chassis_inertia_zz;
// %%
// %%%%%%%%%%%%%
// % Setup Arm %
// %%%%%%%%%%%%%
// % Assume that gravity points up
Eigen::Vector3d gravity_vec(0, 0, -1);
// %%
// %%%%%%%%%%%%%%%
// % Setup Robot %
// %%%%%%%%%%%%%%%
std::vector<std::string> robot_family = {"Rosie"};
std::vector<std::string> robot_names = base_wheel_module_names;
robot_names.insert(robot_names.end(), arm_module_names.begin(), arm_module_names.end());
robot_names.insert(robot_names.end(), arm_gripper_module_name.begin(), arm_gripper_module_name.end());
auto num_modules_ = robot_names.size();
std::vector<uint32_t> wheel_dofs = {0,1,2};
std::vector<uint32_t> arm_dofs = {3,4,5,6,7,8};
std::vector<uint32_t> gripper_dof = {9};
auto robot_group = lookup.getGroupFromNames(robot_family, robot_names);
robot_group->setFeedbackFrequencyHz(100);
//
// %%
// %%%%%%%%%%%%%%%%%
// % Set the Gains %
// %%%%%%%%%%%%%%%%%
auto wheel_group = lookup.getGroupFromNames(robot_family, base_wheel_module_names);
GroupCommand base_gains_command(wheel_group->size());
if (!base_gains_command.readGains("gains/omni-drive-wheel-gains.xml")) {
printf("Could not read omni base gains");
return 1;
}
if (!wheel_group->sendCommandWithAcknowledgement(base_gains_command)) {
printf("Could not send omni base gains");
return 1;
}
auto arm_group = lookup.getGroupFromNames(robot_family, arm_module_names);
GroupCommand arm_gains_command(arm_group->size());
if (!arm_gains_command.readGains("gains/6-dof_arm_gains.xml")) {
printf("Could not read 6 dof arm gains");
return 1;
}
if (!arm_group->sendCommandWithAcknowledgement(arm_gains_command)) {
printf("Could not send 6 dof arm gains");
return 1;
}
auto gripper_group = lookup.getGroupFromNames(robot_family, arm_gripper_module_name);
GroupCommand gripper_gains_command(gripper_group->size());
if (!gripper_gains_command.readGains("gains/gripper_gains.xml")) {
printf("Could not read gripper gains");
return 1;
}
if (!gripper_group->sendCommandWithAcknowledgement(gripper_gains_command)) {
printf("Could not send gripper gains");
return 1;
}
// %%
// %%%%%%%%%%%%%%%%%%%%%%%%%%
// % Setup Mobile I/O Group %
// %%%%%%%%%%%%%%%%%%%%%%%%%%
std::vector<std::string> phone_family = {"HEBI"};
std::vector<std::string> phone_name = {"Mobile IO"};
std::printf("Searching for phone Controller...\n");
std::shared_ptr<Group> phone_group;
while(true) {
if(phone_group = lookup.getGroupFromNames(phone_family, phone_name)) {
break;
}
std::printf("Searching for phone Controller...\n");
}
std::printf("Phone Found. Starting up\n");
// % Get the initial feedback objects that we'll reuse later
GroupFeedback latest_phone_fbk(phone_group->size());// = phone_fbk;
phone_group->getNextFeedback(latest_phone_fbk);
// %%
// %%%%%%%%%%%%%%%%%%%%%%%
// % Begin the demo loop %
// %%%%%%%%%%%%%%%%%%%%%%%
//
// % Start background logging
if(enable_logging) {
robot_group->startLog("logs");
phone_group->startLog("logs");
}
// % This outer loop is what we fall back to anytime we 're-home' the arm
while(true) {
GroupFeedback fbk(robot_group->size());
GroupCommand cmd(robot_group->size());
robot_group->getNextFeedback(fbk);
// % Exaggerate Z-Axis by 2x, X-Y are 1-to-1.
Eigen::Vector3d xyz_scale;
xyz_scale << -1, -1, -2;
//
// % Move to current coordinates
Eigen::Vector3d xyz_target_init;
xyz_target_init << 0.3, 0.0, 0.3;
// % Gripper down
Eigen::MatrixXd rot_mat_target_init(3,3);
rot_mat_target_init << -1,0,0, 0,1,0, 0,0,-1;
Eigen::VectorXd arm_fbk_pos(arm_dofs.size());
for(size_t i = 0; i < arm_fbk_pos.size(); ++i){
arm_fbk_pos[i] = fbk.getPosition()[arm_dofs[i]];
}
Eigen::VectorXd ik_result_joint_angles(arm_dofs.size());
arm_model->solveIK(arm_ik_seed_pos, ik_result_joint_angles, robot_model::EndEffectorPositionObjective(xyz_target_init), robot_model::EndEffectorSO3Objective(rot_mat_target_init));
const size_t len = arm_dofs.size();
Eigen::MatrixXd position(len,2);
position.col(0) = arm_fbk_pos;
position.col(1) = ik_result_joint_angles;
Eigen::VectorXd time(2);
time << 0, arm_min_traj_duration;
auto arm_traj = hebi::trajectory::Trajectory::createUnconstrainedQp(time, position);
auto t0 = fbk.getTime();
auto t = 0.0;
while(t < arm_min_traj_duration) {
//
if(!robot_group->getNextFeedback(fbk)) printf("no feedback recieved\n");
auto temp_t = fbk.getTime();
t = (fbk.getTime() - t0) > arm_min_traj_duration ? arm_min_traj_duration : fbk.getTime() - t0;
getTrajectoryCommand(arm_traj, cmd, arm_dofs, t);
// TODO: dynamicsComp
Eigen::VectorXd masses;
arm_model->getMasses(masses);
Eigen::VectorXd effort(arm_dofs.size());
auto base_accel = fbk[base_num_wheels].imu().accelerometer().get();
Eigen::Vector3d gravity(-base_accel.getX(),
-base_accel.getY(),
-base_accel.getZ());
Eigen::VectorXd arm_positions(arm_dofs.size());
for(size_t i = 0; i < arm_positions.size(); ++i){
arm_positions[i] = fbk.getPosition()[arm_dofs[i]];
}
effort = hebi::util::getGravityCompensationEfforts(*arm_model, masses, arm_positions, gravity);
/*TODO add dynamic_comp*/
// Apply the effort offset as well
effort += arm_effort_offset;
hebi::util::setEffortScattered(cmd, arm_dofs, effort);
robot_group->sendCommand(cmd);
}
// % Grab initial pose
GroupFeedback latest_phone_mobile(phone_group->size());
while(!phone_group->getNextFeedback(latest_phone_mobile)){
printf("feedback not recieved\n\n");
}
auto orient = latest_phone_fbk[0].mobile().arOrientation().get();
Eigen::Quaterniond q;
q.w() = orient.getW();
q.x() = orient.getX();
q.y() = orient.getY();
q.z() = orient.getZ();
auto r_init = q.toRotationMatrix();
auto ar_pos = latest_phone_fbk[0].mobile().arPosition().get();
Eigen::Vector3d xyz_init;
xyz_init << ar_pos.getX(), ar_pos.getY(), ar_pos.getZ();
auto xyz_phone_new = xyz_init;
Eigen::VectorXd end_velocities = Eigen::VectorXd::Zero(arm_dofs.size());
Eigen::VectorXd end_accels = Eigen::VectorXd::Zero(arm_dofs.size());
t0 = fbk.getTime();
auto time_last = t0;
auto chassis_traj_start_time = t0;
GroupCommand wheel_cmd(wheel_group->size());\
wheel_cmd.setPosition(hebi::util::vectorGather(wheel_cmd.getPosition(),wheel_dofs, fbk.getPosition()));
//
// % Replan Trajectory for the mobile base
Eigen::Vector2d omni_base_traj_time;
omni_base_traj_time << 0, base_ramp_time;
//
// % Initialize trajectory for Omnibase
Eigen::MatrixXd positions(3,2);
Eigen::MatrixXd velocities = Eigen::MatrixXd::Zero(3,2);
Eigen::MatrixXd accelerations = Eigen::MatrixXd::Zero(3,2);
Eigen::MatrixXd jerks = Eigen::MatrixXd::Zero(3,2);
auto omni_base_traj = hebi::trajectory::Trajectory::createUnconstrainedQp(time, velocities, &accelerations, &jerks);
bool first_run = true;
while(true) {
// %%%%%%%%%%%%%%%%%%%
// % Gather Feedback %
// %%%%%%%%%%%%%%%%%%%
if(!robot_group->getNextFeedback(fbk)) {
printf("Could not get robot feedback!");
break;
}
//
// % Get feedback with a timeout of 0, which means that they return
// % instantly, but if there was no new feedback, they return empty.
// % This is because the mobile device is on wireless and might drop
// % out or be really delayed, in which case we would rather keep
// % running with an old data instead of waiting here for new data.
bool tmp_fbk = phone_group->getNextFeedback(latest_phone_fbk);
auto time_now = fbk.getTime();
auto dt = time_now - time_last;
time_last = fbk.getTime();
//
// % Reset the Command Struct
cmd.clear();
//
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%
// % Read/Map Joystick Inputs %
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%
//
// % Check for restart command
double b_1 = latest_phone_fbk[0].io().b().hasInt(1) ? latest_phone_fbk[0].io().b().getInt(1) : latest_phone_fbk[0].io().b().getFloat(1);
if(b_1 == 1) break;
//
// % Parameter to limit XYZ Translation of the arm if a slider is
// % pulled down.
double phone_control_scale = (latest_phone_fbk[0].io().a().hasInt(3) ? latest_phone_fbk[0].io().a().getInt(3) : latest_phone_fbk[0].io().a().getFloat(3) + 1)/2;
if(phone_control_scale < .1){
xyz_init = xyz_phone_new;
}
//
// % Joystick Input for Omnibase Control
double x_vel = base_max_lin_speed * (latest_phone_fbk[0].io().a().hasInt(8) ? latest_phone_fbk[0].io().a().getInt(8) : latest_phone_fbk[0].io().a().getFloat(8));
double y_vel = -1*base_max_lin_speed * (latest_phone_fbk[0].io().a().hasInt(7) ? latest_phone_fbk[0].io().a().getInt(7) : latest_phone_fbk[0].io().a().getFloat(7));
double rot_vel = base_max_rot_speed * (latest_phone_fbk[0].io().a().hasInt(1) ? latest_phone_fbk[0].io().a().getInt(1) : latest_phone_fbk[0].io().a().getFloat(1));
//
// % Pose Information for Arm Control
xyz_init << latest_phone_fbk[0].mobile().arPosition().get().getX(), latest_phone_fbk[0].mobile().arPosition().get().getY(), latest_phone_fbk[0].mobile().arPosition().get().getZ();
auto xyz_target = xyz_target_init + (phone_control_scale * xyz_scale.array() * (r_init.transpose() * (xyz_phone_new - xyz_init)).array()).matrix();
q.w() = latest_phone_fbk[0].mobile().arOrientation().get().getW();
q.x() = latest_phone_fbk[0].mobile().arOrientation().get().getX();
q.y() = latest_phone_fbk[0].mobile().arOrientation().get().getY();
q.z() = latest_phone_fbk[0].mobile().arOrientation().get().getZ();
auto rot_mat_target = r_init.transpose() * q.toRotationMatrix() * rot_mat_target_init;
//
// %%%%%%%%%%%%%%%
// % Arm Control %
// %%%%%%%%%%%%%%%
// % Get state of current trajectory
Eigen::VectorXd pos(arm_dofs.size());
Eigen::VectorXd vel(arm_dofs.size());
Eigen::VectorXd acc(arm_dofs.size());
if(first_run) {
pos = hebi::util::vectorGather(pos,arm_dofs,fbk.getPositionCommand());
vel = end_velocities;
acc = end_accels;
hebi::util::setPositionScattered(cmd, arm_dofs, pos);
hebi::util::setVelocityScattered(cmd, arm_dofs, vel);
first_run = false;
} else {
getTrajectoryCommand(arm_traj,cmd,arm_dofs,t,&pos,&vel,&acc);
}
//
// TODO:dynamicsComp
Eigen::VectorXd masses;
arm_model->getMasses(masses);
auto base_accel = fbk[base_num_wheels].imu().accelerometer().get();
Eigen::Vector3d gravity(-base_accel.getX(),
-base_accel.getY(),
-base_accel.getZ());
Eigen::VectorXd arm_positions(arm_dofs.size());
for(size_t i = 0; i < arm_positions.size(); ++i) {
arm_positions[i] = fbk.getPosition()[arm_dofs[i]];
}
Eigen::VectorXd grav_comp = hebi::util::getGravityCompensationEfforts(*arm_model, masses, arm_positions, gravity);
// Apply the effort offset as well
grav_comp += arm_effort_offset;
hebi::util::setEffortScattered(cmd, arm_dofs, grav_comp);
// % Force elbow up config
auto seed_pos_ik = pos;
seed_pos_ik[2] = abs(seed_pos_ik[2]);
// % Find target using inverse kinematics
Eigen::VectorXd ik_position(arm_dofs.size());
arm_model->solveIK(seed_pos_ik, ik_position, robot_model::EndEffectorPositionObjective(xyz_target), robot_model::EndEffectorSO3Objective(rot_mat_target));
// % Start new trajectory at the current state
Eigen::MatrixXd traj_pos(arm_dofs.size(),2);
traj_pos.col(0) = pos;
traj_pos.col(1) = ik_position;
Eigen::MatrixXd traj_vel(arm_dofs.size(),2);
traj_vel.col(0) = vel;
traj_vel.col(1) = end_velocities;
Eigen::MatrixXd traj_acc(arm_dofs.size(),2);
traj_acc.col(0) = acc;
traj_acc.col(1) = end_accels;
arm_traj = hebi::trajectory::Trajectory::createUnconstrainedQp(time, traj_pos, &traj_vel, &traj_acc);
//
// %%%%%%%%%%%%%%%%%%%
// % Gripper Control %
// %%%%%%%%%%%%%%%%%%%
auto effort_tmp = cmd.getEffort();
effort_tmp[gripper_dof[0]] = arm_gripper_close_effort * (latest_phone_fbk[0].io().a().hasInt(6) ? latest_phone_fbk[0].io().a().getInt(6) : latest_phone_fbk[0].io().a().getFloat(6));
cmd.setEffort(effort_tmp);
//
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// % Evaluate Trajectory State %
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// % Chassis (linear velocity)
if(time_now - chassis_traj_start_time < omni_base_traj->getDuration()) {
t = time_now - chassis_traj_start_time;
} else {
t = omni_base_traj->getDuration();
}
Eigen::VectorXd chassis_cmd_vel(base_num_wheels);
Eigen::VectorXd chassis_cmd_acc(base_num_wheels);
Eigen::VectorXd chassis_cmd_jerk(base_num_wheels);
omni_base_traj->getState(t, &chassis_cmd_vel, &chassis_cmd_acc, &chassis_cmd_jerk);
//
// % Chassis (convert linear to joint velocities)
wheel_cmd.setVelocity(base_wheel_velocity_matrix * chassis_cmd_vel);
wheel_cmd.setPosition(wheel_cmd.getPosition() + wheel_cmd.getVelocity() * dt);
wheel_cmd.setEffort(base_wheel_effort_matrix * (chassis_mass_matrix * chassis_cmd_acc));
hebi::util::setPositionScattered(cmd, wheel_dofs, wheel_cmd.getPosition());
hebi::util::setVelocityScattered(cmd, wheel_dofs, wheel_cmd.getVelocity());
hebi::util::setEffortScattered(cmd, wheel_dofs, wheel_cmd.getEffort());
// % Hold down button 8 to put the arm in a compliant grav-comp mode
double b_8 = (latest_phone_fbk[0].io().b().hasInt(8) ? latest_phone_fbk[0].io().b().getInt(8) : latest_phone_fbk[0].io().b().getFloat(8));
if(b_8 == 1){
effort_tmp = cmd.getEffort();
cmd.clear();
cmd.setEffort(effort_tmp);
}
//
// % Send to robot
robot_group->sendCommand(cmd);
//
// % Chassis (linear velocity)
Eigen::Vector3d chassis_desired_vel;
chassis_desired_vel << x_vel, y_vel, rot_vel;
Eigen::MatrixXd velocities(base_num_wheels, 2);
velocities.col(0) = chassis_cmd_vel;
velocities.col(1) = chassis_desired_vel;
Eigen::MatrixXd accelerations(base_num_wheels, 2);
accelerations.col(0) = chassis_cmd_acc;
accelerations.col(1) = Eigen::Vector3d::Zero();
Eigen::MatrixXd jerks(base_num_wheels, 2);
jerks.col(0) = chassis_cmd_jerk;
jerks.col(1) = Eigen::Vector3d::Zero();
omni_base_traj = hebi::trajectory::Trajectory::createUnconstrainedQp(time, velocities, &accelerations , &jerks);
chassis_traj_start_time = time_now;
}
}
}
| 41.072314 | 188 | 0.620806 | HebiRobotics |
b132bb417c4150775cff2e79ccefa108fabaeff5 | 339 | cpp | C++ | Camp_1-2562/06 Function/Sport.cpp | MasterIceZ/POSN_BUU | 56e176fb843d7ddcee0cf4acf2bb141576c260cf | [
"MIT"
] | null | null | null | Camp_1-2562/06 Function/Sport.cpp | MasterIceZ/POSN_BUU | 56e176fb843d7ddcee0cf4acf2bb141576c260cf | [
"MIT"
] | null | null | null | Camp_1-2562/06 Function/Sport.cpp | MasterIceZ/POSN_BUU | 56e176fb843d7ddcee0cf4acf2bb141576c260cf | [
"MIT"
] | null | null | null | #include<stdio.h>
char a[30000011];
int k;
void play(int state,int w,int l){
int i;
if(w==k||l==k){
for(i=0;i<state;i++){
printf("%c ",a[i]);
}
printf("\n");
return;
}
a[state]='W';
play(state+1,w+1,l);
a[state]='L';
play(state+1,w,l+1);
}
int main (){
int w,l;
scanf("%d %d %d",&k,&w,&l);
play(0,w,l);
return 0;
}
| 13.038462 | 33 | 0.516224 | MasterIceZ |
b133e2da0b07725a24dc57e3b2a9ff5d9635dda6 | 2,289 | cpp | C++ | SFGE_lib/MemoryInputStream.cpp | DonRumata710/SFGE | 9b42f2335b62be089046593cd84f265412e2792d | [
"MIT"
] | null | null | null | SFGE_lib/MemoryInputStream.cpp | DonRumata710/SFGE | 9b42f2335b62be089046593cd84f265412e2792d | [
"MIT"
] | null | null | null | SFGE_lib/MemoryInputStream.cpp | DonRumata710/SFGE | 9b42f2335b62be089046593cd84f265412e2792d | [
"MIT"
] | null | null | null | /////////////////////////////////////////////////////////////////////
//
// SFGE - Simple and Fast Game Engine
//
// Copyright (c) 2016-2017 DonRumata710
//
// 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 "MemoryInputStream.h"
using namespace sfge;
MemoryInputStream::MemoryInputStream (const std::unordered_map<std::string, std::vector<char>>& source_data) :
m_source_data (source_data)
{}
MemoryInputStream::MemoryInputStream (std::unordered_map<std::string, std::vector<char>>&& source_data) :
m_source_data (std::move (source_data))
{}
bool MemoryInputStream::open (const std::string& filename)
{
auto it (m_source_data.find (filename));
if (it != m_source_data.end ())
{
m_stream.open (it->second.data (), it->second.size ());
return true;
}
return false;
}
Int64 sfge::MemoryInputStream::read (void* data, Int64 size)
{
return m_stream.read (data, size);
}
Int64 sfge::MemoryInputStream::seek (Int64 position)
{
return m_stream.seek (position);
}
Int64 sfge::MemoryInputStream::tell ()
{
return m_stream.tell ();
}
Int64 sfge::MemoryInputStream::getSize ()
{
return m_stream.getSize ();
}
| 30.118421 | 110 | 0.677588 | DonRumata710 |
b134b1da6a47eecc8f246d7e21105bc938470a8c | 13,635 | cpp | C++ | PortableExecutable.cpp | jseursing/VMLock | 1e12dc86c1a4aeddf37a830100a35c7d8b9f7648 | [
"MIT"
] | null | null | null | PortableExecutable.cpp | jseursing/VMLock | 1e12dc86c1a4aeddf37a830100a35c7d8b9f7648 | [
"MIT"
] | null | null | null | PortableExecutable.cpp | jseursing/VMLock | 1e12dc86c1a4aeddf37a830100a35c7d8b9f7648 | [
"MIT"
] | null | null | null | #include "PortableExecutable.h"
#include <fstream>
/////////////////////////////////////////////////////////////////////////////////////////
//
// Function: BackupFile
//
/////////////////////////////////////////////////////////////////////////////////////////
void PortableExecutable::BackupFile(std::string path, std::string newPath)
{
std::ifstream src(path.c_str(), std::ios::binary);
if (true == src.is_open())
{
std::ofstream dest(newPath.c_str(), std::ios::binary);
dest << src.rdbuf();
dest.close();
src.close();
}
}
/////////////////////////////////////////////////////////////////////////////////////////
//
// Function: Attach
//
/////////////////////////////////////////////////////////////////////////////////////////
bool PortableExecutable::Attach(const char* path, unsigned int preSize)
{
// If path is not specified (NULL), this means we are attaching to the
// current process. Otherwise we need to open the file specified by path
// and read the file contents into memory.
if (0 == path)
{
// Retrieve the virtual base address, DOS, and NT Headers.
ImageBase = reinterpret_cast<unsigned char*>(GetModuleHandle(0));
DosHeader = reinterpret_cast<IMAGE_DOS_HEADER*>(ImageBase);
NtHeaders = reinterpret_cast<IMAGE_NT_HEADERS*>
(ImageBase + DosHeader->e_lfanew);
}
else
{
// Open the specified file, if the FileHandle is invalid, this means the
// file either doesn't exist or is in use (or prohibited).
FileHandle = CreateFileA(path,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if (INVALID_HANDLE_VALUE != FileHandle)
{
// Retrieve the total stub size, this shouldn't require too much memory
// due to be a contentless installer. Copy the file contents to the buf.
StubFileSize = GetFileSize(FileHandle, 0);
FileBuffer = new unsigned char[StubFileSize + preSize];
memset(FileBuffer, 0, StubFileSize + preSize);
unsigned long bytesRead = 0;
if (TRUE == ReadFile(FileHandle, FileBuffer, StubFileSize, &bytesRead, 0))
{
DosHeader = reinterpret_cast<IMAGE_DOS_HEADER*>(FileBuffer);
NtHeaders = reinterpret_cast<IMAGE_NT_HEADERS32*>
(FileBuffer + DosHeader->e_lfanew);
}
}
}
// At this point, DosHeader and therefore NtHeaders should be NON-NULL
// for a successful attach.
if (0 != NtHeaders)
{
// Verify we are dealing with a valid portable executable.
if ((IMAGE_DOS_SIGNATURE == DosHeader->e_magic) ||
(IMAGE_NT_SIGNATURE == NtHeaders->Signature))
{
// Point FirstSectionHeader to the first section.
FirstSectionHeader = IMAGE_FIRST_SECTION(NtHeaders);
// Point NewSectionHeader to the next section.
LastSectionHeader = IMAGE_FIRST_SECTION(NtHeaders) +
(NtHeaders->FileHeader.NumberOfSections - 1);
// Point ExportDirectory to specified section.
unsigned int expVAddr = NtHeaders->OptionalHeader.DataDirectory
[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
// Update the address if dealing with a file opposed to running executable.
SetExportRVA(expVAddr);
// Retrieve pointer to Export Directory.
ExportDirectory = reinterpret_cast<IMAGE_EXPORT_DIRECTORY*>
(reinterpret_cast<unsigned char*>(DosHeader) + expVAddr);
return true;
}
}
return false;
}
/////////////////////////////////////////////////////////////////////////////////////////
//
// Function: InitializeNewSection
//
/////////////////////////////////////////////////////////////////////////////////////////
void PortableExecutable::InitializeNewSection(const char* name)
{
if (0 != NtHeaders)
{
// Point NewSectionHeader to the next section.
NewSectionHeader = IMAGE_FIRST_SECTION(NtHeaders) +
(NtHeaders->FileHeader.NumberOfSections);
memset(NewSectionHeader, 0, sizeof(IMAGE_SECTION_HEADER));
// Adjust characteristics, name the section[8], and set PointerToRawData.
NewSectionHeader->Characteristics = IMAGE_SCN_MEM_WRITE |
IMAGE_SCN_CNT_CODE |
IMAGE_SCN_CNT_UNINITIALIZED_DATA |
IMAGE_SCN_MEM_EXECUTE |
IMAGE_SCN_CNT_INITIALIZED_DATA |
IMAGE_SCN_MEM_READ;
memcpy(NewSectionHeader->Name, name, strlen(name));
NewSectionHeader->PointerToRawData =
AlignToBoundary(LastSectionHeader->PointerToRawData +
LastSectionHeader->SizeOfRawData,
NtHeaders->OptionalHeader.FileAlignment);
NewSectionHeader->VirtualAddress =
AlignToBoundary(LastSectionHeader->VirtualAddress +
LastSectionHeader->Misc.VirtualSize,
NtHeaders->OptionalHeader.SectionAlignment);
// For our use case, we do not know the current size of this new section (yet)
// and will wait for FinalizeNewSection() to fill this out.
// Update LastSectionHeader
LastSectionHeader = NewSectionHeader;
}
}
/////////////////////////////////////////////////////////////////////////////////////////
//
// Function: FinalizeNewSection
//
/////////////////////////////////////////////////////////////////////////////////////////
void PortableExecutable::FinalizeNewSection(unsigned int totalSize)
{
if (0 != NewSectionHeader)
{
// Set the corresponding size and locations of the section in relation
// to the section/file byte alignment.
NewSectionHeader->Misc.VirtualSize =
AlignToBoundary(totalSize, NtHeaders->OptionalHeader.SectionAlignment);
NewSectionHeader->SizeOfRawData =
AlignToBoundary(totalSize, NtHeaders->OptionalHeader.FileAlignment);
// Update the current image size.
NtHeaders->OptionalHeader.SizeOfImage =
AlignToBoundary(NewSectionHeader->VirtualAddress +
NewSectionHeader->Misc.VirtualSize,
NtHeaders->OptionalHeader.SectionAlignment);
// Increaes the section count.
++NtHeaders->FileHeader.NumberOfSections;
// Write the PE Header contents to the file and update the
// end of file location.
unsigned long written = 0;
unsigned int totalSize = NewSectionHeader->PointerToRawData +
NewSectionHeader->SizeOfRawData;
SetFilePointer(FileHandle, 0, 0, FILE_BEGIN);
WriteFile(FileHandle, FileBuffer, totalSize, &written, 0);
SetFilePointer(FileHandle, totalSize, 0, FILE_BEGIN);
SetEndOfFile(FileHandle);
// Free the FileBuffer memory now that it is no longer of us.
delete[] FileBuffer;
FileBuffer = 0;
}
}
/////////////////////////////////////////////////////////////////////////////////////////
//
// Function: InsertIntoNewSection
//
/////////////////////////////////////////////////////////////////////////////////////////
void PortableExecutable::InsertIntoNewSection(unsigned char* data,
unsigned int len,
unsigned int offset) const
{
if (INVALID_HANDLE_VALUE != FileHandle)
{
SetFilePointer(FileHandle,
NewSectionHeader->PointerToRawData + offset,
0,
FILE_BEGIN);
unsigned long bytesWritten = 0;
WriteFile(FileHandle, data, len, &bytesWritten, 0);
// Update file buffer
memcpy(&FileBuffer[NewSectionHeader->PointerToRawData + offset], data, len);
}
}
/////////////////////////////////////////////////////////////////////////////////////////
//
// Function: ExtractFromLastSection
//
/////////////////////////////////////////////////////////////////////////////////////////
void PortableExecutable::ExtractFromLastSection(unsigned char* buf,
unsigned int offset,
unsigned int len) const
{
if (LastSectionHeader->SizeOfRawData > offset)
{
void* source = reinterpret_cast<void*>
(ImageBase + LastSectionHeader->VirtualAddress + offset);
memcpy(buf, source, len);
}
}
/////////////////////////////////////////////////////////////////////////////////////////
//
// Function: PointerToLastSection
//
/////////////////////////////////////////////////////////////////////////////////////////
char* PortableExecutable::PointerToLastSection(unsigned int offset)
{
return reinterpret_cast<char*>(ImageBase + LastSectionHeader->VirtualAddress + offset);
}
/////////////////////////////////////////////////////////////////////////////////////////
//
// Function: PointerToLastSection
//
/////////////////////////////////////////////////////////////////////////////////////////
unsigned char* PortableExecutable::PtrToLastSectionBuf(unsigned int offset)
{
return &FileBuffer[LastSectionHeader->PointerToRawData + offset];
}
/////////////////////////////////////////////////////////////////////////////////////////
//
// Function: DestroyExportFunction
//
/////////////////////////////////////////////////////////////////////////////////////////
bool PortableExecutable::DestroyExportFunction(unsigned int offset,
unsigned int numDeleted)
{
for (unsigned int i = 0; i < ExportDirectory->NumberOfFunctions + numDeleted; ++i)
{
unsigned int addressOfNames = ExportDirectory->AddressOfNames;
SetExportRVA(addressOfNames);
unsigned int funcNameAddress = reinterpret_cast<unsigned int*>
(reinterpret_cast<char*>(DosHeader) + addressOfNames)[i];
SetExportRVA(funcNameAddress);
unsigned int addressOfOrdinals = ExportDirectory->AddressOfNameOrdinals;
SetExportRVA(addressOfOrdinals);
unsigned int addressOfFunctions = ExportDirectory->AddressOfFunctions;
SetExportRVA(addressOfFunctions);
char* functionName = reinterpret_cast<char*>
(reinterpret_cast<char*>(DosHeader) + funcNameAddress);
unsigned short functionOrd = reinterpret_cast<unsigned short*>
(reinterpret_cast<char*>(DosHeader) + addressOfOrdinals)[i];
unsigned int functionOffset = reinterpret_cast<unsigned int*>
(reinterpret_cast<char*>(DosHeader) + addressOfFunctions)[i];
if (functionOffset == offset)
{
// Clear function name
memset(functionName, 0, strlen(functionName));
// Clear function ordinal
reinterpret_cast<unsigned short*>
(reinterpret_cast<char*>(DosHeader) + addressOfOrdinals)[i] = 0;
// Clear function address
reinterpret_cast<unsigned int*>
(reinterpret_cast<char*>(DosHeader) + addressOfFunctions)[i] = 0;
// Decrement Number of functions
--ExportDirectory->NumberOfFunctions;
return true;
}
}
return false;
}
/////////////////////////////////////////////////////////////////////////////////////////
//
// Function: SetExportRVA
//
/////////////////////////////////////////////////////////////////////////////////////////
void PortableExecutable::SetExportRVA(unsigned int& virtual_addr)
{
// If we are dealing with a file opposed to a running executable,
// the data directory resides somewhere inside one of the sections.
if (0 != FileBuffer)
{
for (IMAGE_SECTION_HEADER* section = FirstSectionHeader;
section != LastSectionHeader;
++section)
{
if (virtual_addr < (section->VirtualAddress + section->Misc.VirtualSize))
{
virtual_addr = section->PointerToRawData +
virtual_addr -
section->VirtualAddress;
break;
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////
//
// Function: GetBaseAddress
//
/////////////////////////////////////////////////////////////////////////////////////////
void* PortableExecutable::GetBaseAddress()
{
return reinterpret_cast<void*>(DosHeader);
}
/////////////////////////////////////////////////////////////////////////////////////////
//
// Function: Constructor
//
/////////////////////////////////////////////////////////////////////////////////////////
PortableExecutable::PortableExecutable() :
FileHandle(INVALID_HANDLE_VALUE),
ImageBase(0),
FileBuffer(0),
StubFileSize(0),
DosHeader(0),
NtHeaders(0),
FirstSectionHeader(0),
LastSectionHeader(0),
NewSectionHeader(0),
ExportDirectory(0)
{
}
/////////////////////////////////////////////////////////////////////////////////////////
//
// Function: Destructor
//
/////////////////////////////////////////////////////////////////////////////////////////
PortableExecutable::~PortableExecutable()
{
if (INVALID_HANDLE_VALUE != FileHandle)
{
CloseHandle(FileHandle);
}
// Incase ::FinalizeNewSection() was not called, free the memory.
if (0 != FileBuffer)
{
delete[] FileBuffer;
FileBuffer = 0;
}
}
/////////////////////////////////////////////////////////////////////////////////////////
//
// Function: AlignToBoundary
//
/////////////////////////////////////////////////////////////////////////////////////////
unsigned int PortableExecutable::AlignToBoundary(unsigned int address,
unsigned int alignment)
{
unsigned int correction = address % alignment;
return address + (0 == correction ? 0 : alignment - correction);
}
| 35.600522 | 89 | 0.535387 | jseursing |
b1353d6ed885f22bc74f03f024458f75f53ff393 | 1,550 | cpp | C++ | problem12.cpp | Nadesri/my-project-euler-solutions | a37472d99704e4e80d7344ead3bb250debff52eb | [
"MIT"
] | null | null | null | problem12.cpp | Nadesri/my-project-euler-solutions | a37472d99704e4e80d7344ead3bb250debff52eb | [
"MIT"
] | null | null | null | problem12.cpp | Nadesri/my-project-euler-solutions | a37472d99704e4e80d7344ead3bb250debff52eb | [
"MIT"
] | null | null | null | // Highly divisible triangular number
// The sequence of triangle numbers is generated by adding the natural numbers.
// So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
// 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
// Let us list the factors of the first seven triangle numbers:
// 1: 1
// 3: 1,3
// 6: 1,2,3,6
// 10: 1,2,5,10
// 15: 1,3,5,15
// 21: 1,3,7,21
// 28: 1,2,4,7,14,28
// We can see that 28 is the first triangle number to have over five divisors.
// What is the value of the first triangle number to have over five hundred divisors?
#include <iostream>
#include <time.h> /* clock_t, clock, CLOCKS_PER_SEC */
#include <math.h>
using namespace std;
int trinum(int i);
int numdivisors(int num);
int main() {
int result;
int start = clock();
int i=0;
do {
i++;
result = trinum(i);
result = numdivisors(result);
} while (result<=500);
result = trinum(i);
int end = clock();
cout << "Result: " << result << " , i= " << i << endl;
cout << "Time elapsed: " << ((end-start)*1000)/CLOCKS_PER_SEC << " milliseconds." << endl;
cout << "Time Resolution: " << CLOCKS_PER_SEC << endl;
return 0;
}
int trinum(int i) {
int result=(i*(i+1))/2;
return (result>0)? result : 0;
}
int numdivisors(int mynum) {
int result=0;
for (int i=1; i<=sqrt(mynum); i++) {
if (mynum%i==0) {
if (i==sqrt(mynum)) {
result++; // mynum == i*i.
} else {
result += 2; // There exist two factors; mynum == i*j, some j for the current i.
}
}
}
return result;
} | 22.794118 | 100 | 0.605161 | Nadesri |
b13876e99afa06b4b50ac9e5ba9a521fa6ddb357 | 41,853 | cpp | C++ | src/ir/node_data.cpp | weilewei/phylanx | db9049dc1696e4f1f2090dd830803cf892a122e5 | [
"BSL-1.0"
] | null | null | null | src/ir/node_data.cpp | weilewei/phylanx | db9049dc1696e4f1f2090dd830803cf892a122e5 | [
"BSL-1.0"
] | null | null | null | src/ir/node_data.cpp | weilewei/phylanx | db9049dc1696e4f1f2090dd830803cf892a122e5 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2017-2018 Hartmut Kaiser
// Copyright (c) 2017 Parsa Amini
// Copyright (c) 2018 Tianyi Zhang
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <phylanx/config.hpp>
#include <phylanx/ir/node_data.hpp>
#include <phylanx/util/serialization/blaze.hpp>
#include <phylanx/util/serialization/variant.hpp>
#include <hpx/exception.hpp>
#include <hpx/include/serialization.hpp>
#include <hpx/include/util.hpp>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <iosfwd>
#include <string>
#include <utility>
#include <vector>
namespace phylanx { namespace ir
{
///////////////////////////////////////////////////////////////////////////
// performance counter data (for now, counting all node_data<T>)
static std::atomic<std::int64_t> count_copy_constructions_;
static std::atomic<std::int64_t> count_move_constructions_;
static std::atomic<std::int64_t> count_copy_assignments_;
static std::atomic<std::int64_t> count_move_assignments_;
static std::atomic<bool> enable_counts_;
template <typename T>
void node_data<T>::increment_copy_construction_count()
{
if (enable_counts_.load(std::memory_order_relaxed))
++count_copy_constructions_;
}
template <typename T>
void node_data<T>::increment_move_construction_count()
{
if (enable_counts_.load(std::memory_order_relaxed))
++count_move_constructions_;
}
template <typename T>
void node_data<T>::increment_copy_assignment_count()
{
if (enable_counts_.load(std::memory_order_relaxed))
++count_copy_assignments_;
}
template <typename T>
void node_data<T>::increment_move_assignment_count()
{
if (enable_counts_.load(std::memory_order_relaxed))
++count_move_assignments_;
}
template <typename T>
bool node_data<T>::enable_counts(bool enable)
{
return enable_counts_.exchange(enable, std::memory_order_relaxed);
}
template <typename T>
std::int64_t node_data<T>::copy_construction_count(bool reset)
{
return hpx::util::get_and_reset_value(count_copy_constructions_, reset);
}
template <typename T>
std::int64_t node_data<T>::move_construction_count(bool reset)
{
return hpx::util::get_and_reset_value(count_move_constructions_, reset);
}
template <typename T>
std::int64_t node_data<T>::copy_assignment_count(bool reset)
{
return hpx::util::get_and_reset_value(count_copy_assignments_, reset);
}
template <typename T>
std::int64_t node_data<T>::move_assignment_count(bool reset)
{
return hpx::util::get_and_reset_value(count_move_assignments_, reset);
}
///////////////////////////////////////////////////////////////////////////
/// Create node data for a 0-dimensional value
template <typename T>
node_data<T>::node_data(storage0d_type const& value)
: data_(value)
{
}
template <typename T>
node_data<T>::node_data(storage0d_type&& value)
: data_(std::move(value))
{
}
/// Create node data for a 1-dimensional value
template <typename T>
node_data<T>::node_data(storage1d_type const& values)
: data_(values)
{
increment_copy_construction_count();
}
template <typename T>
node_data<T>::node_data(storage1d_type&& values)
: data_(std::move(values))
{
increment_move_construction_count();
}
template <typename T>
node_data<T>::node_data(dimensions_type const& dims)
{
if (dims[1] != 1)
{
data_ = storage2d_type(dims[0], dims[1]);
}
else if (dims[0] != 1)
{
data_ = storage1d_type(dims[0]);
}
else
{
data_ = storage0d_type();
}
}
template <typename T>
node_data<T>::node_data(dimensions_type const& dims, T default_value)
{
if (dims[1] != 1)
{
data_ = storage2d_type(dims[0], dims[1], default_value);
}
else if (dims[0] != 1)
{
data_ = storage1d_type(dims[0], default_value);
}
else
{
data_ = default_value;
}
}
template <typename T>
node_data<T>::node_data(custom_storage1d_type const& values)
: data_(custom_storage1d_type{
const_cast<T*>(values.data()), values.size(), values.spacing()})
{
increment_move_construction_count();
}
template <typename T>
node_data<T>::node_data(custom_storage1d_type&& values)
: data_(std::move(values))
{
increment_move_construction_count();
}
/// Create node data for a 2-dimensional value
template <typename T>
node_data<T>::node_data(storage2d_type const& values)
: data_(values)
{
increment_copy_construction_count();
}
template <typename T>
node_data<T>::node_data(storage2d_type&& values)
: data_(std::move(values))
{
increment_move_construction_count();
}
template <typename T>
node_data<T>::node_data(custom_storage2d_type const& values)
: data_(custom_storage2d_type{const_cast<T*>(values.data()),
values.rows(), values.columns(), values.spacing()})
{
increment_copy_construction_count();
}
template <typename T>
node_data<T>::node_data(custom_storage2d_type&& values)
: data_(std::move(values))
{
increment_move_construction_count();
}
// conversion helpers for Python bindings
template <typename T>
node_data<T>::node_data(std::vector<T> const& values)
: data_(storage1d_type(values.size()))
{
std::size_t const nx = values.size();
for (std::size_t i = 0; i != nx; ++i)
{
util::get<1>(data_)[i] = values[i];
}
}
template <typename T>
node_data<T>::node_data(std::vector<std::vector<T>> const& values)
: data_(storage2d_type{values.size(), values[0].size()})
{
std::size_t const nx = values.size();
for (std::size_t i = 0; i != nx; ++i)
{
std::vector<T> const& row = values[i];
std::size_t const ny = row.size();
for (std::size_t j = 0; j != ny; ++j)
{
util::get<2>(data_)(i, j) = row[j];
}
}
}
template <typename T>
typename node_data<T>::storage_type node_data<T>::init_data_from(
node_data const& d)
{
switch (d.data_.index())
{
case 0:
return d.data_;
case 1: HPX_FALLTHROUGH;
case 2:
{
increment_copy_construction_count();
return d.data_;
}
break;
case 3:
{
increment_move_construction_count();
auto v = d.vector();
return custom_storage1d_type{v.data(), v.size(), v.spacing()};
}
break;
case 4:
{
increment_move_construction_count();
auto m = d.matrix();
return custom_storage2d_type{
m.data(), m.rows(), m.columns(), m.spacing()};
}
break;
default:
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::node_data<T>",
"node_data object holds unsupported data type");
}
}
/// Create node data from a node data
template <typename T>
node_data<T>::node_data(node_data const& d)
: data_(init_data_from(d))
{
}
template <typename T>
node_data<T>::node_data(node_data&& d)
: data_(std::move(d.data_))
{
increment_move_construction_count();
}
template <typename T>
node_data<T>& node_data<T>::operator=(storage0d_type val)
{
data_ = val;
return *this;
}
template <typename T>
node_data<T>& node_data<T>::operator=(storage1d_type const& val)
{
increment_copy_assignment_count();
data_ = val;
return *this;
}
template <typename T>
node_data<T>& node_data<T>::operator=(storage1d_type && val)
{
increment_move_assignment_count();
data_ = std::move(val);
return *this;
}
template <typename T>
node_data<T>& node_data<T>::operator=(custom_storage1d_type const& val)
{
increment_move_assignment_count();
data_ = custom_storage1d_type{
const_cast<T*>(val.data()), val.size(), val.spacing()};
return *this;
}
template <typename T>
node_data<T>& node_data<T>::operator=(custom_storage1d_type && val)
{
increment_move_assignment_count();
data_ = std::move(val);
return *this;
}
template <typename T>
node_data<T>& node_data<T>::operator=(storage2d_type const& val)
{
increment_copy_assignment_count();
data_ = val;
return *this;
}
template <typename T>
node_data<T>& node_data<T>::operator=(storage2d_type && val)
{
increment_move_assignment_count();
data_ = std::move(val);
return *this;
}
template <typename T>
node_data<T>& node_data<T>::operator=(custom_storage2d_type const& val)
{
increment_move_assignment_count();
data_ = custom_storage2d_type{const_cast<T*>(val.data()), val.rows(),
val.columns(), val.spacing()};
return *this;
}
template <typename T>
node_data<T>& node_data<T>::operator=(custom_storage2d_type && val)
{
increment_move_assignment_count();
data_ = std::move(val);
return *this;
}
template <typename T>
node_data<T>& node_data<T>::operator=(std::vector<T> const& values)
{
data_ = storage1d_type(values.size());
std::size_t const nx = values.size();
for (std::size_t i = 0; i != nx; ++i)
{
util::get<1>(data_)[i] = values[i];
}
return *this;
}
template <typename T>
node_data<T>& node_data<T>::operator=(
std::vector<std::vector<T>> const& values)
{
data_ = storage2d_type{values.size(), values[0].size()};
std::size_t const nx = values.size();
for (std::size_t i = 0; i != nx; ++i)
{
std::vector<T> const& row = values[i];
std::size_t const ny = row.size();
for (std::size_t j = 0; j != ny; ++j)
{
util::get<2>(data_)(i, j) = row[j];
}
}
return *this;
}
template <typename T>
typename node_data<T>::storage_type node_data<T>::copy_data_from(
node_data const& d)
{
switch (d.data_.index())
{
case 0:
return d.data_;
case 1: HPX_FALLTHROUGH;
case 2:
{
increment_copy_assignment_count();
return d.data_;
}
break;
case 3:
{
increment_move_assignment_count();
auto v = d.vector();
return custom_storage1d_type{
v.data(), v.size(), v.spacing()};
}
break;
case 4:
{
increment_move_assignment_count();
auto m = d.matrix();
return custom_storage2d_type{
m.data(), m.rows(), m.columns(), m.spacing()};
}
break;
default:
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::node_data<T>",
"node_data object holds unsupported data type");
}
}
template <typename T>
node_data<T>& node_data<T>::operator=(node_data const& d)
{
if (this != &d)
{
data_ = copy_data_from(d);
}
return *this;
}
template <typename T>
node_data<T>& node_data<T>::operator=(node_data && d)
{
if (this != &d)
{
increment_move_assignment_count();
data_ = std::move(d.data_);
}
return *this;
}
/// Access a specific element of the underlying N-dimensional array
template <typename T>
T& node_data<T>::operator[](std::size_t index)
{
switch(data_.index())
{
case 0:
return scalar();
case 1: HPX_FALLTHROUGH;
case 3:
return vector()[index];
case 2: HPX_FALLTHROUGH;
case 4:
{
auto m = matrix();
std::size_t idx_m = index / m.columns();
std::size_t idx_n = index % m.columns();
return m(idx_m, idx_n);
}
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::operator[]()",
"node_data object holds unsupported data type");
}
template <typename T>
T& node_data<T>::operator[](dimensions_type const& indicies)
{
switch(data_.index())
{
case 0:
return scalar();
case 1: HPX_FALLTHROUGH;
case 3:
return vector()[indicies[0]];
case 2: HPX_FALLTHROUGH;
case 4:
return matrix()(indicies[0], indicies[1]);
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::operator[]()",
"node_data object holds unsupported data type");
}
template <typename T>
T& node_data<T>::at(std::size_t index1, std::size_t index2)
{
switch(data_.index())
{
case 0:
return scalar();
case 1: HPX_FALLTHROUGH;
case 3:
return vector()[index1];
case 2: HPX_FALLTHROUGH;
case 4:
return matrix()(index1, index2);
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::at()",
"node_data object holds unsupported data type");
}
template <typename T>
T const& node_data<T>::operator[](std::size_t index) const
{
switch(data_.index())
{
case 0:
return scalar();
case 1: HPX_FALLTHROUGH;
case 3:
return vector()[index];
case 2: HPX_FALLTHROUGH;
case 4:
{
auto m = matrix();
std::size_t idx_m = index / m.columns();
std::size_t idx_n = index % m.columns();
return m(idx_m, idx_n);
}
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::operator[]()",
"node_data object holds unsupported data type");
}
template <typename T>
T const& node_data<T>::operator[](dimensions_type const& indicies) const
{
switch(data_.index())
{
case 0:
return scalar();
case 1: HPX_FALLTHROUGH;
case 3:
return vector()[indicies[0]];
case 2: HPX_FALLTHROUGH;
case 4:
return matrix()(indicies[0], indicies[1]);
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::operator[]()",
"node_data object holds unsupported data type");
}
template <typename T>
T const& node_data<T>::at(std::size_t index1, std::size_t index2) const
{
switch(data_.index())
{
case 0:
return scalar();
case 1: HPX_FALLTHROUGH;
case 3:
return vector()[index1];
case 2: HPX_FALLTHROUGH;
case 4:
return matrix()(index1, index2);
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::at()",
"node_data object holds unsupported data type");
}
template <typename T>
std::size_t node_data<T>::size() const
{
switch(data_.index())
{
case 0:
return 1;
case 1: HPX_FALLTHROUGH;
case 3:
return vector().size();
case 2: HPX_FALLTHROUGH;
case 4:
{
auto m = matrix();
return m.rows() * m.columns();
}
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::operator[]()",
"node_data object holds unsupported data type");
}
template <typename T>
typename node_data<T>::const_iterator node_data<T>::begin() const
{
return const_iterator(*this, 0);
}
template <typename T>
typename node_data<T>::const_iterator node_data<T>::end() const
{
return const_iterator(*this, size());
}
template <typename T>
typename node_data<T>::const_iterator node_data<T>::cbegin() const
{
return const_iterator(*this, 0);
}
template <typename T>
typename node_data<T>::const_iterator node_data<T>::cend() const
{
return const_iterator(*this, size());
}
template <typename T>
typename node_data<T>::storage2d_type& node_data<T>::matrix_non_ref()
{
storage2d_type* m = util::get_if<storage2d_type>(&data_);
if (m == nullptr)
{
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::matrix_non_ref()",
"node_data object holds unsupported data type");
}
return *m;
}
template <typename T>
typename node_data<T>::storage2d_type const& node_data<T>::matrix_non_ref()
const
{
storage2d_type const* m = util::get_if<storage2d_type>(&data_);
if (m == nullptr)
{
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::matrix_non_ref()",
"node_data object holds unsupported data type");
}
return *m;
}
template <typename T>
typename node_data<T>::storage2d_type node_data<T>::matrix_copy() const
{
custom_storage2d_type const* cm =
util::get_if<custom_storage2d_type>(&data_);
if (cm != nullptr)
{
return storage2d_type{*cm};
}
storage2d_type const* m = util::get_if<storage2d_type>(&data_);
if (m != nullptr)
{
return *m;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::matrix()",
"node_data object holds unsupported data type");
}
template <typename T>
typename node_data<T>::custom_storage2d_type node_data<T>::matrix() &
{
custom_storage2d_type* cm =
util::get_if<custom_storage2d_type>(&data_);
if (cm != nullptr)
{
return *cm;
}
storage2d_type* m = util::get_if<storage2d_type>(&data_);
if (m != nullptr)
{
return custom_storage2d_type(
m->data(), m->rows(), m->columns(), m->spacing());
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::matrix()",
"node_data object holds unsupported data type");
}
template <typename T>
typename node_data<T>::custom_storage2d_type node_data<T>::matrix() const&
{
custom_storage2d_type const* cm =
util::get_if<custom_storage2d_type>(&data_);
if (cm != nullptr)
{
return custom_storage2d_type(const_cast<T*>(cm->data()),
cm->rows(), cm->columns(), cm->spacing());
}
storage2d_type const* m = util::get_if<storage2d_type>(&data_);
if (m != nullptr)
{
return custom_storage2d_type(const_cast<T*>(m->data()),
m->rows(), m->columns(), m->spacing());
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::matrix()",
"node_data object holds unsupported data type");
}
template <typename T>
typename node_data<T>::custom_storage2d_type node_data<T>::matrix() &&
{
custom_storage2d_type* cm =
util::get_if<custom_storage2d_type>(&data_);
if (cm != nullptr)
{
return *cm;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::matrix()",
"node_data::matrix() shouldn't be called on an rvalue");
}
template <typename T>
typename node_data<T>::custom_storage2d_type node_data<T>::matrix() const&&
{
custom_storage2d_type const* cm =
util::get_if<custom_storage2d_type>(&data_);
if (cm != nullptr)
{
return *cm;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::matrix()",
"node_data::matrix() shouldn't be called on an rvalue");
}
template <typename T>
typename node_data<T>::storage1d_type& node_data<T>::vector_non_ref()
{
storage1d_type* v = util::get_if<storage1d_type>(&data_);
if (v == nullptr)
{
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::vector_non_ref()",
"node_data object holds unsupported data type");
}
return *v;
}
template <typename T>
typename node_data<T>::storage1d_type const& node_data<T>::vector_non_ref()
const
{
storage1d_type const* v = util::get_if<storage1d_type>(&data_);
if (v == nullptr)
{
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::vector_non_ref()",
"node_data object holds unsupported data type");
}
return *v;
}
template <typename T>
typename node_data<T>::storage1d_type node_data<T>::vector_copy() const
{
custom_storage1d_type const* cv =
util::get_if<custom_storage1d_type>(&data_);
if (cv != nullptr)
{
return storage1d_type{*cv};
}
storage1d_type const* v = util::get_if<storage1d_type>(&data_);
if (v != nullptr)
{
return *v;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::vector()",
"node_data object holds unsupported data type");
}
template <typename T>
typename node_data<T>::custom_storage1d_type node_data<T>::vector() &
{
custom_storage1d_type* cv =
util::get_if<custom_storage1d_type>(&data_);
if (cv != nullptr)
{
return *cv;
}
storage1d_type* v = util::get_if<storage1d_type>(&data_);
if (v != nullptr)
{
return custom_storage1d_type(v->data(), v->size(), v->spacing());
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::vector()",
"node_data object holds unsupported data type");
}
template <typename T>
typename node_data<T>::custom_storage1d_type node_data<T>::vector() const&
{
custom_storage1d_type const* cv =
util::get_if<custom_storage1d_type>(&data_);
if (cv != nullptr)
{
return custom_storage1d_type{
const_cast<T*>(cv->data()), cv->size(), cv->spacing()};
}
storage1d_type const* v = util::get_if<storage1d_type>(&data_);
if (v != nullptr)
{
return custom_storage1d_type{
const_cast<T*>(v->data()), v->size(), v->spacing()};
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::vector()",
"node_data object holds unsupported data type");
}
template <typename T>
typename node_data<T>::custom_storage1d_type node_data<T>::vector() &&
{
custom_storage1d_type* cv =
util::get_if<custom_storage1d_type>(&data_);
if (cv != nullptr)
{
return *cv;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::vector()",
"node_data::vector shouldn't be called on an rvalue");
}
template <typename T>
typename node_data<T>::custom_storage1d_type node_data<T>::vector() const&&
{
custom_storage1d_type const* cv =
util::get_if<custom_storage1d_type>(&data_);
if (cv != nullptr)
{
return *cv;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::vector()",
"node_data::vector shouldn't be called on an rvalue");
}
template <typename T>
typename node_data<T>::storage0d_type& node_data<T>::scalar()
{
storage0d_type* s = util::get_if<storage0d_type>(&data_);
if (s == nullptr)
{
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::scalar()",
"node_data object holds unsupported data type");
}
return *s;
}
template <typename T>
typename node_data<T>::storage0d_type const& node_data<T>::scalar() const
{
storage0d_type const* s = util::get_if<storage0d_type>(&data_);
if (s == nullptr)
{
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::scalar()",
"node_data object holds unsupported data type");
}
return *s;
}
/// Extract the dimensionality of the underlying data array.
template <typename T>
std::size_t node_data<T>::num_dimensions() const
{
switch(data_.index())
{
case 0:
return 0;
case 1: HPX_FALLTHROUGH;
case 3:
return 1;
case 2: HPX_FALLTHROUGH;
case 4:
return 2;
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::num_dimensions()",
"node_data object holds unsupported data type");
}
/// Extract the dimensional extends of the underlying data array.
template <typename T>
typename node_data<T>::dimensions_type node_data<T>::dimensions() const
{
switch(data_.index())
{
case 0:
return dimensions_type{1ul, 1ul};
case 1: HPX_FALLTHROUGH;
case 3:
return dimensions_type{vector().size(), 1ul};
case 2: HPX_FALLTHROUGH;
case 4:
{
auto m = matrix();
return dimensions_type{m.rows(), m.columns()};
}
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::dimensions()",
"node_data object holds unsupported data type");
}
template <typename T>
std::size_t node_data<T>::dimension(int dim) const
{
switch(data_.index())
{
case 0:
return 1ul;
case 1: HPX_FALLTHROUGH;
case 3:
return (dim == 0) ? vector().size() : 1ul;
case 2: HPX_FALLTHROUGH;
case 4:
{
auto m = matrix();
return (dim == 0) ? m.rows() : m.columns();
}
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::dimension()",
"node_data object holds unsupported data type");
}
/// Return a new instance of node_data referring to this instance.
template <typename T>
node_data<T> node_data<T>::ref() &
{
switch(data_.index())
{
case 1:
return node_data<T>{vector()};
case 2:
return node_data<T>{matrix()};
case 0: HPX_FALLTHROUGH;
case 3: HPX_FALLTHROUGH;
case 4:
return *this;
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::ref()",
"node_data object holds unsupported data type");
}
template <typename T>
node_data<T> node_data<T>::ref() const&
{
switch(data_.index())
{
case 1:
return node_data<T>{vector()};
case 2:
return node_data<T>{matrix()};
case 0: HPX_FALLTHROUGH;
case 3: HPX_FALLTHROUGH;
case 4:
return *this;
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::ref()",
"node_data object holds unsupported data type");
}
template <typename T>
node_data<T> node_data<T>::ref() &&
{
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::ref()",
"node_data object holds unsupported data type");
}
template <typename T>
node_data<T> node_data<T>::ref() const&&
{
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::ref()",
"node_data object holds unsupported data type");
}
/// Return a new instance of node_data holding a copy of this instance.
template <typename T>
node_data<T> node_data<T>::copy() const
{
switch(data_.index())
{
case 0: HPX_FALLTHROUGH;
case 1: HPX_FALLTHROUGH;
case 2:
return *this;
case 3:
return node_data<T>{vector_copy()};
case 4:
return node_data<T>{matrix_copy()};
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::ref()",
"node_data object holds unsupported data type");
}
/// Return whether the internal representation is referring to another
/// instance of node_data
template <typename T>
bool node_data<T>::is_ref() const
{
switch(data_.index())
{
case 0: HPX_FALLTHROUGH;
case 1: HPX_FALLTHROUGH;
case 2:
return false;
case 3: HPX_FALLTHROUGH;
case 4:
return true;
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::is_ref()",
"node_data object holds unsupported data type");
}
// conversion helpers for Python bindings
template <typename T>
std::vector<T> node_data<T>::as_vector() const
{
switch(data_.index())
{
case 1: HPX_FALLTHROUGH;
case 3:
{
auto v = vector();
return std::vector<T>(v.begin(), v.end());
}
case 0: HPX_FALLTHROUGH;
case 2: HPX_FALLTHROUGH;
case 4: HPX_FALLTHROUGH;
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::as_vector()",
"node_data object holds unsupported data type");
}
template <typename T>
std::vector<std::vector<T>> node_data<T>::as_matrix() const
{
switch(data_.index())
{
case 2: HPX_FALLTHROUGH;
case 4:
{
auto m = matrix();
std::vector<std::vector<T>> result(m.rows());
for (std::size_t i = 0; i != m.rows(); ++i)
{
result[i].assign(m.begin(i), m.end(i));
}
return result;
}
case 0: HPX_FALLTHROUGH;
case 1: HPX_FALLTHROUGH;
case 3: HPX_FALLTHROUGH;
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::as_matrix()",
"node_data object holds unsupported data type");
}
///////////////////////////////////////////////////////////////////////////
bool operator==(node_data<double> const& lhs, node_data<double> const& rhs)
{
if (lhs.num_dimensions() != rhs.num_dimensions() ||
lhs.dimensions() != rhs.dimensions())
{
return false;
}
switch (lhs.num_dimensions())
{
case 0:
return lhs.scalar() == rhs.scalar();
case 1: HPX_FALLTHROUGH;
case 3:
return lhs.vector() == rhs.vector();
case 2: HPX_FALLTHROUGH;
case 4:
return lhs.matrix() == rhs.matrix();
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::operator==()",
"node_data object holds unsupported data type");
}
bool operator==(
node_data<std::uint8_t> const& lhs, node_data<std::uint8_t> const& rhs)
{
if (lhs.num_dimensions() != rhs.num_dimensions() ||
lhs.dimensions() != rhs.dimensions())
{
return false;
}
switch (lhs.num_dimensions())
{
case 0:
return lhs.scalar() == rhs.scalar();
case 1: HPX_FALLTHROUGH;
case 3:
return lhs.vector() == rhs.vector();
case 2: HPX_FALLTHROUGH;
case 4:
return lhs.matrix() == rhs.matrix();
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::operator==()",
"node_data object holds unsupported data type");
}
bool operator==(
node_data<std::int64_t> const& lhs, node_data<std::int64_t> const& rhs)
{
if (lhs.num_dimensions() != rhs.num_dimensions() ||
lhs.dimensions() != rhs.dimensions())
{
return false;
}
switch (lhs.num_dimensions())
{
case 0:
return lhs.scalar() == rhs.scalar();
case 1:
HPX_FALLTHROUGH;
case 3:
return lhs.vector() == rhs.vector();
case 2:
HPX_FALLTHROUGH;
case 4:
return lhs.matrix() == rhs.matrix();
default:
break;
}
HPX_THROW_EXCEPTION(hpx::invalid_status,
"phylanx::ir::node_data<T>::operator==()",
"node_data object holds unsupported data type");
}
///////////////////////////////////////////////////////////////////////////
namespace detail
{
template <typename T, typename Range>
void print_array(std::ostream& out, Range const& r, std::size_t size)
{
out << "[";
for (std::size_t i = 0; i != size; ++i)
{
if (i != 0)
{
out << ", ";
}
out << T(r[i]);
}
out << "]";
}
}
///////////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& out, node_data<double> const& nd)
{
std::size_t dims = nd.num_dimensions();
switch (dims)
{
case 0:
out << nd[0];
break;
case 1: HPX_FALLTHROUGH;
case 3:
detail::print_array<double>(out, nd.vector(), nd.size());
break;
case 2: HPX_FALLTHROUGH;
case 4:
{
out << "[";
auto data = nd.matrix();
for (std::size_t row = 0; row != data.rows(); ++row)
{
if (row != 0)
out << ", ";
detail::print_array<double>(
out, blaze::row(data, row), data.columns());
}
out << "]";
}
break;
default:
HPX_THROW_EXCEPTION(hpx::invalid_status,
"node_data<double>::operator<<()",
"invalid dimensionality: " + std::to_string(dims));
}
return out;
}
std::ostream& operator<<(std::ostream& out, node_data<std::int64_t> const& nd)
{
std::size_t dims = nd.num_dimensions();
switch (dims)
{
case 0:
out << nd[0];
break;
case 1: HPX_FALLTHROUGH;
case 3:
detail::print_array<std::int64_t>(out, nd.vector(), nd.size());
break;
case 2: HPX_FALLTHROUGH;
case 4:
{
out << "[";
auto data = nd.matrix();
for (std::size_t row = 0; row != data.rows(); ++row)
{
if (row != 0)
out << ", ";
detail::print_array<std::int64_t>(
out, blaze::row(data, row), data.columns());
}
out << "]";
}
break;
default:
HPX_THROW_EXCEPTION(hpx::invalid_status,
"node_data<std::int64_t>::operator<<()",
"invalid dimensionality: " + std::to_string(dims));
}
return out;
}
///////////////////////////////////////////////////////////////////////////
template <typename T>
node_data<T>::operator bool() const
{
std::size_t dims = num_dimensions();
switch (dims)
{
case 0:
return scalar() != 0;
case 1: HPX_FALLTHROUGH;
case 3:
return vector().nonZeros() != 0;
case 2: HPX_FALLTHROUGH;
case 4:
return matrix().nonZeros() != 0;
default:
HPX_THROW_EXCEPTION(hpx::invalid_status,
"node_data<double>::operator bool",
"invalid dimensionality: " + std::to_string(dims));
}
return false;
}
///////////////////////////////////////////////////////////////////////////
template <typename T>
void node_data<T>::serialize(hpx::serialization::output_archive& ar,
unsigned)
{
std::size_t index = data_.index();
ar << index;
switch (index)
{
case 0:
ar << util::get<0>(data_);
break;
case 1:
ar << util::get<1>(data_);
break;
case 2:
ar << util::get<2>(data_);
break;
case 3:
ar << util::get<3>(data_);
break;
case 4:
ar << util::get<4>(data_);
break;
default:
HPX_THROW_EXCEPTION(hpx::invalid_status,
"node_data<T>::serialize",
"node_data object holds unsupported data type");
}
}
template <typename T>
void node_data<T>::serialize(hpx::serialization::input_archive& ar,
unsigned)
{
std::size_t index = 0;
ar >> index;
switch (index)
{
case 0:
{
double val = 0;
ar >> val;
data_ = val;
}
break;
case 1: HPX_FALLTHROUGH;
case 3: // deserialize CustomVector as DynamicVector
{
storage1d_type v;
ar >> v;
data_ = std::move(v);
}
break;
case 2: HPX_FALLTHROUGH;
case 4: // deserialize CustomMatrix as DynamicMatrix
{
storage2d_type m;
ar >> m;
data_ = std::move(m);
}
break;
default:
HPX_THROW_EXCEPTION(hpx::invalid_status,
"node_data<T>::serialize",
"node_data object holds unsupported data type");
}
}
///////////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& out, node_data<std::uint8_t> const& nd)
{
std::size_t dims = nd.num_dimensions();
switch (dims)
{
case 0:
out << std::boolalpha << std::to_string(bool{nd[0] != 0});
break;
case 1: HPX_FALLTHROUGH;
case 3:
out << std::boolalpha;
detail::print_array<bool>(out, nd.vector(), nd.size());
break;
case 2: HPX_FALLTHROUGH;
case 4:
{
out << std::boolalpha << "[";
auto data = nd.matrix();
for (std::size_t row = 0; row != data.rows(); ++row)
{
if (row != 0)
out << ", ";
detail::print_array<bool>(
out, blaze::row(data, row), data.columns());
}
out << "]";
}
break;
default:
HPX_THROW_EXCEPTION(hpx::invalid_status,
"node_data<std::uint8_t>::operator<<()",
"invalid dimensionality: " + std::to_string(dims));
}
return out;
}
}}
template class PHYLANX_EXPORT phylanx::ir::node_data<double>;
template class PHYLANX_EXPORT phylanx::ir::node_data<std::uint8_t>;
template class PHYLANX_EXPORT phylanx::ir::node_data<std::int64_t>;
| 27.390707 | 87 | 0.518195 | weilewei |
b13a03ab2c246191aefc6477322944d7ea4d8e47 | 728 | cpp | C++ | src/NullOutput.cpp | 9elements/pwrseqd | fa435d8fed2de2c7948cbc1f0e55f9257786c907 | [
"Apache-2.0"
] | null | null | null | src/NullOutput.cpp | 9elements/pwrseqd | fa435d8fed2de2c7948cbc1f0e55f9257786c907 | [
"Apache-2.0"
] | null | null | null | src/NullOutput.cpp | 9elements/pwrseqd | fa435d8fed2de2c7948cbc1f0e55f9257786c907 | [
"Apache-2.0"
] | null | null | null |
#include "NullOutput.hpp"
#include "Config.hpp"
#include "SignalProvider.hpp"
using namespace std;
// Name returns the instance name
string NullOutput::Name(void)
{
return this->name;
}
void NullOutput::Apply(void)
{
if (this->newLevel != this->active)
{
this->active = this->newLevel;
}
}
void NullOutput::Update(void)
{
this->newLevel = this->in->GetLevel();
}
bool NullOutput::GetLevel(void)
{
return this->active;
}
NullOutput::NullOutput(struct ConfigOutput* cfg, SignalProvider& prov)
{
this->in = prov.FindOrAdd(cfg->SignalName);
this->in->AddReceiver(this);
this->newLevel = false;
this->active = false;
this->name = cfg->Name;
}
NullOutput::~NullOutput()
{}
| 16.545455 | 70 | 0.660714 | 9elements |
b13b02531d45ef8917795560ce0a69e11e6b3747 | 10,791 | hpp | C++ | include/OVRSimpleJSON/JSONLazyCreator.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/OVRSimpleJSON/JSONLazyCreator.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/OVRSimpleJSON/JSONLazyCreator.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: OVRSimpleJSON.JSONNode
#include "OVRSimpleJSON/JSONNode.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: OVRSimpleJSON
namespace OVRSimpleJSON {
// Forward declaring type: JSONNodeType
struct JSONNodeType;
// Forward declaring type: JSONArray
class JSONArray;
// Forward declaring type: JSONObject
class JSONObject;
// Forward declaring type: JSONTextMode
struct JSONTextMode;
}
// Forward declaring namespace: System::Text
namespace System::Text {
// Forward declaring type: StringBuilder
class StringBuilder;
}
// Completed forward declares
// Type namespace: OVRSimpleJSON
namespace OVRSimpleJSON {
// Size: 0x20
#pragma pack(push, 1)
// Autogenerated type: OVRSimpleJSON.JSONLazyCreator
// [DefaultMemberAttribute] Offset: DCDF18
class JSONLazyCreator : public OVRSimpleJSON::JSONNode {
public:
// private OVRSimpleJSON.JSONNode m_Node
// Size: 0x8
// Offset: 0x10
OVRSimpleJSON::JSONNode* m_Node;
// Field size check
static_assert(sizeof(OVRSimpleJSON::JSONNode*) == 0x8);
// private System.String m_Key
// Size: 0x8
// Offset: 0x18
::Il2CppString* m_Key;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// Creating value type constructor for type: JSONLazyCreator
JSONLazyCreator(OVRSimpleJSON::JSONNode* m_Node_ = {}, ::Il2CppString* m_Key_ = {}) noexcept : m_Node{m_Node_}, m_Key{m_Key_} {}
// public System.Void .ctor(OVRSimpleJSON.JSONNode aNode)
// Offset: 0x1613F50
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static JSONLazyCreator* New_ctor(OVRSimpleJSON::JSONNode* aNode) {
static auto ___internal__logger = ::Logger::get().WithContext("OVRSimpleJSON::JSONLazyCreator::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<JSONLazyCreator*, creationType>(aNode)));
}
// public System.Void .ctor(OVRSimpleJSON.JSONNode aNode, System.String aKey)
// Offset: 0x1614E7C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static JSONLazyCreator* New_ctor(OVRSimpleJSON::JSONNode* aNode, ::Il2CppString* aKey) {
static auto ___internal__logger = ::Logger::get().WithContext("OVRSimpleJSON::JSONLazyCreator::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<JSONLazyCreator*, creationType>(aNode, aKey)));
}
// private T Set(T aVal)
// Offset: 0xFFFFFFFF
template<class T>
T Set(T aVal) {
static_assert(std::is_convertible_v<T, OVRSimpleJSON::JSONNode*>);
static auto ___internal__logger = ::Logger::get().WithContext("OVRSimpleJSON::JSONLazyCreator::Set");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Set", std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(aVal)})));
static auto* ___generic__method = THROW_UNLESS(::il2cpp_utils::MakeGenericMethod(___internal__method, std::vector<Il2CppClass*>{::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<T>::get()}));
return ::il2cpp_utils::RunMethodThrow<T, false>(this, ___generic__method, aVal);
}
// public override OVRSimpleJSON.JSONNodeType get_Tag()
// Offset: 0x1614E54
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: OVRSimpleJSON.JSONNodeType JSONNode::get_Tag()
OVRSimpleJSON::JSONNodeType get_Tag();
// public override OVRSimpleJSON.JSONNode/Enumerator GetEnumerator()
// Offset: 0x1614E5C
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: OVRSimpleJSON.JSONNode/Enumerator JSONNode::GetEnumerator()
OVRSimpleJSON::JSONNode::Enumerator GetEnumerator();
// public override OVRSimpleJSON.JSONNode get_Item(System.Int32 aIndex)
// Offset: 0x1614EFC
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: OVRSimpleJSON.JSONNode JSONNode::get_Item(System.Int32 aIndex)
OVRSimpleJSON::JSONNode* get_Item(int aIndex);
// public override System.Void set_Item(System.Int32 aIndex, OVRSimpleJSON.JSONNode value)
// Offset: 0x1614F5C
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Void JSONNode::set_Item(System.Int32 aIndex, OVRSimpleJSON.JSONNode value)
void set_Item(int aIndex, OVRSimpleJSON::JSONNode* value);
// public override OVRSimpleJSON.JSONNode get_Item(System.String aKey)
// Offset: 0x1614FF0
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: OVRSimpleJSON.JSONNode JSONNode::get_Item(System.String aKey)
OVRSimpleJSON::JSONNode* get_Item(::Il2CppString* aKey);
// public override System.Void set_Item(System.String aKey, OVRSimpleJSON.JSONNode value)
// Offset: 0x1615060
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Void JSONNode::set_Item(System.String aKey, OVRSimpleJSON.JSONNode value)
void set_Item(::Il2CppString* aKey, OVRSimpleJSON::JSONNode* value);
// public override System.Void Add(OVRSimpleJSON.JSONNode aItem)
// Offset: 0x1615100
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Void JSONNode::Add(OVRSimpleJSON.JSONNode aItem)
void Add(OVRSimpleJSON::JSONNode* aItem);
// public override System.Void Add(System.String aKey, OVRSimpleJSON.JSONNode aItem)
// Offset: 0x1615194
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Void JSONNode::Add(System.String aKey, OVRSimpleJSON.JSONNode aItem)
void Add(::Il2CppString* aKey, OVRSimpleJSON::JSONNode* aItem);
// public override System.Boolean Equals(System.Object obj)
// Offset: 0x1615264
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Boolean JSONNode::Equals(System.Object obj)
bool Equals(::Il2CppObject* obj);
// public override System.Int32 GetHashCode()
// Offset: 0x161527C
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Int32 JSONNode::GetHashCode()
int GetHashCode();
// public override System.Int32 get_AsInt()
// Offset: 0x1615284
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Int32 JSONNode::get_AsInt()
int get_AsInt();
// public override System.Void set_AsInt(System.Int32 value)
// Offset: 0x1615300
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Void JSONNode::set_AsInt(System.Int32 value)
void set_AsInt(int value);
// public override System.Single get_AsFloat()
// Offset: 0x1615380
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Single JSONNode::get_AsFloat()
float get_AsFloat();
// public override System.Void set_AsFloat(System.Single value)
// Offset: 0x16153FC
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Void JSONNode::set_AsFloat(System.Single value)
void set_AsFloat(float value);
// public override System.Double get_AsDouble()
// Offset: 0x161547C
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Double JSONNode::get_AsDouble()
double get_AsDouble();
// public override System.Void set_AsDouble(System.Double value)
// Offset: 0x16154F8
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Void JSONNode::set_AsDouble(System.Double value)
void set_AsDouble(double value);
// public override System.Int64 get_AsLong()
// Offset: 0x1615578
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Int64 JSONNode::get_AsLong()
int64_t get_AsLong();
// public override System.Void set_AsLong(System.Int64 value)
// Offset: 0x1615658
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Void JSONNode::set_AsLong(System.Int64 value)
void set_AsLong(int64_t value);
// public override System.Boolean get_AsBool()
// Offset: 0x1615768
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Boolean JSONNode::get_AsBool()
bool get_AsBool();
// public override System.Void set_AsBool(System.Boolean value)
// Offset: 0x16157E0
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Void JSONNode::set_AsBool(System.Boolean value)
void set_AsBool(bool value);
// public override OVRSimpleJSON.JSONArray get_AsArray()
// Offset: 0x161585C
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: OVRSimpleJSON.JSONArray JSONNode::get_AsArray()
OVRSimpleJSON::JSONArray* get_AsArray();
// public override OVRSimpleJSON.JSONObject get_AsObject()
// Offset: 0x16158C8
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: OVRSimpleJSON.JSONObject JSONNode::get_AsObject()
OVRSimpleJSON::JSONObject* get_AsObject();
// override System.Void WriteToStringBuilder(System.Text.StringBuilder aSB, System.Int32 aIndent, System.Int32 aIndentInc, OVRSimpleJSON.JSONTextMode aMode)
// Offset: 0x1615938
// Implemented from: OVRSimpleJSON.JSONNode
// Base method: System.Void JSONNode::WriteToStringBuilder(System.Text.StringBuilder aSB, System.Int32 aIndent, System.Int32 aIndentInc, OVRSimpleJSON.JSONTextMode aMode)
void WriteToStringBuilder(System::Text::StringBuilder* aSB, int aIndent, int aIndentInc, OVRSimpleJSON::JSONTextMode aMode);
}; // OVRSimpleJSON.JSONLazyCreator
#pragma pack(pop)
static check_size<sizeof(JSONLazyCreator), 24 + sizeof(::Il2CppString*)> __OVRSimpleJSON_JSONLazyCreatorSizeCheck;
static_assert(sizeof(JSONLazyCreator) == 0x20);
// static public System.Boolean op_Equality(OVRSimpleJSON.JSONLazyCreator a, System.Object b)
// Offset: 0x1615234
bool operator ==(OVRSimpleJSON::JSONLazyCreator* a, ::Il2CppObject& b);
// static public System.Boolean op_Inequality(OVRSimpleJSON.JSONLazyCreator a, System.Object b)
// Offset: 0x161524C
bool operator !=(OVRSimpleJSON::JSONLazyCreator* a, ::Il2CppObject& b);
}
DEFINE_IL2CPP_ARG_TYPE(OVRSimpleJSON::JSONLazyCreator*, "OVRSimpleJSON", "JSONLazyCreator");
| 52.639024 | 260 | 0.721064 | darknight1050 |
b13b1398503ff027aa1141c40fc44ac1a56f9463 | 510 | cpp | C++ | Tefnout/src/Tefnout/ECS/Entity.cpp | JeremyBois/Tefnout | 3e0d79c96857a395d2f00a61bb25a49ce39c8c89 | [
"Apache-2.0",
"MIT"
] | null | null | null | Tefnout/src/Tefnout/ECS/Entity.cpp | JeremyBois/Tefnout | 3e0d79c96857a395d2f00a61bb25a49ce39c8c89 | [
"Apache-2.0",
"MIT"
] | null | null | null | Tefnout/src/Tefnout/ECS/Entity.cpp | JeremyBois/Tefnout | 3e0d79c96857a395d2f00a61bb25a49ce39c8c89 | [
"Apache-2.0",
"MIT"
] | null | null | null | #include "TefnoutPCH.hpp"
#include "Entity.hpp"
#include "Tefnout/Core/Debug.hpp"
#include <limits>
namespace Tefnout
{
namespace ECS
{
Entity::Entity() : m_id(std::numeric_limits<entity_type>::max())
{
}
Entity::Entity(entity_type id) : m_id(id)
{
TEFNOUT_ASSERT(id != std::numeric_limits<entity_type>::max(),
"New ID equals Entity::s_null. {0}",
"<id> must not be equals to std::numeric_limits<entity_type>::max()");
}
} // namespace ECS
} // namespace Tefnout
| 20.4 | 89 | 0.647059 | JeremyBois |
b13b2ef5cbd9d6f0bfc3b68102d01661da6d0400 | 8,196 | cpp | C++ | src/sim/cgi/sim_Effects.cpp | marek-cel/fightersfs | 5511162726861fee17357f39274461250370c224 | [
"MIT"
] | 4 | 2021-01-28T17:39:38.000Z | 2022-02-11T20:13:46.000Z | src/sim/cgi/sim_Effects.cpp | marek-cel/fightersfs | 5511162726861fee17357f39274461250370c224 | [
"MIT"
] | null | null | null | src/sim/cgi/sim_Effects.cpp | marek-cel/fightersfs | 5511162726861fee17357f39274461250370c224 | [
"MIT"
] | 3 | 2021-02-22T21:22:30.000Z | 2022-01-10T19:32:12.000Z | /****************************************************************************//*
* Copyright (C) 2021 Marek M. Cel
*
* 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 <sim/cgi/sim_Effects.h>
#include <osg/PositionAttitudeTransform>
#include <osgParticle/ModularEmitter>
#include <osgParticle/ParticleSystemUpdater>
////////////////////////////////////////////////////////////////////////////////
using namespace sim;
////////////////////////////////////////////////////////////////////////////////
osg::Group* Effects::createExplosion( float scale )
{
osg::ref_ptr<osg::Group> group = new osg::Group();
osg::ref_ptr<osg::PositionAttitudeTransform> pat = new osg::PositionAttitudeTransform();
group->addChild( pat.get() );
pat->setAttitude( osg::Quat( 0.0, osg::Z_AXIS,
-osg::PI_2, osg::Y_AXIS,
-osg::PI_2, osg::X_AXIS ) );
osg::ref_ptr<osgParticle::ParticleSystem> ps = new osgParticle::ParticleSystem();
ps->getDefaultParticleTemplate().setLifeTime( 0.75f );
ps->getDefaultParticleTemplate().setShape( osgParticle::Particle::QUAD );
ps->getDefaultParticleTemplate().setSizeRange( osgParticle::rangef(1.0f, scale) );
ps->getDefaultParticleTemplate().setAlphaRange( osgParticle::rangef(1.0f, 0.0f) );
ps->getDefaultParticleTemplate().setColorRange(
osgParticle::rangev4(osg::Vec4(1.0f,1.0f,0.5f,1.0f), osg::Vec4(1.0f,0.5f,0.0f,1.0f)) );
ps->setDefaultAttributes( getPath( "textures/explosion.rgb" ), true, false );
osg::ref_ptr<osgParticle::RandomRateCounter> rrc = new osgParticle::RandomRateCounter();
rrc->setRateRange( 10, 20 );
osg::ref_ptr<osgParticle::RadialShooter> shooter = new osgParticle::RadialShooter();
shooter->setThetaRange( -osg::PI, osg::PI );
shooter->setPhiRange( -osg::PI, osg::PI );
shooter->setInitialSpeedRange( -10.0f, 10.0f );
osg::ref_ptr<osgParticle::ModularEmitter> emitter = new osgParticle::ModularEmitter();
emitter->setParticleSystem( ps.get() );
emitter->setCounter( rrc.get() );
emitter->setShooter( shooter.get() );
emitter->setEndless( false );
emitter->setLifeTime( 0.75f );
pat->addChild( emitter.get() );
osg::ref_ptr<osgParticle::ParticleSystemUpdater> updater = new osgParticle::ParticleSystemUpdater();
updater->addParticleSystem( ps.get() );
osg::ref_ptr<osg::Geode> geode = new osg::Geode();
geode->addDrawable( ps.get() );
group->addChild( updater.get() );
group->addChild( geode.get() );
return group.release();
}
////////////////////////////////////////////////////////////////////////////////
osg::Group* Effects::createFlames( const char *texture )
{
osg::ref_ptr<osg::Group> group = new osg::Group();
osg::ref_ptr<osgParticle::ParticleSystemUpdater> updater = new osgParticle::ParticleSystemUpdater();
osg::ref_ptr<osg::Geode> geode = new osg::Geode();
osg::ref_ptr<osgParticle::ParticleSystem> ps = new osgParticle::ParticleSystem();
ps->getDefaultParticleTemplate().setLifeTime( 1.5f );
ps->getDefaultParticleTemplate().setShape( osgParticle::Particle::QUAD );
ps->getDefaultParticleTemplate().setSizeRange( osgParticle::rangef(1.0f, 0.4f) );
ps->getDefaultParticleTemplate().setAlphaRange( osgParticle::rangef(1.0f, 0.0f) );
ps->getDefaultParticleTemplate().setColorRange(
osgParticle::rangev4(osg::Vec4(1.0f,1.0f,0.5f,1.0f), osg::Vec4(1.0f,0.5f,0.0f,1.0f)) );
ps->setDefaultAttributes( texture, true, false );
osg::ref_ptr<osgParticle::RandomRateCounter> rrc = new osgParticle::RandomRateCounter();
rrc->setRateRange( 7, 15 );
osg::ref_ptr<osgParticle::RadialShooter> shooter = new osgParticle::RadialShooter();
shooter->setThetaRange( -osg::PI_4*0.05f, osg::PI_4*0.05f );
shooter->setPhiRange( -osg::PI_4, osg::PI_4 );
shooter->setInitialSpeedRange( 7.5f, 15.0f );
shooter->setInitialRotationalSpeedRange( osg::Vec3( 0.0f, 0.0, 5.0 ),
osg::Vec3( 0.0f, 0.0, 5.0 ) );
osg::ref_ptr<osgParticle::ModularEmitter> emitter = new osgParticle::ModularEmitter();
emitter->setParticleSystem( ps.get() );
emitter->setCounter( rrc.get() );
emitter->setShooter( shooter.get() );
group->addChild( emitter.get() );
updater->addParticleSystem( ps.get() );
geode->addDrawable( ps.get() );
group->addChild( updater.get() );
group->addChild( geode.get() );
return group.release();
}
////////////////////////////////////////////////////////////////////////////////
osg::Group* Effects::createSmoke( float lifeTime,
float size0, float size1,
float spread,
float intensity,
float speed )
{
if ( spread > 1.0f ) spread = 1.0f;
if ( intensity > 1.0f ) intensity = 1.0f;
if ( speed > 1.0f ) speed = 1.0f;
osg::ref_ptr<osg::Group> group = new osg::Group();
osg::ref_ptr<osgParticle::ParticleSystemUpdater> updater = new osgParticle::ParticleSystemUpdater();
osg::ref_ptr<osg::Geode> geode = new osg::Geode();
osg::ref_ptr<osgParticle::ParticleSystem> ps = new osgParticle::ParticleSystem();
ps->getDefaultParticleTemplate().setLifeTime( lifeTime );
ps->getDefaultParticleTemplate().setShape( osgParticle::Particle::QUAD );
ps->getDefaultParticleTemplate().setSizeRange( osgParticle::rangef(size0, size1) );
ps->getDefaultParticleTemplate().setAlphaRange( osgParticle::rangef(1.0f, 0.0f) );
ps->getDefaultParticleTemplate().setColorRange(
osgParticle::rangev4(osg::Vec4(1.0f,1.0f,1.0f,1.0f), osg::Vec4(1.0f,1.0f,1.0f,0.0f)) );
ps->setDefaultAttributes( getPath( "textures/smoke_dark.rgb" ), false, false );
osg::ref_ptr<osgParticle::RandomRateCounter> rrc = new osgParticle::RandomRateCounter();
rrc->setRateRange( 20.0f * intensity, 30.0f * intensity );
osg::ref_ptr<osgParticle::RadialShooter> shooter = new osgParticle::RadialShooter();
shooter->setThetaRange( -osg::PI_4*0.5*spread, osg::PI_4*0.5*spread );
shooter->setPhiRange( -osg::PI_4*0.5*spread, osg::PI_4*0.5*spread );
shooter->setInitialSpeedRange( 7.5f*speed, 15.0f*speed );
osg::ref_ptr<osgParticle::ModularEmitter> emitter = new osgParticle::ModularEmitter();
emitter->setParticleSystem( ps.get() );
emitter->setCounter( rrc.get() );
emitter->setShooter( shooter.get() );
group->addChild( emitter.get() );
updater->addParticleSystem( ps.get() );
geode->addDrawable( ps.get() );
group->addChild( updater.get() );
group->addChild( geode.get() );
return group.release();
}
////////////////////////////////////////////////////////////////////////////////
Effects::Smoke* Effects::createSmokeTrail()
{
Smoke *smokeTrail = new Smoke();
smokeTrail->setTextureFileName( getPath( "textures/smoke_light.rgb" ) );
smokeTrail->setIntensity( 10.0f );
smokeTrail->setEmitterDuration( 1000.0 );
return smokeTrail;
}
| 43.136842 | 104 | 0.63165 | marek-cel |
b1406a118d4e588aa9b38f18bcb133cc88cd732b | 494 | hpp | C++ | source/URI/QueryParser.hpp | kurocha/uri | b920d01de5323126eaf539d4217d357b47fde64e | [
"Unlicense",
"MIT"
] | 2 | 2018-07-06T19:43:16.000Z | 2018-07-06T19:44:46.000Z | source/URI/QueryParser.hpp | kurocha/uri | b920d01de5323126eaf539d4217d357b47fde64e | [
"Unlicense",
"MIT"
] | null | null | null | source/URI/QueryParser.hpp | kurocha/uri | b920d01de5323126eaf539d4217d357b47fde64e | [
"Unlicense",
"MIT"
] | null | null | null | //
// QueryParser.hpp
// File file is part of the "URI" project and released under the MIT License.
//
// Created by Samuel Williams on 17/7/2017.
// Copyright, 2017, by Samuel Williams. All rights reserved.
//
#pragma once
#include <string>
#include <map>
namespace URI
{
namespace QueryParser
{
using Byte = unsigned char;
using NamedValues = std::multimap<std::string, std::string>;
std::size_t parse(const Byte * begin, const Byte * end, NamedValues & named_values);
}
}
| 20.583333 | 86 | 0.696356 | kurocha |
b142e71ee8eade50fd18f4b483022876d232d313 | 6,560 | cpp | C++ | lgc/patch/PatchPeepholeOpt.cpp | yukli-amd/llpc | 9ad8550a09fe6616f5eff53d6c3688a8bf43b465 | [
"MIT"
] | 112 | 2018-07-02T06:56:25.000Z | 2022-02-08T12:07:19.000Z | lgc/patch/PatchPeepholeOpt.cpp | yukli-amd/llpc | 9ad8550a09fe6616f5eff53d6c3688a8bf43b465 | [
"MIT"
] | 1,612 | 2018-07-04T19:08:21.000Z | 2022-03-31T23:24:55.000Z | lgc/patch/PatchPeepholeOpt.cpp | vettoreldaniele/llpc | 41fd5608f7b697c1416b983b89b2f62f0907d4a3 | [
"MIT"
] | 114 | 2018-07-04T18:47:13.000Z | 2022-03-30T19:53:19.000Z | /*
***********************************************************************************************************************
*
* Copyright (c) 2018-2021 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file PatchPeepholeOpt.cpp
* @brief LLPC source file: contains implementation of class lgc::PatchPeepholeOpt.
***********************************************************************************************************************
*/
#include "PatchPeepholeOpt.h"
#include "lgc/patch/Patch.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#define DEBUG_TYPE "lgc-patch-peephole-opt"
using namespace lgc;
using namespace llvm;
namespace lgc {
// =====================================================================================================================
// Define static members (no initializer needed as LLVM only cares about the address of ID, never its value).
char PatchPeepholeOpt::ID;
// =====================================================================================================================
// Pass creator, creates the pass of LLVM patching operations for peephole optimizations.
FunctionPass *createPatchPeepholeOpt() {
return new PatchPeepholeOpt();
}
PatchPeepholeOpt::PatchPeepholeOpt() : FunctionPass(ID) {
}
// =====================================================================================================================
// Executes this LLVM pass on the specified LLVM function.
//
// @param [in/out] function : Function that we will peephole optimize.
bool PatchPeepholeOpt::runOnFunction(Function &function) {
LLVM_DEBUG(dbgs() << "Run the pass Patch-Peephole-Opt\n");
visit(function);
const bool changed = !m_instsToErase.empty();
for (Instruction *const inst : m_instsToErase) {
// Lastly delete any instructions we replaced.
inst->eraseFromParent();
}
m_instsToErase.clear();
return changed;
}
// =====================================================================================================================
// Specify what analysis passes this pass depends on.
//
// @param [in/out] analysisUsage : The place to record our analysis pass usage requirements.
void PatchPeepholeOpt::getAnalysisUsage(AnalysisUsage &analysisUsage) const {
analysisUsage.setPreservesCFG();
}
// =====================================================================================================================
// Visit an inttoptr instruction.
//
// Change inttoptr ( add x, const ) -> gep ( inttoptr x, const ) to improve value tracking and load/store vectorization.
//
// Note: we decided to implement this transformation here and not in LLVM. From the point of view of alias analysis, the
// pointer returned by inttoptr ( add x, const ) is different from the pointer returned by gep ( inttoptr x, const ):
// the former is associated with whatever x AND const point to; the latter is associated ONLY with whatever x points to.
//
// In LLPC/LGC, we can assume that const does not point to any object (which makes this transformation valid) but that's
// not an assumption that can be made in general in LLVM with all its different front-ends.
//
// Reference: https://groups.google.com/g/llvm-dev/c/x4K7ppGLbg8/m/f_3NySRhjlcJ
// @param intToPtr: The "inttoptr" instruction to visit.
void PatchPeepholeOpt::visitIntToPtr(IntToPtrInst &intToPtr) {
// Check if we are using add to do pointer arithmetic.
auto *const binaryOperator = dyn_cast<BinaryOperator>(intToPtr.getOperand(0));
if (!binaryOperator || binaryOperator->getOpcode() != Instruction::Add)
return;
// Check that we have a constant offset.
const auto *const constOffset = dyn_cast<ConstantInt>(binaryOperator->getOperand(1));
if (!constOffset)
return;
// Create a getelementptr instruction (using offset / size).
const DataLayout &dataLayout = intToPtr.getModule()->getDataLayout();
auto elementType = intToPtr.getType()->getPointerElementType();
const uint64_t size = dataLayout.getTypeAllocSize(elementType);
APInt index = constOffset->getValue().udiv(size);
if (constOffset->getValue().urem(size) != 0)
return;
// Change inttoptr ( add x, const ) -> gep ( inttoptr x, const ).
auto *const newIntToPtr = new IntToPtrInst(binaryOperator->getOperand(0), intToPtr.getType());
newIntToPtr->insertAfter(binaryOperator);
auto *const getElementPtr =
GetElementPtrInst::Create(elementType, newIntToPtr, ConstantInt::get(newIntToPtr->getContext(), index));
getElementPtr->insertAfter(newIntToPtr);
// Set every instruction to use the newly calculated pointer.
intToPtr.replaceAllUsesWith(getElementPtr);
// If the add instruction has no other users then mark to erase.
if (binaryOperator->getNumUses() == 0)
m_instsToErase.push_back(binaryOperator);
}
} // namespace lgc
// =====================================================================================================================
// Initializes the pass of LLVM patching operations for peephole optimizations.
INITIALIZE_PASS(PatchPeepholeOpt, DEBUG_TYPE, "Patch LLVM for peephole optimizations", false, false)
| 46.197183 | 120 | 0.61189 | yukli-amd |
b143961dcb092abe46045bbee7b1220ddad288d9 | 12,471 | cpp | C++ | libs/maps/src/opengl/CAngularObservationMesh.cpp | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | 2 | 2017-03-25T18:09:17.000Z | 2017-05-22T08:14:48.000Z | libs/maps/src/opengl/CAngularObservationMesh.cpp | shivangag/mrpt | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | null | null | null | libs/maps/src/opengl/CAngularObservationMesh.cpp | shivangag/mrpt | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | 1 | 2017-06-30T18:23:45.000Z | 2017-06-30T18:23:45.000Z | /* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "maps-precomp.h" // Precomp header
#include <mrpt/opengl/CAngularObservationMesh.h>
#include <mrpt/poses/CPoint3D.h>
#include <mrpt/utils/stl_serialization.h>
#include <mrpt/utils/CStream.h>
#if MRPT_HAS_OPENGL_GLUT
#ifdef MRPT_OS_WINDOWS
// Windows:
#include <windows.h>
#endif
#ifdef MRPT_OS_APPLE
#include <OpenGL/gl.h>
#else
#include <GL/gl.h>
#endif
#endif
// Include libraries in linking:
#if MRPT_HAS_OPENGL_GLUT && defined(MRPT_OS_WINDOWS)
// WINDOWS:
#if defined(_MSC_VER) || defined(__BORLANDC__)
#pragma comment (lib,"opengl32.lib")
#pragma comment (lib,"GlU32.lib")
#endif
#endif // MRPT_HAS_OPENGL_GLUT
using namespace mrpt;
using namespace mrpt::obs;
using namespace mrpt::maps;
using namespace mrpt::math;
using namespace mrpt::opengl;
using namespace mrpt::utils;
using namespace mrpt::poses;
using namespace mrpt::math;
IMPLEMENTS_SERIALIZABLE(CAngularObservationMesh,CRenderizableDisplayList,mrpt::opengl)
void CAngularObservationMesh::addTriangle(const TPoint3D &p1,const TPoint3D &p2,const TPoint3D &p3) const {
const TPoint3D *arr[3]={&p1,&p2,&p3};
CSetOfTriangles::TTriangle t;
for (size_t i=0;i<3;i++) {
t.x[i]=arr[i]->x;
t.y[i]=arr[i]->y;
t.z[i]=arr[i]->z;
t.r[i]=m_color.R*(1.f/255);
t.g[i]=m_color.G*(1.f/255);
t.b[i]=m_color.B*(1.f/255);
t.a[i]=m_color.A*(1.f/255);
}
triangles.push_back(t);
CRenderizableDisplayList::notifyChange();
}
void CAngularObservationMesh::updateMesh() const {
CRenderizableDisplayList::notifyChange();
size_t numRows=scanSet.size();
triangles.clear();
if (numRows<=1) {
actualMesh.setSize(0,0);
validityMatrix.setSize(0,0);
meshUpToDate=true;
return;
}
if (pitchBounds.size()!=numRows&&pitchBounds.size()!=2) return;
size_t numCols=scanSet[0].scan.size();
actualMesh.setSize(numRows,numCols);
validityMatrix.setSize(numRows,numCols);
double *pitchs=new double[numRows];
if (pitchBounds.size()==2) {
double p1=pitchBounds[0];
double p2=pitchBounds[1];
for (size_t i=0;i<numRows;i++) pitchs[i]=p1+(p2-p1)*static_cast<double>(i)/static_cast<double>(numRows-1);
} else for (size_t i=0;i<numRows;i++) pitchs[i]=pitchBounds[i];
const bool rToL=scanSet[0].rightToLeft;
for (size_t i=0;i<numRows;i++) {
const std::vector<float> &scan=scanSet[i].scan;
const std::vector<char> valid=scanSet[i].validRange;
const double pitchIncr=scanSet[i].deltaPitch;
const double aperture=scanSet[i].aperture;
const CPose3D origin=scanSet[i].sensorPose;
//This is not an error...
for (size_t j=0;j<numCols;j++) if ((validityMatrix(i,j)=(valid[j]!=0))) {
double pYaw=aperture*((static_cast<double>(j)/static_cast<double>(numCols-1))-0.5);
// Without the pitch since it's already within each sensorPose:
actualMesh(i,j)=(origin+CPose3D(0,0,0,rToL?pYaw:-pYaw,pitchIncr))+CPoint3D(scan[j],0,0);
}
}
delete[] pitchs;
triangles.reserve(2*(numRows-1)*(numCols-1));
for (size_t k=0;k<numRows-1;k++) {
for (size_t j=0;j<numCols-1;j++) {
int b1=validityMatrix(k,j)?1:0;
int b2=validityMatrix(k,j+1)?1:0;
int b3=validityMatrix(k+1,j)?1:0;
int b4=validityMatrix(k+1,j+1)?1:0;
switch (b1+b2+b3+b4) {
case 0:
case 1:
case 2:
break;
case 3:
if (!b1) addTriangle(actualMesh(k,j+1),actualMesh(k+1,j),actualMesh(k+1,j+1));
else if (!b2) addTriangle(actualMesh(k,j),actualMesh(k+1,j),actualMesh(k+1,j+1));
else if (!b3) addTriangle(actualMesh(k,j),actualMesh(k,j+1),actualMesh(k+1,j+1));
else if (!b4) addTriangle(actualMesh(k,j),actualMesh(k,j+1),actualMesh(k+1,j));
break;
case 4:
addTriangle(actualMesh(k,j),actualMesh(k,j+1),actualMesh(k+1,j));
addTriangle(actualMesh(k+1,j+1),actualMesh(k,j+1),actualMesh(k+1,j));
}
}
}
meshUpToDate=true;
}
void CAngularObservationMesh::render_dl() const {
#if MRPT_HAS_OPENGL_GLUT
if (mEnableTransparency) {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
} else {
glEnable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
}
glEnable(GL_COLOR_MATERIAL);
glShadeModel(GL_SMOOTH);
if (!meshUpToDate) updateMesh();
if (!mWireframe) glBegin(GL_TRIANGLES);
for (size_t i=0;i<triangles.size();i++) {
const CSetOfTriangles::TTriangle &t=triangles[i];
float ax=t.x[1]-t.x[0];
float bx=t.x[2]-t.x[0];
float ay=t.y[1]-t.y[0];
float by=t.y[2]-t.y[0];
float az=t.z[1]-t.z[0];
float bz=t.z[2]-t.z[0];
glNormal3f(ay*bz-az*by,az*bx-ax*bz,ax*by-ay*bx);
if (mWireframe) glBegin(GL_LINE_LOOP);
for (int i=0;i<3;i++) {
glColor4f(t.r[i],t.g[i],t.b[i],t.a[i]);
glVertex3f(t.x[i],t.y[i],t.z[i]);
}
if (mWireframe) glEnd();
}
if (!mWireframe) glEnd();
glDisable(GL_BLEND);
glDisable(GL_LIGHTING);
#endif
}
bool CAngularObservationMesh::traceRay(const mrpt::poses::CPose3D &o,double &dist) const {
MRPT_UNUSED_PARAM(o);
MRPT_UNUSED_PARAM(dist);
//TODO: redo
return false;
}
bool CAngularObservationMesh::setScanSet(const std::vector<mrpt::obs::CObservation2DRangeScan> &scans) {
CRenderizableDisplayList::notifyChange();
//Returns false if the scan is inconsistent
if (scans.size()>0) {
size_t setSize=scans[0].scan.size();
bool rToL=scans[0].rightToLeft;
for (std::vector<CObservation2DRangeScan>::const_iterator it=scans.begin()+1;it!=scans.end();++it) {
if (it->scan.size()!=setSize) return false;
if (it->rightToLeft!=rToL) return false;
}
}
scanSet=scans;
meshUpToDate=false;
return true;
}
void CAngularObservationMesh::setPitchBounds(const double initial,const double final) {
CRenderizableDisplayList::notifyChange();
pitchBounds.clear();
pitchBounds.push_back(initial);
pitchBounds.push_back(final);
meshUpToDate=false;
}
void CAngularObservationMesh::setPitchBounds(const std::vector<double> &bounds) {
CRenderizableDisplayList::notifyChange();
pitchBounds=bounds;
meshUpToDate=false;
}
void CAngularObservationMesh::getPitchBounds(double &initial,double &final) const {
initial=pitchBounds.front();
final=pitchBounds.back();
}
void CAngularObservationMesh::getPitchBounds(std::vector<double> &bounds) const {
bounds=pitchBounds;
}
void CAngularObservationMesh::getScanSet(std::vector<CObservation2DRangeScan> &scans) const {
scans=scanSet;
}
void CAngularObservationMesh::generateSetOfTriangles(CSetOfTrianglesPtr &res) const {
if (!meshUpToDate) updateMesh();
res->insertTriangles(triangles.begin(),triangles.end());
//for (vector<CSetOfTriangles::TTriangle>::iterator it=triangles.begin();it!=triangles.end();++it) res->insertTriangle(*it);
}
struct CAngularObservationMesh_fnctr {
CPointsMap *m;
CAngularObservationMesh_fnctr(CPointsMap *p):m(p) {}
inline void operator()(const CObservation2DRangeScan &obj) {
m->insertObservation(&obj);
}
};
void CAngularObservationMesh::generatePointCloud(CPointsMap *out_map) const {
ASSERT_(out_map);
out_map->clear();
/* size_t numRows=scanSet.size();
if ((pitchBounds.size()!=numRows)&&(pitchBounds.size()!=2)) return;
std::vector<double> pitchs(numRows);
if (pitchBounds.size()==2) {
double p1=pitchBounds[0];
double p2=pitchBounds[1];
for (size_t i=0;i<numRows;i++) pitchs[i]=p1+(p2-p1)*static_cast<double>(i)/static_cast<double>(numRows-1);
} else for (size_t i=0;i<numRows;i++) pitchs[i]=pitchBounds[i];
for (size_t i=0;i<numRows;i++) out_map->insertObservation(&scanSet[i]);
*/
std::for_each(scanSet.begin(),scanSet.end(),CAngularObservationMesh_fnctr(out_map));
}
/*---------------------------------------------------------------
Implements the writing to a CStream capability of
CSerializable objects
---------------------------------------------------------------*/
void CAngularObservationMesh::writeToStream(mrpt::utils::CStream &out,int *version) const {
if (version) *version=0;
else {
writeToStreamRender(out);
//Version 0:
out<<pitchBounds<<scanSet<<mWireframe<<mEnableTransparency;
}
}
/*---------------------------------------------------------------
Implements the reading from a CStream capability of
CSerializable objects
---------------------------------------------------------------*/
void CAngularObservationMesh::readFromStream(mrpt::utils::CStream &in,int version) {
switch (version) {
case 0:
readFromStreamRender(in);
in>>pitchBounds>>scanSet>>mWireframe>>mEnableTransparency;
break;
default:
MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version)
};
meshUpToDate=false;
}
void CAngularObservationMesh::TDoubleRange::values(std::vector<double> &vals) const {
double value=initialValue();
double incr=increment();
size_t am=amount();
vals.resize(am);
for (size_t i=0;i<am-1;i++,value+=incr) vals[i]=value;
vals[am-1]=finalValue();
}
void CAngularObservationMesh::getTracedRays(CSetOfLinesPtr &res) const {
if (!meshUpToDate) updateMesh();
size_t count=0;
for (size_t i=0;i<validityMatrix.getRowCount();i++) for (size_t j=0;j<validityMatrix.getColCount();j++) if (validityMatrix(i,j)) count++;
res->reserve(count);
for (size_t i=0;i<actualMesh.getRowCount();i++) for (size_t j=0;j<actualMesh.getColCount();j++) if (validityMatrix(i,j)) res->appendLine(TPose3D(scanSet[i].sensorPose),actualMesh(i,j));
}
class FAddUntracedLines {
public:
CSetOfLinesPtr &lins;
const CPoint3D &pDist;
std::vector<double> pitchs;
FAddUntracedLines(CSetOfLinesPtr &l,const CPoint3D &p,const std::vector<double> &pi):lins(l),pDist(p),pitchs() {
pitchs.reserve(pi.size());
for (std::vector<double>::const_reverse_iterator it=pi.rbegin();it!=pi.rend();++it) pitchs.push_back(*it);
}
void operator()(const CObservation2DRangeScan& obs) {
size_t hm=obs.scan.size();
for (std::vector<char>::const_iterator it=obs.validRange.begin();it!=obs.validRange.end();++it) if (*it) hm--;
lins->reserve(hm);
for (size_t i=0;i<obs.scan.size();i++) if (!obs.validRange[i]) {
double yaw=obs.aperture*((static_cast<double>(i)/static_cast<double>(obs.scan.size()-1))-0.5);
lins->appendLine(TPoint3D(obs.sensorPose),TPoint3D(obs.sensorPose+CPose3D(0,0,0,obs.rightToLeft?yaw:-yaw,obs.deltaPitch*i+pitchs.back(),0)+pDist));
}
pitchs.pop_back();
}
};
void CAngularObservationMesh::getUntracedRays(CSetOfLinesPtr &res,double dist) const {
for_each(scanSet.begin(),scanSet.end(),FAddUntracedLines(res,dist,pitchBounds));
}
TPolygon3D createFromTriangle(const CSetOfTriangles::TTriangle &t) {
TPolygon3D res(3);
for (size_t i=0;i<3;i++) {
res[i].x=t.x[i];
res[i].y=t.y[i];
res[i].z=t.z[i];
}
return res;
}
void CAngularObservationMesh::generateSetOfTriangles(std::vector<TPolygon3D> &res) const {
if (!meshUpToDate) updateMesh();
res.resize(triangles.size());
transform(triangles.begin(),triangles.end(),res.begin(),createFromTriangle);
}
void CAngularObservationMesh::getBoundingBox(mrpt::math::TPoint3D &bb_min, mrpt::math::TPoint3D &bb_max) const
{
if (!meshUpToDate) updateMesh();
bb_min = mrpt::math::TPoint3D(std::numeric_limits<double>::max(),std::numeric_limits<double>::max(), std::numeric_limits<double>::max());
bb_max = mrpt::math::TPoint3D(-std::numeric_limits<double>::max(),-std::numeric_limits<double>::max(),-std::numeric_limits<double>::max());
for (size_t i=0;i<triangles.size();i++)
{
const CSetOfTriangles::TTriangle &t=triangles[i];
keep_min(bb_min.x, t.x[0]); keep_max(bb_max.x, t.x[0]);
keep_min(bb_min.y, t.y[0]); keep_max(bb_max.y, t.y[0]);
keep_min(bb_min.z, t.z[0]); keep_max(bb_max.z, t.z[0]);
keep_min(bb_min.x, t.x[1]); keep_max(bb_max.x, t.x[1]);
keep_min(bb_min.y, t.y[1]); keep_max(bb_max.y, t.y[1]);
keep_min(bb_min.z, t.z[1]); keep_max(bb_max.z, t.z[1]);
keep_min(bb_min.x, t.x[2]); keep_max(bb_max.x, t.x[2]);
keep_min(bb_min.y, t.y[2]); keep_max(bb_max.y, t.y[2]);
keep_min(bb_min.z, t.z[2]); keep_max(bb_max.z, t.z[2]);
}
// Convert to coordinates of my parent:
m_pose.composePoint(bb_min, bb_min);
m_pose.composePoint(bb_max, bb_max);
}
| 34.641667 | 186 | 0.675567 | feroze |
b143e171d020e8b6675fa2b92ccbef44b1dfa3e3 | 1,564 | hpp | C++ | engine/src/engine/input/Keyboard.hpp | CaptureTheBanana/CaptureTheBanana | 1398bedc80608e502c87b880c5b57d272236f229 | [
"MIT"
] | 1 | 2018-08-14T05:45:29.000Z | 2018-08-14T05:45:29.000Z | engine/src/engine/input/Keyboard.hpp | CaptureTheBanana/CaptureTheBanana | 1398bedc80608e502c87b880c5b57d272236f229 | [
"MIT"
] | null | null | null | engine/src/engine/input/Keyboard.hpp | CaptureTheBanana/CaptureTheBanana | 1398bedc80608e502c87b880c5b57d272236f229 | [
"MIT"
] | null | null | null | // This file is part of CaptureTheBanana++.
//
// Copyright (c) 2018 the CaptureTheBanana++ contributors (see CONTRIBUTORS.md)
// This file is licensed under the MIT license; see LICENSE file in the root of this
// project for details.
#ifndef _ENGINE_INPUT_KEYBOARD_HPP
#define _ENGINE_INPUT_KEYBOARD_HPP
#include <map>
#include <vector>
#include "engine/input/Input.hpp"
namespace ctb {
namespace engine {
/***
* A class to handle input from keyboard and mouse
*/
class Keyboard : public Input {
public:
/***
* Creates a Keyboard with given \ref window_h
*/
Keyboard();
~Keyboard() override = default;
/***
* Handles occuring mousemotion and -button events and calls corresponding
*
* @param event the occuring (mouse-)event, needed to access more
* specific information about the event
*/
void handleSdlEvent(const SDL_Event& event) override;
/***
* Name for rendering in the start menu
*
* @return An InputDeviceType to cast safely from Input (to Keyboard)
*/
InputDeviceType getType() override { return InputDeviceType::Keyboard; }
/***
* Handles occuring mousemotion and -button events
*
* @param event the occuring (mouse-)event, needed to access more
* specific information about the event
*/
void pollInput(const Uint8* keyStates) override;
private:
/// Map all key actions to input types.
std::map<InputType, std::vector<unsigned int>> m_keyMap;
};
} // namespace engine
} // namespace ctb
#endif
| 25.639344 | 84 | 0.674552 | CaptureTheBanana |
b14b78e560febd405419c52194930fdc606bc1fa | 373 | hpp | C++ | test/test_Defs.hpp | ToruNiina/AX | c99ddaa683dc94c7ec856a7cf1e10c0a6189951a | [
"MIT"
] | 1 | 2017-01-16T13:56:31.000Z | 2017-01-16T13:56:31.000Z | test/test_Defs.hpp | ToruNiina/AX | c99ddaa683dc94c7ec856a7cf1e10c0a6189951a | [
"MIT"
] | null | null | null | test/test_Defs.hpp | ToruNiina/AX | c99ddaa683dc94c7ec856a7cf1e10c0a6189951a | [
"MIT"
] | null | null | null | #ifndef AX_TEST_DEFINITIONS
#define AX_TEST_DEFINITIONS
#include <cstddef>
namespace ax
{
namespace test
{
constexpr static double tolerance = 1e-12;
constexpr static unsigned seed = 10;
constexpr static std::size_t Dim_N = 10;
constexpr static std::size_t Dim_M = 12;
}
}
#endif /* AX_TEST_DEFINITIONS */
| 21.941176 | 55 | 0.635389 | ToruNiina |
b151458cab7ed9a120ef68029ed8fb0bc5ad80aa | 1,352 | hpp | C++ | Include/Graphics/BackgroundPixelFetcher.hpp | ShannonHG/Modest-GB | f39851cd36bf0c752ce56c60783035e2bf2fd19c | [
"MIT"
] | 6 | 2022-01-25T06:55:00.000Z | 2022-01-25T18:39:25.000Z | Include/Graphics/BackgroundPixelFetcher.hpp | ShannonHG/Modest-GB | f39851cd36bf0c752ce56c60783035e2bf2fd19c | [
"MIT"
] | null | null | null | Include/Graphics/BackgroundPixelFetcher.hpp | ShannonHG/Modest-GB | f39851cd36bf0c752ce56c60783035e2bf2fd19c | [
"MIT"
] | 1 | 2022-01-25T08:09:54.000Z | 2022-01-25T08:09:54.000Z | #pragma once
#include "Graphics/PixelFetcher.hpp"
#include "Memory/Register8.hpp"
namespace ModestGB
{
enum class BackgroundPixelFetcherMode
{
Background,
Window
};
enum class BackgroundPixelFetcherState
{
FetchingTileIndex,
FetchingLowTileData,
FetchingHighTileData,
Sleeping,
PushingPixelsToQueue
};
class BackgroundPixelFetcher : public PixelFetcher
{
public:
BackgroundPixelFetcher(Memory& vram, Register8& lcdc, Register8& scx, Register8& scy, Register8& wx, Register8& wy);
void SetMode(BackgroundPixelFetcherMode mode);
BackgroundPixelFetcherMode GetCurrentMode();
void Tick() override;
void Reset() override;
private:
BackgroundPixelFetcherState currentState = BackgroundPixelFetcherState::FetchingTileIndex;
BackgroundPixelFetcherMode currentMode = BackgroundPixelFetcherMode::Background;
uint32_t currentStateElapsedCycles = 0;
uint8_t currentTileIndex = 0;
uint8_t currentLowTileData = 0;
uint8_t currentHighTileData = 0;
Register8* lcdc = nullptr;
Register8* scx = nullptr;
Register8* scy = nullptr;
Register8* wx = nullptr;
Register8* wy = nullptr;
Memory* vram = nullptr;
void UpdateTileIndexFetchState();
void UpdateLowTileDataFetchState();
void UpdateHighTileDataFetchState();
void UpdateSleepState();
void UpdatePixelPushState();
uint8_t GetAdjustedY();
};
} | 25.509434 | 118 | 0.775888 | ShannonHG |
b151bbf2073058974c3b3533eec78d77a8e848c3 | 751 | cpp | C++ | synth-mini-EQ.cpp | visualizersdotnl/FM-BISON | d212ab65bae16e208c4f67a38a63d0af44931cad | [
"MIT"
] | null | null | null | synth-mini-EQ.cpp | visualizersdotnl/FM-BISON | d212ab65bae16e208c4f67a38a63d0af44931cad | [
"MIT"
] | null | null | null | synth-mini-EQ.cpp | visualizersdotnl/FM-BISON | d212ab65bae16e208c4f67a38a63d0af44931cad | [
"MIT"
] | null | null | null |
/*
FM. BISON hybrid FM synthesis -- Mini EQ (3-band).
(C) njdewit technologies (visualizers.nl) & bipolaraudio.nl
MIT license applies, please see https://en.wikipedia.org/wiki/MIT_License or LICENSE in the project root!
*/
#include "synth-mini-EQ.h"
namespace SFM
{
void MiniEQ::SetTargetdBs(float bassdB, float trebledB, float middB /* = 0.f */)
{
SFM_ASSERT(bassdB >= kMiniEQMindB && bassdB <= kMiniEQMaxdB);
SFM_ASSERT(trebledB >= kMiniEQMindB && trebledB <= kMiniEQMaxdB);
SFM_ASSERT(middB >= kMiniEQMindB && middB <= kMiniEQMaxdB);
// FIXME: why?
bassdB += kEpsilon;
trebledB += kEpsilon;
middB += kEpsilon;
m_bassdB.SetTarget(bassdB);
m_trebledB.SetTarget(trebledB);
m_middB.SetTarget(middB);
}
}
| 26.821429 | 106 | 0.689747 | visualizersdotnl |
b15428c60d3d3b946774fc3d2b75850afb491b65 | 3,975 | cpp | C++ | test/functions.cpp | vincent-picaud/MissionImpossible | e21119b4ac42d2a6e914978aa91ba666611b42f8 | [
"MIT"
] | 15 | 2020-01-12T16:23:46.000Z | 2022-01-19T15:26:52.000Z | test/functions.cpp | vincent-picaud/MissionImpossible | e21119b4ac42d2a6e914978aa91ba666611b42f8 | [
"MIT"
] | null | null | null | test/functions.cpp | vincent-picaud/MissionImpossible | e21119b4ac42d2a6e914978aa91ba666611b42f8 | [
"MIT"
] | 2 | 2020-02-11T00:24:32.000Z | 2020-02-11T14:19:42.000Z | #include "MissionImpossible/functions.hpp"
#include "MissionImpossible/derivatives.hpp"
#include <gtest/gtest.h>
#include <cmath>
#include <vector>
using namespace MissionImpossible;
TEST(Function, abs)
{
AD<double> x = 3, y;
y = abs(2 * x);
auto grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), 6);
ASSERT_DOUBLE_EQ(grad[x], 2);
x = -3;
y = abs(2 * x);
grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), 6);
ASSERT_DOUBLE_EQ(grad[x], -2);
}
//////////////////////////////////////////////////////////////////
TEST(Function, min)
{
AD<double> x0 = 2, x1 = 3, y;
y = min(2 * x0, x0 + x1);
auto grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), 4);
ASSERT_DOUBLE_EQ(grad[x0], 2);
ASSERT_DOUBLE_EQ(grad[x1], 0);
y = min(4, x0 + x1);
grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), 4);
ASSERT_DOUBLE_EQ(grad[x0], 0);
ASSERT_DOUBLE_EQ(grad[x1], 0);
y = min(10, 2 * x0 + x1);
grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), 7);
ASSERT_DOUBLE_EQ(grad[x0], 2);
ASSERT_DOUBLE_EQ(grad[x1], 1);
// y = max(2 * x0, x0 + x1);
// grad = gradient(y);
// ASSERT_DOUBLE_EQ(y.value(), 4);
// ASSERT_DOUBLE_EQ(grad[x0], 2);
// ASSERT_DOUBLE_EQ(grad[x1], 0);
}
TEST(Function, max)
{
AD<double> x0 = 2, x1 = 3, y;
y = max(2 * x0, x0 + 2 * x1);
auto grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), 8);
ASSERT_DOUBLE_EQ(grad[x0], 1);
ASSERT_DOUBLE_EQ(grad[x1], 2);
y = max(6, x0 + x1);
grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), 6);
ASSERT_DOUBLE_EQ(grad[x0], 0);
ASSERT_DOUBLE_EQ(grad[x1], 0);
y = max(1, 2 * x0 + x1);
grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), 7);
ASSERT_DOUBLE_EQ(grad[x0], 2);
ASSERT_DOUBLE_EQ(grad[x1], 1);
}
//////////////////////////////////////////////////////////////////
TEST(Function, pow)
{
AD<double> x = 2, y;
y = pow(x, 3);
auto grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), pow(x.value(), 3));
ASSERT_DOUBLE_EQ(grad[x], 3 * pow(x.value(), 2));
}
TEST(Function, exp)
{
AD<double> x = 2, y;
y = exp(x);
auto grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), exp(x.value()));
ASSERT_DOUBLE_EQ(grad[x], exp(x.value()));
}
TEST(Function, log_exp)
{
AD<double> x = 2, y;
y = log(exp(x));
auto grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), x.value());
ASSERT_DOUBLE_EQ(grad[x], 1);
}
TEST(Function, sin)
{
AD<double> x = 2, y;
y = sin(x);
auto grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), sin(x.value()));
ASSERT_DOUBLE_EQ(grad[x], cos(x.value()));
}
TEST(Function, cos)
{
AD<double> x = 2, y;
y = cos(x);
auto grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), cos(x.value()));
ASSERT_DOUBLE_EQ(grad[x], -sin(x.value()));
}
TEST(Function, tan)
{
AD<double> x = 2, y;
y = tan(x);
auto grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), tan(x.value()));
ASSERT_DOUBLE_EQ(grad[x], 1 / pow(cos(x.value()), 2));
}
TEST(Function, exp_sin)
{
AD<double> x = 2, y;
y = exp(sin(x)) * exp(x);
auto grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), exp(sin(x.value())) * exp(x.value()));
ASSERT_DOUBLE_EQ(grad[x], exp(x.value() + sin(x.value())) * (1 + cos(x.value())));
}
//////////////////////////////////////////////////////////////////
TEST(Function, sigmoid)
{
AD<double> x = 2, y;
y = 1 / (1 + exp(-x));
auto grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), 1 / (1 + exp(-x.value())));
ASSERT_DOUBLE_EQ(grad[x], exp(-x.value()) / pow(1 + exp(-x.value()), 2));
}
//////////////////////////////////////////////////////////////////
TEST(Function, sqrt)
{
AD<double> x = 3, y;
y = sqrt(x * x);
auto grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), 3);
ASSERT_DOUBLE_EQ(grad[x], 1);
x = -3;
y = sqrt(x * x);
grad = gradient(y);
ASSERT_DOUBLE_EQ(y.value(), 3);
ASSERT_DOUBLE_EQ(grad[x], -1);
}
| 22.206704 | 84 | 0.535094 | vincent-picaud |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.