blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
80f2385ba7a65c0a7cd0a45d2dcc7518d6e7b4eb | ac62cdceb0860477a115b787d03559396164fd57 | /EPG.h | 3c780104eba5f03cd65e6f4c481debaf20a3fa16 | [] | no_license | nmickevicius/epgSim | f03e32406222ea1ece2d581c808bc97c6c998b2e | 2d9455b6d541ecf719988971d84fad8c31a7a916 | refs/heads/master | 2022-12-02T01:53:21.521653 | 2020-08-06T13:07:35 | 2020-08-06T13:07:35 | 285,573,135 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,294 | h | #ifndef EPG_H
#define EPG_H
#endif
#include <iostream>
#include <complex>
using namespace std;
class EPG {
int nrf; // maximum number of states
int nstates;
int idxF0;
int nz; // number of points along slice-select axis
complex<float>** T; // RF transition state operator
public:
// constructor
EPG(int, int, int);
// apply RF transition operator
void rf(complex<float>***, float*, float);
// overloaded apply RF transition operator
void rf(complex<float>***, float*, float, int, int);
// apply relaxation and recovery
void relax(complex<float>***, float, float, float);
// overloaded relaxation and recovery method
void relax(complex<float>***, float, float, float, int, int);
// apply diffusion operator
void diffusion(complex<float>***, float, float, float, float);
// overloaded diffusion operator
void diffusion(complex<float>***, float, float, float, float, int, int);
// dephasing/crushing/shifting operator
void dephase(complex<float>***, int);
// overloaded dephasing operator
void dephase(complex<float>***, int, int, int);
// sum F0 signal over slice profile
complex<float> F0(complex<float>***);
// get maximum number of states
int getNumStates();
// get index to Z(k=0)
int getIdxZ0();
// get k=0 index
int getIdxK0();
// destructor
~EPG();
private:
// complex-valued matrix multiplication
void mtimes(complex<float>**, complex<float>**, complex<float>**, int, int, int);
// overloaded complex-valued matrix multiplication
void mtimes(complex<float>**, complex<float>**, complex<float>**, int, int, int, int, int);
// build RF transition operator
void buildRF(float, float);
// dephasing with "positive" crusher gradient
void dephasePlus(complex<float>**, complex<float>**, int);
// overloaded dephasing with "positive" crusher gradient
void dephasePlus(complex<float>**, complex<float>**, int, int, int);
// dephasing with "negative" crusher gradient
void dephaseMinus(complex<float>**, complex<float>**, int);
// overloaded dephasing with "negative" crusher gradient
void dephaseMinus(complex<float>**, complex<float>**, int, int, int);
}; // end of EPG class
| [
"[email protected]"
] | |
4ab6e0bba9eaa6d53f6ba77709529bceaf57cbec | 067690553cf7fa81b5911e8dd4fb405baa96b5b7 | /1076/1076.cpp | 0ec8c556d28abfff4a7f9dd015c0e22f4f8bb3de | [
"MIT"
] | permissive | isac322/BOJ | 4c79aab453c884cb253e7567002fc00e605bc69a | 35959dd1a63d75ebca9ed606051f7a649d5c0c7b | refs/heads/master | 2021-04-18T22:30:05.273182 | 2019-02-21T11:36:58 | 2019-02-21T11:36:58 | 43,806,421 | 14 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 613 | cpp | #include <cstdio>
using namespace std;
const int arr[] = { 1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000 };
char str[9];
int get() {
switch (str[0]) {
case 'b':
switch (str[1]) {
case 'l':
if (str[2] == 'a') return 0;
else return 6;
case 'r':
return 1;
}
case 'r': return 2;
case 'o': return 3;
case 'y': return 4;
case 'g':
if (str[3] == 'y') return 8;
else return 5;
case 'v': return 7;
case 'w': return 9;
}
}
int main() {
gets(str);
long long a = get();
gets(str);
a = a * 10 + get();
gets(str);
printf("%lld", a*arr[get()]);
} | [
"[email protected]"
] | |
0f8ad27505c328f25193aa611e8e3794b5fde220 | ca539e64fef0b2525f01511f1e8482881918d199 | /cfiles/sumskipnan.cpp | b8c2d024ececbdf7c15ba10ae84922e12e37aec7 | [] | no_license | eko222/nm | ec776eeaf1b7ce91b48d6cb1feaaaf7fb6379ca7 | 77bed01b224fba22d0d1d95dd1e2ef725f1e9c43 | refs/heads/master | 2023-04-23T15:06:07.277242 | 2021-05-12T22:18:49 | 2021-05-12T22:18:49 | 366,855,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,642 | cpp | //-------------------------------------------------------------------
#pragma hdrstop
//-------------------------------------------------------------------
// C-MEX implementation of SUMSKIPNAN - this function is part of the NaN-toolbox.
//
// 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 2 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, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//
// sumskipnan: sums all non-NaN values
//
// Input:
// - array to sum
// - dimension to sum (1=columns; 2=rows; doesn't work for dim>2!!)
//
// Output:
// - sums
// - count of valid elements (optional)
// - sums of squares (optional)
// - sums of squares of squares (optional)
//
// Author: Patrick Houweling ([email protected])
// Version: 1.0
// Date: 17 september 2003
//
// modified:
// Alois Schloegl <[email protected]>
// $Revision: 1.1 $
// $Id: sumskipnan.cpp,v 1.1 2003/10/31 18:13:28 schloegl Exp $
//
//-------------------------------------------------------------------
//#include <stdlib>
#include <math.h>
#include "mex.h"
//-------------------------------------------------------------------
void mexFunction(int POutputCount, mxArray* POutput[], int PInputCount, const mxArray *PInputs[])
{
const int *SZ;
double* LInput;
double* LInputI;
double* LOutputSum;
double* LOutputSumI;
double* LOutputCount;
double* LOutputSum2;
double* LOutputSum4;
double x, x2;
unsigned long LCount, LCountI;
double LSum, LSum2, LSum4;
unsigned DIM = 0;
unsigned long D1, D2, D3; // NN; //
unsigned ND, ND2; // number of dimensions: input, output
unsigned long ix1, ix2; // index to input and output
unsigned j, k, l; // running indices
int *SZ2; // size of output
// check for proper number of input and output arguments
if ((PInputCount <= 0) || (PInputCount > 2))
mexErrMsgTxt("SumSkipNan.MEX requires 1 or 2 arguments.");
if (POutputCount > 4)
mexErrMsgTxt("SumSkipNan.MEX has 1 to 4 output arguments.");
// get 1st argument
if(!mxIsNumeric(PInputs[0]))
mexErrMsgTxt("First argument must be NUMERIC.");
if(!mxIsDouble(PInputs[0]))
mexErrMsgTxt("First argument must be DOUBLE.");
if(mxIsComplex(PInputs[0]) & (POutputCount > 3))
mexErrMsgTxt("More than 3 output arguments only supported for REAL data ");
LInput = mxGetPr(PInputs[0]);
// get 2nd argument
if (PInputCount == 2){
switch (mxGetNumberOfElements(PInputs[1])) {
case 0: x = 0.0; // accept empty element
break;
case 1: x = (mxIsNumeric(PInputs[1]) ? mxGetScalar(PInputs[1]) : -1.0);
break;
default:x = -1.0; // invalid
}
if ((x < 0) || (x > 65535) || (x != floor(x)))
mexErrMsgTxt("Error SUMSKIPNAN.MEX: DIM-argument must be a positive integer scalar");
DIM = (unsigned)floor(x);
}
// get size
ND = mxGetNumberOfDimensions(PInputs[0]);
// NN = mxGetNumberOfElements(PInputs[0]);
SZ = mxGetDimensions(PInputs[0]);
// if DIM==0 (undefined), look for first dimension with more than 1 element.
for (k = 0; (DIM < 1) && (k < ND); k++)
if (SZ[k]>1) DIM = k+1;
if (DIM < 1) DIM=1; // in case DIM is still undefined
ND2 = (ND>DIM ? ND : DIM); // number of dimensions of output
SZ2 = (int*)mxCalloc(ND2, sizeof(int)); // allocate memory for output size
for (j=0; j<ND; j++) // copy size of input;
SZ2[j] = SZ[j];
for (j=ND; j<ND2; j++) // in case DIM > ND, add extra elements 1
SZ2[j] = 1;
for (j=0, D1=1; j<DIM-1; D1=D1*SZ2[j++]); // D1 is the number of elements between two elements along dimension DIM
D2 = SZ2[DIM-1]; // D2 contains the size along dimension DIM
for (j=DIM, D3=1; j<ND; D3=D3*SZ2[j++]); // D3 is the number of blocks containing D1*D2 elements
SZ2[DIM-1] = 1; // size of output is same as size of input but SZ(DIM)=1;
// create outputs
#define TYP mxDOUBLE_CLASS
if(mxIsComplex(PInputs[0]))
{ POutput[0] = mxCreateNumericArray(ND2, SZ2, TYP, mxCOMPLEX);
LOutputSum = mxGetPr(POutput[0]);
LOutputSumI= mxGetPi(POutput[0]);
LInputI = mxGetPi(PInputs[0]);
}
else
{ POutput[0] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
LOutputSum = mxGetPr(POutput[0]);
}
if (POutputCount >= 2){
POutput[1] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
LOutputCount = mxGetPr(POutput[1]);
}
if (POutputCount >= 3){
POutput[2] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
LOutputSum2 = mxGetPr(POutput[2]);
}
if (POutputCount >= 4){
POutput[3] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
LOutputSum4 = mxGetPr(POutput[3]);
}
mxFree(SZ2);
// OUTER LOOP: along dimensions > DIM
for (l = 0; l<D3; l++)
{
ix2 = l*D1; // index for output
ix1 = ix2*D2; // index for input
// Inner LOOP: along dimensions < DIM
for (k = 0; k<D1; k++, ix1++, ix2++)
{
LCount = 0;
LSum = 0.0;
LSum2 = 0.0;
LSum4 = 0.0;
// LOOP along dimension DIM
for (j=0; j<D2; j++)
{
x = LInput[ix1 + j*D1];
if (!mxIsNaN(x))
{
LCount++;
LSum += x;
x2 = x*x;
LSum2 += x2;
LSum4 += x2*x2;
}
}
LOutputSum[ix2] = LSum;
if (POutputCount >= 2)
LOutputCount[ix2] = (double)LCount;
if (POutputCount >= 3)
LOutputSum2[ix2] = LSum2;
if (POutputCount >= 4)
LOutputSum4[ix2] = LSum4;
if(mxIsComplex(PInputs[0]))
{
LSum = 0.0;
LCountI = 0;
LSum2 = 0.0;
for (j=0; j<D2; j++)
{
x = LInputI[ix1 + j*D1];
if (!mxIsNaN(x))
{
LCountI++;
LSum += x;
LSum2 += x*x;
}
}
LOutputSumI[ix2] = LSum;
if (LCount != LCountI)
mexErrMsgTxt("Number of NaNs is different for REAL and IMAG part");
if (POutputCount >= 3)
LOutputSum2[ix2] += LSum2;
}
}
}
}
| [
"[email protected]"
] | |
07db102e8ba3cd377d571dac137a880ab0afbe8b | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /chrome/browser/ui/views/web_apps/web_app_integration_browsertest_win_linux.cc | 0010c7bfa601deedbfb141c54dd541cceabf178f | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 30,059 | cc | // Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/web_apps/web_app_integration_test_driver.h"
#include "content/public/test/browser_test.h"
namespace web_app::integration_tests {
namespace {
using WebAppIntegration = WebAppIntegrationTest;
// Manual tests:
// Generated tests:
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_29NotPromotableWindowed_12NotPromotable_7NotPromotable_1NotPromotable_24) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.CreateShortcut(Site::kNotPromotable, WindowOptions::kWindowed);
helper_.CheckAppInListWindowed(Site::kNotPromotable);
helper_.CheckPlatformShortcutAndIcon(Site::kNotPromotable);
helper_.LaunchFromPlatformShortcut(Site::kNotPromotable);
helper_.CheckWindowCreated();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_31Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_1Standalone_79StandaloneStandaloneOriginal_24_26) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallOmniboxIcon(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckWindowDisplayStandalone();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_31Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_149Standalone_11Standalone_1Standalone_22One_163Standalone) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallOmniboxIcon(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.SetOpenInTabFromAppSettings(Site::kStandalone);
helper_.CheckAppInListTabbed(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckTabCreated(Number::kOne);
helper_.CheckAppLoadedInTab(Site::kStandalone);
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_31Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_147Standalone_11Standalone_1Standalone_22One_163Standalone) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallOmniboxIcon(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.SetOpenInTabFromAppHome(Site::kStandalone);
helper_.CheckAppInListTabbed(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckTabCreated(Number::kOne);
helper_.CheckAppLoadedInTab(Site::kStandalone);
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_31Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_74Standalone_72Standalone_1Standalone_24) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallOmniboxIcon(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.DeletePlatformShortcut(Site::kStandalone);
helper_.CreateShortcutsFromList(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_31Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_32StandaloneNoShortcutBrowserWebApp_7Standalone_12Standalone_1Standalone_24) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallOmniboxIcon(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.InstallPolicyApp(Site::kStandalone, ShortcutOptions::kNoShortcut,
WindowOptions::kBrowser, InstallMode::kWebApp);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_31Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_32StandaloneWithShortcutBrowserWebApp_12Standalone_1Standalone_24) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallOmniboxIcon(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.InstallPolicyApp(Site::kStandalone, ShortcutOptions::kWithShortcut,
WindowOptions::kBrowser, InstallMode::kWebApp);
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_31Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_116StandaloneBrowser_117Standalone_1Standalone_24_94_25) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallOmniboxIcon(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.ManifestUpdateDisplay(Site::kStandalone, Display::kBrowser);
helper_.AwaitManifestUpdate(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
helper_.CheckTabNotCreated();
helper_.CheckWindowDisplayMinimal();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_31Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_116StandaloneMinimalUi_117Standalone_1Standalone_24_94_25) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallOmniboxIcon(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.ManifestUpdateDisplay(Site::kStandalone, Display::kMinimalUi);
helper_.AwaitManifestUpdate(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
helper_.CheckTabNotCreated();
helper_.CheckWindowDisplayMinimal();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_47Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_1Standalone_79StandaloneStandaloneOriginal_24_26) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallMenuOption(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckWindowDisplayStandalone();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_47Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_149Standalone_11Standalone_1Standalone_22One_163Standalone) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallMenuOption(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.SetOpenInTabFromAppSettings(Site::kStandalone);
helper_.CheckAppInListTabbed(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckTabCreated(Number::kOne);
helper_.CheckAppLoadedInTab(Site::kStandalone);
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_47Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_147Standalone_11Standalone_1Standalone_22One_163Standalone) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallMenuOption(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.SetOpenInTabFromAppHome(Site::kStandalone);
helper_.CheckAppInListTabbed(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckTabCreated(Number::kOne);
helper_.CheckAppLoadedInTab(Site::kStandalone);
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_47Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_74Standalone_72Standalone_1Standalone_24) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallMenuOption(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.DeletePlatformShortcut(Site::kStandalone);
helper_.CreateShortcutsFromList(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_47Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_32StandaloneNoShortcutBrowserWebApp_7Standalone_12Standalone_1Standalone_24) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallMenuOption(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.InstallPolicyApp(Site::kStandalone, ShortcutOptions::kNoShortcut,
WindowOptions::kBrowser, InstallMode::kWebApp);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_47Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_32StandaloneWithShortcutBrowserWebApp_12Standalone_1Standalone_24) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallMenuOption(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.InstallPolicyApp(Site::kStandalone, ShortcutOptions::kWithShortcut,
WindowOptions::kBrowser, InstallMode::kWebApp);
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_47Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_116StandaloneBrowser_117Standalone_1Standalone_24_94_25) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallMenuOption(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.ManifestUpdateDisplay(Site::kStandalone, Display::kBrowser);
helper_.AwaitManifestUpdate(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
helper_.CheckTabNotCreated();
helper_.CheckWindowDisplayMinimal();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_47Standalone_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_116StandaloneMinimalUi_117Standalone_1Standalone_24_94_25) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallMenuOption(InstallableSite::kStandalone);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.ManifestUpdateDisplay(Site::kStandalone, Display::kMinimalUi);
helper_.AwaitManifestUpdate(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
helper_.CheckTabNotCreated();
helper_.CheckWindowDisplayMinimal();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_32StandaloneWithShortcutWindowedWebApp_79StandaloneStandaloneOriginal_12Standalone_7Standalone_116StandaloneBrowser_117Standalone_1Standalone_24_94_25) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallPolicyApp(Site::kStandalone, ShortcutOptions::kWithShortcut,
WindowOptions::kWindowed, InstallMode::kWebApp);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.ManifestUpdateDisplay(Site::kStandalone, Display::kBrowser);
helper_.AwaitManifestUpdate(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
helper_.CheckTabNotCreated();
helper_.CheckWindowDisplayMinimal();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_32StandaloneWithShortcutWindowedWebApp_79StandaloneStandaloneOriginal_12Standalone_7Standalone_116StandaloneMinimalUi_117Standalone_1Standalone_24_94_25) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.InstallPolicyApp(Site::kStandalone, ShortcutOptions::kWithShortcut,
WindowOptions::kWindowed, InstallMode::kWebApp);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.ManifestUpdateDisplay(Site::kStandalone, Display::kMinimalUi);
helper_.AwaitManifestUpdate(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
helper_.CheckTabNotCreated();
helper_.CheckWindowDisplayMinimal();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_29StandaloneWindowed_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_1Standalone_24_26) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.CreateShortcut(Site::kStandalone, WindowOptions::kWindowed);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
helper_.CheckWindowDisplayStandalone();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_29StandaloneWindowed_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_149Standalone_11Standalone_1Standalone_22One_163Standalone) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.CreateShortcut(Site::kStandalone, WindowOptions::kWindowed);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.SetOpenInTabFromAppSettings(Site::kStandalone);
helper_.CheckAppInListTabbed(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckTabCreated(Number::kOne);
helper_.CheckAppLoadedInTab(Site::kStandalone);
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_29StandaloneWindowed_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_147Standalone_11Standalone_1Standalone_22One_163Standalone) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.CreateShortcut(Site::kStandalone, WindowOptions::kWindowed);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.SetOpenInTabFromAppHome(Site::kStandalone);
helper_.CheckAppInListTabbed(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckTabCreated(Number::kOne);
helper_.CheckAppLoadedInTab(Site::kStandalone);
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_29StandaloneWindowed_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_74Standalone_72Standalone_1Standalone_24) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.CreateShortcut(Site::kStandalone, WindowOptions::kWindowed);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.DeletePlatformShortcut(Site::kStandalone);
helper_.CreateShortcutsFromList(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_29StandaloneWindowed_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_32StandaloneNoShortcutBrowserWebApp_7Standalone_12Standalone_1Standalone_24) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.CreateShortcut(Site::kStandalone, WindowOptions::kWindowed);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.InstallPolicyApp(Site::kStandalone, ShortcutOptions::kNoShortcut,
WindowOptions::kBrowser, InstallMode::kWebApp);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_29StandaloneWindowed_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_32StandaloneWithShortcutBrowserWebApp_12Standalone_1Standalone_24) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.CreateShortcut(Site::kStandalone, WindowOptions::kWindowed);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.InstallPolicyApp(Site::kStandalone, ShortcutOptions::kWithShortcut,
WindowOptions::kBrowser, InstallMode::kWebApp);
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_29StandaloneWindowed_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_116StandaloneBrowser_117Standalone_1Standalone_24_94_25) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.CreateShortcut(Site::kStandalone, WindowOptions::kWindowed);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.ManifestUpdateDisplay(Site::kStandalone, Display::kBrowser);
helper_.AwaitManifestUpdate(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
helper_.CheckTabNotCreated();
helper_.CheckWindowDisplayMinimal();
}
IN_PROC_BROWSER_TEST_F(
WebAppIntegration,
WAI_29StandaloneWindowed_79StandaloneStandaloneOriginal_24_12Standalone_7Standalone_112StandaloneNotShown_116StandaloneMinimalUi_117Standalone_1Standalone_24_94_25) {
// Test contents are generated by script. Please do not modify!
// See `docs/webapps/why-is-this-test-failing.md` or
// `docs/webapps/integration-testing-framework` for more info.
// Sheriffs: Disabling this test is supported.
helper_.CreateShortcut(Site::kStandalone, WindowOptions::kWindowed);
helper_.CheckAppTitle(Site::kStandalone, Title::kStandaloneOriginal);
helper_.CheckWindowCreated();
helper_.CheckAppInListWindowed(Site::kStandalone);
helper_.CheckPlatformShortcutAndIcon(Site::kStandalone);
helper_.CheckWindowControlsOverlayToggle(Site::kStandalone,
IsShown::kNotShown);
helper_.ManifestUpdateDisplay(Site::kStandalone, Display::kMinimalUi);
helper_.AwaitManifestUpdate(Site::kStandalone);
helper_.LaunchFromPlatformShortcut(Site::kStandalone);
helper_.CheckWindowCreated();
helper_.CheckTabNotCreated();
helper_.CheckWindowDisplayMinimal();
}
} // namespace
} // namespace web_app::integration_tests
| [
"[email protected]"
] | |
4f798ec2e6642a90764beff22ec8f76cc2c194ec | 96cfaaa771c2d83fc0729d8c65c4d4707235531a | /OnlineDB/ESCondDB/src/ODScanCycle.cc | b7064ee8b216484af91eed41a5da5324c8366e92 | [] | no_license | khotilov/cmssw | a22a160023c7ce0e4d59d15ef1f1532d7227a586 | 7636f72278ee0796d0203ac113b492b39da33528 | refs/heads/master | 2021-01-15T18:51:30.061124 | 2013-04-20T17:18:07 | 2013-04-20T17:18:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,533 | cc | #include <stdexcept>
#include "OnlineDB/Oracle/interface/Oracle.h"
#include "OnlineDB/ESCondDB/interface/ODScanCycle.h"
using namespace std;
using namespace oracle::occi;
ODScanCycle::ODScanCycle()
{
m_env = NULL;
m_conn = NULL;
m_writeStmt = NULL;
m_readStmt = NULL;
//
m_ID = 0;
m_scan_config_id = 0;
}
ODScanCycle::~ODScanCycle()
{
}
void ODScanCycle::prepareWrite()
throw(runtime_error)
{
this->checkConnection();
try {
m_writeStmt = m_conn->createStatement();
m_writeStmt->setSQL("INSERT INTO Es_Scan_Cycle (cycle_id, scan_id ) "
"VALUES (:1, :2 )");
} catch (SQLException &e) {
throw(runtime_error("ODScanCycle::prepareWrite(): "+e.getMessage()));
}
}
void ODScanCycle::writeDB() throw(runtime_error)
{
this->checkConnection();
this->checkPrepare();
try {
m_writeStmt->setInt(1, this->getId());
m_writeStmt->setInt(2, this->getScanConfigurationID());
m_writeStmt->executeUpdate();
} catch (SQLException &e) {
throw(runtime_error("ODScanCycle::writeDB: "+e.getMessage()));
}
// Now get the ID
if (!this->fetchID()) {
throw(runtime_error("ODScanCycle::writeDB: Failed to write"));
}
}
void ODScanCycle::clear(){
m_scan_config_id=0;
}
int ODScanCycle::fetchID()
throw(runtime_error)
{
// Return from memory if available
if (m_ID) {
return m_ID;
}
this->checkConnection();
try {
Statement* stmt = m_conn->createStatement();
stmt->setSQL("SELECT cycle_id, scan_id FROM es_scan_cycle "
"WHERE cycle_id = :1 ");
stmt->setInt(1, m_ID);
ResultSet* rset = stmt->executeQuery();
if (rset->next()) {
m_ID = rset->getInt(1);
m_scan_config_id = rset->getInt(2);
} else {
m_ID = 0;
}
m_conn->terminateStatement(stmt);
} catch (SQLException &e) {
throw(runtime_error("ODScanCycle::fetchID: "+e.getMessage()));
}
return m_ID;
}
void ODScanCycle::setByID(int id)
throw(std::runtime_error)
{
this->checkConnection();
try {
Statement* stmt = m_conn->createStatement();
stmt->setSQL("SELECT cycle_id, scan_configuration_id FROM es_scan_cycle "
"WHERE cycle_id = :1 ");
stmt->setInt(1, id);
ResultSet* rset = stmt->executeQuery();
if (rset->next()) {
m_ID = rset->getInt(1);
m_scan_config_id = rset->getInt(2);
} else {
m_ID = 0;
}
m_conn->terminateStatement(stmt);
} catch (SQLException &e) {
throw(runtime_error("ODScanCycle::fetchID: "+e.getMessage()));
}
}
void ODScanCycle::fetchData(ODScanCycle * result)
throw(runtime_error)
{
this->checkConnection();
result->clear();
if(result->getId()==0){
throw(runtime_error("ODScanConfig::fetchData(): no Id defined for this ODScanConfig "));
}
try {
m_readStmt->setSQL("SELECT scan_configuration_id FROM es_scan_cycle "
"WHERE cycle_id = :1 ");
m_readStmt->setInt(1, result->getId());
ResultSet* rset = m_readStmt->executeQuery();
rset->next();
result->setScanConfigurationID( rset->getInt(1) );
} catch (SQLException &e) {
throw(runtime_error("ODScanCycle::fetchData(): "+e.getMessage()));
}
}
void ODScanCycle::insertConfig()
throw(std::runtime_error)
{
try {
prepareWrite();
writeDB();
m_conn->commit();
terminateWriteStatement();
} catch (std::runtime_error &e) {
m_conn->rollback();
throw(e);
} catch (...) {
m_conn->rollback();
throw(std::runtime_error("ESCondDBInterface::insertDataSet: Unknown exception caught"));
}
}
| [
"[email protected]"
] | |
d1b02607d927ebbad8db83b372ced7f9b545fb58 | 428c5d8bdf6a9ba1a051c22c96830858593521b9 | /relations/Item.cpp | 620c424d116cbe2cfac355dfc63a44ce52cce739 | [] | no_license | annn31051984/bcw4.04.10.2020 | 04f9bef708150c67aec826a9105442802386c273 | 1629cdfb463ae3da614b4237b0272c04844e9eda | refs/heads/master | 2022-12-26T05:07:43.728451 | 2020-10-04T16:57:21 | 2020-10-04T16:57:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 856 | cpp | #include "Item.h"
Item::Item(const char* title, double price, Category* category)
: title(title), price(price), category(category) {
this->category->addItem(this);
}
Item::~Item() {
this->category->removeItem(this);
}
const char* Item::getTitle() const {
return this->title;
}
double Item::getPrice() const {
return this->price;
}
const Category& Item::getCategory() const {
return *(this->category);
}
void Item::setTitle(const char* title) {
this->title = title;
}
void Item::setPrice(double price) {
this->price = price;
}
void Item::setCategory(Category* category) {
this->category = category;
}
std::ostream& operator<<(std::ostream& out, const Item& item) {
out << item.getTitle() << "(";
out << item.getCategory().getTitle() << ", ";
out << item.getPrice() << ")";
return out;
}
| [
"[email protected]"
] | |
df84cde7112528509da462c8bce61c8b5a866532 | df6a7072020c0cce62a2362761f01c08f1375be7 | /doc/quickbook/oglplus/quickref/enums/debug_output_source_class.hpp | 4daebeb850ee7a22861afc41c971e13021819f4e | [
"BSL-1.0"
] | permissive | matus-chochlik/oglplus | aa03676bfd74c9877d16256dc2dcabcc034bffb0 | 76dd964e590967ff13ddff8945e9dcf355e0c952 | refs/heads/develop | 2023-03-07T07:08:31.615190 | 2021-10-26T06:11:43 | 2021-10-26T06:11:43 | 8,885,160 | 368 | 58 | BSL-1.0 | 2018-09-21T16:57:52 | 2013-03-19T17:52:30 | C++ | UTF-8 | C++ | false | false | 1,270 | hpp | // File doc/quickbook/oglplus/quickref/enums/debug_output_source_class.hpp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/debug_output_source.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2019 Matus Chochlik.
// 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
//
//[oglplus_enums_debug_output_source_class
#if !__OGLPLUS_NO_ENUM_VALUE_CLASSES
namespace enums {
template <typename Base, template <__DebugOutputSource> class Transform>
class __EnumToClass<Base, __DebugOutputSource, Transform> /*<
Specialization of __EnumToClass for the __DebugOutputSource enumeration.
>*/
: public Base {
public:
EnumToClass();
EnumToClass(Base&& base);
Transform<DebugOutputSource::API> API;
Transform<DebugOutputSource::WindowSystem> WindowSystem;
Transform<DebugOutputSource::ShaderCompiler> ShaderCompiler;
Transform<DebugOutputSource::ThirdParty> ThirdParty;
Transform<DebugOutputSource::Application> Application;
Transform<DebugOutputSource::Other> Other;
Transform<DebugOutputSource::DontCare> DontCare;
};
} // namespace enums
#endif
//]
| [
"[email protected]"
] | |
6ed6cc15292a021cb95aa9be3e707a27e21a9ee1 | adad161dfff829f10aaf5e41a49d9f4ef5275857 | /top_down_test/grid_datastructure.cpp | 7d6f33148ea35a60af98a418968ab6c7cf4c06dd | [] | no_license | rmitra/Masters-Project | e8ec19dcda1c9ec2845ba546c36cc691fc0438c0 | 62109d29a53f23dcec5089c8969cad754a13dab7 | refs/heads/master | 2020-04-30T07:40:44.510278 | 2015-01-22T17:33:40 | 2015-01-22T17:33:40 | 23,255,696 | 5 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 6,968 | cpp | #include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
/* point cloud header fils */
#include <pcl/io/pcd_io.h>
#include <pcl/io/ply_io.h>
#include <pcl/point_types.h>
/* end of header files */
#ifndef GRID_HEADER
#define GRID_HEADER
#define EPS 0.001
using namespace std;
class grid_element { // element for every grid node
public:
pcl::PointCloud<pcl::PointXYZ>::Ptr p_list; // list of those points.
pcl::PointCloud<pcl::Normal>::Ptr n_list; // list of normals.
//int rep[3];
bool used;
grid_element(){ // constructor
p_list = pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>);
n_list = pcl::PointCloud<pcl::Normal>::Ptr(new pcl::PointCloud<pcl::Normal>);
used = false;
}
/*void setRep(int x, int y, int z){
rep[0] = x;
rep[1] = y;
rep[2] = z;
}*/
};
class grid {
public:
// pcl::PointXYZ resolution; // dimension of a cubical voxel
double resolution;
grid_element *** data;
int length, width, height; // dimension of the grid
pcl::PointXYZ ref_point; // here the min point is taken as the reference point
/* Constructor taking resolution and min and max point of the point cloud
and determines the no. voxels in length, width and height.
*/
grid(pcl::PointXYZ res, pcl::PointXYZ minPoint, pcl::PointXYZ maxPoint){
// resolution = res;
if(res.x < res.y){
if(res.x < res.z)
resolution = res.x;
else
resolution = res.z;
}
else{
if(res.y < res.z)
resolution = res.y;
else
resolution = res.z;
}
// double xdiff_int = (int)( ((maxPoint.x - minPoint.x)/resolution) + 1.0f );
// double xdiff = (maxPoint.x - minPoint.x)/resolution;
//if( xdiff_int - xdiff < 0.00001f)
// length = (int)( ((maxPoint.x - minPoint.x)/resolution) + 1.5f);
//else
length = (int)( ((maxPoint.x - minPoint.x)/resolution) + 1.0f);
// double ydiff_int = (int)( ((maxPoint.y - minPoint.y)/resolution) + 1.0f );
// double ydiff = (maxPoint.y - minPoint.y)/resolution;
//if( ydiff_int - ydiff < 0.00001f)
// width = (int)( ((maxPoint.y - minPoint.y)/resolution) + 1.5f);
//else
width = (int)( ((maxPoint.y - minPoint.y)/resolution) + 1.0f);
// double zdiff_int = (int)( ((maxPoint.z - minPoint.z)/resolution) + 1.0f );
// double zdiff = (maxPoint.z - minPoint.z)/resolution;
//if( zdiff_int - zdiff < 0.00001f)
// height = (int)( ((maxPoint.z - minPoint.z)/resolution) + 1.5f);
//else
height = (int)( ((maxPoint.z - minPoint.z)/resolution) + 1.0f);
data = new grid_element** [length];
for(int i = 0; i < length; i++)
{
data[i] = new grid_element* [width];
for( int j = 0; j < width; j++)
data[i][j] = new grid_element[height];
}
ref_point = minPoint;
}
void display_dimensions(){
cout<<"Length: "<<length<<endl;
cout<<"Width: "<<width<<endl;
cout<<"Height: "<<height<<endl;
cout<<"Resolution: "<<resolution<<"\n"; //<<" "<<resolution.y<<" "<<resolution.z<<endl<<endl;
cout<<"Ref Point: x: "<<ref_point.x<<endl;
cout<<"Ref Point: y: "<<ref_point.y<<endl;
cout<<"Ref Point: z: "<<ref_point.z<<endl;
}
/* function allocates a points of a cloud to a voxel in the grid
* Input point cloud
*/
void allocate_points_to_grid( pcl::PointCloud<pcl::PointXYZ> cloud, pcl::PointCloud<pcl::Normal> cloud_normals ){
double xdiff, ydiff, zdiff;
int xindex, yindex, zindex;
for(int i = 0; i < cloud.points.size(); i++){
xdiff = (cloud.points[i].x - ref_point.x)/resolution ;
ydiff = (cloud.points[i].y - ref_point.y)/resolution ;
zdiff = (cloud.points[i].z - ref_point.z)/resolution ;
xindex = (int)(xdiff); // + 1.0f);
yindex = (int)(ydiff); // + 1.0f);
zindex = (int)(zdiff); // + 1.0f);
//if(xindex - xdiff > 0.00001f)
// xindex = xindex -1;
//if(yindex - ydiff > 0.00001f)
// yindex = yindex - 1;
//if(zindex - zdiff > 0.00001f)
// zindex = zindex - 1;
data[xindex][yindex][zindex].p_list->points.push_back(cloud.points[i]);
data[xindex][yindex][zindex].n_list->points.push_back(cloud_normals.points[i]);
}
return;
}
void remove_voxels(int threshold){
long voxel_used_count = 0;
for(int i = 0; i < length; i++){
for(int j = 0; j < width; j++){
for(int k = 0; k < height; k++){
if(data[i][j][k].p_list->points.size() >= threshold){
data[i][j][k].used = true;
voxel_used_count++;
}
}
}
}
// cout<<"Voxel used after thresholding: "<<voxel_used_count<<endl;
return;
}
};
class Block{
public:
int x;
int y;
int z;
int length;
int width;
int height;
Block(){
x = y = z = 0;
length = width = height = 1;
}
Block(const Block &b){
x = b.x;
y = b.y;
z = b.z;
length = b.length;
width = b.width;
height = b.height;
}
Block(int x_i, int y_i, int z_i, int l_i, int w_i, int h_i ){
x = x_i;
y = y_i;
z = z_i;
length = l_i;
width = w_i;
height = h_i;
}
};
class Training_block{
public:
double asp_1;
double asp_2;
double asp_3;
int model_number;
int is_splited;
//double cut_frac;
double x_1, y_1, z_1;
double x_2, y_2, z_2;
double l_1, w_1, h_1;
double l_2, w_2, h_2;
string model_name;
Training_block(){
asp_1 = asp_2 = asp_3 = 0.0;
x_1 = y_1 = z_1 = l_1 = w_1 = h_1 = -1;
x_2 = y_2 = z_2 = l_2 = w_2 = h_2 = -1;
model_number = -1;
is_splited = -1;
}
Training_block(double _asp_1, double _asp_2, double _asp_3, int _model_number, double _x_1, double _y_1, double _z_1, double _l_1, double _w_1, double _h_1, double _x_2, double _y_2, double _z_2, double _l_2, double _w_2, double _h_2){
asp_1 = _asp_1;
asp_2 = _asp_2;
asp_3 = _asp_3;
x_1 = _x_1;
y_1 = _y_1;
z_1 = _z_1;
l_1 = _l_1;
w_1 = _w_1;
h_1 = _h_1;
x_2 = _x_2;
y_2 = _y_2;
z_2 = _z_2;
l_2 = _l_2;
w_2 = _w_2;
h_2 = _h_2;
model_number = _model_number;
}
Training_block(const Training_block &b){
asp_1 = b.asp_1;
asp_2 = b.asp_2;
asp_3 = b.asp_3;
//plane = b.plane;
//cut_frac = b.cut_frac;
x_1 = b.x_1;
y_1 = b.y_1;
z_1 = b.z_1;
l_1 = b.l_1;
w_1 = b.w_1;
h_1 = b.h_1;
x_2 = b.x_2;
y_2 = b.y_2;
z_2 = b.z_2;
l_2 = b.l_2;
w_2 = b.w_2;
h_2 = b.h_2;
is_splited = b.is_splited;
model_number = b.model_number;
model_name = b.model_name;
}
};
int search_block(string model_name, int model_number, vector<Training_block> &tr_data_list){
for(int i = 0; i < tr_data_list.size(); i++){
if( tr_data_list[i].model_name.compare(model_name) == 0 && tr_data_list[i].model_number == model_number)
return i;
}
return -1;
}
#endif
| [
"[email protected]"
] | |
23d5013593984f41b9427d577e7805a16cf7da0c | a2ba5bb5afe7c397162e48988a3d6a10180061da | /ClassicIE9/ClassicIE9DLL/SettingsUI.cpp | 40789dacb4de3e5b88ce0926493bf7975a87b47e | [
"MIT"
] | permissive | jebeld17/ClassicShell | 140e4d4d707b25caa6053850f5f540ecf0f394be | c7d4bac036d7da8e053bc12decfcd2e3744e0e76 | refs/heads/master | 2021-01-22T11:11:00.312078 | 2015-08-28T22:45:46 | 2015-08-28T22:45:46 | 92,674,274 | 1 | 0 | null | 2017-05-28T16:52:29 | 2017-05-28T16:52:29 | null | UTF-8 | C++ | false | false | 6,625 | cpp | // Classic Shell (c) 2009-2013, Ivo Beltchev
// The sources for Classic Shell are distributed under the MIT open source license
#include "stdafx.h"
#include "Settings.h"
#include "SettingsUIHelper.h"
#include "ResourceHelper.h"
#include "Translations.h"
#include "resource.h"
#include "dllmain.h"
#include "ClassicIE9DLL.h"
#include <dwmapi.h>
#include <vssym32.h>
///////////////////////////////////////////////////////////////////////////////
static CSetting g_Settings[]={
{L"Basic",CSetting::TYPE_GROUP,IDS_BASIC_SETTINGS},
{L"EnableSettings",CSetting::TYPE_BOOL,0,0,1,CSetting::FLAG_HIDDEN},
{L"LogLevel",CSetting::TYPE_INT,0,0,0,CSetting::FLAG_HIDDEN},
{L"TitleBar",CSetting::TYPE_GROUP,IDS_TITLE_SETTINGS},
{L"ShowCaption",CSetting::TYPE_BOOL,IDS_SHOW_CAPTION,IDS_SHOW_CAPTION_TIP,1,CSetting::FLAG_WARM|CSetting::FLAG_BASIC},
{L"ShowIcon",CSetting::TYPE_BOOL,IDS_SHOW_ICON,IDS_SHOW_ICON_TIP,1,CSetting::FLAG_WARM|CSetting::FLAG_BASIC,L"ShowCaption"},
{L"CenterCaption",CSetting::TYPE_BOOL,IDS_CENTER_CAPTION,IDS_CENTER_CAPTION_TIP,0,CSetting::FLAG_WARM|CSetting::FLAG_BASIC,L"ShowCaption"},
{L"CaptionFont",CSetting::TYPE_FONT,IDS_CAPTION_FONT,IDS_CAPTION_FONT_TIP,L"Segoe UI, normal, 9",CSetting::FLAG_WARM,L"ShowCaption"},
{L"TextColor",CSetting::TYPE_COLOR,IDS_TEXT_COLOR,IDS_TEXT_COLOR_TIP,0,CSetting::FLAG_WARM,L"ShowCaption"},
{L"MaxColor",CSetting::TYPE_COLOR,IDS_MAXTEXT_COLOR,IDS_MAXTEXT_COLOR_TIP,0,CSetting::FLAG_WARM|(1<<24),L"ShowCaption"},
{L"InactiveColor",CSetting::TYPE_COLOR,IDS_INTEXT_COLOR,IDS_INTEXT_COLOR_TIP,0,CSetting::FLAG_WARM|(2<<24),L"ShowCaption"},
{L"InactiveMaxColor",CSetting::TYPE_COLOR,IDS_MAXINTEXT_COLOR,IDS_MAXINTEXT_COLOR_TIP,0,CSetting::FLAG_WARM|(3<<24),L"ShowCaption"},
{L"Glow",CSetting::TYPE_BOOL,IDS_GLOW,IDS_GLOW_TIP,0,CSetting::FLAG_WARM,L"ShowCaption"},
{L"GlowColor",CSetting::TYPE_COLOR,IDS_GLOW_COLOR,IDS_GLOW_COLOR_TIP,0xFFFFFF,CSetting::FLAG_WARM|(4<<24),L"#Glow"},
{L"MaxGlow",CSetting::TYPE_BOOL,IDS_MAXGLOW,IDS_MAXGLOW_TIP,0,CSetting::FLAG_WARM,L"ShowCaption"},
{L"MaxGlowColor",CSetting::TYPE_COLOR,IDS_MAXGLOW_COLOR,IDS_MAXGLOW_COLOR_TIP,0xFFFFFF,CSetting::FLAG_WARM|(5<<24),L"#MaxGlow"},
{L"StatusBar",CSetting::TYPE_GROUP,IDS_STATUS_SETTINGS},
{L"ShowProgress",CSetting::TYPE_BOOL,IDS_SHOW_PROGRESS,IDS_SHOW_PROGRESS_TIP,1,CSetting::FLAG_WARM|CSetting::FLAG_BASIC},
{L"ShowZone",CSetting::TYPE_BOOL,IDS_SHOW_ZONE,IDS_SHOW_ZONE_TIP,1,CSetting::FLAG_WARM|CSetting::FLAG_BASIC},
{L"ShowProtected",CSetting::TYPE_BOOL,IDS_SHOW_PROTECTED,IDS_SHOW_PROTECTED_TIP,1,CSetting::FLAG_WARM,L"ShowZone"},
{L"Language",CSetting::TYPE_GROUP,IDS_LANGUAGE_SETTINGS,0,0,0,NULL,GetLanguageSettings()},
{L"Language",CSetting::TYPE_STRING,0,0,L"",CSetting::FLAG_SHARED},
{NULL}
};
void UpdateSettings( void )
{
bool bVista=(GetWinVersion()==WIN_VER_VISTA);
bool bWin8=(GetWinVersion()>=WIN_VER_WIN8);
BOOL bComposition=0;
if (FAILED(DwmIsCompositionEnabled(&bComposition)))
bComposition=FALSE;
if (bComposition && bWin8)
{
// check for High Contrast theme on Win8
HIGHCONTRAST contrast={sizeof(contrast)};
if (SystemParametersInfo(SPI_GETHIGHCONTRAST,sizeof(contrast),&contrast,0) && (contrast.dwFlags&HCF_HIGHCONTRASTON))
bComposition=FALSE;
else
{
// check for Basic theme
DWORD color;
BOOL opaque;
if (SUCCEEDED(DwmGetColorizationColor(&color,&opaque)) && opaque)
bComposition=FALSE;
}
}
UpdateSetting(L"Glow",CComVariant(bComposition?1:0),false);
UpdateSetting(L"MaxGlow",CComVariant((bComposition && !bVista)?1:0),false);
UpdateSetting(L"CenterCaption",CComVariant(bWin8?1:0),false);
// create a dummy window to get a theme
HWND hwnd=CreateWindow(L"#32770",L"",WS_OVERLAPPEDWINDOW,0,0,0,0,NULL,NULL,NULL,0);
HTHEME theme=OpenThemeData(hwnd,L"Window");
if (theme)
{
HDC hdc=GetDC(NULL);
int dpi=GetDeviceCaps(hdc,LOGPIXELSY);
ReleaseDC(NULL,hdc);
LOGFONT font;
GetThemeSysFont(theme,TMT_CAPTIONFONT,&font);
wchar_t text[256];
const wchar_t *type=font.lfItalic?L"italic":L"normal";
if (font.lfWeight>=FW_BOLD)
type=font.lfItalic?L"bold_italic":L"bold";
Sprintf(text,_countof(text),L"%s, %s, %d",font.lfFaceName,type,(-font.lfHeight*72+dpi/2)/dpi);
UpdateSetting(L"CaptionFont",CComVariant(text),false);
int color=GetThemeSysColor(theme,COLOR_CAPTIONTEXT);
UpdateSetting(L"TextColor",CComVariant(color),false);
UpdateSetting(L"MaxColor",CComVariant((bVista && bComposition)?0xFFFFFF:color),false);
if (bVista || bWin8)
color=GetThemeSysColor(theme,COLOR_INACTIVECAPTIONTEXT);
UpdateSetting(L"InactiveColor",CComVariant(color),false);
UpdateSetting(L"InactiveMaxColor",CComVariant((bVista && bComposition)?0xFFFFFF:color),false);
CloseThemeData(theme);
}
else
{
int color=GetSysColor(COLOR_CAPTIONTEXT);
UpdateSetting(L"TextColor",CComVariant(color),false);
UpdateSetting(L"MaxColor",CComVariant(color),false);
color=GetSysColor(COLOR_INACTIVECAPTIONTEXT);
UpdateSetting(L"InactiveColor",CComVariant(color),false);
UpdateSetting(L"InactiveMaxColor",CComVariant(color),false);
}
DestroyWindow(hwnd);
CRegKey regKey;
wchar_t language[100]=L"";
if (regKey.Open(HKEY_LOCAL_MACHINE,L"Software\\IvoSoft\\ClassicShell",KEY_READ|KEY_WOW64_64KEY)==ERROR_SUCCESS)
{
ULONG size=_countof(language);
if (regKey.QueryStringValue(L"DefaultLanguage",language,&size)!=ERROR_SUCCESS)
language[0]=0;
}
UpdateSetting(L"Language",language,false);
}
void InitSettings( void )
{
InitSettings(g_Settings,COMPONENT_IE9);
}
void ClosingSettings( HWND hWnd, int flags, int command )
{
if (command==IDOK)
{
if (flags&CSetting::FLAG_WARM)
{
if (FindWindow(L"IEFrame",NULL))
MessageBox(hWnd,LoadStringEx(IDS_NEW_SETTINGS),LoadStringEx(IDS_APP_TITLE),MB_OK|MB_ICONINFORMATION);
}
}
}
CSIE9API void ShowIE9Settings( void )
{
if (!GetSettingBool(L"EnableSettings"))
return;
wchar_t title[100];
DWORD ver=GetVersionEx(g_Instance);
if (ver)
Sprintf(title,_countof(title),LoadStringEx(IDS_SETTINGS_TITLE_VER),ver>>24,(ver>>16)&0xFF,ver&0xFFFF);
else
Sprintf(title,_countof(title),LoadStringEx(IDS_SETTINGS_TITLE));
EditSettings(title,true,0);
}
CSIE9API DWORD GetIE9Settings( void )
{
DWORD res=0;
if (GetSettingBool(L"ShowCaption")) res|=IE9_SETTING_CAPTION;
if (GetSettingBool(L"ShowProgress")) res|=IE9_SETTING_PROGRESS;
if (GetSettingBool(L"ShowZone")) res|=IE9_SETTING_ZONE;
if (GetSettingBool(L"ShowProtected")) res|=IE9_SETTING_PROTECTED;
return res;
}
| [
"[email protected]"
] | |
8aedd9283299ef8a302def241682e2c05b53093c | a885c7bceafa7b3d6c5a756230fe08ecec6e011f | /ionGUI/imGUI.cpp | ce78bcef01758e7aa96849be4a187b4b19a97331 | [
"MIT"
] | permissive | GSerralara/ionEngine | 38984960db4d4300c4176974c0564348abb777b3 | 7ce3394dafbabf0e0bb9f5d07dbfae31161800d4 | refs/heads/master | 2021-10-09T13:00:04.123300 | 2018-12-28T10:46:33 | 2018-12-28T10:46:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 100 | cpp |
#include "imGUI.h"
#include <imgui.cpp>
#include <imgui_draw.cpp>
#include <imgui_demo.cpp>
| [
"[email protected]"
] | |
8456a880d1445c406f04640a541f9ed522340331 | bc7e05dc6be0cd3c613991664d03107a58ec2b9c | /aoapc-bac2nd/ch10/UVa11440.cpp | 307e889ffc57d767025eba1d10c8b6618811c11b | [] | no_license | 4ker/aoapc-book | cba435a4aee65e7d95c7e62e7fedab333ecf0a79 | addedfedd8be907e67229a2af6732f48c0f74dbd | refs/heads/master | 2021-01-17T22:47:09.027018 | 2016-08-29T16:55:03 | 2016-08-29T16:55:03 | 65,923,801 | 0 | 0 | null | 2016-08-17T16:27:54 | 2016-08-17T16:27:53 | null | UTF-8 | C++ | false | false | 793 | cpp | // UVa11440 Help Mr. Tomisu
// Rujia Liu
#include<cstdio>
#include<cmath>
#include<cstring>
const int maxn = 10000000 + 10;
const int MOD = 100000007;
int vis[maxn], phifac[maxn];
void gen_primes(int n) {
int m = (int)sqrt(n+0.5);
int c = 0;
memset(vis, 0, sizeof(vis));
for(int i = 2; i <= m; i++) if(!vis[i]) {
for(int j = i*i; j <= n; j+=i) vis[j] = 1;
}
}
int main() {
int n, m;
gen_primes(10000000);
phifac[1] = phifac[2] = 1;
for(int i = 3; i <= 10000000; i++)
phifac[i] = (long long)phifac[i-1] * (vis[i] ? i : i-1) % MOD;
while(scanf("%d%d", &n, &m) == 2 && n) {
int ans = phifac[m];
for(int i = m+1; i <= n; i++) ans = (long long)ans * i % MOD;
printf("%d\n", (ans-1+MOD)%MOD);
}
return 0;
}
| [
"[email protected]"
] | |
6793a05eb16a7be71280a12293fa062e584882d5 | 3d424a8d682d4e056668b5903206ccc603f6e997 | /NeoScriptTools/debugging/qscriptdebuggerstackmodel_p.h | b71a8540602d39d4a7b2818ba5c7a4db76fb306a | [] | no_license | markus851/NeoLoader | 515e238b385354b83bbc4f7399a85524d5b03d12 | 67c9b642054ead500832406a9c301a7b4cbfffd3 | refs/heads/master | 2022-04-22T07:51:15.418184 | 2015-05-08T11:37:53 | 2015-05-08T11:37:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,895 | h | /****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtSCriptTools module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QSCRIPTDEBUGGERSTACKMODEL_P_H
#define QSCRIPTDEBUGGERSTACKMODEL_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include <QtCore/qabstractitemmodel.h>
#include <QtCore/qlist.h>
QT_BEGIN_NAMESPACE
class QScriptDebuggerContextInfo;
class QScriptDebuggerStackModelPrivate;
class Q_AUTOTEST_EXPORT QScriptDebuggerStackModel
: public QAbstractTableModel
{
public:
QScriptDebuggerStackModel(QObject *parent = 0);
~QScriptDebuggerStackModel();
QList<QScriptDebuggerContextInfo> contextInfos() const;
void setContextInfos(const QList<QScriptDebuggerContextInfo> &infos);
int columnCount(const QModelIndex &parent) const;
int rowCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation, int role) const;
private:
Q_DECLARE_PRIVATE(QScriptDebuggerStackModel)
Q_DISABLE_COPY(QScriptDebuggerStackModel)
};
QT_END_NAMESPACE
#endif
| [
"[email protected]"
] | |
7c82fa35088b091bf3c51e60fcd8024f81ae280d | 5583a6c9556ac5b96148f276573894e242ce1e3f | /src/IO_tools.hpp | abe40350bde3cad220714c5a5746d1fc7fb6a516 | [] | no_license | wphu/FV_with_petsc | 19e060d2f9578fcf6e66ddf377f1c2a6e541025d | eb6b9262e7e33073b8a9e8229c823c8a7374a4ef | refs/heads/master | 2020-03-22T22:56:11.272363 | 2017-12-18T22:12:30 | 2017-12-18T22:28:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,358 | hpp | // Most of this was copy-pasted from Ryan Davis's PADI software:
// https://github.com/rsdavis/ParallelDiffuseInterface-PADI
// It provides utilities for reading input parameters from a text file.
// The logging code has been removed.
#ifndef IO_TOOLS_H
#define IO_TOOLS_H
#include <map>
#include <string>
#include "bc.hpp"
// Process boundary condition types input from the input file.
BC_type convert_to_BCtype(std::string name);
// utility function for appending numbers to hdf5 filenames, if there is a series
std::string number_filename(std::string base_filename, int counter);
template <typename T> // primary template
void unpack(std::map<std::string, std::string> params, std::string name, T ¶meter);
template <> // explicit specialization for T = double
void unpack(std::map<std::string, std::string> hash, std::string name, double ¶meter);
template <> // explicit specialization for T = int
void unpack(std::map<std::string, std::string> hash, std::string name, int ¶meter);
template <> // explicit specialization for T = BC
void unpack(std::map<std::string, std::string> hash, std::string name, BC ¶meter);
void unpack(std::map<std::string, int> name_index, std::string name, int &index);
void read_parameters(std::map<std::string, std::string> ¶ms,
std::string input_file="input.txt");
#endif
| [
"[email protected]"
] | |
4ef3c8361063514758e933f6b1e4a6324bb56a64 | 23177c3166b3d6d801c09d846b731425c77788da | /Intermediate/Build/Win64/UE4/Inc/Assignment/MainAnimInstance.gen.cpp | 63f44834bb79c1672a8dd65d88cc47f98d99210c | [] | no_license | ffEuryale/Unreal_Portfolio | 143340df29e004ca147c89431e79374200adf97f | 272e111066999b26baaaa7e03bb5c611e91b7b06 | refs/heads/main | 2023-03-21T07:21:29.023017 | 2021-03-03T12:06:46 | 2021-03-03T12:06:46 | 342,631,540 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,442 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "Assignment/MainAnimInstance.h"
#include "Engine/Classes/Components/SkeletalMeshComponent.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeMainAnimInstance() {}
// Cross Module References
ASSIGNMENT_API UClass* Z_Construct_UClass_UMainAnimInstance_NoRegister();
ASSIGNMENT_API UClass* Z_Construct_UClass_UMainAnimInstance();
ENGINE_API UClass* Z_Construct_UClass_UAnimInstance();
UPackage* Z_Construct_UPackage__Script_Assignment();
ASSIGNMENT_API UClass* Z_Construct_UClass_AMainCharacter_NoRegister();
ENGINE_API UClass* Z_Construct_UClass_APawn_NoRegister();
// End Cross Module References
DEFINE_FUNCTION(UMainAnimInstance::execUpdateAnimationProperties)
{
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->UpdateAnimationProperties();
P_NATIVE_END;
}
void UMainAnimInstance::StaticRegisterNativesUMainAnimInstance()
{
UClass* Class = UMainAnimInstance::StaticClass();
static const FNameNativePtrPair Funcs[] = {
{ "UpdateAnimationProperties", &UMainAnimInstance::execUpdateAnimationProperties },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs));
}
struct Z_Construct_UFunction_UMainAnimInstance_UpdateAnimationProperties_Statics
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UMainAnimInstance_UpdateAnimationProperties_Statics::Function_MetaDataParams[] = {
{ "Category", "AnimationProperties" },
{ "ModuleRelativePath", "MainAnimInstance.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UMainAnimInstance_UpdateAnimationProperties_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UMainAnimInstance, nullptr, "UpdateAnimationProperties", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UMainAnimInstance_UpdateAnimationProperties_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UMainAnimInstance_UpdateAnimationProperties_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_UMainAnimInstance_UpdateAnimationProperties()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UMainAnimInstance_UpdateAnimationProperties_Statics::FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_UMainAnimInstance_NoRegister()
{
return UMainAnimInstance::StaticClass();
}
struct Z_Construct_UClass_UMainAnimInstance_Statics
{
static UObject* (*const DependentSingletons[])();
static const FClassFunctionLinkInfo FuncInfo[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Main_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Main;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Pawn_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Pawn;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bIsInAir_MetaData[];
#endif
static void NewProp_bIsInAir_SetBit(void* Obj);
static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bIsInAir;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MovementSpeed_MetaData[];
#endif
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_MovementSpeed;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_UMainAnimInstance_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_UAnimInstance,
(UObject* (*)())Z_Construct_UPackage__Script_Assignment,
};
const FClassFunctionLinkInfo Z_Construct_UClass_UMainAnimInstance_Statics::FuncInfo[] = {
{ &Z_Construct_UFunction_UMainAnimInstance_UpdateAnimationProperties, "UpdateAnimationProperties" }, // 3483567489
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMainAnimInstance_Statics::Class_MetaDataParams[] = {
{ "Comment", "/**\n * \n */" },
{ "HideCategories", "AnimInstance" },
{ "IncludePath", "MainAnimInstance.h" },
{ "ModuleRelativePath", "MainAnimInstance.h" },
};
#endif
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_Main_MetaData[] = {
{ "Category", "Movement" },
{ "ModuleRelativePath", "MainAnimInstance.h" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_Main = { "Main", nullptr, (EPropertyFlags)0x0010000000000015, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMainAnimInstance, Main), Z_Construct_UClass_AMainCharacter_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_Main_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_Main_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_Pawn_MetaData[] = {
{ "Category", "Movement" },
{ "ModuleRelativePath", "MainAnimInstance.h" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_Pawn = { "Pawn", nullptr, (EPropertyFlags)0x0010000000000015, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMainAnimInstance, Pawn), Z_Construct_UClass_APawn_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_Pawn_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_Pawn_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_bIsInAir_MetaData[] = {
{ "Category", "Movement" },
{ "ModuleRelativePath", "MainAnimInstance.h" },
};
#endif
void Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_bIsInAir_SetBit(void* Obj)
{
((UMainAnimInstance*)Obj)->bIsInAir = 1;
}
const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_bIsInAir = { "bIsInAir", nullptr, (EPropertyFlags)0x0010000000000015, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(UMainAnimInstance), &Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_bIsInAir_SetBit, METADATA_PARAMS(Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_bIsInAir_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_bIsInAir_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_MovementSpeed_MetaData[] = {
{ "Category", "Movement" },
{ "ModuleRelativePath", "MainAnimInstance.h" },
};
#endif
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_MovementSpeed = { "MovementSpeed", nullptr, (EPropertyFlags)0x0010000000000015, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UMainAnimInstance, MovementSpeed), METADATA_PARAMS(Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_MovementSpeed_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_MovementSpeed_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UMainAnimInstance_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_Main,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_Pawn,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_bIsInAir,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UMainAnimInstance_Statics::NewProp_MovementSpeed,
};
const FCppClassTypeInfoStatic Z_Construct_UClass_UMainAnimInstance_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<UMainAnimInstance>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UMainAnimInstance_Statics::ClassParams = {
&UMainAnimInstance::StaticClass,
nullptr,
&StaticCppClassTypeInfo,
DependentSingletons,
FuncInfo,
Z_Construct_UClass_UMainAnimInstance_Statics::PropPointers,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
UE_ARRAY_COUNT(FuncInfo),
UE_ARRAY_COUNT(Z_Construct_UClass_UMainAnimInstance_Statics::PropPointers),
0,
0x009000A8u,
METADATA_PARAMS(Z_Construct_UClass_UMainAnimInstance_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UMainAnimInstance_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_UMainAnimInstance()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UMainAnimInstance_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(UMainAnimInstance, 2809650281);
template<> ASSIGNMENT_API UClass* StaticClass<UMainAnimInstance>()
{
return UMainAnimInstance::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_UMainAnimInstance(Z_Construct_UClass_UMainAnimInstance, &UMainAnimInstance::StaticClass, TEXT("/Script/Assignment"), TEXT("UMainAnimInstance"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(UMainAnimInstance);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| [
"[email protected]"
] | |
a541781f97d76fe3468289a3386769b2bcba3244 | 2e09ae7a5bea9be801045a3e52c23917d201587c | /source/Operations/RasterPosition.h | 8ebcba2aee5640679aa87f733c274ec5bbc1ea50 | [] | no_license | rpethes/terRAIN | 62f6cd28a635b8abdbcd022998e420386fd264e8 | 1f2b586ad632a31e8e1713eee90e53653c9ee113 | refs/heads/master | 2016-09-06T11:49:15.590676 | 2015-11-16T19:01:40 | 2015-11-16T19:01:40 | 33,692,680 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 634 | h | #ifndef RASTERPOSITION_H
#define RASTERPOSITION_H
#include <ostream>
namespace TR
{
class RasterPosition
{
private:
size_t _row;
size_t _col;
public:
RasterPosition():_row(0), _col(0){}
RasterPosition(size_t row, size_t col) :_row(row), _col(col){}
inline void set(size_t row, size_t col) {
_row = row;
_col = col;
}
inline size_t getCol() const
{
return _col;
}
size_t getRow() const
{
return _row;
}
friend std::ostream & operator<<(std::ostream & os, RasterPosition & rasterPos)
{
os<<"[ ";
os<< rasterPos.getRow();
os<<",";
os<< rasterPos.getCol();
os<<" ]";
return os;
}
};
}
#endif | [
"[email protected]"
] | |
6344d4ec524fe00ed8fcf51bce6fa41303575fde | 54b9e493500440edbcd8a3fac8876260f25c4d92 | /vectors/main.cpp | e0e18025d4ca2b1d7666b3a3f18bc43684a843bb | [] | no_license | element2112/cpp_udemy_course | 3f35b117b7f007385d560ceeb2002eff3c0d47c8 | 23f1fdf78e15f7725716fc5e39925f8010f9fc90 | refs/heads/master | 2022-08-19T14:34:17.634055 | 2020-05-25T23:55:23 | 2020-05-25T23:55:23 | 252,863,739 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,936 | cpp | #include <iostream>
#include <vector>
using namespace std;
// a vector is just a dynamic array like an arraylist
// vectors are an object
int main()
{
vector <char> vowels;
vector <int> test_scores {100, 95, 99, 87, 88};
vector <char> more_vowels (5); // constructor initialization. initalizing arraylist to 5
vector <char> some_vowels {'a', 'e', 'i', 'o', 'u'};
vector <double> hi_temps (365, 90.5); // 365 indicies and initializing them all to 90.5
cout << "First score: " << test_scores[0] << endl;
cout << "Second score: " << test_scores[1] << endl;
// etc etc
cout << "First score " << test_scores.at(0) << endl;
cout << "Second score " << test_scores.at(1) << endl;
cout << "Third score " << test_scores.at(2) << endl;
cout << "Enter 5 scores " << endl;
cin >> test_scores.at(0);
cin >> test_scores.at(1);
cin >> test_scores.at(2);
cin >> test_scores.at(3);
cin >> test_scores.at(4);
test_scores.push_back(80);
test_scores.push_back(100);
cout << test_scores.at(5) << endl;
cout << test_scores.at(6) << endl;
cout << "Size of vector: " << test_scores.size() << endl;
for (int i = 0; i < test_scores.size(); i++)
{
if (test_scores.at(i) < 50)
test_scores.push_back(70);
cout << "Score: " << test_scores.at(i) << endl;
}
// 2D vector (vector of vectors)
vector <vector<int>> my_vect
{
{1,2,3,4},
{5,6,7,8,9},
{10, 11, 12}
};
int n = my_vect.size();
for (int i = 0; i < n; i++)
{
int k = my_vect.at(i).size();
for (int j = 0; j < k; j++)
{
cout << "Element: " << my_vect.at(i).at(j) << endl;
}
}
return 0;
} | [
"[email protected]"
] | |
f42ade96f15aabf89b53cc8451f886b68302cdb9 | 579dbb681f772870d692f468322470612fa553aa | /third-party/Eigen/src/Eigenvalues/ComplexSchur_MKL.h | 1607dcd0b27db616576c324ac64572f159fecdfb | [] | no_license | chipbuster/niftyreg | eb69441dc3ee76930da08d580f61550fd448271d | d9bd674a1cdae37688444777cc07862dec366228 | refs/heads/master | 2021-01-11T08:50:14.626799 | 2016-12-16T20:46:28 | 2016-12-16T20:46:28 | 76,684,058 | 0 | 0 | null | 2016-12-16T20:37:50 | 2016-12-16T20:37:50 | null | UTF-8 | C++ | false | false | 4,014 | h | /*
Copyright (c) 2011, Intel Corporation. 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 Intel Corporation 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.
********************************************************************************
* Content : Eigen bindings to Intel(R) MKL
* Complex Schur needed to complex unsymmetrical eigenvalues/eigenvectors.
********************************************************************************
*/
#ifndef EIGEN_COMPLEX_SCHUR_MKL_H
#define EIGEN_COMPLEX_SCHUR_MKL_H
#include "Eigen/src/Core/util/MKL_support.h"
namespace Eigen
{
/** \internal Specialization for the data types supported by MKL */
#define EIGEN_MKL_SCHUR_COMPLEX(EIGTYPE, MKLTYPE, MKLPREFIX, MKLPREFIX_U, EIGCOLROW, MKLCOLROW) \
template<> inline \
ComplexSchur<Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW> >& \
ComplexSchur<Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW> >::compute(const Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW>& matrix, bool computeU) \
{ \
typedef Matrix<EIGTYPE, Dynamic, Dynamic, EIGCOLROW> MatrixType; \
typedef MatrixType::Scalar Scalar; \
typedef MatrixType::RealScalar RealScalar; \
typedef std::complex<RealScalar> ComplexScalar; \
\
eigen_assert(matrix.cols() == matrix.rows()); \
\
m_matUisUptodate = false; \
if(matrix.cols() == 1) \
{ \
m_matT = matrix.cast<ComplexScalar>(); \
if(computeU) m_matU = ComplexMatrixType::Identity(1,1); \
m_info = Success; \
m_isInitialized = true; \
m_matUisUptodate = computeU; \
return *this; \
} \
lapack_int n = matrix.cols(), sdim, info; \
lapack_int lda = matrix.outerStride(); \
lapack_int matrix_order = MKLCOLROW; \
char jobvs, sort='N'; \
LAPACK_##MKLPREFIX_U##_SELECT1 select = 0; \
jobvs = (computeU) ? 'V' : 'N'; \
m_matU.resize(n, n); \
lapack_int ldvs = m_matU.outerStride(); \
m_matT = matrix; \
Matrix<EIGTYPE, Dynamic, Dynamic> w; \
w.resize(n, 1);\
info = LAPACKE_##MKLPREFIX##gees( matrix_order, jobvs, sort, select, n, (MKLTYPE*)m_matT.data(), lda, &sdim, (MKLTYPE*)w.data(), (MKLTYPE*)m_matU.data(), ldvs ); \
if(info == 0) \
m_info = Success; \
else \
m_info = NoConvergence; \
\
m_isInitialized = true; \
m_matUisUptodate = computeU; \
return *this; \
\
}
EIGEN_MKL_SCHUR_COMPLEX(dcomplex, MKL_Complex16, z, Z, ColMajor, LAPACK_COL_MAJOR)
EIGEN_MKL_SCHUR_COMPLEX(scomplex, MKL_Complex8, c, C, ColMajor, LAPACK_COL_MAJOR)
EIGEN_MKL_SCHUR_COMPLEX(dcomplex, MKL_Complex16, z, Z, RowMajor, LAPACK_ROW_MAJOR)
EIGEN_MKL_SCHUR_COMPLEX(scomplex, MKL_Complex8, c, C, RowMajor, LAPACK_ROW_MAJOR)
} // end namespace Eigen
#endif // EIGEN_COMPLEX_SCHUR_MKL_H
| [
"[email protected]"
] | |
4fdbe9bc92233169a10b359e5cad46e09d26cfbf | 6b18884327584cd84e677b53a5c1c121cbed7aaf | /2D Physics Engine ERawlings/RenderData.h | 2839e008afa2a5104e405fc72608220b28583584 | [
"MIT"
] | permissive | EmmaRawlings/2D-Physics-Engine-ERawlings | dfa9ef64d71ac71aed0c57cfa88ade5e9859a85d | 63e1c330321bb7f826049ca12dfa95c4ddb346e8 | refs/heads/master | 2021-11-27T00:32:03.064186 | 2017-02-07T20:21:42 | 2017-02-07T20:21:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,469 | h | #pragma once
#include "Vector2.h"
#include <list>
#include <string>
//blend mode?
struct Position{
int x;
int y;
int z;
};
struct Colour {
int r;
int g;
int b;
int a;
};
struct Point {
Position position;
Colour colour;
int size;
};
struct Line {
int x1;
int y1;
int z1;
int x2;
int y2;
int z2;
Colour colour;
int width;
};
/*
struct Lines {
std::list<Position> positions;
Colour colour;
int width;
};*/
/*
struct Sprite {
int id;
Position position;
int a;
int top;
int left;
int bottom;
int right;
//transformations
};*/
struct Text {
std::string text;
int size;
Position position;
//font type
Colour colour;
int a;
//transformations
};
class RenderData
{
public:
RenderData(void);
RenderData(const RenderData& rData);
RenderData& operator=(const RenderData& rData);
void addRenderData(const RenderData& rData);
void addRenderData(const RenderData& rData, const Position& position);
void addPoint(const int x, const int y, const int z, const int r, const int g, const int b, const int a, const int size);
void addLine(const int x1, const int y1, const int z1, const int x2, const int y2, const int z2, const int r, const int g, const int b, const int a, const int width);
void addText(const int x, const int y, const int z, const int r, const int g, const int b, const int a, const int size, const std::string text);
~RenderData(void);
std::list<Point>* points;
std::list<Line>* lines;
std::list<Text>* texts;
};
| [
"[email protected]"
] | |
ed5972250da6a52b159b3fcaeaec504522629a4e | 483194ec10e6149c3245ff48c1857f48deba1578 | /External/asio/buffer.hpp | 8d415b7b464c3c9d157bfe20b446b1124592a77e | [] | no_license | davidroze/StormWebrtc | 3efc68c9e16b34da0728716f460f44ca8a50f59d | cd471d5107c3bfe0cb885caf81063915ad4d386a | refs/heads/master | 2021-05-08T16:43:43.539787 | 2018-02-04T10:05:43 | 2018-02-04T10:05:43 | 120,167,513 | 0 | 0 | null | 2018-02-04T08:24:11 | 2018-02-04T08:24:11 | null | UTF-8 | C++ | false | false | 89,021 | hpp | //
// buffer.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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)
//
#ifndef ASIO_BUFFER_HPP
#define ASIO_BUFFER_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include <cstddef>
#include <cstring>
#include <limits>
#include <stdexcept>
#include <string>
#include <vector>
#include "asio/detail/array_fwd.hpp"
#include "asio/detail/is_buffer_sequence.hpp"
#include "asio/detail/throw_exception.hpp"
#include "asio/detail/type_traits.hpp"
#if defined(ASIO_MSVC)
# if defined(_HAS_ITERATOR_DEBUGGING) && (_HAS_ITERATOR_DEBUGGING != 0)
# if !defined(ASIO_DISABLE_BUFFER_DEBUGGING)
# define ASIO_ENABLE_BUFFER_DEBUGGING
# endif // !defined(ASIO_DISABLE_BUFFER_DEBUGGING)
# endif // defined(_HAS_ITERATOR_DEBUGGING)
#endif // defined(ASIO_MSVC)
#if defined(__GNUC__)
# if defined(_GLIBCXX_DEBUG)
# if !defined(ASIO_DISABLE_BUFFER_DEBUGGING)
# define ASIO_ENABLE_BUFFER_DEBUGGING
# endif // !defined(ASIO_DISABLE_BUFFER_DEBUGGING)
# endif // defined(_GLIBCXX_DEBUG)
#endif // defined(__GNUC__)
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
# include "asio/detail/functional.hpp"
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
#if defined(ASIO_HAS_BOOST_WORKAROUND)
# include <boost/detail/workaround.hpp>
# if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582)) \
|| BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x590))
# define ASIO_ENABLE_ARRAY_BUFFER_WORKAROUND
# endif // BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582))
// || BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x590))
#endif // defined(ASIO_HAS_BOOST_WORKAROUND)
#if defined(ASIO_ENABLE_ARRAY_BUFFER_WORKAROUND)
# include "asio/detail/type_traits.hpp"
#endif // defined(ASIO_ENABLE_ARRAY_BUFFER_WORKAROUND)
#include "asio/detail/push_options.hpp"
namespace asio {
class mutable_buffer;
class const_buffer;
namespace detail {
void* buffer_cast_helper(const mutable_buffer&);
const void* buffer_cast_helper(const const_buffer&);
std::size_t buffer_size_helper(const mutable_buffer&);
std::size_t buffer_size_helper(const const_buffer&);
} // namespace detail
/// Holds a buffer that can be modified.
/**
* The mutable_buffer class provides a safe representation of a buffer that can
* be modified. It does not own the underlying data, and so is cheap to copy or
* assign.
*
* @par Accessing Buffer Contents
*
* The contents of a buffer may be accessed using the @ref buffer_size
* and @ref buffer_cast functions:
*
* @code asio::mutable_buffer b1 = ...;
* std::size_t s1 = asio::buffer_size(b1);
* unsigned char* p1 = asio::buffer_cast<unsigned char*>(b1);
* @endcode
*
* The asio::buffer_cast function permits violations of type safety, so
* uses of it in application code should be carefully considered.
*/
class mutable_buffer
{
public:
/// Construct an empty buffer.
mutable_buffer()
: data_(0),
size_(0)
{
}
/// Construct a buffer to represent a given memory range.
mutable_buffer(void* data, std::size_t size)
: data_(data),
size_(size)
{
}
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
mutable_buffer(void* data, std::size_t size,
asio::detail::function<void()> debug_check)
: data_(data),
size_(size),
debug_check_(debug_check)
{
}
const asio::detail::function<void()>& get_debug_check() const
{
return debug_check_;
}
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
private:
friend void* asio::detail::buffer_cast_helper(
const mutable_buffer& b);
friend std::size_t asio::detail::buffer_size_helper(
const mutable_buffer& b);
void* data_;
std::size_t size_;
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
asio::detail::function<void()> debug_check_;
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
};
namespace detail {
inline void* buffer_cast_helper(const mutable_buffer& b)
{
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
if (b.size_ && b.debug_check_)
b.debug_check_();
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
return b.data_;
}
inline std::size_t buffer_size_helper(const mutable_buffer& b)
{
return b.size_;
}
} // namespace detail
/// Adapts a single modifiable buffer so that it meets the requirements of the
/// MutableBufferSequence concept.
class mutable_buffers_1
: public mutable_buffer
{
public:
/// The type for each element in the list of buffers.
typedef mutable_buffer value_type;
/// A random-access iterator type that may be used to read elements.
typedef const mutable_buffer* const_iterator;
/// Construct to represent a given memory range.
mutable_buffers_1(void* data, std::size_t size)
: mutable_buffer(data, size)
{
}
/// Construct to represent a single modifiable buffer.
explicit mutable_buffers_1(const mutable_buffer& b)
: mutable_buffer(b)
{
}
/// Get a random-access iterator to the first element.
const_iterator begin() const
{
return this;
}
/// Get a random-access iterator for one past the last element.
const_iterator end() const
{
return begin() + 1;
}
};
/// Holds a buffer that cannot be modified.
/**
* The const_buffer class provides a safe representation of a buffer that cannot
* be modified. It does not own the underlying data, and so is cheap to copy or
* assign.
*
* @par Accessing Buffer Contents
*
* The contents of a buffer may be accessed using the @ref buffer_size
* and @ref buffer_cast functions:
*
* @code asio::const_buffer b1 = ...;
* std::size_t s1 = asio::buffer_size(b1);
* const unsigned char* p1 = asio::buffer_cast<const unsigned char*>(b1);
* @endcode
*
* The asio::buffer_cast function permits violations of type safety, so
* uses of it in application code should be carefully considered.
*/
class const_buffer
{
public:
/// Construct an empty buffer.
const_buffer()
: data_(0),
size_(0)
{
}
/// Construct a buffer to represent a given memory range.
const_buffer(const void* data, std::size_t size)
: data_(data),
size_(size)
{
}
/// Construct a non-modifiable buffer from a modifiable one.
const_buffer(const mutable_buffer& b)
: data_(asio::detail::buffer_cast_helper(b)),
size_(asio::detail::buffer_size_helper(b))
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, debug_check_(b.get_debug_check())
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
{
}
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
const_buffer(const void* data, std::size_t size,
asio::detail::function<void()> debug_check)
: data_(data),
size_(size),
debug_check_(debug_check)
{
}
const asio::detail::function<void()>& get_debug_check() const
{
return debug_check_;
}
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
private:
friend const void* asio::detail::buffer_cast_helper(
const const_buffer& b);
friend std::size_t asio::detail::buffer_size_helper(
const const_buffer& b);
const void* data_;
std::size_t size_;
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
asio::detail::function<void()> debug_check_;
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
};
namespace detail {
inline const void* buffer_cast_helper(const const_buffer& b)
{
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
if (b.size_ && b.debug_check_)
b.debug_check_();
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
return b.data_;
}
inline std::size_t buffer_size_helper(const const_buffer& b)
{
return b.size_;
}
} // namespace detail
/// Adapts a single non-modifiable buffer so that it meets the requirements of
/// the ConstBufferSequence concept.
class const_buffers_1
: public const_buffer
{
public:
/// The type for each element in the list of buffers.
typedef const_buffer value_type;
/// A random-access iterator type that may be used to read elements.
typedef const const_buffer* const_iterator;
/// Construct to represent a given memory range.
const_buffers_1(const void* data, std::size_t size)
: const_buffer(data, size)
{
}
/// Construct to represent a single non-modifiable buffer.
explicit const_buffers_1(const const_buffer& b)
: const_buffer(b)
{
}
/// Get a random-access iterator to the first element.
const_iterator begin() const
{
return this;
}
/// Get a random-access iterator for one past the last element.
const_iterator end() const
{
return begin() + 1;
}
};
/// Trait to determine whether a type satisfies the MutableBufferSequence
/// requirements.
template <typename T>
struct is_mutable_buffer_sequence
#if defined(GENERATING_DOCUMENTATION)
: integral_constant<bool, automatically_determined>
#else // defined(GENERATING_DOCUMENTATION)
: asio::detail::is_buffer_sequence<T, mutable_buffer>
#endif // defined(GENERATING_DOCUMENTATION)
{
};
/// Trait to determine whether a type satisfies the ConstBufferSequence
/// requirements.
template <typename T>
struct is_const_buffer_sequence
#if defined(GENERATING_DOCUMENTATION)
: integral_constant<bool, automatically_determined>
#else // defined(GENERATING_DOCUMENTATION)
: asio::detail::is_buffer_sequence<T, const_buffer>
#endif // defined(GENERATING_DOCUMENTATION)
{
};
/// Trait to determine whether a type satisfies the DynamicBufferSequence
/// requirements.
template <typename T>
struct is_dynamic_buffer_sequence
#if defined(GENERATING_DOCUMENTATION)
: integral_constant<bool, automatically_determined>
#else // defined(GENERATING_DOCUMENTATION)
: asio::detail::is_dynamic_buffer_sequence<T>
#endif // defined(GENERATING_DOCUMENTATION)
{
};
/// (Deprecated: Use the socket/descriptor wait() and async_wait() member
/// functions.) An implementation of both the ConstBufferSequence and
/// MutableBufferSequence concepts to represent a null buffer sequence.
class null_buffers
{
public:
/// The type for each element in the list of buffers.
typedef mutable_buffer value_type;
/// A random-access iterator type that may be used to read elements.
typedef const mutable_buffer* const_iterator;
/// Get a random-access iterator to the first element.
const_iterator begin() const
{
return &buf_;
}
/// Get a random-access iterator for one past the last element.
const_iterator end() const
{
return &buf_;
}
private:
mutable_buffer buf_;
};
/** @defgroup buffer_size asio::buffer_size
*
* @brief The asio::buffer_size function determines the total number of
* bytes in a buffer or buffer sequence.
*/
/*@{*/
/// Get the number of bytes in a modifiable buffer.
inline std::size_t buffer_size(const mutable_buffer& b)
{
return detail::buffer_size_helper(b);
}
/// Get the number of bytes in a modifiable buffer.
inline std::size_t buffer_size(const mutable_buffers_1& b)
{
return detail::buffer_size_helper(b);
}
/// Get the number of bytes in a non-modifiable buffer.
inline std::size_t buffer_size(const const_buffer& b)
{
return detail::buffer_size_helper(b);
}
/// Get the number of bytes in a non-modifiable buffer.
inline std::size_t buffer_size(const const_buffers_1& b)
{
return detail::buffer_size_helper(b);
}
/// Get the total number of bytes in a buffer sequence.
/**
* The @c BufferSequence template parameter may meet either of the @c
* ConstBufferSequence or @c MutableBufferSequence type requirements.
*/
template <typename BufferSequence>
inline std::size_t buffer_size(const BufferSequence& b,
typename enable_if<
is_const_buffer_sequence<BufferSequence>::value
>::type* = 0)
{
std::size_t total_buffer_size = 0;
typename BufferSequence::const_iterator iter = b.begin();
typename BufferSequence::const_iterator end = b.end();
for (; iter != end; ++iter)
total_buffer_size += detail::buffer_size_helper(*iter);
return total_buffer_size;
}
/*@}*/
/** @defgroup buffer_cast asio::buffer_cast
*
* @brief The asio::buffer_cast function is used to obtain a pointer to
* the underlying memory region associated with a buffer.
*
* @par Examples:
*
* To access the memory of a non-modifiable buffer, use:
* @code asio::const_buffer b1 = ...;
* const unsigned char* p1 = asio::buffer_cast<const unsigned char*>(b1);
* @endcode
*
* To access the memory of a modifiable buffer, use:
* @code asio::mutable_buffer b2 = ...;
* unsigned char* p2 = asio::buffer_cast<unsigned char*>(b2);
* @endcode
*
* The asio::buffer_cast function permits violations of type safety, so
* uses of it in application code should be carefully considered.
*/
/*@{*/
/// Cast a non-modifiable buffer to a specified pointer to POD type.
template <typename PointerToPodType>
inline PointerToPodType buffer_cast(const mutable_buffer& b)
{
return static_cast<PointerToPodType>(detail::buffer_cast_helper(b));
}
/// Cast a non-modifiable buffer to a specified pointer to POD type.
template <typename PointerToPodType>
inline PointerToPodType buffer_cast(const const_buffer& b)
{
return static_cast<PointerToPodType>(detail::buffer_cast_helper(b));
}
/*@}*/
/// Create a new modifiable buffer that is offset from the start of another.
/**
* @relates mutable_buffer
*/
inline mutable_buffer operator+(const mutable_buffer& b, std::size_t start)
{
if (start > buffer_size(b))
return mutable_buffer();
char* new_data = buffer_cast<char*>(b) + start;
std::size_t new_size = buffer_size(b) - start;
return mutable_buffer(new_data, new_size
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, b.get_debug_check()
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
);
}
/// Create a new modifiable buffer that is offset from the start of another.
/**
* @relates mutable_buffer
*/
inline mutable_buffer operator+(std::size_t start, const mutable_buffer& b)
{
if (start > buffer_size(b))
return mutable_buffer();
char* new_data = buffer_cast<char*>(b) + start;
std::size_t new_size = buffer_size(b) - start;
return mutable_buffer(new_data, new_size
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, b.get_debug_check()
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
);
}
/// Create a new non-modifiable buffer that is offset from the start of another.
/**
* @relates const_buffer
*/
inline const_buffer operator+(const const_buffer& b, std::size_t start)
{
if (start > buffer_size(b))
return const_buffer();
const char* new_data = buffer_cast<const char*>(b) + start;
std::size_t new_size = buffer_size(b) - start;
return const_buffer(new_data, new_size
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, b.get_debug_check()
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
);
}
/// Create a new non-modifiable buffer that is offset from the start of another.
/**
* @relates const_buffer
*/
inline const_buffer operator+(std::size_t start, const const_buffer& b)
{
if (start > buffer_size(b))
return const_buffer();
const char* new_data = buffer_cast<const char*>(b) + start;
std::size_t new_size = buffer_size(b) - start;
return const_buffer(new_data, new_size
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, b.get_debug_check()
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
);
}
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
namespace detail {
template <typename Iterator>
class buffer_debug_check
{
public:
buffer_debug_check(Iterator iter)
: iter_(iter)
{
}
~buffer_debug_check()
{
#if defined(ASIO_MSVC) && (ASIO_MSVC == 1400)
// MSVC 8's string iterator checking may crash in a std::string::iterator
// object's destructor when the iterator points to an already-destroyed
// std::string object, unless the iterator is cleared first.
iter_ = Iterator();
#endif // defined(ASIO_MSVC) && (ASIO_MSVC == 1400)
}
void operator()()
{
*iter_;
}
private:
Iterator iter_;
};
} // namespace detail
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
/** @defgroup buffer asio::buffer
*
* @brief The asio::buffer function is used to create a buffer object to
* represent raw memory, an array of POD elements, a vector of POD elements,
* or a std::string.
*
* A buffer object represents a contiguous region of memory as a 2-tuple
* consisting of a pointer and size in bytes. A tuple of the form <tt>{void*,
* size_t}</tt> specifies a mutable (modifiable) region of memory. Similarly, a
* tuple of the form <tt>{const void*, size_t}</tt> specifies a const
* (non-modifiable) region of memory. These two forms correspond to the classes
* mutable_buffer and const_buffer, respectively. To mirror C++'s conversion
* rules, a mutable_buffer is implicitly convertible to a const_buffer, and the
* opposite conversion is not permitted.
*
* The simplest use case involves reading or writing a single buffer of a
* specified size:
*
* @code sock.send(asio::buffer(data, size)); @endcode
*
* In the above example, the return value of asio::buffer meets the
* requirements of the ConstBufferSequence concept so that it may be directly
* passed to the socket's write function. A buffer created for modifiable
* memory also meets the requirements of the MutableBufferSequence concept.
*
* An individual buffer may be created from a builtin array, std::vector,
* std::array or boost::array of POD elements. This helps prevent buffer
* overruns by automatically determining the size of the buffer:
*
* @code char d1[128];
* size_t bytes_transferred = sock.receive(asio::buffer(d1));
*
* std::vector<char> d2(128);
* bytes_transferred = sock.receive(asio::buffer(d2));
*
* std::array<char, 128> d3;
* bytes_transferred = sock.receive(asio::buffer(d3));
*
* boost::array<char, 128> d4;
* bytes_transferred = sock.receive(asio::buffer(d4)); @endcode
*
* In all three cases above, the buffers created are exactly 128 bytes long.
* Note that a vector is @e never automatically resized when creating or using
* a buffer. The buffer size is determined using the vector's <tt>size()</tt>
* member function, and not its capacity.
*
* @par Accessing Buffer Contents
*
* The contents of a buffer may be accessed using the @ref buffer_size and
* @ref buffer_cast functions:
*
* @code asio::mutable_buffer b1 = ...;
* std::size_t s1 = asio::buffer_size(b1);
* unsigned char* p1 = asio::buffer_cast<unsigned char*>(b1);
*
* asio::const_buffer b2 = ...;
* std::size_t s2 = asio::buffer_size(b2);
* const void* p2 = asio::buffer_cast<const void*>(b2); @endcode
*
* The asio::buffer_cast function permits violations of type safety, so
* uses of it in application code should be carefully considered.
*
* For convenience, the @ref buffer_size function also works on buffer
* sequences (that is, types meeting the ConstBufferSequence or
* MutableBufferSequence type requirements). In this case, the function returns
* the total size of all buffers in the sequence.
*
* @par Buffer Copying
*
* The @ref buffer_copy function may be used to copy raw bytes between
* individual buffers and buffer sequences.
*
* In particular, when used with the @ref buffer_size, the @ref buffer_copy
* function can be used to linearise a sequence of buffers. For example:
*
* @code vector<const_buffer> buffers = ...;
*
* vector<unsigned char> data(asio::buffer_size(buffers));
* asio::buffer_copy(asio::buffer(data), buffers); @endcode
*
* Note that @ref buffer_copy is implemented in terms of @c memcpy, and
* consequently it cannot be used to copy between overlapping memory regions.
*
* @par Buffer Invalidation
*
* A buffer object does not have any ownership of the memory it refers to. It
* is the responsibility of the application to ensure the memory region remains
* valid until it is no longer required for an I/O operation. When the memory
* is no longer available, the buffer is said to have been invalidated.
*
* For the asio::buffer overloads that accept an argument of type
* std::vector, the buffer objects returned are invalidated by any vector
* operation that also invalidates all references, pointers and iterators
* referring to the elements in the sequence (C++ Std, 23.2.4)
*
* For the asio::buffer overloads that accept an argument of type
* std::basic_string, the buffer objects returned are invalidated according to
* the rules defined for invalidation of references, pointers and iterators
* referring to elements of the sequence (C++ Std, 21.3).
*
* @par Buffer Arithmetic
*
* Buffer objects may be manipulated using simple arithmetic in a safe way
* which helps prevent buffer overruns. Consider an array initialised as
* follows:
*
* @code boost::array<char, 6> a = { 'a', 'b', 'c', 'd', 'e' }; @endcode
*
* A buffer object @c b1 created using:
*
* @code b1 = asio::buffer(a); @endcode
*
* represents the entire array, <tt>{ 'a', 'b', 'c', 'd', 'e' }</tt>. An
* optional second argument to the asio::buffer function may be used to
* limit the size, in bytes, of the buffer:
*
* @code b2 = asio::buffer(a, 3); @endcode
*
* such that @c b2 represents the data <tt>{ 'a', 'b', 'c' }</tt>. Even if the
* size argument exceeds the actual size of the array, the size of the buffer
* object created will be limited to the array size.
*
* An offset may be applied to an existing buffer to create a new one:
*
* @code b3 = b1 + 2; @endcode
*
* where @c b3 will set to represent <tt>{ 'c', 'd', 'e' }</tt>. If the offset
* exceeds the size of the existing buffer, the newly created buffer will be
* empty.
*
* Both an offset and size may be specified to create a buffer that corresponds
* to a specific range of bytes within an existing buffer:
*
* @code b4 = asio::buffer(b1 + 1, 3); @endcode
*
* so that @c b4 will refer to the bytes <tt>{ 'b', 'c', 'd' }</tt>.
*
* @par Buffers and Scatter-Gather I/O
*
* To read or write using multiple buffers (i.e. scatter-gather I/O), multiple
* buffer objects may be assigned into a container that supports the
* MutableBufferSequence (for read) or ConstBufferSequence (for write) concepts:
*
* @code
* char d1[128];
* std::vector<char> d2(128);
* boost::array<char, 128> d3;
*
* boost::array<mutable_buffer, 3> bufs1 = {
* asio::buffer(d1),
* asio::buffer(d2),
* asio::buffer(d3) };
* bytes_transferred = sock.receive(bufs1);
*
* std::vector<const_buffer> bufs2;
* bufs2.push_back(asio::buffer(d1));
* bufs2.push_back(asio::buffer(d2));
* bufs2.push_back(asio::buffer(d3));
* bytes_transferred = sock.send(bufs2); @endcode
*/
/*@{*/
/// Create a new modifiable buffer from an existing buffer.
/**
* @returns <tt>mutable_buffers_1(b)</tt>.
*/
inline mutable_buffers_1 buffer(const mutable_buffer& b)
{
return mutable_buffers_1(b);
}
/// Create a new modifiable buffer from an existing buffer.
/**
* @returns A mutable_buffers_1 value equivalent to:
* @code mutable_buffers_1(
* buffer_cast<void*>(b),
* min(buffer_size(b), max_size_in_bytes)); @endcode
*/
inline mutable_buffers_1 buffer(const mutable_buffer& b,
std::size_t max_size_in_bytes)
{
return mutable_buffers_1(
mutable_buffer(buffer_cast<void*>(b),
buffer_size(b) < max_size_in_bytes
? buffer_size(b) : max_size_in_bytes
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, b.get_debug_check()
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
));
}
/// Create a new non-modifiable buffer from an existing buffer.
/**
* @returns <tt>const_buffers_1(b)</tt>.
*/
inline const_buffers_1 buffer(const const_buffer& b)
{
return const_buffers_1(b);
}
/// Create a new non-modifiable buffer from an existing buffer.
/**
* @returns A const_buffers_1 value equivalent to:
* @code const_buffers_1(
* buffer_cast<const void*>(b),
* min(buffer_size(b), max_size_in_bytes)); @endcode
*/
inline const_buffers_1 buffer(const const_buffer& b,
std::size_t max_size_in_bytes)
{
return const_buffers_1(
const_buffer(buffer_cast<const void*>(b),
buffer_size(b) < max_size_in_bytes
? buffer_size(b) : max_size_in_bytes
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, b.get_debug_check()
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
));
}
/// Create a new modifiable buffer that represents the given memory range.
/**
* @returns <tt>mutable_buffers_1(data, size_in_bytes)</tt>.
*/
inline mutable_buffers_1 buffer(void* data, std::size_t size_in_bytes)
{
return mutable_buffers_1(mutable_buffer(data, size_in_bytes));
}
/// Create a new non-modifiable buffer that represents the given memory range.
/**
* @returns <tt>const_buffers_1(data, size_in_bytes)</tt>.
*/
inline const_buffers_1 buffer(const void* data,
std::size_t size_in_bytes)
{
return const_buffers_1(const_buffer(data, size_in_bytes));
}
/// Create a new modifiable buffer that represents the given POD array.
/**
* @returns A mutable_buffers_1 value equivalent to:
* @code mutable_buffers_1(
* static_cast<void*>(data),
* N * sizeof(PodType)); @endcode
*/
template <typename PodType, std::size_t N>
inline mutable_buffers_1 buffer(PodType (&data)[N])
{
return mutable_buffers_1(mutable_buffer(data, N * sizeof(PodType)));
}
/// Create a new modifiable buffer that represents the given POD array.
/**
* @returns A mutable_buffers_1 value equivalent to:
* @code mutable_buffers_1(
* static_cast<void*>(data),
* min(N * sizeof(PodType), max_size_in_bytes)); @endcode
*/
template <typename PodType, std::size_t N>
inline mutable_buffers_1 buffer(PodType (&data)[N],
std::size_t max_size_in_bytes)
{
return mutable_buffers_1(
mutable_buffer(data,
N * sizeof(PodType) < max_size_in_bytes
? N * sizeof(PodType) : max_size_in_bytes));
}
/// Create a new non-modifiable buffer that represents the given POD array.
/**
* @returns A const_buffers_1 value equivalent to:
* @code const_buffers_1(
* static_cast<const void*>(data),
* N * sizeof(PodType)); @endcode
*/
template <typename PodType, std::size_t N>
inline const_buffers_1 buffer(const PodType (&data)[N])
{
return const_buffers_1(const_buffer(data, N * sizeof(PodType)));
}
/// Create a new non-modifiable buffer that represents the given POD array.
/**
* @returns A const_buffers_1 value equivalent to:
* @code const_buffers_1(
* static_cast<const void*>(data),
* min(N * sizeof(PodType), max_size_in_bytes)); @endcode
*/
template <typename PodType, std::size_t N>
inline const_buffers_1 buffer(const PodType (&data)[N],
std::size_t max_size_in_bytes)
{
return const_buffers_1(
const_buffer(data,
N * sizeof(PodType) < max_size_in_bytes
? N * sizeof(PodType) : max_size_in_bytes));
}
#if defined(ASIO_ENABLE_ARRAY_BUFFER_WORKAROUND)
// Borland C++ and Sun Studio think the overloads:
//
// unspecified buffer(boost::array<PodType, N>& array ...);
//
// and
//
// unspecified buffer(boost::array<const PodType, N>& array ...);
//
// are ambiguous. This will be worked around by using a buffer_types traits
// class that contains typedefs for the appropriate buffer and container
// classes, based on whether PodType is const or non-const.
namespace detail {
template <bool IsConst>
struct buffer_types_base;
template <>
struct buffer_types_base<false>
{
typedef mutable_buffer buffer_type;
typedef mutable_buffers_1 container_type;
};
template <>
struct buffer_types_base<true>
{
typedef const_buffer buffer_type;
typedef const_buffers_1 container_type;
};
template <typename PodType>
struct buffer_types
: public buffer_types_base<is_const<PodType>::value>
{
};
} // namespace detail
template <typename PodType, std::size_t N>
inline typename detail::buffer_types<PodType>::container_type
buffer(boost::array<PodType, N>& data)
{
typedef typename asio::detail::buffer_types<PodType>::buffer_type
buffer_type;
typedef typename asio::detail::buffer_types<PodType>::container_type
container_type;
return container_type(
buffer_type(data.c_array(), data.size() * sizeof(PodType)));
}
template <typename PodType, std::size_t N>
inline typename detail::buffer_types<PodType>::container_type
buffer(boost::array<PodType, N>& data, std::size_t max_size_in_bytes)
{
typedef typename asio::detail::buffer_types<PodType>::buffer_type
buffer_type;
typedef typename asio::detail::buffer_types<PodType>::container_type
container_type;
return container_type(
buffer_type(data.c_array(),
data.size() * sizeof(PodType) < max_size_in_bytes
? data.size() * sizeof(PodType) : max_size_in_bytes));
}
#else // defined(ASIO_ENABLE_ARRAY_BUFFER_WORKAROUND)
/// Create a new modifiable buffer that represents the given POD array.
/**
* @returns A mutable_buffers_1 value equivalent to:
* @code mutable_buffers_1(
* data.data(),
* data.size() * sizeof(PodType)); @endcode
*/
template <typename PodType, std::size_t N>
inline mutable_buffers_1 buffer(boost::array<PodType, N>& data)
{
return mutable_buffers_1(
mutable_buffer(data.c_array(), data.size() * sizeof(PodType)));
}
/// Create a new modifiable buffer that represents the given POD array.
/**
* @returns A mutable_buffers_1 value equivalent to:
* @code mutable_buffers_1(
* data.data(),
* min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode
*/
template <typename PodType, std::size_t N>
inline mutable_buffers_1 buffer(boost::array<PodType, N>& data,
std::size_t max_size_in_bytes)
{
return mutable_buffers_1(
mutable_buffer(data.c_array(),
data.size() * sizeof(PodType) < max_size_in_bytes
? data.size() * sizeof(PodType) : max_size_in_bytes));
}
/// Create a new non-modifiable buffer that represents the given POD array.
/**
* @returns A const_buffers_1 value equivalent to:
* @code const_buffers_1(
* data.data(),
* data.size() * sizeof(PodType)); @endcode
*/
template <typename PodType, std::size_t N>
inline const_buffers_1 buffer(boost::array<const PodType, N>& data)
{
return const_buffers_1(
const_buffer(data.data(), data.size() * sizeof(PodType)));
}
/// Create a new non-modifiable buffer that represents the given POD array.
/**
* @returns A const_buffers_1 value equivalent to:
* @code const_buffers_1(
* data.data(),
* min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode
*/
template <typename PodType, std::size_t N>
inline const_buffers_1 buffer(boost::array<const PodType, N>& data,
std::size_t max_size_in_bytes)
{
return const_buffers_1(
const_buffer(data.data(),
data.size() * sizeof(PodType) < max_size_in_bytes
? data.size() * sizeof(PodType) : max_size_in_bytes));
}
#endif // defined(ASIO_ENABLE_ARRAY_BUFFER_WORKAROUND)
/// Create a new non-modifiable buffer that represents the given POD array.
/**
* @returns A const_buffers_1 value equivalent to:
* @code const_buffers_1(
* data.data(),
* data.size() * sizeof(PodType)); @endcode
*/
template <typename PodType, std::size_t N>
inline const_buffers_1 buffer(const boost::array<PodType, N>& data)
{
return const_buffers_1(
const_buffer(data.data(), data.size() * sizeof(PodType)));
}
/// Create a new non-modifiable buffer that represents the given POD array.
/**
* @returns A const_buffers_1 value equivalent to:
* @code const_buffers_1(
* data.data(),
* min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode
*/
template <typename PodType, std::size_t N>
inline const_buffers_1 buffer(const boost::array<PodType, N>& data,
std::size_t max_size_in_bytes)
{
return const_buffers_1(
const_buffer(data.data(),
data.size() * sizeof(PodType) < max_size_in_bytes
? data.size() * sizeof(PodType) : max_size_in_bytes));
}
#if defined(ASIO_HAS_STD_ARRAY) || defined(GENERATING_DOCUMENTATION)
/// Create a new modifiable buffer that represents the given POD array.
/**
* @returns A mutable_buffers_1 value equivalent to:
* @code mutable_buffers_1(
* data.data(),
* data.size() * sizeof(PodType)); @endcode
*/
template <typename PodType, std::size_t N>
inline mutable_buffers_1 buffer(std::array<PodType, N>& data)
{
return mutable_buffers_1(
mutable_buffer(data.data(), data.size() * sizeof(PodType)));
}
/// Create a new modifiable buffer that represents the given POD array.
/**
* @returns A mutable_buffers_1 value equivalent to:
* @code mutable_buffers_1(
* data.data(),
* min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode
*/
template <typename PodType, std::size_t N>
inline mutable_buffers_1 buffer(std::array<PodType, N>& data,
std::size_t max_size_in_bytes)
{
return mutable_buffers_1(
mutable_buffer(data.data(),
data.size() * sizeof(PodType) < max_size_in_bytes
? data.size() * sizeof(PodType) : max_size_in_bytes));
}
/// Create a new non-modifiable buffer that represents the given POD array.
/**
* @returns A const_buffers_1 value equivalent to:
* @code const_buffers_1(
* data.data(),
* data.size() * sizeof(PodType)); @endcode
*/
template <typename PodType, std::size_t N>
inline const_buffers_1 buffer(std::array<const PodType, N>& data)
{
return const_buffers_1(
const_buffer(data.data(), data.size() * sizeof(PodType)));
}
/// Create a new non-modifiable buffer that represents the given POD array.
/**
* @returns A const_buffers_1 value equivalent to:
* @code const_buffers_1(
* data.data(),
* min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode
*/
template <typename PodType, std::size_t N>
inline const_buffers_1 buffer(std::array<const PodType, N>& data,
std::size_t max_size_in_bytes)
{
return const_buffers_1(
const_buffer(data.data(),
data.size() * sizeof(PodType) < max_size_in_bytes
? data.size() * sizeof(PodType) : max_size_in_bytes));
}
/// Create a new non-modifiable buffer that represents the given POD array.
/**
* @returns A const_buffers_1 value equivalent to:
* @code const_buffers_1(
* data.data(),
* data.size() * sizeof(PodType)); @endcode
*/
template <typename PodType, std::size_t N>
inline const_buffers_1 buffer(const std::array<PodType, N>& data)
{
return const_buffers_1(
const_buffer(data.data(), data.size() * sizeof(PodType)));
}
/// Create a new non-modifiable buffer that represents the given POD array.
/**
* @returns A const_buffers_1 value equivalent to:
* @code const_buffers_1(
* data.data(),
* min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode
*/
template <typename PodType, std::size_t N>
inline const_buffers_1 buffer(const std::array<PodType, N>& data,
std::size_t max_size_in_bytes)
{
return const_buffers_1(
const_buffer(data.data(),
data.size() * sizeof(PodType) < max_size_in_bytes
? data.size() * sizeof(PodType) : max_size_in_bytes));
}
#endif // defined(ASIO_HAS_STD_ARRAY) || defined(GENERATING_DOCUMENTATION)
/// Create a new modifiable buffer that represents the given POD vector.
/**
* @returns A mutable_buffers_1 value equivalent to:
* @code mutable_buffers_1(
* data.size() ? &data[0] : 0,
* data.size() * sizeof(PodType)); @endcode
*
* @note The buffer is invalidated by any vector operation that would also
* invalidate iterators.
*/
template <typename PodType, typename Allocator>
inline mutable_buffers_1 buffer(std::vector<PodType, Allocator>& data)
{
return mutable_buffers_1(
mutable_buffer(data.size() ? &data[0] : 0, data.size() * sizeof(PodType)
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, detail::buffer_debug_check<
typename std::vector<PodType, Allocator>::iterator
>(data.begin())
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
));
}
/// Create a new modifiable buffer that represents the given POD vector.
/**
* @returns A mutable_buffers_1 value equivalent to:
* @code mutable_buffers_1(
* data.size() ? &data[0] : 0,
* min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode
*
* @note The buffer is invalidated by any vector operation that would also
* invalidate iterators.
*/
template <typename PodType, typename Allocator>
inline mutable_buffers_1 buffer(std::vector<PodType, Allocator>& data,
std::size_t max_size_in_bytes)
{
return mutable_buffers_1(
mutable_buffer(data.size() ? &data[0] : 0,
data.size() * sizeof(PodType) < max_size_in_bytes
? data.size() * sizeof(PodType) : max_size_in_bytes
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, detail::buffer_debug_check<
typename std::vector<PodType, Allocator>::iterator
>(data.begin())
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
));
}
/// Create a new non-modifiable buffer that represents the given POD vector.
/**
* @returns A const_buffers_1 value equivalent to:
* @code const_buffers_1(
* data.size() ? &data[0] : 0,
* data.size() * sizeof(PodType)); @endcode
*
* @note The buffer is invalidated by any vector operation that would also
* invalidate iterators.
*/
template <typename PodType, typename Allocator>
inline const_buffers_1 buffer(
const std::vector<PodType, Allocator>& data)
{
return const_buffers_1(
const_buffer(data.size() ? &data[0] : 0, data.size() * sizeof(PodType)
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, detail::buffer_debug_check<
typename std::vector<PodType, Allocator>::const_iterator
>(data.begin())
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
));
}
/// Create a new non-modifiable buffer that represents the given POD vector.
/**
* @returns A const_buffers_1 value equivalent to:
* @code const_buffers_1(
* data.size() ? &data[0] : 0,
* min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode
*
* @note The buffer is invalidated by any vector operation that would also
* invalidate iterators.
*/
template <typename PodType, typename Allocator>
inline const_buffers_1 buffer(
const std::vector<PodType, Allocator>& data, std::size_t max_size_in_bytes)
{
return const_buffers_1(
const_buffer(data.size() ? &data[0] : 0,
data.size() * sizeof(PodType) < max_size_in_bytes
? data.size() * sizeof(PodType) : max_size_in_bytes
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, detail::buffer_debug_check<
typename std::vector<PodType, Allocator>::const_iterator
>(data.begin())
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
));
}
/// Create a new modifiable buffer that represents the given string.
/**
* @returns <tt>mutable_buffers_1(data.size() ? &data[0] : 0,
* data.size() * sizeof(Elem))</tt>.
*
* @note The buffer is invalidated by any non-const operation called on the
* given string object.
*/
template <typename Elem, typename Traits, typename Allocator>
inline mutable_buffers_1 buffer(
std::basic_string<Elem, Traits, Allocator>& data)
{
return mutable_buffers_1(mutable_buffer(data.size() ? &data[0] : 0,
data.size() * sizeof(Elem)
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, detail::buffer_debug_check<
typename std::basic_string<Elem, Traits, Allocator>::iterator
>(data.begin())
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
));
}
/// Create a new non-modifiable buffer that represents the given string.
/**
* @returns A mutable_buffers_1 value equivalent to:
* @code mutable_buffers_1(
* data.size() ? &data[0] : 0,
* min(data.size() * sizeof(Elem), max_size_in_bytes)); @endcode
*
* @note The buffer is invalidated by any non-const operation called on the
* given string object.
*/
template <typename Elem, typename Traits, typename Allocator>
inline mutable_buffers_1 buffer(
std::basic_string<Elem, Traits, Allocator>& data,
std::size_t max_size_in_bytes)
{
return mutable_buffers_1(
mutable_buffer(data.size() ? &data[0] : 0,
data.size() * sizeof(Elem) < max_size_in_bytes
? data.size() * sizeof(Elem) : max_size_in_bytes
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, detail::buffer_debug_check<
typename std::basic_string<Elem, Traits, Allocator>::iterator
>(data.begin())
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
));
}
/// Create a new non-modifiable buffer that represents the given string.
/**
* @returns <tt>const_buffers_1(data.data(), data.size() * sizeof(Elem))</tt>.
*
* @note The buffer is invalidated by any non-const operation called on the
* given string object.
*/
template <typename Elem, typename Traits, typename Allocator>
inline const_buffers_1 buffer(
const std::basic_string<Elem, Traits, Allocator>& data)
{
return const_buffers_1(const_buffer(data.data(), data.size() * sizeof(Elem)
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, detail::buffer_debug_check<
typename std::basic_string<Elem, Traits, Allocator>::const_iterator
>(data.begin())
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
));
}
/// Create a new non-modifiable buffer that represents the given string.
/**
* @returns A const_buffers_1 value equivalent to:
* @code const_buffers_1(
* data.data(),
* min(data.size() * sizeof(Elem), max_size_in_bytes)); @endcode
*
* @note The buffer is invalidated by any non-const operation called on the
* given string object.
*/
template <typename Elem, typename Traits, typename Allocator>
inline const_buffers_1 buffer(
const std::basic_string<Elem, Traits, Allocator>& data,
std::size_t max_size_in_bytes)
{
return const_buffers_1(
const_buffer(data.data(),
data.size() * sizeof(Elem) < max_size_in_bytes
? data.size() * sizeof(Elem) : max_size_in_bytes
#if defined(ASIO_ENABLE_BUFFER_DEBUGGING)
, detail::buffer_debug_check<
typename std::basic_string<Elem, Traits, Allocator>::const_iterator
>(data.begin())
#endif // ASIO_ENABLE_BUFFER_DEBUGGING
));
}
/*@}*/
/// Adapt a basic_string to the DynamicBufferSequence requirements.
/**
* Requires that <tt>sizeof(Elem) == 1</tt>.
*/
template <typename Elem, typename Traits, typename Allocator>
class dynamic_string_buffer
{
public:
/// The type used to represent the input sequence as a list of buffers.
typedef const_buffers_1 const_buffers_type;
/// The type used to represent the output sequence as a list of buffers.
typedef mutable_buffers_1 mutable_buffers_type;
/// Construct a dynamic buffer from a string.
/**
* @param s The string to be used as backing storage for the dynamic buffer.
* Any existing data in the string is treated as the dynamic buffer's input
* sequence. The object stores a reference to the string and the user is
* responsible for ensuring that the string object remains valid until the
* dynamic_string_buffer object is destroyed.
*
* @param maximum_size Specifies a maximum size for the buffer, in bytes.
*/
explicit dynamic_string_buffer(std::basic_string<Elem, Traits, Allocator>& s,
std::size_t maximum_size = (std::numeric_limits<std::size_t>::max)())
: string_(s),
size_(string_.size()),
max_size_(maximum_size)
{
}
#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Move construct a dynamic buffer.
dynamic_string_buffer(dynamic_string_buffer&& other)
: string_(other.string_),
size_(other.size_),
max_size_(other.max_size_)
{
}
#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Get the size of the input sequence.
std::size_t size() const ASIO_NOEXCEPT
{
return size_;
}
/// Get the maximum size of the dynamic buffer.
/**
* @returns The allowed maximum of the sum of the sizes of the input sequence
* and output sequence.
*/
std::size_t max_size() const ASIO_NOEXCEPT
{
return max_size_;
}
/// Get the current capacity of the dynamic buffer.
/**
* @returns The current total capacity of the buffer, i.e. for both the input
* sequence and output sequence.
*/
std::size_t capacity() const ASIO_NOEXCEPT
{
return string_.capacity();
}
/// Get a list of buffers that represents the input sequence.
/**
* @returns An object of type @c const_buffers_type that satisfies
* ConstBufferSequence requirements, representing the basic_string memory in
* input sequence.
*
* @note The returned object is invalidated by any @c dynamic_string_buffer
* or @c basic_string member function that modifies the input sequence or
* output sequence.
*/
const_buffers_type data() const ASIO_NOEXCEPT
{
return asio::buffer(string_, size_);
}
/// Get a list of buffers that represents the output sequence, with the given
/// size.
/**
* Ensures that the output sequence can accommodate @c n bytes, resizing the
* basic_string object as necessary.
*
* @returns An object of type @c mutable_buffers_type that satisfies
* MutableBufferSequence requirements, representing basic_string memory
* at the start of the output sequence of size @c n.
*
* @throws std::length_error If <tt>size() + n > max_size()</tt>.
*
* @note The returned object is invalidated by any @c dynamic_string_buffer
* or @c basic_string member function that modifies the input sequence or
* output sequence.
*/
mutable_buffers_type prepare(std::size_t n)
{
if (size () > max_size() || max_size() - size() < n)
{
std::length_error ex("dynamic_string_buffer too long");
asio::detail::throw_exception(ex);
}
string_.resize(size_ + n);
return asio::buffer(asio::buffer(string_) + size_, n);
}
/// Move bytes from the output sequence to the input sequence.
/**
* @param n The number of bytes to append from the start of the output
* sequence to the end of the input sequence. The remainder of the output
* sequence is discarded.
*
* Requires a preceding call <tt>prepare(x)</tt> where <tt>x >= n</tt>, and
* no intervening operations that modify the input or output sequence.
*
* @note If @c n is greater than the size of the output sequence, the entire
* output sequence is moved to the input sequence and no error is issued.
*/
void commit(std::size_t n)
{
size_ += (std::min)(n, string_.size() - size_);
string_.resize(size_);
}
/// Remove characters from the input sequence.
/**
* Removes @c n characters from the beginning of the input sequence.
*
* @note If @c n is greater than the size of the input sequence, the entire
* input sequence is consumed and no error is issued.
*/
void consume(std::size_t n)
{
std::size_t consume_length = (std::min)(n, size_);
string_.erase(consume_length);
size_ -= consume_length;
}
private:
std::basic_string<Elem, Traits, Allocator>& string_;
std::size_t size_;
const std::size_t max_size_;
};
/// Adapt a vector to the DynamicBufferSequence requirements.
/**
* Requires that <tt>sizeof(Elem) == 1</tt>.
*/
template <typename Elem, typename Allocator>
class dynamic_vector_buffer
{
public:
/// The type used to represent the input sequence as a list of buffers.
typedef const_buffers_1 const_buffers_type;
/// The type used to represent the output sequence as a list of buffers.
typedef mutable_buffers_1 mutable_buffers_type;
/// Construct a dynamic buffer from a string.
/**
* @param v The vector to be used as backing storage for the dynamic buffer.
* Any existing data in the vector is treated as the dynamic buffer's input
* sequence. The object stores a reference to the vector and the user is
* responsible for ensuring that the vector object remains valid until the
* dynamic_vector_buffer object is destroyed.
*
* @param maximum_size Specifies a maximum size for the buffer, in bytes.
*/
explicit dynamic_vector_buffer(std::vector<Elem, Allocator>& v,
std::size_t maximum_size = (std::numeric_limits<std::size_t>::max)())
: vector_(v),
size_(vector_.size()),
max_size_(maximum_size)
{
}
#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Move construct a dynamic buffer.
dynamic_vector_buffer(dynamic_vector_buffer&& other)
: vector_(other.vector_),
size_(other.size_),
max_size_(other.max_size_)
{
}
#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
/// Get the size of the input sequence.
std::size_t size() const ASIO_NOEXCEPT
{
return size_;
}
/// Get the maximum size of the dynamic buffer.
/**
* @returns The allowed maximum of the sum of the sizes of the input sequence
* and output sequence.
*/
std::size_t max_size() const ASIO_NOEXCEPT
{
return max_size_;
}
/// Get the current capacity of the dynamic buffer.
/**
* @returns The current total capacity of the buffer, i.e. for both the input
* sequence and output sequence.
*/
std::size_t capacity() const ASIO_NOEXCEPT
{
return vector_.capacity();
}
/// Get a list of buffers that represents the input sequence.
/**
* @returns An object of type @c const_buffers_type that satisfies
* ConstBufferSequence requirements, representing the basic_string memory in
* input sequence.
*
* @note The returned object is invalidated by any @c dynamic_vector_buffer
* or @c basic_string member function that modifies the input sequence or
* output sequence.
*/
const_buffers_type data() const ASIO_NOEXCEPT
{
return asio::buffer(vector_, size_);
}
/// Get a list of buffers that represents the output sequence, with the given
/// size.
/**
* Ensures that the output sequence can accommodate @c n bytes, resizing the
* basic_string object as necessary.
*
* @returns An object of type @c mutable_buffers_type that satisfies
* MutableBufferSequence requirements, representing basic_string memory
* at the start of the output sequence of size @c n.
*
* @throws std::length_error If <tt>size() + n > max_size()</tt>.
*
* @note The returned object is invalidated by any @c dynamic_vector_buffer
* or @c basic_string member function that modifies the input sequence or
* output sequence.
*/
mutable_buffers_type prepare(std::size_t n)
{
if (size () > max_size() || max_size() - size() < n)
{
std::length_error ex("dynamic_vector_buffer too long");
asio::detail::throw_exception(ex);
}
vector_.resize(size_ + n);
return asio::buffer(asio::buffer(vector_) + size_, n);
}
/// Move bytes from the output sequence to the input sequence.
/**
* @param n The number of bytes to append from the start of the output
* sequence to the end of the input sequence. The remainder of the output
* sequence is discarded.
*
* Requires a preceding call <tt>prepare(x)</tt> where <tt>x >= n</tt>, and
* no intervening operations that modify the input or output sequence.
*
* @note If @c n is greater than the size of the output sequence, the entire
* output sequence is moved to the input sequence and no error is issued.
*/
void commit(std::size_t n)
{
size_ += (std::min)(n, vector_.size() - size_);
vector_.resize(size_);
}
/// Remove characters from the input sequence.
/**
* Removes @c n characters from the beginning of the input sequence.
*
* @note If @c n is greater than the size of the input sequence, the entire
* input sequence is consumed and no error is issued.
*/
void consume(std::size_t n)
{
std::size_t consume_length = (std::min)(n, size_);
vector_.erase(consume_length);
size_ -= consume_length;
}
private:
std::vector<Elem, Allocator>& vector_;
std::size_t size_;
const std::size_t max_size_;
};
/** @defgroup dynamic_buffer asio::dynamic_buffer
*
* @brief The asio::dynamic_buffer function is used to create a
* dynamically resized buffer from a @c std::basic_string or @c std::vector.
*/
/*@{*/
/// Create a new dynamic buffer that represents the given string.
/**
* @returns <tt>dynamic_string_buffer<Elem, Traits, Allocator>(data)</tt>.
*/
template <typename Elem, typename Traits, typename Allocator>
inline dynamic_string_buffer<Elem, Traits, Allocator> dynamic_buffer(
std::basic_string<Elem, Traits, Allocator>& data)
{
return dynamic_string_buffer<Elem, Traits, Allocator>(data);
}
/// Create a new dynamic buffer that represents the given string.
/**
* @returns <tt>dynamic_string_buffer<Elem, Traits, Allocator>(data,
* max_size)</tt>.
*/
template <typename Elem, typename Traits, typename Allocator>
inline dynamic_string_buffer<Elem, Traits, Allocator> dynamic_buffer(
std::basic_string<Elem, Traits, Allocator>& data, std::size_t max_size)
{
return dynamic_string_buffer<Elem, Traits, Allocator>(data, max_size);
}
/// Create a new dynamic buffer that represents the given vector.
/**
* @returns <tt>dynamic_vector_buffer<Elem, Allocator>(data)</tt>.
*/
template <typename Elem, typename Allocator>
inline dynamic_vector_buffer<Elem, Allocator> dynamic_buffer(
std::vector<Elem, Allocator>& data)
{
return dynamic_vector_buffer<Elem, Allocator>(data);
}
/// Create a new dynamic buffer that represents the given vector.
/**
* @returns <tt>dynamic_vector_buffer<Elem, Allocator>(data, max_size)</tt>.
*/
template <typename Elem, typename Allocator>
inline dynamic_vector_buffer<Elem, Allocator> dynamic_buffer(
std::vector<Elem, Allocator>& data, std::size_t max_size)
{
return dynamic_vector_buffer<Elem, Allocator>(data, max_size);
}
/*@}*/
/** @defgroup buffer_copy asio::buffer_copy
*
* @brief The asio::buffer_copy function is used to copy bytes from a
* source buffer (or buffer sequence) to a target buffer (or buffer sequence).
*
* The @c buffer_copy function is available in two forms:
*
* @li A 2-argument form: @c buffer_copy(target, source)
*
* @li A 3-argument form: @c buffer_copy(target, source, max_bytes_to_copy)
*
* Both forms return the number of bytes actually copied. The number of bytes
* copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c If specified, @c max_bytes_to_copy.
*
* This prevents buffer overflow, regardless of the buffer sizes used in the
* copy operation.
*
* Note that @ref buffer_copy is implemented in terms of @c memcpy, and
* consequently it cannot be used to copy between overlapping memory regions.
*/
/*@{*/
/// Copies bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A non-modifiable buffer representing the memory region from
* which the bytes will be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffer& target,
const const_buffer& source)
{
using namespace std; // For memcpy.
std::size_t target_size = buffer_size(target);
std::size_t source_size = buffer_size(source);
std::size_t n = target_size < source_size ? target_size : source_size;
memcpy(buffer_cast<void*>(target), buffer_cast<const void*>(source), n);
return n;
}
/// Copies bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A non-modifiable buffer representing the memory region from
* which the bytes will be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffer& target,
const const_buffers_1& source)
{
return buffer_copy(target, static_cast<const const_buffer&>(source));
}
/// Copies bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A modifiable buffer representing the memory region from which
* the bytes will be copied. The contents of the source buffer will not be
* modified.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffer& target,
const mutable_buffer& source)
{
return buffer_copy(target, const_buffer(source));
}
/// Copies bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A modifiable buffer representing the memory region from which
* the bytes will be copied. The contents of the source buffer will not be
* modified.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffer& target,
const mutable_buffers_1& source)
{
return buffer_copy(target, const_buffer(source));
}
/// Copies bytes from a source buffer sequence to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A non-modifiable buffer sequence representing the memory
* regions from which the bytes will be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
template <typename ConstBufferSequence>
std::size_t buffer_copy(const mutable_buffer& target,
const ConstBufferSequence& source,
typename enable_if<
is_const_buffer_sequence<ConstBufferSequence>::value
>::type* = 0)
{
std::size_t total_bytes_copied = 0;
typename ConstBufferSequence::const_iterator source_iter = source.begin();
typename ConstBufferSequence::const_iterator source_end = source.end();
for (mutable_buffer target_buffer(target);
buffer_size(target_buffer) && source_iter != source_end; ++source_iter)
{
const_buffer source_buffer(*source_iter);
std::size_t bytes_copied = buffer_copy(target_buffer, source_buffer);
total_bytes_copied += bytes_copied;
target_buffer = target_buffer + bytes_copied;
}
return total_bytes_copied;
}
/// Copies bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A non-modifiable buffer representing the memory region from
* which the bytes will be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffers_1& target,
const const_buffer& source)
{
return buffer_copy(static_cast<const mutable_buffer&>(target), source);
}
/// Copies bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A non-modifiable buffer representing the memory region from
* which the bytes will be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffers_1& target,
const const_buffers_1& source)
{
return buffer_copy(static_cast<const mutable_buffer&>(target),
static_cast<const const_buffer&>(source));
}
/// Copies bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A modifiable buffer representing the memory region from which
* the bytes will be copied. The contents of the source buffer will not be
* modified.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffers_1& target,
const mutable_buffer& source)
{
return buffer_copy(static_cast<const mutable_buffer&>(target),
const_buffer(source));
}
/// Copies bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A modifiable buffer representing the memory region from which
* the bytes will be copied. The contents of the source buffer will not be
* modified.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffers_1& target,
const mutable_buffers_1& source)
{
return buffer_copy(static_cast<const mutable_buffer&>(target),
const_buffer(source));
}
/// Copies bytes from a source buffer sequence to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A non-modifiable buffer sequence representing the memory
* regions from which the bytes will be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
template <typename ConstBufferSequence>
inline std::size_t buffer_copy(const mutable_buffers_1& target,
const ConstBufferSequence& source,
typename enable_if<
is_const_buffer_sequence<ConstBufferSequence>::value
>::type* = 0)
{
return buffer_copy(static_cast<const mutable_buffer&>(target), source);
}
/// Copies bytes from a source buffer to a target buffer sequence.
/**
* @param target A modifiable buffer sequence representing the memory regions to
* which the bytes will be copied.
*
* @param source A non-modifiable buffer representing the memory region from
* which the bytes will be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
template <typename MutableBufferSequence>
std::size_t buffer_copy(const MutableBufferSequence& target,
const const_buffer& source,
typename enable_if<
is_mutable_buffer_sequence<MutableBufferSequence>::value
>::type* = 0)
{
std::size_t total_bytes_copied = 0;
typename MutableBufferSequence::const_iterator target_iter = target.begin();
typename MutableBufferSequence::const_iterator target_end = target.end();
for (const_buffer source_buffer(source);
buffer_size(source_buffer) && target_iter != target_end; ++target_iter)
{
mutable_buffer target_buffer(*target_iter);
std::size_t bytes_copied = buffer_copy(target_buffer, source_buffer);
total_bytes_copied += bytes_copied;
source_buffer = source_buffer + bytes_copied;
}
return total_bytes_copied;
}
/// Copies bytes from a source buffer to a target buffer sequence.
/**
* @param target A modifiable buffer sequence representing the memory regions to
* which the bytes will be copied.
*
* @param source A non-modifiable buffer representing the memory region from
* which the bytes will be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
template <typename MutableBufferSequence>
inline std::size_t buffer_copy(const MutableBufferSequence& target,
const const_buffers_1& source,
typename enable_if<
is_mutable_buffer_sequence<MutableBufferSequence>::value
>::type* = 0)
{
return buffer_copy(target, static_cast<const const_buffer&>(source));
}
/// Copies bytes from a source buffer to a target buffer sequence.
/**
* @param target A modifiable buffer sequence representing the memory regions to
* which the bytes will be copied.
*
* @param source A modifiable buffer representing the memory region from which
* the bytes will be copied. The contents of the source buffer will not be
* modified.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
template <typename MutableBufferSequence>
inline std::size_t buffer_copy(const MutableBufferSequence& target,
const mutable_buffer& source,
typename enable_if<
is_mutable_buffer_sequence<MutableBufferSequence>::value
>::type* = 0)
{
return buffer_copy(target, const_buffer(source));
}
/// Copies bytes from a source buffer to a target buffer sequence.
/**
* @param target A modifiable buffer sequence representing the memory regions to
* which the bytes will be copied.
*
* @param source A modifiable buffer representing the memory region from which
* the bytes will be copied. The contents of the source buffer will not be
* modified.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
template <typename MutableBufferSequence>
inline std::size_t buffer_copy(const MutableBufferSequence& target,
const mutable_buffers_1& source,
typename enable_if<
is_mutable_buffer_sequence<MutableBufferSequence>::value
>::type* = 0)
{
return buffer_copy(target, const_buffer(source));
}
/// Copies bytes from a source buffer sequence to a target buffer sequence.
/**
* @param target A modifiable buffer sequence representing the memory regions to
* which the bytes will be copied.
*
* @param source A non-modifiable buffer sequence representing the memory
* regions from which the bytes will be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
template <typename MutableBufferSequence, typename ConstBufferSequence>
std::size_t buffer_copy(const MutableBufferSequence& target,
const ConstBufferSequence& source,
typename enable_if<
is_mutable_buffer_sequence<MutableBufferSequence>::value &&
is_const_buffer_sequence<ConstBufferSequence>::value
>::type* = 0)
{
std::size_t total_bytes_copied = 0;
typename MutableBufferSequence::const_iterator target_iter = target.begin();
typename MutableBufferSequence::const_iterator target_end = target.end();
std::size_t target_buffer_offset = 0;
typename ConstBufferSequence::const_iterator source_iter = source.begin();
typename ConstBufferSequence::const_iterator source_end = source.end();
std::size_t source_buffer_offset = 0;
while (target_iter != target_end && source_iter != source_end)
{
mutable_buffer target_buffer =
mutable_buffer(*target_iter) + target_buffer_offset;
const_buffer source_buffer =
const_buffer(*source_iter) + source_buffer_offset;
std::size_t bytes_copied = buffer_copy(target_buffer, source_buffer);
total_bytes_copied += bytes_copied;
if (bytes_copied == buffer_size(target_buffer))
{
++target_iter;
target_buffer_offset = 0;
}
else
target_buffer_offset += bytes_copied;
if (bytes_copied == buffer_size(source_buffer))
{
++source_iter;
source_buffer_offset = 0;
}
else
source_buffer_offset += bytes_copied;
}
return total_bytes_copied;
}
/// Copies a limited number of bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A non-modifiable buffer representing the memory region from
* which the bytes will be copied.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffer& target,
const const_buffer& source, std::size_t max_bytes_to_copy)
{
return buffer_copy(buffer(target, max_bytes_to_copy), source);
}
/// Copies a limited number of bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A non-modifiable buffer representing the memory region from
* which the bytes will be copied.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffer& target,
const const_buffers_1& source, std::size_t max_bytes_to_copy)
{
return buffer_copy(buffer(target, max_bytes_to_copy), source);
}
/// Copies a limited number of bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A modifiable buffer representing the memory region from which
* the bytes will be copied. The contents of the source buffer will not be
* modified.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffer& target,
const mutable_buffer& source, std::size_t max_bytes_to_copy)
{
return buffer_copy(buffer(target, max_bytes_to_copy), source);
}
/// Copies a limited number of bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A modifiable buffer representing the memory region from which
* the bytes will be copied. The contents of the source buffer will not be
* modified.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffer& target,
const mutable_buffers_1& source, std::size_t max_bytes_to_copy)
{
return buffer_copy(buffer(target, max_bytes_to_copy), source);
}
/// Copies a limited number of bytes from a source buffer sequence to a target
/// buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A non-modifiable buffer sequence representing the memory
* regions from which the bytes will be copied.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
template <typename ConstBufferSequence>
inline std::size_t buffer_copy(const mutable_buffer& target,
const ConstBufferSequence& source, std::size_t max_bytes_to_copy,
typename enable_if<
is_const_buffer_sequence<ConstBufferSequence>::value
>::type* = 0)
{
return buffer_copy(buffer(target, max_bytes_to_copy), source);
}
/// Copies a limited number of bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A non-modifiable buffer representing the memory region from
* which the bytes will be copied.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffers_1& target,
const const_buffer& source, std::size_t max_bytes_to_copy)
{
return buffer_copy(buffer(target, max_bytes_to_copy), source);
}
/// Copies a limited number of bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A non-modifiable buffer representing the memory region from
* which the bytes will be copied.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffers_1& target,
const const_buffers_1& source, std::size_t max_bytes_to_copy)
{
return buffer_copy(buffer(target, max_bytes_to_copy), source);
}
/// Copies a limited number of bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A modifiable buffer representing the memory region from which
* the bytes will be copied. The contents of the source buffer will not be
* modified.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffers_1& target,
const mutable_buffer& source, std::size_t max_bytes_to_copy)
{
return buffer_copy(buffer(target, max_bytes_to_copy), source);
}
/// Copies a limited number of bytes from a source buffer to a target buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A modifiable buffer representing the memory region from which
* the bytes will be copied. The contents of the source buffer will not be
* modified.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
inline std::size_t buffer_copy(const mutable_buffers_1& target,
const mutable_buffers_1& source, std::size_t max_bytes_to_copy)
{
return buffer_copy(buffer(target, max_bytes_to_copy), source);
}
/// Copies a limited number of bytes from a source buffer sequence to a target
/// buffer.
/**
* @param target A modifiable buffer representing the memory region to which
* the bytes will be copied.
*
* @param source A non-modifiable buffer sequence representing the memory
* regions from which the bytes will be copied.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
template <typename ConstBufferSequence>
inline std::size_t buffer_copy(const mutable_buffers_1& target,
const ConstBufferSequence& source, std::size_t max_bytes_to_copy,
typename enable_if<
is_const_buffer_sequence<ConstBufferSequence>::value
>::type* = 0)
{
return buffer_copy(buffer(target, max_bytes_to_copy), source);
}
/// Copies a limited number of bytes from a source buffer to a target buffer
/// sequence.
/**
* @param target A modifiable buffer sequence representing the memory regions to
* which the bytes will be copied.
*
* @param source A non-modifiable buffer representing the memory region from
* which the bytes will be copied.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
template <typename MutableBufferSequence>
inline std::size_t buffer_copy(const MutableBufferSequence& target,
const const_buffer& source, std::size_t max_bytes_to_copy,
typename enable_if<
is_mutable_buffer_sequence<MutableBufferSequence>::value
>::type* = 0)
{
return buffer_copy(target, buffer(source, max_bytes_to_copy));
}
/// Copies a limited number of bytes from a source buffer to a target buffer
/// sequence.
/**
* @param target A modifiable buffer sequence representing the memory regions to
* which the bytes will be copied.
*
* @param source A non-modifiable buffer representing the memory region from
* which the bytes will be copied.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
template <typename MutableBufferSequence>
inline std::size_t buffer_copy(const MutableBufferSequence& target,
const const_buffers_1& source, std::size_t max_bytes_to_copy,
typename enable_if<
is_mutable_buffer_sequence<MutableBufferSequence>::value
>::type* = 0)
{
return buffer_copy(target, buffer(source, max_bytes_to_copy));
}
/// Copies a limited number of bytes from a source buffer to a target buffer
/// sequence.
/**
* @param target A modifiable buffer sequence representing the memory regions to
* which the bytes will be copied.
*
* @param source A modifiable buffer representing the memory region from which
* the bytes will be copied. The contents of the source buffer will not be
* modified.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
template <typename MutableBufferSequence>
inline std::size_t buffer_copy(const MutableBufferSequence& target,
const mutable_buffer& source, std::size_t max_bytes_to_copy,
typename enable_if<
is_mutable_buffer_sequence<MutableBufferSequence>::value
>::type* = 0)
{
return buffer_copy(target, buffer(source, max_bytes_to_copy));
}
/// Copies a limited number of bytes from a source buffer to a target buffer
/// sequence.
/**
* @param target A modifiable buffer sequence representing the memory regions to
* which the bytes will be copied.
*
* @param source A modifiable buffer representing the memory region from which
* the bytes will be copied. The contents of the source buffer will not be
* modified.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
template <typename MutableBufferSequence>
inline std::size_t buffer_copy(const MutableBufferSequence& target,
const mutable_buffers_1& source, std::size_t max_bytes_to_copy,
typename enable_if<
is_mutable_buffer_sequence<MutableBufferSequence>::value
>::type* = 0)
{
return buffer_copy(target, buffer(source, max_bytes_to_copy));
}
/// Copies a limited number of bytes from a source buffer sequence to a target
/// buffer sequence.
/**
* @param target A modifiable buffer sequence representing the memory regions to
* which the bytes will be copied.
*
* @param source A non-modifiable buffer sequence representing the memory
* regions from which the bytes will be copied.
*
* @param max_bytes_to_copy The maximum number of bytes to be copied.
*
* @returns The number of bytes copied.
*
* @note The number of bytes copied is the lesser of:
*
* @li @c buffer_size(target)
*
* @li @c buffer_size(source)
*
* @li @c max_bytes_to_copy
*
* This function is implemented in terms of @c memcpy, and consequently it
* cannot be used to copy between overlapping memory regions.
*/
template <typename MutableBufferSequence, typename ConstBufferSequence>
std::size_t buffer_copy(const MutableBufferSequence& target,
const ConstBufferSequence& source, std::size_t max_bytes_to_copy,
typename enable_if<
is_mutable_buffer_sequence<MutableBufferSequence>::value &&
is_const_buffer_sequence<ConstBufferSequence>::value
>::type* = 0)
{
std::size_t total_bytes_copied = 0;
typename MutableBufferSequence::const_iterator target_iter = target.begin();
typename MutableBufferSequence::const_iterator target_end = target.end();
std::size_t target_buffer_offset = 0;
typename ConstBufferSequence::const_iterator source_iter = source.begin();
typename ConstBufferSequence::const_iterator source_end = source.end();
std::size_t source_buffer_offset = 0;
while (total_bytes_copied != max_bytes_to_copy
&& target_iter != target_end && source_iter != source_end)
{
mutable_buffer target_buffer =
mutable_buffer(*target_iter) + target_buffer_offset;
const_buffer source_buffer =
const_buffer(*source_iter) + source_buffer_offset;
std::size_t bytes_copied = buffer_copy(target_buffer,
source_buffer, max_bytes_to_copy - total_bytes_copied);
total_bytes_copied += bytes_copied;
if (bytes_copied == buffer_size(target_buffer))
{
++target_iter;
target_buffer_offset = 0;
}
else
target_buffer_offset += bytes_copied;
if (bytes_copied == buffer_size(source_buffer))
{
++source_iter;
source_buffer_offset = 0;
}
else
source_buffer_offset += bytes_copied;
}
return total_bytes_copied;
}
/*@}*/
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // ASIO_BUFFER_HPP
| [
"[email protected]"
] | |
bdffb036a95b305c393e902c7da1f2054ab61d37 | f12f4aeca340c2183704377fc6ce6ff4131fc5a0 | /Source/Wesley_S_Final/Final_GameStateBase.cpp | 63ddb9484fb3d7babd5d8a238767e5bbc4dfa79b | [] | no_license | WesleySweazey/Wesley_S_Final | 04b8a0fa0afa63035e494edac91a71a35d467465 | d765927ff53b35946dcc692e7c8e7ba72b64a025 | refs/heads/master | 2020-05-01T19:13:22.887974 | 2019-03-29T00:47:27 | 2019-03-29T00:47:27 | 177,642,555 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,401 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "Final_GameStateBase.h"
#include "GameFramework/GameStateBase.h"
#include "Net/UnrealNetwork.h"
AFinal_GameStateBase::AFinal_GameStateBase()
{
bIsPlayerOneLoggedIn = false;
bIsPlayerTwoLoggedIn = false;
//SetReplicates(true);
}
void AFinal_GameStateBase::Multicast_SetScoreTeamOne_Implementation(int Score)
{
TeamOneScore = Score;
}
void AFinal_GameStateBase::Multicast_SetScoreTeamTwo_Implementation(int Score)
{
TeamTwoScore = Score;
}
//TODO Week 7: REPLICATE Variables
void AFinal_GameStateBase::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
//REPLICATE
//DOREPLIFETIME(AFinal_GameStateBase, TeamsEnabled);
DOREPLIFETIME(AFinal_GameStateBase, TeamOneScore);
DOREPLIFETIME(AFinal_GameStateBase, TeamTwoScore);
DOREPLIFETIME(AFinal_GameStateBase, bIsPlayerOneLoggedIn);
DOREPLIFETIME(AFinal_GameStateBase, bIsPlayerTwoLoggedIn);
//DOREPLIFETIME(ABaseGameState, TeamOneSize);
//DOREPLIFETIME(ABaseGameState, TeamTwoSize);
//DOREPLIFETIME(ABaseGameState, GameTime);
DOREPLIFETIME(AFinal_GameStateBase, TeamOnePMaterials);
DOREPLIFETIME(AFinal_GameStateBase, TeamTwoPMaterials);
DOREPLIFETIME(AFinal_GameStateBase, TeamThreePMaterials);
}
| [
"[email protected]"
] | |
ed2f55b2910df75307eea363169beab209bd1676 | 1c390cd4fd3605046914767485b49a929198b470 | /luogu/P2209.cpp | 91ca8ed43df9a18858f47994b5248f4223f19459 | [] | no_license | wwwwodddd/Zukunft | f87fe736b53506f69ab18db674311dd60de04a43 | 03ffffee9a76e99f6e00bba6dbae91abc6994a34 | refs/heads/master | 2023-01-24T06:14:35.691292 | 2023-01-21T15:42:32 | 2023-01-21T15:42:32 | 163,685,977 | 7 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 973 | cpp | #include <bits/stdc++.h>
using namespace std;
int n, g, b, d;
long long z;
pair<int, int> a[50020];
deque<pair<int, int> > q;
int main()
{
scanf("%d%d%d%d", &n, &g, &b, &d);
for (int i = 1; i <= n; i++)
{
scanf("%d%d", &a[i].first, &a[i].second);
}
sort(a + 1, a + n + 1);
a[n + 1].first = d;
q.push_back(make_pair(b, 0));
for (int i = 1; i <= n + 1; i++)
{
int l = a[i].first - a[i - 1].first;
while (l > 0 && q.size() > 0)
{
if (q.front().first > l)
{
z += (long long)l * q.front().second;
b -= l;
q.front().first -= l;
l = 0;
}
else
{
z += (long long)q.front().first * q.front().second;
b -= q.front().first;
l -= q.front().first;
q.pop_front();
}
}
if (l > 0)
{
printf("-1\n");
return 0;
}
while (q.size() > 0 && a[i].second <= q.back().second)
{
b -= q.back().first;
q.pop_back();
}
q.push_back(make_pair(g - b, a[i].second));
b = g;
}
printf("%lld\n", z);
return 0;
} | [
"[email protected]"
] | |
2a8f2299ed4b3ff677a38dcfcc777133bc3bfc35 | 7be1f02caba12f7a4ccc9a16a5c65b104aa124cf | /Collada.cpp | 78b876b63219b9cae977a9180db9056bffa2a2bd | [] | no_license | sungsoosmess/ColladaVR | 6c720a00e75bd24ad459923e48f99da8fd6cbc9c | df3335e71ae1708093332fc8f779bfa56e7e7472 | refs/heads/master | 2022-03-28T08:35:37.302964 | 2019-12-31T22:08:36 | 2019-12-31T22:08:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,265 | cpp | // Collada.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "Collada.h"
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_COLLADA, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_COLLADA));
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_COLLADA));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCE(IDC_COLLADA);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HINSTANCE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
switch (message)
{
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
| [
"[email protected]"
] | |
b7a27bbfb48106843ee73d62f02cb8ec9b497a8f | 1d0a700bbd7e8542a1f45a133b5e146cad35a9d1 | /Ponto.cpp | a88a94690b5530c8076ce4c30b1ec7c6e0500cc2 | [] | no_license | rbpimenta/CG-2015-UFES-TC1 | 3674c533739a3b324114ff2256a864cf27c046e2 | 317e043ad2d0b03d0a984c4b038d095dab36c67d | refs/heads/master | 2022-02-19T14:25:57.801847 | 2022-02-08T12:47:47 | 2022-02-08T12:47:47 | 43,628,402 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 600 | cpp | /*
* Ponto.cpp
*
* Created on: 20/08/2015
* Author: rodrigo
*/
#include "Ponto.h"
Ponto::Ponto(int x, int y, int id) {
// TODO Auto-generated constructor stub
this->x = x;
this->y = y;
this->identificador = id;
}
Ponto::~Ponto() {
// TODO Auto-generated destructor stub
}
float Ponto::getX(){
return this->x;
}
void Ponto::setX(float x) {
this->x = x;
}
float Ponto::getY () {
return this->y;
}
void Ponto::setY (float y) {
this->y = y;
}
int Ponto::getIdentificador() {
return this->identificador;
}
void Ponto::setIdentificador(int id) {
this->identificador = id;
}
| [
"[email protected]"
] | |
024fce5710bdc87664dad80ca0092cddd289d791 | bd1b37597a9e4baac3913f73f28ee5e897b33e76 | /plugins/matchmaker/pluginsrc/matchmaker_plugin.cpp | 7a77d548b4adfb4fc3072a64d18ded976ebea8b1 | [
"BSD-2-Clause"
] | permissive | pretty-wise/link | 3f3b00b9ca9d17dad0a9d5db6cd3063633918587 | 16a4241c4978136d8c4bd1caab20bdf37df9caaf | refs/heads/master | 2023-01-13T08:33:20.969484 | 2019-11-29T01:43:34 | 2019-11-29T01:43:34 | 58,286,721 | 0 | 0 | null | 2023-01-04T05:22:28 | 2016-05-07T22:20:45 | C++ | UTF-8 | C++ | false | false | 2,764 | cpp | /*
* Copywrite 2014-2015 Krzysztof Stasik. All rights reserved.
*/
#include "matchmaker_plugin.h"
#include "link/plugin_log.h"
#include "tinyxml2.h"
#include "common/protobuf_stream.h"
#include "common/json/json_writer.h"
//#include "protocol/gate.pb.h"
namespace Link {
namespace Matchmaker {
MatchmakerPlugin::MatchmakerPlugin()
: SimplePlugin(kUpdateDeltaMs) {
m_recv_buffer = malloc(kRecvBufferSize);
}
MatchmakerPlugin::~MatchmakerPlugin() {
free(m_recv_buffer);
}
bool MatchmakerPlugin::OnStartup(const char* config, streamsize nbytes) {
if(!config || nbytes == 0) {
PLUGIN_ERROR("no config");
return false;
}
tinyxml2::XMLDocument doc;
tinyxml2::XMLError err = doc.Parse(config, nbytes);
if(err != tinyxml2::XML_SUCCESS){
PLUGIN_ERROR("problem parsing config: %s(%d)", doc.ErrorName(), err);
return false;
}
/*
u16 port = 0;
tinyxml2::XMLElement* root = doc.RootElement();
if(root->Attribute("port")) {
port = root->IntAttribute("port");
PLUGIN_INFO("port read %d", port);
} else {
PLUGIN_WARN("no port specified, defaulting to 0");
}
if(!root->Attribute("max_connections")) {
PLUGIN_ERROR("maximum connection count not specified");
return false;
}
u32 max_connections = root->IntAttribute("max_connections");
PLUGIN_INFO("maximum number of connections: %d", max_connections);
*/
return true;
}
void MatchmakerPlugin::OnShutdown() {
}
void MatchmakerPlugin::OnUpdate(unsigned int dt) {
(void)dt;
}
void MatchmakerPlugin::OnRecvReady(const ConnectionNotification& notif) {
SimplePlugin::Recv(notif.handle, m_recv_buffer, kRecvBufferSize, [&](void* buffer, unsigned int nbytes){
ParseDataReceived(buffer, nbytes, notif.handle, notif.endpoint);
});
}
void MatchmakerPlugin::OnNotification(const Notification& notif) {
ProcessNotification(notif);
}
void MatchmakerPlugin::OnPluginConnected(const ConnectionNotification& notif) {
if(GetRestConnection() == notif.handle) {
return; // ignore rest plugin connection.
}
}
void MatchmakerPlugin::OnConnected(const ConnectionNotification& notif) {
if(GetRestConnection() == notif.handle) {
return; // ignore rest plugin connection.
}
}
void MatchmakerPlugin::OnDisconnected(const ConnectionNotification& notif) {
if(GetRestConnection() == notif.handle) {
return; // ignore rest plugin connection.
}
}
void MatchmakerPlugin::ParseDataReceived(void* buffer, unsigned int nbytes, ConnectionHandle connection, PluginHandle plugin) {
}
} // namespace Matchmaker
} // namespace Link
const char* SimplePlugin::Name = "match";
const char* SimplePlugin::Version = "0.1";
SimplePlugin* SimplePlugin::CreatePlugin() {
return new Link::Matchmaker::MatchmakerPlugin();
}
void SimplePlugin::DestroyPlugin(SimplePlugin* plugin) {
delete plugin;
}
| [
"[email protected]"
] | |
29aa7059b3c5566f6a3fb1ba756aeffbc3663853 | 4b9dd6830cf2857de6dc273eee9255d2b6b9d7e5 | /剑指offer/52-两个链表的第一个公共结点/JZ52.cpp | aac68727d0dca77619d2ba60b9ba497b1fbdef53 | [
"MIT"
] | permissive | ZhuchaWenjiu/coding-for-algorithms | 2aa0eaa5f40b93f68426ee3a007f6bda75a638df | f2ca1addaa0b41ae62a8d71e2bec9635161cfe6a | refs/heads/master | 2022-12-01T09:14:10.766258 | 2020-08-13T06:36:35 | 2020-08-13T06:36:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,183 | cpp | /*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if (!(pHead1 && pHead2)) return nullptr;
unsigned int length1 = getListLength(pHead1);
unsigned int length2 = getListLength(pHead2);
ListNode *pLong, *pShort;
// 在 if...else...里定义 pLong 和 pShort 可不行,因为 {} 的作用域有限
if (length1 >= length2)
{
pLong = pHead1;
pShort = pHead2;
}
else
{
pLong = pHead2;
pShort = pHead1;
}
for (int i = 0; i < abs(int(length1 - length2)); ++i)
pLong = pLong->next;
while (pLong && pShort && pLong != pShort)
{
pLong = pLong->next;
pShort = pShort->next;
}
return pLong;
}
unsigned int getListLength(ListNode* head)
{
unsigned int length = 0;
ListNode* p = head;
while (p)
{
length++;
p = p->next;
}
return length;
}
}; | [
"[email protected]"
] | |
3f5f9af4f11da5491f34eca5320dfb4304e842f4 | c0f5d7ef2b590c155af58d83e8cbbf0854a3f995 | /include/caffe/layers/tanh_layer.hpp | 8d18b8f8e8adbd2fdb82e056bac28bfe375e4984 | [
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | JiahaoLi-gdut/CAFFE-DACH | c8a039d437775b65c6ed6f4508b47acc66e025d4 | 388c826d8019f66bf0657acb2041dfccf4797fc9 | refs/heads/master | 2023-03-27T16:00:10.865638 | 2021-03-30T15:18:51 | 2021-03-30T15:18:51 | 353,027,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,681 | hpp | #ifndef CAFFE_TANH_LAYER_HPP_
#define CAFFE_TANH_LAYER_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/layers/neuron_layer.hpp"
namespace caffe {
/**
* @brief TanH hyperbolic tangent non-linearity @f$
* y = \frac{\exp(2x) - 1}{\exp(2x) + 1}
* @f$, popular in auto-encoders.
*
* Note that the gradient vanishes as the values move away from 0.
* The ReLULayer is often a better choice for this reason.
*/
template <typename Dtype>
class TanHLayer : public NeuronLayer<Dtype> {
public:
explicit TanHLayer(const LayerParameter& param)
: NeuronLayer<Dtype>(param) {}
virtual inline const char* type() const { return "TanH"; }
protected:
/**
* @param bottom input Blob vector (length 1)
* -# @f$ (N \times C \times H \times W) @f$
* the inputs @f$ x @f$
* @param top output Blob vector (length 1)
* -# @f$ (N \times C \times H \times W) @f$
* the computed outputs @f$
* y = \frac{\exp(2x) - 1}{\exp(2x) + 1}
* @f$
*/
virtual void Forward_cpu(
const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top,
const bool preforward_flag);
virtual void Forward_gpu(
const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top,
const bool preforward_flag);
/**
* @brief Computes the error gradient w.r.t. the sigmoid inputs.
*
* @param top output Blob vector (length 1), providing the error gradient with
* respect to the outputs
* -# @f$ (N \times C \times H \times W) @f$
* containing error gradients @f$ \frac{\partial E}{\partial y} @f$
* with respect to computed outputs @f$ y @f$
* @param propagate_down see Layer::Backward.
* @param bottom input Blob vector (length 1)
* -# @f$ (N \times C \times H \times W) @f$
* the inputs @f$ x @f$; Backward fills their diff with
* gradients @f$
* \frac{\partial E}{\partial x}
* = \frac{\partial E}{\partial y}
* \left(1 - \left[\frac{\exp(2x) - 1}{exp(2x) + 1} \right]^2 \right)
* = \frac{\partial E}{\partial y} (1 - y^2)
* @f$ if propagate_down[0]
*/
virtual void Backward_cpu(
const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down,
const vector<Blob<Dtype>*>& bottom,
const bool prebackward_flag);
virtual void Backward_gpu(
const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down,
const vector<Blob<Dtype>*>& bottom,
const bool prebackward_flag);
};
} // namespace caffe
#endif // CAFFE_TANH_LAYER_HPP_
| [
"[email protected]"
] | |
854f41ff4f8f4acbdd604002d18634484387eaa2 | 6e892420c9f690d6e6204170889085639005f16c | /parallel_algos/array_sum/parallel_sum2.cpp | 913848e345700c4ecc11caf3c6401e014529b168 | [] | no_license | yashagarwal23/hpclabwork | 582ade526855e1a2a88c2c2306985249498ba154 | e7a08fb73208e57eef108fbff9ab6b97d9b5d173 | refs/heads/master | 2020-07-07T17:42:49.433645 | 2020-01-14T11:40:37 | 2020-01-14T11:40:37 | 203,425,485 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,529 | cpp | #include <iostream>
#include <utility>
#include <numeric>
#include <pthread.h>
using namespace std;
typedef long long ll;
int n;
ll *arr;
struct sum_struct
{
int startIndex;
int endIndex;
ll answer;
};
void* sum(void* arg)
{
sum_struct* sum_arg = (sum_struct*)arg;
int startIndex = sum_arg->startIndex;
int endIndex = sum_arg->endIndex;
if(endIndex - startIndex <= 10)
{
ll ans = 0;
for(int i = startIndex; i <= endIndex; i++)
ans += arr[i];
sum_arg->answer = ans;
return NULL;
}
int mid = (startIndex + endIndex)/2;
sum_struct left_sum_arg;
left_sum_arg.startIndex = startIndex;
left_sum_arg.endIndex = mid;
sum_struct right_sum_arg;
right_sum_arg.startIndex = mid+1;
right_sum_arg.endIndex = endIndex;
pthread_t left, right;
pthread_create(&left, NULL, sum, (void*)&left_sum_arg);
pthread_create(&right, NULL, sum, (void*)&right_sum_arg);
pthread_join(left, NULL);
pthread_join(right, NULL);
sum_arg->answer = left_sum_arg.answer + right_sum_arg.answer;
return NULL;
}
// parallel sum each thread dividing task into 2 different threads
int main()
{
cout << "Enter Number of elements : ";
cin >> n;
cout << "Enter array elements : ";
arr = new ll[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
sum_struct arg;
arg.startIndex = 0;
arg.endIndex = n-1;
sum((void*)&arg);
cout << "sum : " << arg.answer << endl;
return 0;
} | [
"[email protected]"
] | |
2f5587c0eb73a1dbbbe76741ddbd0314207c4f45 | 24b143ea43bb3a74b9c329c8a9a0ecd4ca71413c | /Serpinski challenges/serpinski 3_01/main.cpp | 662063e45e1509764ed563620eabce16c9a0bf16 | [] | no_license | xiaorine/Graphics-Programming | 7bc1d3f607a648aa119d3434bd8be475fcfe1434 | 2eaffb782333b6f652cd6c470f14eedaefdca022 | refs/heads/master | 2021-12-28T09:14:16.110481 | 2013-01-16T23:31:38 | 2013-01-16T23:31:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,832 | cpp | #pragma comment(lib, "GLFW")
#pragma comment(lib, "OpenGL32")
#include <GL\glfw.h>
#include <glm\glm.hpp>
#include <glm\gtc\matrix_transform.hpp>
#include <glm\gtc\type_ptr.hpp>
#include <glm\gtx\constants.hpp>
#include "geometry.h"
#include <cstdlib>
bool running = true;
render_object cube;
render_object tetrahedron;
geometry geom;
void initialise()
{
glClearColor(0.0f, 1.0f, 1.0f, 1.0f);
glm::mat4 projection = glm::perspective(10.0f,
800.0f/600.0f,
0.1f,
10000.0f);
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(glm::value_ptr(projection));
glMatrixMode(GL_MODELVIEW);
glEnable(GL_DEPTH_TEST);
glEnable(GL_VERTEX_ARRAY);
//geometry* geom = createBox();//call to create box
//geometry* geom = createPyramid();
//geometry* geom = createTetrahedron();
//geometry* geom = createDisk(200);
//geometry* geom = createCylinder(5, 10);
//geometry* geom = createSphere(20, 20);
//geometry* geom = createTorus(5.0f, 10, 30);
//geometry* geom = createPlane(20, 20);
geometry* geom = createSierpinski(5);
cube.geometry = geom;
cube.colour = glm::vec3(1.0f, 0.0f, 0.0f);
cube.transform.position = glm::vec3(0.0f, 0.5f, 0.0f);
}
void update(double deltaTime)
{
//running = !glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam(GLFW_OPENED);
//cube.transform.rotate(-glm::pi<float>() / 400.0f, glm::vec3(0.0f, 0.0f, 1.0f)); //Self roation code
//cube.transform.rotate(-glm::pi<float>() / 400.0f, glm::vec3(1.0f, 0.0f, 0.0f));
//cube.transform.rotate(glm::pi<float>() / 400.0f, glm::vec3(0.0f, 1.0f, 0.0f));
//manual rotation code
if (glfwGetKey(GLFW_KEY_UP))
cube.transform.rotate(0.1f,glm::vec3(0.0, 0.0, 0.1));
if (glfwGetKey(GLFW_KEY_DOWN))
cube.transform.rotate(-0.1f,glm::vec3(0.1, 0.0, 0.1));
if (glfwGetKey(GLFW_KEY_LEFT))
cube.transform.rotate(-0.1f,glm::vec3(0.1, 0.0, 0.0));
if (glfwGetKey(GLFW_KEY_RIGHT))
cube.transform.rotate(0.1f,glm::vec3(0.1, 0.0, 0.0));
if (glfwGetKey('W'))
cube.transform.rotate(0.1f, glm::vec3(0.0f, 0.1f, 0.0f));
if (glfwGetKey('S'))
cube.transform.rotate(-0.1f, glm::vec3(0.0f, 0.1f, 0.0f));
}
void render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glm::mat4 view = glm::lookAt(glm::vec3(10.0f, 10.0f, 10.0f),
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 0.0f));
glMatrixMode(GL_MODELVIEW);
cube.render(view);
glfwSwapBuffers();
}
int main()
{
if (!glfwInit())
exit(EXIT_FAILURE);
if (!glfwOpenWindow(800, 600, 0, 0, 0, 0, 0, 0, GLFW_WINDOW))
{
glfwTerminate();
exit(EXIT_FAILURE);
}
initialise();
double prevTimeStamp = glfwGetTime();
double currentTimeStamp;
while (running)
{
currentTimeStamp = glfwGetTime();
update(currentTimeStamp - prevTimeStamp);
render();
prevTimeStamp = currentTimeStamp;
}
glfwTerminate();
exit(EXIT_SUCCESS);
}
| [
"[email protected]"
] | |
9329b542909a92a9f22a928b6c5ecb5481ae1859 | 59179e4f655a40b421fa9aeda9c90736b8c11b1b | /compiler/.history/lab1/lexical_20210412111549.cpp | 9e749358afe8ee6b26bee1829b3f104bd2421c51 | [] | no_license | wjw136/course_designing_project | ccd39da420f0de22b39fa2fea032054f4cbe8bfd | 2614928bd779bc0d996857b123e2862836d81333 | refs/heads/master | 2023-06-04T12:52:40.501335 | 2021-06-17T13:19:23 | 2021-06-17T13:19:23 | 374,384,252 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,311 | cpp | #include <iostream>
#include <windows.h>
#include <string.h>
#include <queue>
#include <math.h>
#include "stdio.h"
#define ll long long
#define inf 100000
#define clr1(a) memset(a,-1,sizeof(a))
# define clr(a) memset(a, 0, sizeof(a))
using namespace std;
//reserved word
static char reserveword[35][20]={
"and","array","begin","bool","call","case",
"char","constant","dim","do","else","end",
"false","for","if","input","integer","not",
"of","or","output","procedure","program","read",
"real","repeat","set","stop","then","to","true",
"until","var","while","write"
};
//operator
static char myoperator[22][10]={
"(",")","*","*/","+",",","-",
"..","/","/*",":",":=",";","<",
"<=","<>","=",">",">=","[","]"
};
bool isDigit(char ch){
if(ch>='0'&&ch<='9')
return true;
else
{
return false;
}
}
bool isLetter(char ch){
if((ch>='a'&&ch<='z')||(ch<='Z'&&ch>='A')||ch=='_')
return true;
else
{
return false;
}
}
int isReserve(char *s){
for(int i=0;i<35;++i){
if(strcmp(reserveword[i],s)==0){
return i+1;
}
}
return -1;
}
//filter
void filter(char *s,int len){
char tmp[10000];
int p=0;
for(int i=0;i<len;++i){
//注释
if(s[i]=='/'&&s[i+1]=='*'){
i+=2;
while(s[i]!='*'||s[i+1]!='/'){
if(s[i]=='\0'&&s[i]=='\n'){
cout<<"Annotation error!";
exit(0);
}
i++;
}
i+=2;
}
//去除换行等
if(s[i]!='\n'&&s[i]!='\t'&&s[i]!='\v'&&s[i]!='r'){
tmp[p]=s[i];
p++;
//i++;
}
}
tmp[p]='\0';
strcpy(s,tmp);
}
//scanner
void scannner(int &syn,char *project,char *token,int &p){
int count=0;
char ch;
ch=project[p];
while(cjh==" "){//white space
++p;
ch=project[p];
}
for(int i=0;i<20;i++){
token[i]='\0';
}
if(isLetter(project[p])){
token[count++]=project[p++];
while(isLetter(project[p]||isDigit(project[p]))){
token[count++]=project[p++];
}
}
}
int main(){
// string s="sss";
// cout<<(s[1]=='\0');
//system("pause");
return 0;
}
| [
"[email protected]"
] | |
68c1f3492321d6c392930137815027e79acb2db1 | 636f92553b5077f82e9c2b6dfa84508a7d7ede0a | /Happic Engine/Src/Platform/Windows/Win32Input.h | c6a6e59acfc866b52cfd18ae42377adca5c1eca5 | [] | no_license | Happic-Games/Happic-Game-Engine | c7f3edaa88ca9388ea4b295775d0bad06ecdb3a8 | 18af6621abf43883640d14e815cd0bc7819c761e | refs/heads/master | 2020-04-20T08:36:59.879767 | 2019-02-03T06:04:20 | 2019-02-03T06:04:20 | 168,744,549 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 515 | h | #pragma once
#include "../../Core/IDisplayInput.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
namespace Happic { namespace Core {
class Win32Input : public IDisplayInput
{
public:
Win32Input(const HWND& handle);
Math::Vector2f GetCursorPosition() const override;
void SetCursorPosition(const Math::Vector2f& pos) const override;
void SetCursorVisible(bool visible) const override;
bool IsCursorVisible() const override;
private:
HWND m_handle;
mutable bool m_isCursorVisible;
};
} }
| [
"[email protected]"
] | |
d0190dde961e85b3b39073997fc9b4cf65f8c2d3 | bf798d5af7effdb06f373ac653e98cb4dd145a5c | /src/qif191/QIFDocument/type_t.CStatsNumericalBaseType.h | 5f4a39139d939aa5977a1ca815d08d2e774e6625 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | QualityInformationFramework/QIFResourcesEditor | 73387fca4f4280cc1145fae32438c5d2fdc63cd5 | 4ff1de9d1dd20d9c43eaa9cc320caeff1c57760e | refs/heads/master | 2022-07-29T15:57:04.341916 | 2021-08-04T16:36:42 | 2021-08-04T16:36:42 | 298,856,948 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,057 | h | #pragma once
#include "type_t.CStatsBaseType.h"
namespace qif191
{
namespace t
{
class CStatsNumericalBaseType : public ::qif191::t::CStatsBaseType
{
public:
QIF191_EXPORT CStatsNumericalBaseType(xercesc::DOMNode* const& init);
QIF191_EXPORT CStatsNumericalBaseType(CStatsNumericalBaseType const& init);
void operator=(CStatsNumericalBaseType const& other) { m_node = other.m_node; }
static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_t_altova_CStatsNumericalBaseType); }
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_Average> Average;
struct Average { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CSubgroupDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_SubgroupAverage> SubgroupAverage;
struct SubgroupAverage { typedef Iterator<t::CSubgroupDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_Difference> Difference;
struct Difference { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CSubgroupDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_SubgroupDifference> SubgroupDifference;
struct SubgroupDifference { typedef Iterator<t::CSubgroupDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_RootMeanSquare> RootMeanSquare;
struct RootMeanSquare { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_Maximum> Maximum;
struct Maximum { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CQIFReferenceFullType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_MaximumId> MaximumId;
struct MaximumId { typedef Iterator<t::CQIFReferenceFullType> iterator; };
MemberElement<t::CSubgroupDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_SubgroupMaximum> SubgroupMaximum;
struct SubgroupMaximum { typedef Iterator<t::CSubgroupDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_Minimum> Minimum;
struct Minimum { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CQIFReferenceFullType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_MinimumId> MinimumId;
struct MinimumId { typedef Iterator<t::CQIFReferenceFullType> iterator; };
MemberElement<t::CSubgroupDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_SubgroupMinimum> SubgroupMinimum;
struct SubgroupMinimum { typedef Iterator<t::CSubgroupDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_Range> Range;
struct Range { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CSubgroupDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_SubgroupRange> SubgroupRange;
struct SubgroupRange { typedef Iterator<t::CSubgroupDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_AverageRange> AverageRange;
struct AverageRange { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_StandardDeviation> StandardDeviation;
struct StandardDeviation { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_Skew> Skew;
struct Skew { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_Kurtosis> Kurtosis;
struct Kurtosis { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_Normality> Normality;
struct Normality { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_ProcessVariation> ProcessVariation;
struct ProcessVariation { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_EstimatedStandardDeviation> EstimatedStandardDeviation;
struct EstimatedStandardDeviation { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_UpperControlLimit> UpperControlLimit;
struct UpperControlLimit { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_LowerControlLimit> LowerControlLimit;
struct LowerControlLimit { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_UpperControlLimitRange> UpperControlLimitRange;
struct UpperControlLimitRange { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_LowerControlLimitRange> LowerControlLimitRange;
struct LowerControlLimitRange { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<xs::CnonNegativeIntegerType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_NumberOutOfControl> NumberOutOfControl;
struct NumberOutOfControl { typedef Iterator<xs::CnonNegativeIntegerType> iterator; };
MemberElement<t::CArrayReferenceFullType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_OutOfControlIds> OutOfControlIds;
struct OutOfControlIds { typedef Iterator<t::CArrayReferenceFullType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_AppraiserVariation> AppraiserVariation;
struct AppraiserVariation { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_EquipmentVariation> EquipmentVariation;
struct EquipmentVariation { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_Interaction> Interaction;
struct Interaction { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_GageRandR> GageRandR;
struct GageRandR { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_PartVariation> PartVariation;
struct PartVariation { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_TotalVariation> TotalVariation;
struct TotalVariation { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_Linearity> Linearity;
struct Linearity { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_Bias> Bias;
struct Bias { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_RelativeLinearity> RelativeLinearity;
struct RelativeLinearity { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_RelativeBias> RelativeBias;
struct RelativeBias { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_GoodnessOfFit> GoodnessOfFit;
struct GoodnessOfFit { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_RegressionSlope> RegressionSlope;
struct RegressionSlope { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_RegressionIntercept> RegressionIntercept;
struct RegressionIntercept { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_UpperConfidenceLimit> UpperConfidenceLimit;
struct UpperConfidenceLimit { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_LowerConfidenceLimit> LowerConfidenceLimit;
struct LowerConfidenceLimit { typedef Iterator<t::CActualDecimalType> iterator; };
MemberElement<t::CActualDecimalType, _altova_mi_t_altova_CStatsNumericalBaseType_altova_TDistribution> TDistribution;
struct TDistribution { typedef Iterator<t::CActualDecimalType> iterator; };
QIF191_EXPORT void SetXsiType();
};
} // namespace t
} // namespace qif191
//#endif // _ALTOVA_INCLUDED_QIFDocument_ALTOVA_t_ALTOVA_CStatsNumericalBaseType
| [
"[email protected]"
] | |
3bd86ff317413bcd0786f4b5352373e6245f56a7 | 83552346a7d778e88569fdc16d686576836a1977 | /Plan/main.cpp | 0732972378ade10c53ec99576a6e85ad0bac7b55 | [] | no_license | Berezowski-Dominik/Plan_generator | 75baddb2a4aadf6543e64b6fdef70889a683419f | 66edc08eb6c5428bf733f77b3e8e4f3400c6e225 | refs/heads/master | 2023-08-22T22:58:06.735671 | 2021-10-10T19:00:07 | 2021-10-10T19:00:07 | 415,674,221 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 66,307 | cpp | #include <stdio.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <cmath>
#include <map>
#include <cmath>
#include <set>
#include <ctime>
#include <algorithm>
#include <sys/stat.h>
#include "Przedmiot.h"
#include "Nauczyciel.h"
#include "Nad_grupa.h"
#include "Grupa.h"
#include "Zajecia.h"
#include "Sala.h"
using namespace std;
int Wczytanie_Przedmiotow(vector<vector<Przedmiot>>&Przedmioty_Lab,vector<vector<Przedmiot>>&Przedmioty_Cw,vector<vector<Przedmiot>>&Przedmioty_Wykl);
int Wczytanie_Nauczycieli(vector < Nauczyciel> &Nauczyciele);
void Wczytanie_Grup(vector <vector<Nad_grupa>> &Grupy_Wyk, vector <vector<Nad_grupa>> &Grupy_Cw, vector<vector<Grupa>> &Grupy_Lab);
void Wczytanie_Sal(vector <Sala> &Sala_Wykl,vector <Sala> &Sala_Cw,vector <Sala> &Sala_Lab);
int Czy_istnieje_plik(const char* nazwa_pliku);
void Podzial_nauczycieli_i_przedmiotow();
void Dop_godz_nauczycieli(vector < Nauczyciel> &Nauczyciele);
void Niedop_godz_nauczycieli(vector < Nauczyciel> &Nauczyciele);
void Grup_Wyk_Podz(vector <vector<Nad_grupa>> &Grupy_Wyk,vector <vector<Grupa>> &Grupy_Lab,vector <vector<Nad_grupa>> &Grupy_Cw);
void Grup_Cw_Podz(vector<vector<Nad_grupa>> &Grupy_Cw, vector <vector<Grupa>> &Grupy_Lab);
void Wczytanie_nauczycieli_wykladow(vector <vector<Przedmiot>> &Przedmioty_Wykl,vector <Nauczyciel> &Nauczyciele);
void Wczytanie_nauczycieli_cwiczen(vector <vector<Przedmiot>> &Przedmioty_Cw,vector < Nauczyciel> &Nauczyciele);
void Wczytanie_nauczycieli_laborek(vector <vector<Przedmiot>> &Przedmioty_Lab,vector < Nauczyciel> &Nauczyciele);
void Zajecia_wykladowe(vector <Zajecia> &Zajecie,vector<vector<Przedmiot>> &Przedmioty_Wykl,vector <vector<Nad_grupa>> &Grupy_Wyk,vector<Sala> &Sala_Wykl,int &il_wykl);
void Zajecia_cwiczeniowe(vector <Zajecia> &Zajecie,vector<vector<Przedmiot>> &Przedmioty_Cw,vector <vector<Nad_grupa>> &Grupy_Cw,vector<Sala> &Sala_Cw, int &il_wykl_i_cw);
void Zajecia_laborki(vector <Zajecia> &Zajecie,vector <vector<Przedmiot>> &Przedmioty_Lab,vector <vector<Grupa>> &Grupy_Lab,vector<Sala> &Sala_Lab);
void Zajecia_nauczyciele(vector<Zajecia> &Zajecie,vector<Nauczyciel> &Nauczyciele,int il_wykl,int il_wykl_i_cw);
void Tworzenie_harmonogramu(vector <Zajecia> &Zajecie);
void Wypisanie_danych_harmonogramu(vector <Zajecia> &Zajecie,vector <vector<Grupa>> &Grupy_Lab, vector <Nauczyciel> &Nauczyciele);
float Kara_laczna_grup(vector<vector<Grupa>> &Grupy_Lab);
float Kara_laczna_nauczycieli(vector <Nauczyciel> &Nauczyciele);
float Ogolna_kara_planu(vector <vector<Grupa>> &Grupy_Lab,vector <Nauczyciel> &Nauczyciele);
void Poprawianie_grupy(vector <Zajecia> &Zajecie,vector <float>::iterator &it, vector <float> &kara_grupy, vector <Grupa*> &Grupy_Lab, int &najg_grupa);
void Poprawianie_nauczycieli(vector <Zajecia> &Zajecie,vector <float>::iterator &it, vector <float> &kara_nauczy, vector <Nauczyciel> &Nauczyciele, int &najg_nauczy);
void Poprawianie_harmonogramu(vector <Zajecia> &Zajecie,vector <vector<Grupa>> &Grupy_Lab,vector <Nauczyciel> &Nauczyciele, vector <Sala> Sala_Lab, int ile_popraw);
void Wypisywanie_planow_grup(vector <vector<Grupa>> &Grupy_Lab,vector <Zajecia> &Zajecie_Naj);
void Wypisywanie_planow_nauczycieli(vector <Nauczyciel> &Nauczyciele_Naj,vector <Zajecia> &Zajecie_Naj);
int main(int argc, char **argv)
{
srand(time(NULL));
fstream plik;
vector<vector<Przedmiot>>Przedmioty_Lab;
vector<vector<Przedmiot>>Przedmioty_Cw;
vector<vector<Przedmiot>>Przedmioty_Wykl;
vector<vector<Grupa>>Grupy_Lab;
vector<vector<Nad_grupa>>Grupy_Cw;
vector<vector<Nad_grupa>>Grupy_Wykl;
vector <Sala> Sala_Wykl;
vector <Sala> Sala_Cw;
vector <Sala> Sala_Lab;
vector <Zajecia> Zajecie;
vector<Nauczyciel>Nauczyciele;
int il_wykl = 0;
int il_wykl_i_cw = 0;
if(Czy_istnieje_plik("wyklady_nauczyciele.csv") == 0)
{
cout << "Brak koniecznych pilkow do stworzenia planiu !!!" << endl;
cout << "Uzupelnij stworzone plik w katalogu programu: " << endl;
cout << "wyklady_nauczyciele.csv,cwiczenia_nauczyciele.csv,laborki_nauczyciele.csv" << endl;
Podzial_nauczycieli_i_przedmiotow();
}
else if(Czy_istnieje_plik("wyklady_nauczyciele.csv") != 0)
{
Wczytanie_Przedmiotow(Przedmioty_Lab,Przedmioty_Cw,Przedmioty_Wykl);
Wczytanie_Nauczycieli(Nauczyciele);
Wczytanie_Grup(Grupy_Wykl,Grupy_Cw,Grupy_Lab);
Wczytanie_Sal(Sala_Wykl,Sala_Cw,Sala_Lab);
Grup_Wyk_Podz(Grupy_Wykl,Grupy_Lab,Grupy_Cw);
Grup_Cw_Podz(Grupy_Cw,Grupy_Lab);
Wczytanie_nauczycieli_wykladow(Przedmioty_Wykl,Nauczyciele);
Wczytanie_nauczycieli_cwiczen(Przedmioty_Cw,Nauczyciele);
Wczytanie_nauczycieli_laborek(Przedmioty_Lab,Nauczyciele);
Zajecia_wykladowe(Zajecie,Przedmioty_Wykl,Grupy_Wykl,Sala_Wykl,il_wykl);
Zajecia_cwiczeniowe(Zajecie,Przedmioty_Cw,Grupy_Cw,Sala_Cw,il_wykl_i_cw);
Zajecia_laborki(Zajecie,Przedmioty_Lab,Grupy_Lab,Sala_Lab);
Zajecia_nauczyciele(Zajecie,Nauczyciele,il_wykl,il_wykl_i_cw);
Tworzenie_harmonogramu(Zajecie);
Poprawianie_harmonogramu(Zajecie,Grupy_Lab,Nauczyciele,Sala_Lab,10);
cout <<"Kara najlepszego rozwiazania wynosi: " << Ogolna_kara_planu(Grupy_Lab,Nauczyciele) << endl;
Wypisywanie_planow_grup(Grupy_Lab,Zajecie);
Wypisywanie_planow_nauczycieli(Nauczyciele,Zajecie);
}
return 0;
}
void Wypisywanie_planow_nauczycieli(vector <Nauczyciel> &Nauczyciele,vector <Zajecia> &Zajecie)
{
int ilosc_nauczycieli = Nauczyciele.size();
string nazwa_pliku;
ofstream plik;
nazwa_pliku.append("plany_nauczycieli.csv");
plik.open(nazwa_pliku,ios::out);
string do_pliku;
for(int i = 0; i < ilosc_nauczycieli; i++)
{
do_pliku.append(Nauczyciele[i].Zwroc_imie_i_nazwisko());
do_pliku.append("\n");
for(int j = 0; j < 4; j++)
{
for(int k = 0; k < 20; k+=4)
{
if(Nauczyciele[i].Numer_zajecia(k+j) != 0)
{
do_pliku.append(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].przedmiot()->Zwroc_nazwe());
do_pliku.append(" ");
do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].sala()->Zwroc_numer()));
do_pliku.append(" ");
if(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].nad_grupa() == NULL)
{
do_pliku.append(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].grupa()->Zwroc_kierunek());
do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].grupa()->Zwroc_stopien()));
do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].grupa()->Zwroc_rocznik()));
do_pliku.append(to_string(3));
do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].grupa()->Zwroc_numer()));
}
if(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].nad_grupa() != NULL)
{
do_pliku.append(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].nad_grupa()->grupa_lab(0)->Zwroc_kierunek());
do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].nad_grupa()->grupa_lab(0)->Zwroc_stopien()));
do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].nad_grupa()->grupa_lab(0)->Zwroc_rocznik()));
do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].nad_grupa()->Zwroc_rodzaj()));
do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].nad_grupa()->Zwroc_numer_grupy()));
}
do_pliku.append(",");
}
else
{
do_pliku.append("Wolne,");
}
}
do_pliku.append("\n");
plik << do_pliku;
do_pliku.clear();
}
do_pliku.append("\n");
}
plik.close();
}
void Wypisywanie_planow_grup(vector <vector<Grupa>> &Grupy_Lab,vector <Zajecia> &Zajecie)
{
int ilosc_zbiorow_grup = Grupy_Lab.size();
int ilosc_grup = 0;
string nazwa_pliku;
ofstream plik;
for(int l = 0; l < ilosc_zbiorow_grup; l++)
{
nazwa_pliku.append(Grupy_Lab[l][0].Zwroc_kierunek());
nazwa_pliku.append(to_string(Grupy_Lab[l][0].Zwroc_stopien()));
nazwa_pliku.append(to_string(Grupy_Lab[l][0].Zwroc_rocznik()));
nazwa_pliku.append(".csv");
plik.open(nazwa_pliku,ios::out);
nazwa_pliku.clear();
string do_pliku;
ilosc_grup = Grupy_Lab[l].size();
for(int i = 0; i < ilosc_grup; i++)
{
do_pliku.append("Grupa");
do_pliku.append(to_string(Grupy_Lab[l][i].Zwroc_numer()));
do_pliku.append("\n");
for(int j = 0; j < 4; j++)
{
for(int k = 0; k < 20; k+=4)
{
if(Grupy_Lab[l][i].Zwroc_numer_zaj(k+j) != 0)
{
do_pliku.append(Zajecie[Grupy_Lab[l][i].Zwroc_numer_zaj(k+j)-1].przedmiot()->Zwroc_nazwe());
do_pliku.append(" ");
do_pliku.append(Zajecie[Grupy_Lab[l][i].Zwroc_numer_zaj(k+j)-1].Zwroc_imie_i_nazwisko_nauczyciela());
do_pliku.append(" ");
do_pliku.append(to_string(Zajecie[Grupy_Lab[l][i].Zwroc_numer_zaj(k+j)-1].sala()->Zwroc_numer()));
do_pliku.append(",");
}
else
{
do_pliku.append("Wolne,");
}
}
do_pliku.append("\n");
plik << do_pliku;
do_pliku.clear();
}
do_pliku.append("\n");
}
plik.close();
}
}
void Podzial_nauczycieli_i_przedmiotow()
{
vector<Nauczyciel> nauczyciele;
vector<vector<Przedmiot>> przedmioty_lab;
vector<vector<Przedmiot>> przedmioty_cw;
vector<vector<Przedmiot>> przedmioty_wykl;
vector<vector<Grupa>> grupy_lab;
vector<vector<Nad_grupa>> grupy_cw;
vector<vector<Nad_grupa>> grupy_wykl;
Wczytanie_Nauczycieli(nauczyciele);
Wczytanie_Przedmiotow(przedmioty_lab,przedmioty_cw,przedmioty_wykl);
Wczytanie_Grup(grupy_wykl,grupy_cw,grupy_lab);
int ilosc_zbiorow_wykladow = przedmioty_wykl.size();
int ilosc_zbiorow_cwiczen = przedmioty_cw.size();
int ilosc_zbiorow_laborek = przedmioty_lab.size();
int ilosc_nauczycieli = nauczyciele.size();
int ilosc_wykladow = 0;
int ilosc_cwiczen = 0;
int ilosc_laborek = 0;
ofstream plik;
plik.open("wyklady_nauczyciele.csv",ios::out);
for(int i = 0; i < ilosc_zbiorow_wykladow; i++)
{
ilosc_wykladow = przedmioty_wykl[i].size();
for(int j = 0; j < ilosc_wykladow; j++)
{
plik << ",";
plik << przedmioty_wykl[i][j].Zwroc_nazwe();
}
plik << ",Ilosc grup-";
plik << grupy_wykl[i].size();
plik << ",";
}
plik << "\n";
for(int i = 0; i < ilosc_nauczycieli; i++)
{
plik << nauczyciele[i].Zwroc_imie_i_nazwisko();
plik << ",\n";
}
plik.close();
plik.open("cwiczenia_nauczyciele.csv",ios::out);
for(int i = 0; i < ilosc_zbiorow_cwiczen; i++)
{
ilosc_cwiczen = przedmioty_cw[i].size();
for(int j = 0; j < ilosc_cwiczen; j++)
{
plik << ",";
plik << przedmioty_cw[i][j].Zwroc_nazwe();
}
plik << ",Ilosc grup-";
plik << grupy_cw[i].size();
plik << ",";
}
plik << "\n";
for(int i = 0; i < ilosc_nauczycieli; i++)
{
plik << nauczyciele[i].Zwroc_imie_i_nazwisko();
plik << ",\n";
}
plik.close();
plik.open("laborki_nauczyciele.csv",ios::out);
for(int i = 0; i < ilosc_zbiorow_laborek; i++)
{
ilosc_laborek = przedmioty_lab[i].size();
for(int j = 0; j < ilosc_laborek; j++)
{
plik << ",";
plik << przedmioty_lab[i][j].Zwroc_nazwe();
}
plik << ",Ilosc grup-";
plik << grupy_lab[i].size();
plik << ",";
}
plik << "\n";
for(int i = 0; i < ilosc_nauczycieli; i++)
{
plik << nauczyciele[i].Zwroc_imie_i_nazwisko();
plik << ",\n";
}
plik.close();
}
float Ogolna_kara_planu(vector <vector<Grupa>> &Grupy_Lab,vector <Nauczyciel> &Nauczyciele)
{
return Kara_laczna_grup(Grupy_Lab) + Kara_laczna_nauczycieli(Nauczyciele);
}
void Poprawianie_nauczycieli(vector <Zajecia> &Zajecie,vector <float>::iterator &it, vector <float> &kara_nauczy, vector <Nauczyciel> &Nauczyciele, int &najg_nauczy)
{
vector <int> pozyc_labek;
vector <int> sprawdz_nauczy;
int labki = 0;
int ile_spraw_naucz = 0;
int i = 0;
while(i == 0)
{
int ilosc_labek = Nauczyciele[najg_nauczy].Ile_lab_w_planie();
for(int i = 0; i < ilosc_labek; i++)
{
pozyc_labek.push_back(Nauczyciele[najg_nauczy].Termin_labek(i));
}
ilosc_labek++;
pozyc_labek.push_back(20);
labki = ilosc_labek-1;
do
{
pozyc_labek.erase(pozyc_labek.begin()+labki);
ilosc_labek--;
labki = rand() % ilosc_labek;
}while((!Zajecie[Nauczyciele[najg_nauczy].Numer_zajecia(pozyc_labek[labki])-1].Mozliwosc_zmiany()) || (ilosc_labek == 0));
if(ilosc_labek == 0)
{
i--;
kara_nauczy[najg_nauczy] = 0;
sprawdz_nauczy.push_back(najg_nauczy);
it = max_element(kara_nauczy.begin(),kara_nauczy.end());
najg_nauczy = distance(kara_nauczy.begin(), it);
}
else
{
Zajecie[Nauczyciele[najg_nauczy].Numer_zajecia(pozyc_labek[labki])-1].Zmiana_terminu();
kara_nauczy[najg_nauczy] = Nauczyciele[najg_nauczy].Zwroc_kare();
ile_spraw_naucz = sprawdz_nauczy.size();
for(int i = 0; i < ile_spraw_naucz; i++)
{
kara_nauczy[sprawdz_nauczy[i]] = Nauczyciele[sprawdz_nauczy[i]].Zwroc_kare();
}
}
sprawdz_nauczy.clear();
pozyc_labek.clear();
it = max_element(kara_nauczy.begin(),kara_nauczy.end());
najg_nauczy = distance(kara_nauczy.begin(), it);
i++;
}
}
void Poprawianie_grupy(vector <Zajecia> &Zajecie,vector <float>::iterator &it, vector <float> &kara_grupy, vector <Grupa*> &Grupy_Lab,int &najg_grupa)
{
vector <int> pozyc_labek;
vector <int> sprawdzone_grupy;
int labki = 0;
int ile_spraw_grup = 0;
int i = 0;
while(i == 0)
{
int ilosc_labek = Grupy_Lab[najg_grupa]->Ile_lab_w_planie();
for(int i = 0; i < ilosc_labek; i++)
{
pozyc_labek.push_back(Grupy_Lab[najg_grupa]->Termin_labek(i));
}
ilosc_labek++;
pozyc_labek.push_back(20);
labki = ilosc_labek-1;
do
{
pozyc_labek.erase(pozyc_labek.begin()+labki);
ilosc_labek--;
labki = rand() % ilosc_labek;
}while((!Zajecie[Grupy_Lab[najg_grupa]->Zwroc_numer_zaj(pozyc_labek[labki])-1].Mozliwosc_zmiany()) || (ilosc_labek == 0));
if(ilosc_labek == 0)
{
i--;
kara_grupy[najg_grupa] = 0;
sprawdzone_grupy.push_back(najg_grupa);
it = max_element(kara_grupy.begin(),kara_grupy.end());
najg_grupa = distance(kara_grupy.begin(), it);
}
else
{
Zajecie[Grupy_Lab[najg_grupa]->Zwroc_numer_zaj(pozyc_labek[labki])-1].Zmiana_terminu();
kara_grupy[najg_grupa] = Grupy_Lab[najg_grupa]->Zwroc_kare();
ile_spraw_grup = sprawdzone_grupy.size();
for(int i = 0; i < ile_spraw_grup; i++)
{
kara_grupy[sprawdzone_grupy[i]] = Grupy_Lab[sprawdzone_grupy[i]]->Zwroc_kare();
}
}
sprawdzone_grupy.clear();
pozyc_labek.clear();
it = max_element(kara_grupy.begin(),kara_grupy.end());
najg_grupa = distance(kara_grupy.begin(), it);
i++;
}
}
float Kara_laczna_grup(vector<vector<Grupa>> &Grupy_Lab)
{
int ilosc_zbiorow_grup = Grupy_Lab.size();
float suma_kar = 0;
for(int j = 0; j < ilosc_zbiorow_grup;j++)
{
int ilosc_grup = Grupy_Lab[j].size();
for(int i = 0; i < ilosc_grup; i++)
{
suma_kar += Grupy_Lab[j][i].Oblicz_kare();
}
}
return suma_kar;
}
float Kara_laczna_nauczycieli(vector < Nauczyciel> &Nauczyciele)
{
int ilosc_nauczycieli = Nauczyciele.size();
float suma_kar = 0;
for(int i = 0; i < ilosc_nauczycieli; i++)
{
suma_kar += Nauczyciele[i].Oblicz_kare();
}
return suma_kar;
}
void Grup_Cw_Podz(vector <Nad_grupa> &Grupy_Cw, vector <Grupa> &Grupy_Lab,vector <Nad_grupa> &Grupy_Wyk)
{
int Wszystkie_gr_lab = Grupy_Lab.size();
float nie_przydzielone_gr_lab = Grupy_Lab.size();
int ilosc_gr_do_stworzenia = Grupy_Cw.size();
float wielkosc_nowa_gr_cwiczeniowa = 0;
for (int i = ilosc_gr_do_stworzenia; i > 0; i--)
{
wielkosc_nowa_gr_cwiczeniowa = round(nie_przydzielone_gr_lab / i);
for(int j = 0; j < wielkosc_nowa_gr_cwiczeniowa; j++)
{
Grupy_Cw[ilosc_gr_do_stworzenia - i].grupa_lab()->push_back(&Grupy_Lab[j + Wszystkie_gr_lab - nie_przydzielone_gr_lab]);
}
nie_przydzielone_gr_lab -= wielkosc_nowa_gr_cwiczeniowa;
}
}
int Wczytanie_Nauczycieli(vector < Nauczyciel> &Nauczyciele)
{
fstream plik;
plik.open("nauczyciele.csv", ios::in | ios::out);
if(plik.is_open())
{
cout << "Poprawne otwarcie pliku z nauczycielami" << endl;
string linia;
string czesc;
vector <string> dane;
int i = 0;
while(!plik.eof())
{
plik >> linia;
if(linia == ";")
{
break;
return 1;
}
else
{
if(linia == "")
cout << "Blad w wierszu " << i << endl;
else
Nauczyciele.push_back({linia});
}
i++;
}
plik.close();
}
else
cout<<"Nie udało się otworzyć pliku z nauczycielami";
return 1;
}
void Dop_godz_nauczycieli(vector < Nauczyciel> &Nauczyciele)
{
fstream plik;
plik.open("dop_term_nauczycieli.csv", ios::in | ios::out);
int numer = 0;
if(plik.is_open())
{
cout << "Plik z dopuszczalnymi terminami nauczycieli otwarty" << endl << endl;
string linia;
string czesc;
vector <string> dane;
int ile_godzin = 0;
while(!plik.eof())
{
plik >> linia;
if(linia == ";")
break;
stringstream strumien(linia);
while(getline(strumien,czesc,','))
{
dane.push_back(czesc);
}
if(dane[0] == "")
{
dane.erase(dane.begin(), dane.end());
numer++;
continue;
}
else if(dane[0] != "")
{
ile_godzin = dane.size();
for(int i = 0; i < ile_godzin; i++)
{
Nauczyciele[numer].Dodanie_dop_terminu(stoi(dane[i])-1);
}
dane.erase(dane.begin(), dane.end());
numer++;
}
}
plik.close();
}
else
cout<<"Nie udało się otworzyć pliku z dopuszczalnymi terminami nauczycieli";
}
void Niedop_godz_nauczycieli(vector < Nauczyciel> &Nauczyciele)
{
fstream plik;
plik.open("niedop_term_nauczycieli.csv", ios::in | ios::out);
int numer = 0;
if(plik.is_open())
{
cout << "Plik z niedopuszczalnymi terminami nauczycieli otwarty" << endl << endl;
string linia;
string czesc;
vector <string> dane;
int ile_godzin = 0;
while(!plik.eof())
{
plik >> linia;
if(linia == ";")
break;
stringstream strumien(linia);
while(getline(strumien,czesc,','))
{
dane.push_back(czesc);
}
if(dane[0] == "")
{
dane.erase(dane.begin(), dane.end());
numer++;
continue;
}
else if(dane[0] != "")
{
ile_godzin = dane.size();
for(int i = 0; i < ile_godzin; i++)
{
Nauczyciele[numer].Dodanie_niedos_terminu(stoi(dane[i])-1);
Nauczyciele[numer].Dodanie_zaj_terminu(stoi(dane[i])-1);
}
dane.erase(dane.begin(), dane.end());
numer++;
}
}
plik.close();
}
else
cout<<"Nie udało się otworzyć pliku z niedopuszczalnymi terminami nauczycieli";
}
int Wczytanie_Przedmiotow(vector<vector<Przedmiot>>&Przedmioty_Lab,vector<vector<Przedmiot>>&Przedmioty_Cw,vector<vector<Przedmiot>>&Przedmioty_Wykl)
{
string linia;
string czesc;
vector <string> dane;
int numer_wyk = 0;
int numer_cw = 0;
int numer_lab = 0;
int przedmioty = 0;
int numer_wiersza = 1;
Przedmioty_Wykl.push_back(vector<Przedmiot>());
Przedmioty_Cw.push_back(vector<Przedmiot>());
Przedmioty_Lab.push_back(vector<Przedmiot>());
fstream plik;
plik.open("przedmioty.csv", ios::in | ios::out);
if(plik.is_open())
{
cout << "Poprawne otwarcie pliku z przedmiotami" << endl;
while(!plik.eof())
{
plik >> linia;
stringstream strumien(linia);
while(getline(strumien,czesc,','))
{
dane.push_back(czesc);
}
if(dane[0] == "" && dane[1] == "")
{
Przedmioty_Wykl.push_back(vector<Przedmiot>());
Przedmioty_Cw.push_back(vector<Przedmiot>());
Przedmioty_Lab.push_back(vector<Przedmiot>());
przedmioty++;
}
else if(dane[0] == ";")
{
break;
return 1;
}
else
{
if(dane[0] == "") {cout << "Brak nazwy przedmiotu w wierszu " << numer_wiersza << endl; return 0;}
if((dane[1] == "") || ((dane[1] != "1") && (dane[1] != "2") && (dane[1] != "3"))) {cout << "Bledna wartosc w 2 kolumnie wiersza " << numer_wiersza << endl; return 0;}
if((dane[2] == "") || ((dane[2] != "1") && (dane[2] != "2"))) {cout << "Bledna wartosc w 3 kolumnie wiersza " << numer_wiersza << endl; return 0;}
if(stoi(dane[1]) == 1)
{
Przedmioty_Wykl[przedmioty].push_back({dane[0],stoi(dane[1]),stoi(dane[2]),numer_wyk});
numer_wyk++;
}
else if(stoi(dane[1]) == 2)
{
Przedmioty_Cw[przedmioty].push_back({dane[0],stoi(dane[1]),stoi(dane[2]),numer_cw});
numer_cw++;
}
else if(stoi(dane[1]) == 3)
{
Przedmioty_Lab[przedmioty].push_back({dane[0],stoi(dane[1]),stoi(dane[2]),numer_lab});
numer_lab++;
}
}
numer_wiersza++;
dane.erase(dane.begin(), dane.end());
}
plik.close();
}
else
cout<<"Nie udało się otworzyć pliku z przedmiotami";
return 1;
}
int Czy_istnieje_plik(const char* nazwa_pliku)
{
struct stat bufor;
if (stat(nazwa_pliku,&bufor) == 0)
return 1;
else
return 0;
}
void Wczytanie_Grup(vector<vector<Nad_grupa>>&Grupy_Wyk, vector<vector<Nad_grupa>>&Grupy_Cw, vector<vector<Grupa>>&Grupy_Lab)
{
string linia;
string czesc;
vector <string> dane;
int zbior_grup = 0;
int j = 0;
fstream plik;
plik.open("grupy.csv", ios::in | ios::out);
if(plik.is_open())
{
while(!plik.eof())
{
plik >> linia;
stringstream strumien(linia);
while(getline(strumien,czesc,','))
{
dane.push_back(czesc);
}
if(dane[0] != "" && dane[0] != ";")
{
Grupy_Wyk.push_back(vector<Nad_grupa>());
Grupy_Cw.push_back(vector<Nad_grupa>());
Grupy_Lab.push_back(vector<Grupa>());
if(dane[1] == "" || dane[2] == "" || dane[3] == "" || dane[4] == "" || dane[5] == "")
cout << "Blad w wierszu " << j << endl;
else
{
for(int i = 0; i < stoi(dane[3]); i++)
{
Grupy_Wyk[zbior_grup].push_back({1,i+1});
}
for(int i = 0; i < stoi(dane[4]); i++)
{
Grupy_Cw[zbior_grup].push_back({2,i+1});
}
for(int i = 0; i < stoi(dane[5]); i++)
{
Grupy_Lab[zbior_grup].push_back({dane[0],stoi(dane[1]),stoi(dane[2]),i+1});
}
zbior_grup++;
}
}
else if(dane[0] == ";")
{
break;
}
j++;
dane.erase(dane.begin(), dane.end());
}
plik.close();
}
else
cout<<"Nie udało się otworzyć pliku z przedmiotami";
}
void Wczytanie_Sal(vector <Sala> &Sala_Wykl,vector <Sala> &Sala_Cw,vector <Sala> &Sala_Lab)
{
fstream plik;
plik.open("sale.csv", ios::in | ios::out);
if(plik.is_open())
{
string linia;
string czesc;
vector <string> dane;
while(!plik.eof())
{
plik >> linia;
stringstream strumien(linia);
while(getline(strumien,czesc,','))
{
dane.push_back(czesc);
}
if(dane[0] != "" && dane[0] != ";")
{
if(stoi(dane[0]) == 1)
{
for(int i = 0; i < stoi(dane[1]); i++)
{
if(dane[2+i] == "")
{
cout << "Brak numeru sali wykladowej" << endl;
}
else
{
Sala_Wykl.push_back({stoi(dane[2+i])});
}
}
}
else if(stoi(dane[0]) == 2)
{
for(int i = 0; i < stoi(dane[1]); i++)
{
if(dane[2+i] == "")
{
cout << "Brak numeru sali cwiczeniowej" << endl;
}
else
{
Sala_Cw.push_back({stoi(dane[2+i])});
}
}
}
else if(stoi(dane[0]) == 3)
{
for(int i = 0; i < stoi(dane[1]); i++)
{
if(dane[2+i] == "")
{
cout << "Brak numeru sali laboratoryjnej" << endl;
}
else
{
Sala_Lab.push_back({stoi(dane[2+i])});
}
}
}
}
else if(dane[0] == ";")
{
break;
}
dane.erase(dane.begin(), dane.end());
}
plik.close();
}
else
cout<<"Nie udało się otworzyć pliku z salami";
}
void Grup_Wyk_Podz(vector<vector<Nad_grupa>> &Grupy_Wyk,vector<vector<Grupa>> &Grupy_Lab,vector <vector<Nad_grupa>> &Grupy_Cw)
{
int ilosc_rocznikow = Grupy_Wyk.size();
for(int k = 0; k < ilosc_rocznikow; k++)
{
int Wszystkie_gr_lab = Grupy_Lab[k].size();
int nie_przydzielone_gr_lab = Grupy_Lab[k].size();
int Wszystkie_gr_cw = Grupy_Cw[k].size();
int nie_przydzielone_gr_cw = Grupy_Cw[k].size();
int ilosc_gr_do_stworzenia = Grupy_Wyk[k].size();
int wielkosc_nowa_gr_wykladowa = 0;
for (int i = ilosc_gr_do_stworzenia; i > 0; i--)
{
wielkosc_nowa_gr_wykladowa = round(nie_przydzielone_gr_cw / i);
for(int j = 0; j < wielkosc_nowa_gr_wykladowa; j++)
{
Grupy_Wyk[k][ilosc_gr_do_stworzenia - i].grupa_cw()->push_back(&Grupy_Cw[k][j + Wszystkie_gr_cw - nie_przydzielone_gr_cw]);
}
nie_przydzielone_gr_cw -= wielkosc_nowa_gr_wykladowa;
}
for (int i = ilosc_gr_do_stworzenia; i > 0; i--)
{
wielkosc_nowa_gr_wykladowa = round(nie_przydzielone_gr_lab / i);
for(int j = 0; j < wielkosc_nowa_gr_wykladowa; j++)
{
Grupy_Wyk[k][ilosc_gr_do_stworzenia - i].grupa_lab()->push_back(&Grupy_Lab[k][j + Wszystkie_gr_lab - nie_przydzielone_gr_lab]);
}
nie_przydzielone_gr_lab -= wielkosc_nowa_gr_wykladowa;
}
}
}
void Grup_Cw_Podz(vector<vector<Nad_grupa>> &Grupy_Cw, vector <vector<Grupa>> &Grupy_Lab)
{
int ilosc_rocznikow = Grupy_Cw.size();
for(int k = 0; k < ilosc_rocznikow; k++)
{
int Wszystkie_gr_lab = Grupy_Lab[k].size();
float nie_przydzielone_gr_lab = Grupy_Lab[k].size();
int ilosc_gr_do_stworzenia = Grupy_Cw[k].size();
float wielkosc_nowa_gr_cwiczeniowa = 0;
for (int i = ilosc_gr_do_stworzenia; i > 0; i--)
{
wielkosc_nowa_gr_cwiczeniowa = round(nie_przydzielone_gr_lab / i);
for(int j = 0; j < wielkosc_nowa_gr_cwiczeniowa; j++)
{
Grupy_Cw[k][ilosc_gr_do_stworzenia - i].grupa_lab()->push_back(&Grupy_Lab[k][j + Wszystkie_gr_lab - nie_przydzielone_gr_lab]);
}
nie_przydzielone_gr_lab -= wielkosc_nowa_gr_cwiczeniowa;
}
}
}
void Wczytanie_nauczycieli_wykladow(vector <vector<Przedmiot>> &Przedmioty_Wykl,vector <Nauczyciel> &Nauczyciele)
{
fstream plik;
plik.open("wyklady_nauczyciele.csv", ios::in | ios::out);
if(plik.is_open())
{
cout << "Plik z nauczycielami wykladow otwarty" << endl << endl;
string linia;
string czesc;
int numer_nauczyciela = 0;
int numer_wykladu = 0;
int ile_wykladow = 0;
int ile_wykl_wcze = 0;
vector <string> dane;
int il_zbiorow_wykladow = Przedmioty_Wykl.size();
while(!plik.eof())
{
plik >> linia;
stringstream strumien(linia);
while(getline(strumien,czesc,','))
{
dane.push_back(czesc);
}
if(dane[0] != "" && dane[0] != ";")
{
numer_wykladu = 0;
ile_wykladow = Przedmioty_Wykl[0].size();
ile_wykl_wcze = 0;
for(int j = 0; j < il_zbiorow_wykladow;j++)
{
for(int i = numer_wykladu; i < ile_wykladow; i++)
{
if(stoi(dane[i]) != 0)
{
Nauczyciele[numer_nauczyciela].Godziny_wykl(i,stoi(dane[i]));
Przedmioty_Wykl[j][i-ile_wykl_wcze].Dodaj_nauczyciela(numer_nauczyciela);
}
else if(stoi(dane[i]) == "")
{
cout << "Blad w pliku nauczyciele_wykladow wiersz " << numer_nauczyciela << endl;
}
numer_wykladu++;
}
ile_wykl_wcze = ile_wykladow;
ile_wykladow += Przedmioty_Wykl[j+1].size();
}
}
else if(dane[0] == ";")
{
break;
}
dane.erase(dane.begin(), dane.end());
numer_nauczyciela++;
}
plik.close();
}
else
cout<<"Nie udało się otworzyć pliku z nauczycielami wykladow przedmiotow";
}
void Wczytanie_nauczycieli_cwiczen(vector<vector<Przedmiot>> &Przedmioty_Cw,vector <Nauczyciel> &Nauczyciele)
{
fstream plik;
plik.open("cwiczenia_nauczyciele.csv", ios::in | ios::out);
if(plik.is_open())
{
cout << "Plik z nauczycielami cwiczeniami otwarty" << endl << endl;
string linia;
string czesc;
int numer_nauczyciela = 0;
int numer_cwiczenia = 0;
int ile_cwiczen = 0;
int ile_cw_wcze = 0;
vector <string> dane;
int il_zbiorow_cwiczen = Przedmioty_Cw.size();
while(!plik.eof())
{
plik >> linia;
stringstream strumien(linia);
while(getline(strumien,czesc,','))
{
dane.push_back(czesc);
}
if(dane[0] != "" && dane[0] != ";")
{
numer_cwiczenia = 0;
ile_cwiczen = Przedmioty_Cw[0].size();
ile_cw_wcze = 0;
for(int j = 0; j < il_zbiorow_cwiczen;j++)
{
for(int i = numer_cwiczenia; i < ile_cwiczen; i++)
{
if(stoi(dane[i]) != 0)
{
Nauczyciele[numer_nauczyciela].Godziny_cw(i,stoi(dane[i]));
Przedmioty_Cw[j][i-ile_cw_wcze].Dodaj_nauczyciela(numer_nauczyciela);
}
else if(stoi(dane[i]) == "")
{
cout << "Blad w pliku nauczyciele_cwiczen wiersz:" << numer_nauczyciela << endl;
}
numer_cwiczenia++;
}
ile_cw_wcze = ile_cwiczen;
ile_cwiczen += Przedmioty_Cw[j+1].size();
}
}
else if(dane[0] == ";")
{
break;
}
dane.erase(dane.begin(), dane.end());
numer_nauczyciela++;
}
plik.close();
}
else
cout<<"Nie udało się otworzyć pliku z nauczycielami cwiczen przedmiotow";
}
void Wczytanie_nauczycieli_laborek(vector <vector<Przedmiot>> &Przedmioty_Lab,vector < Nauczyciel> &Nauczyciele)
{
fstream plik;
plik.open("laborki_nauczyciele.csv", ios::in | ios::out);
if(plik.is_open())
{
cout << "Plik z nauczycielami laborek otwarty" << endl << endl;
string linia;
string czesc;
int numer_nauczyciela = 0;
int numer_laborek = 0;
int ile_laborek = 0;
int ile_lab_wcze = 0;
vector <string> dane;
int il_zbiorow_labek = Przedmioty_Lab.size();
while(!plik.eof())
{
plik >> linia;
stringstream strumien(linia);
while(getline(strumien,czesc,','))
{
dane.push_back(czesc);
}
if(dane[0] != "" && dane[0] != ";")
{
numer_laborek = 0;
ile_laborek = Przedmioty_Lab[0].size();
ile_lab_wcze = 0;
for(int j = 0; j < il_zbiorow_labek;j++)
{
for(int i = numer_laborek; i < ile_laborek; i++)
{
if(stoi(dane[i]) != 0)
{
Nauczyciele[numer_nauczyciela].Godziny_labek(i,stoi(dane[i]));
Przedmioty_Lab[j][i-ile_lab_wcze].Dodaj_nauczyciela(numer_nauczyciela);
}
else if(stoi(dane[i]) == "")
{
cout << "Blad w pliku nauczyciele_laborek wiersz: " << numer_nauczyciela << endl;
}
numer_laborek++;
}
ile_lab_wcze = ile_laborek;
ile_laborek += Przedmioty_Lab[j+1].size();
}
}
else if(dane[0] == ";")
{
break;
}
dane.erase(dane.begin(), dane.end());
numer_nauczyciela++;
}
plik.close();
}
else
cout<<"Nie udało się otworzyć pliku z nauczycielami laborek przedmiotow";
}
void Zajecia_wykladowe(vector <Zajecia>&Zajecie,vector<vector<Przedmiot>>&Przedmioty_Wykl,vector<vector<Nad_grupa>>&Grupy_Wykl,vector<Sala>&Sala_Wykl,int &il_wykl)
{
int ile_zbior_gr_wykl = Grupy_Wykl.size();
int ile_zbior_wykl = Przedmioty_Wykl.size();
int ilosc_wykladow = 0;
int ilosc_grup = 0;
int maks_ile_grup = 0;
int maks_ile_wykl = 0;
vector<vector<Przedmiot>>::iterator it1 = Przedmioty_Wykl.begin();
vector<vector<Nad_grupa>>::iterator it2 = Grupy_Wykl.begin();
for(;it1 != Przedmioty_Wykl.end() && it2 != Grupy_Wykl.end();it1++,it2++)
{
ilosc_wykladow = it1->size();
ilosc_grup = it2->size();
if(maks_ile_wykl < ilosc_wykladow)
maks_ile_wykl = ilosc_wykladow;
if(maks_ile_grup < ilosc_grup)
maks_ile_grup = ilosc_grup;
}
int numer_zajecia = 0;
if(ile_zbior_gr_wykl == ile_zbior_wykl)
{
for(int k = 0; k < maks_ile_wykl; k++)
{
for(int i = 0; i < maks_ile_grup; i++)
{
for(int j = 0; j < ile_zbior_wykl; j++)
{
ilosc_wykladow = Przedmioty_Wykl[j].size();
ilosc_grup = Grupy_Wykl[j].size();
if(k < ilosc_wykladow && i < ilosc_grup)
{
Zajecie.push_back({{&Przedmioty_Wykl[j][k]},{NULL},{&Grupy_Wykl[j][i]},(numer_zajecia+1)});
numer_zajecia++;
}
}
}
}
int sala_wykl = 0;
int ilosc_sal = Sala_Wykl.size();
int ilosc_zajec = Zajecie.size();
for(int i = 0; i < ilosc_zajec; i++)
{
if(sala_wykl == ilosc_sal)
sala_wykl = 0;
Zajecie[i].dodaj_sale()->push_back({&Sala_Wykl[sala_wykl]});
sala_wykl++;
}
il_wykl = Zajecie.size();
}
else
{
cout << "Zbiory wykladow i grup wykladowych nie sa sobie rowne" << endl;
}
}
void Zajecia_cwiczeniowe(vector <Zajecia> &Zajecie,vector<vector<Przedmiot>> &Przedmioty_Cw,vector <vector<Nad_grupa>> &Grupy_Cw,vector<Sala> &Sala_Cw,int &il_wykl_i_cw)
{
int ile_zbior_gr_cw = Grupy_Cw.size();
int ile_zbior_cw = Przedmioty_Cw.size();
int ilosc_cwiczen = 0;
int ilosc_grup = 0;
int maks_ile_grup = 0;
int maks_ile_cw = 0;
vector<vector<Przedmiot>>::iterator it1 = Przedmioty_Cw.begin();
vector<vector<Nad_grupa>>::iterator it2 = Grupy_Cw.begin();
for(;it1 != Przedmioty_Cw.end() && it2 != Grupy_Cw.end();it1++,it2++)
{
ilosc_cwiczen = it1->size();
ilosc_grup = it2->size();
if(maks_ile_cw < ilosc_cwiczen)
maks_ile_cw = ilosc_cwiczen;
if(maks_ile_grup < ilosc_grup)
maks_ile_grup = ilosc_grup;
}
int numer_zajecia = Zajecie.size();
int ilosc_wykladow = Zajecie.size();
if(ile_zbior_gr_cw == ile_zbior_cw)
{
for(int k = 0; k < maks_ile_cw; k++)
{
for(int i = 0; i < maks_ile_grup; i++)
{
for(int j = 0; j < ile_zbior_cw; j++)
{
ilosc_cwiczen = Przedmioty_Cw[j].size();
ilosc_grup = Grupy_Cw[j].size();
if(k < ilosc_cwiczen && i < ilosc_grup)
{
Zajecie.push_back({{&Przedmioty_Cw[j][k]},{NULL},{&Grupy_Cw[j][i]},(numer_zajecia+1)});
numer_zajecia++;
}
}
}
}
int sala_cw = 0;
int ilosc_sal = Sala_Cw.size();
int ilosc_zajec = Zajecie.size();
for(int i = ilosc_wykladow; i < ilosc_zajec; i++)
{
if(sala_cw == ilosc_sal)
sala_cw = 0;
Zajecie[i].dodaj_sale()->push_back({&Sala_Cw[sala_cw]});
sala_cw++;
}
il_wykl_i_cw = Zajecie.size();
}
else
{
cout << "Zbiory cwiczen i grup cwiczeniowych nie sa sobie rowne" << endl;
}
}
void Zajecia_laborki(vector <Zajecia> &Zajecie,vector <vector<Przedmiot>> &Przedmioty_Lab,vector<vector<Grupa>> &Grupy_Lab,vector<Sala> &Sala_Lab)
{
int ile_zbior_gr_lab = Grupy_Lab.size();
int ile_zbior_lab = Przedmioty_Lab.size();
int ilosc_laborek = 0;
int ilosc_grup = 0;
int maks_ile_grup = 0;
int maks_ile_lab = 0;
vector<vector<Przedmiot>>::iterator it1 = Przedmioty_Lab.begin();
vector<vector<Grupa>>::iterator it2 = Grupy_Lab.begin();
for(;it1 != Przedmioty_Lab.end() && it2 != Grupy_Lab.end();it1++,it2++)
{
ilosc_laborek = it1->size();
ilosc_grup = it2->size();
if(maks_ile_lab < ilosc_laborek)
maks_ile_lab = ilosc_laborek;
if(maks_ile_grup < ilosc_grup)
maks_ile_grup = ilosc_grup;
}
int numer_zajecia = Zajecie.size();
int ilosc_wykl_i_cw = Zajecie.size();
if(ile_zbior_gr_lab == ile_zbior_lab)
{
for(int k = 0; k < maks_ile_lab; k++)
{
for(int i = 0; i < maks_ile_grup; i++)
{
for(int j = 0; j < ile_zbior_lab; j++)
{
ilosc_laborek = Przedmioty_Lab[j].size();
ilosc_grup = Grupy_Lab[j].size();
if(k < ilosc_laborek && i < ilosc_grup)
{
Zajecie.push_back({{&Przedmioty_Lab[j][k]},{&Grupy_Lab[j][i]},{NULL},numer_zajecia+1});
numer_zajecia++;
}
}
}
}
int sala_lab = 0;
int ilosc_sal = Sala_Lab.size();
int ilosc_zajec = Zajecie.size();
for(int i = ilosc_wykl_i_cw; i < ilosc_zajec; i++)
{
if(sala_lab == ilosc_sal)
sala_lab = 0;
Zajecie[i].dodaj_sale()->push_back({&Sala_Lab[sala_lab]});
sala_lab++;
}
}
else
{
cout << "Zbiory laborek i grup laboratoryjnych nie sa sobie rowne" << endl;
}
}
void Zajecia_nauczyciele(vector<Zajecia> &Zajecie,vector<Nauczyciel> &Nauczyciele,int il_wykl,int il_wykl_i_cw)
{
int ilosc_zajec = Zajecie.size();
for(int i = 0; i < il_wykl; i++)
{
if(Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()].Dostepny_wykl(Zajecie[i].przedmiot()->Zwroc_numer()))
{
Zajecie[i].nauczyciel()->push_back(&Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()]);
}
else
{
Zajecie[i].przedmiot()->Nastepny_nauczyciel();
Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()].Dostepny_wykl(Zajecie[i].przedmiot()->Zwroc_numer());
Zajecie[i].nauczyciel()->push_back(&Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()]);
}
}
for(int i = il_wykl; i < il_wykl_i_cw; i++)
{
if(Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()].Dostepny_cw(Zajecie[i].przedmiot()->Zwroc_numer()))
{
Zajecie[i].nauczyciel()->push_back(&Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()]);
}
else
{
Zajecie[i].przedmiot()->Nastepny_nauczyciel();
Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()].Dostepny_cw(Zajecie[i].przedmiot()->Zwroc_numer());
Zajecie[i].nauczyciel()->push_back(&Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()]);
}
}
for(int i = il_wykl_i_cw; i < ilosc_zajec; i++)
{
if(Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()].Dostepny_lab(Zajecie[i].przedmiot()->Zwroc_numer()))
{
Zajecie[i].nauczyciel()->push_back(&Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()]);
}
else
{
Zajecie[i].przedmiot()->Nastepny_nauczyciel();
Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()].Dostepny_lab(Zajecie[i].przedmiot()->Zwroc_numer());
Zajecie[i].nauczyciel()->push_back(&Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()]);
}
}
}
void Tworzenie_harmonogramu(vector <Zajecia> &Zajecie)
{
int ilosc_zajec = Zajecie.size();
for(int i = 0; i < ilosc_zajec; i++)
{
int losowa = rand() % 2;
Zajecie[i].Termin_zajec(losowa);
}
}
void Wypisanie_danych_harmonogramu(vector <Zajecia> &Zajecie,vector <vector<Grupa>> &Grupy_Lab, vector <Nauczyciel> &Nauczyciele)
{
int ilosc_nauczycieli = Nauczyciele.size();
int ilosc_zajec = 0;
set <int>::iterator it;
for(int i = 0; i < ilosc_nauczycieli; i++)
{
cout << "Plan nauczyciela " << i+1 << endl;
for(int j = 0; j < 20; j++)
{
Nauczyciele[i].Wypisz_poz_w_plan(j);
}
cout << endl;
ilosc_zajec = Nauczyciele[i].Ile_zajec();
cout << "Ilosc zajec nauczyciela: " << ilosc_zajec << endl;
it = Nauczyciele[i].Pierwszy_zaj_termin();
cout << "Zajecie pierwsze: " << *it << endl;
it = --Nauczyciele[i].Ostatni_zaj_termin();
cout << "Zajecie ostatnie: " << *it << endl;
cout << "Kara: " << Nauczyciele[i].Oblicz_kare() << endl;
cout << "Godziny dopuszczalne: ";
for(it = Nauczyciele[i].Pierwszy_dop_termin(); it != Nauczyciele[i].Ostatni_dop_termin(); it++)
{
cout << *it << " ";
}
cout << endl;
cout << "Terminy wykluczone: ";
for(it = Nauczyciele[i].Pierwszy_niedop_termin(); it != Nauczyciele[i].Ostatni_niedop_termin(); it++)
{
cout << *it << " ";
}
cout << endl;
cout << "Zajete terminy: ";
for(it = Nauczyciele[i].Pierwszy_zaj_termin(); it != Nauczyciele[i].Ostatni_zaj_termin(); it++)
{
cout << *it << " ";
}
cout << endl << endl;
}
cout << "Suma kar dla nauczycieli: " << Kara_laczna_nauczycieli(Nauczyciele) << endl << endl;
int ile_zbior_grup = Grupy_Lab.size();
int ilosc_grup = 0;
for(int k = 0; k < ile_zbior_grup; k++)
{
ilosc_grup = Grupy_Lab[k].size();
for(int i = 0; i < ilosc_grup; i++)
{
cout << "Plan Grupy " << i+1 << endl;
for(int j = 0; j < 20; j++)
{
cout << Grupy_Lab[k][i].Zwroc_numer_zaj(j) << " ";
}
cout << endl;
ilosc_zajec = Grupy_Lab[k][i].Ile_zajec();
cout << "Ilosc zajec grup: " << ilosc_zajec << endl;
it = Grupy_Lab[k][i].Pierwszy_zaj_termin();
cout << "Zajecie pierwsze: " << *it << endl;
it = --Grupy_Lab[k][i].Ostatni_zaj_termin();
cout << "Zajecie ostatnie: " << *it << endl;
cout << "Kara planu: " << Grupy_Lab[k][i].Oblicz_kare() << endl;
cout << "Zajete terminy: ";
for(it = Grupy_Lab[k][i].Pierwszy_zaj_termin(); it != Grupy_Lab[k][i].Ostatni_zaj_termin(); it++)
{
cout << *it << " ";
}
cout << endl << endl;
}
}
cout << "Suma kar dla grup: " << Kara_laczna_grup(Grupy_Lab) << endl << endl;
cout << "Kara laczna dla grup i nauczycieli: " << Kara_laczna_nauczycieli(Nauczyciele) + Kara_laczna_grup(Grupy_Lab) << endl << endl;
}
void Poprawianie_harmonogramu(vector <Zajecia> &Zajecie,vector <vector<Grupa>> &Grupy_Lab,vector <Nauczyciel> &Nauczyciele, vector <Sala> Sala_Lab, int ile_popraw)
{
vector <Sala> Sala_Lab_Naj = Sala_Lab;
vector <vector<Grupa>> Grupy_Lab_Naj = Grupy_Lab;
vector <Nauczyciel> Nauczyciele_Naj = Nauczyciele;
vector <Zajecia> Zajecie_Naj = Zajecie;
vector <float> kara_grupy;
vector <float> kara_nauczyciel;
vector <float>::iterator it;
vector <Nauczyciel*> nauczyciele_labek;
vector <Grupa*> grupy;
int ilosc_zbiorow_grup = Grupy_Lab.size();
int ilosc_grup = 0;
int ilosc_nauczy = Nauczyciele.size();
int il_nauczy_lab = 0;
int najg_nauczy = 0;
int najg_grupa = 0;
int ile_zmian = 0;
for(int i = 0; i < ilosc_zbiorow_grup; i++)
{
ilosc_grup = Grupy_Lab[i].size();
for(int j = 0; j < ilosc_grup; j++)
{
grupy.push_back({&Grupy_Lab[i][j]});
}
}
ilosc_grup = grupy.size();
for(int i = 0; i < ilosc_grup; i++)
{
kara_grupy.push_back({grupy[i]->Oblicz_kare()});
}
cout << endl;
it = max_element(kara_grupy.begin(),kara_grupy.end());
najg_grupa = distance(kara_grupy.begin(), it);
for(int i = 0; i < ilosc_nauczy; i++)
{
if(Nauczyciele[i].Ile_lab_w_planie() != 0)
nauczyciele_labek.push_back({&Nauczyciele[i]});
}
il_nauczy_lab = nauczyciele_labek.size();
for(int i = 0; i < il_nauczy_lab; i++)
{
kara_nauczyciel.push_back(nauczyciele_labek[i]->Oblicz_kare());
}
it = max_element(kara_nauczyciel.begin(),kara_nauczyciel.end());
najg_nauczy = distance(kara_nauczyciel.begin(), it);
cout << "Ogolna wartosc kary planu: " << Ogolna_kara_planu(Grupy_Lab,Nauczyciele) << endl;
for(int i = 0; i < ile_popraw; i++)
{
Poprawianie_grupy(Zajecie,it,kara_grupy,grupy,najg_grupa);
Poprawianie_nauczycieli(Zajecie,it,kara_nauczyciel,Nauczyciele,najg_nauczy);
if(Ogolna_kara_planu(Grupy_Lab,Nauczyciele) < Ogolna_kara_planu(Grupy_Lab_Naj,Nauczyciele_Naj))
{
Sala_Lab_Naj = Sala_Lab;
Grupy_Lab_Naj = Grupy_Lab;
Nauczyciele_Naj = Nauczyciele;
Zajecie_Naj = Zajecie;
ile_zmian = 0;
}
else if(ile_zmian == 2)
{
Sala_Lab = Sala_Lab_Naj;
Grupy_Lab = Grupy_Lab_Naj;
Nauczyciele = Nauczyciele_Naj;
Zajecie = Zajecie_Naj;
for(int i = 0; i < ilosc_grup; i++)
{
kara_grupy[i] = grupy[i]->Zwroc_kare();
}
for(int i = 0; i < il_nauczy_lab; i++)
{
kara_nauczyciel[i] = Nauczyciele[i].Zwroc_kare();
}
ile_zmian = 0;
}
cout << "Ogolna wartosc kary planu: " << Ogolna_kara_planu(Grupy_Lab,Nauczyciele) << endl;
}
Sala_Lab = Sala_Lab_Naj;
Grupy_Lab = Grupy_Lab_Naj;
Nauczyciele = Nauczyciele_Naj;
Zajecie = Zajecie_Naj;
}
| [
"[email protected]"
] | |
2bcbe0f2f66fa7f38e8d1c4b20e5b469132dc932 | 7abd1d2bccc8848bc2d42cc12351b7e745b9ef7b | /objects/Flower.h | 2676e745388187f06846021a0c38eb675f609bfb | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | vinz9/vstvisframework | f98f48ab064cef7c908a262810bd3e0ca4dfd696 | 0c4e1508d313c8deb588def77aa1a23f131c9333 | refs/heads/master | 2021-07-15T21:10:38.230197 | 2016-09-16T21:02:49 | 2016-09-16T21:02:49 | 8,673,426 | 14 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 723 | h | /* flower code from http://asilvast.kapsi.fi/pseudotoad/projects */
#ifndef FLOWER_H_
#define FLOWER_H_
#include "Object3d.h"
typedef float Vect[3];
class Flower : public Object3d
{
public:
Flower();
Flower(AudioEffect* effect, int m, float stg1, float stg2);
~Flower();
void draw();
void setInput(int input);
private:
float* audiobars;
void spline3DMorph(float factor, float poikkeama);
void splineTCP(float u, Vect * control, Vect * result);
void updateActive();
int active[12];
float tension, continuity, bias;
float tension_new, continuity_new, bias_new;
float spd;
float posz, posz_new;
float timef;
int montime, in, mode, freq, np, nbands;
float timeinput, st1, st2, def;
};
#endif
| [
"[email protected]"
] | |
2a1fb4641c92acbc5bff6165c23261bd00c63cad | 8191afce54f369c18f98c602b1ee99fcb5a75004 | /Composite/Leaf.h | 45f73608ae43cf657c68867da18b4ad661c7ad85 | [] | no_license | KoiKomei/INGSW | 07f9a49a9c735ec0bba10537840b9e3ae4d0811f | 456b6f366177772c3340bf2c469f01dd218171d9 | refs/heads/master | 2020-04-01T17:24:29.858283 | 2018-11-14T18:04:52 | 2018-11-14T18:04:52 | 153,427,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 236 | h | #pragma once
#ifndef LEAF_H
#define LEAF_H
#include "Component.h"
class Leaf :public Component {
public:
Leaf(int val) {
value = val;
}
void traverse() {
cout << value << ' ';
}
private:
int value;
};
#endif // !LEAF_H
| [
"[email protected]"
] | |
e7fe513735ca9bb29ae4c652941f342b7b211cac | 367012d9c5656d78ee1c013adf99fa41c6d3339c | /Chap5/Chap5/Stacks/ragnarstest.cpp | 479c84f7ca51f0e6e580627ba7c7fd05b5c5a1f4 | [] | no_license | alflinusjonsson/DALGO-Drawing | 6fedf45630e0fbe5ea2852535910e4570e38c102 | e3e64c43c8d1bedd7b6b36a7a5799c26024c83e5 | refs/heads/master | 2022-05-16T06:09:06.960659 | 2020-04-29T07:15:47 | 2020-04-29T07:15:47 | 259,852,708 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,359 | cpp | #include "ragnarstest.h"
#include "student2_arrstack.h"
#include "student1_liststack.h"
#include <iostream>
#include <string>
#include <QThread>
#include <QElapsedTimer>
#include <assert.h>
using namespace std;
template<class CStack> bool stackTest1(int recursionDepth=0)
{
QThread::msleep(300);
cout << " stackTest1 (recursionDepth " << recursionDepth << ")" << endl;
const int size = 100;
float arr[size];
for (int i=0;i<size;++i)
arr[i] = (float) rand()/RAND_MAX;
CStack stack;
for (int i=0; i<size ;++i){
int z = stack.size();
if (z!=i)
{ cout << "Fel storlek på stacken!! "<< z << " i st för "<< i <<endl;;
return false;
}
stack.pushBack( arr[i] );
}
if (recursionDepth==0 && stackTest1<CStack>(1)==false)// Testar att stacken kan användas i en rekursion.
return false;
for (int i=size; i>0 ;i--)
{
if (stack.size()!=i){
cout << "Fel stackstorlek, vid poppningen\n";
return false;
}
if (stack.back()!=arr[i-1]){
cout << "Fel TOP-värde p stacken\n";
return false;
}
stack.popBack();
}
return true;
}// stackTest
template<class CStack> bool stackTest2(){
cout << " stackTest2 (tidtagning)" << endl;
const int big = 1000000;
CStack stack;
QElapsedTimer myTimer;
myTimer.start();
for (int i=0;i<big ; ++i){
stack.pushBack( 1.2 );
if (big%100==0){
int duration = myTimer.elapsed();
if (duration>1000){
cout << "BUG: Stacken är för långsam!!!" << endl;
cout << " testen avslutades vid i=" << i << "av ("<<big<<")" << endl;
return false;
}
}
}
int duration = myTimer.elapsed();
cout << " stackTest2 avslutades inom " << duration << " ms." << endl;
return true;
}//stackTest2
bool testStart( const char *testName, const char *studentName ){
cout << endl << endl;
cout << "------------------------------------------\n";
cout << "Testing " << testName << " for student:" << studentName << endl;
assert( string("Homer Simpson") != studentName );
return true;
}
bool testStop( const char *testName, bool success ){
QThread::msleep(500);
cout << endl << testName << " " << (success? "Lyckades" : "MISSLYCKADES\7") << endl;
cout << "------------------------------------------\n";
assert( success );
return true;
}
//***********************************************************************
// ANROP: ragnarsTest( );
// VERSION: 2010-01-15
// UPPFIFT: Testar en eller flera rutiner som studenten har skrivit.
//***********************************************************************
bool ragnarsTest(){
setlocale(LC_ALL, "Swedish" );
cout << "\n\n ragnarsTest" << endl;
bool ok = true;
// testStart("LStack" , nameOfStudentLStack() );
// ok = ok && stackTest1<LStack>();
// ok = ok && stackTest2<LStack>();
// testStop("LStack", ok);
testStart("AStack" , nameOfStudentAStack() );
ok = ok && stackTest1<AStack>();
ok = ok && stackTest2<AStack>();
testStop("AStack", ok);
if (ok)
cout << "(självtesten lyckades!)" << endl;
return ok;
}// ragnarsTest
| [
"[email protected]"
] | |
9abc41d8d846b05335da7807f49359a553d84907 | 412e41b21e0f93b4a89c49a62c5501b54e3818fe | /examples/Advanced/Display/UTFT_demo/UTFT_demo.ino | 4acfe6a6d68a72849e212ba581d178fe05a07861 | [
"MIT"
] | permissive | UT2UH/MaixAmigo | 11f3d3c269765f0357d0d8645846eb2f892b0c45 | 0bd593dd2b9591960d6fdb079a7356266d0a8d3d | refs/heads/main | 2023-01-07T19:50:53.679766 | 2020-11-13T09:25:55 | 2020-11-13T09:25:55 | 312,208,128 | 9 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,144 | ino | // Demo based on:
// UTFT_Demo_320x240 by Henning Karlsen
// web: http://www.henningkarlsen.com/electronics
//
/*
This sketch uses the GLCD and font 2 only.
Make sure all the display driver and pin comnenctions are correct by
editting the User_Setup.h file in the TFT_eSPI library folder.
#########################################################################
###### DON'T FORGET TO UPDATE THE User_Setup.h FILE IN THE LIBRARY ######
#########################################################################
*/
#include <MaixAmigo.h>
#define TFT_GREY 0x7BEF
unsigned long runTime = 0;
void setup()
{
randomSeed(analogRead(A0));
// Setup the LCD
MA.begin();
// MA.Lcd.setRotation(1);
}
void loop()
{
randomSeed(millis());
//randomSeed(1234); // This ensure test is repeatable with exact same draws each loop
int buf[318];
int x, x2;
int y, y2;
int r;
runTime = millis();
// Clear the screen and draw the frame
MA.Lcd.fillScreen(TFT_BLACK);
MA.Lcd.fillRect(0, 0, 319, 14,TFT_RED);
MA.Lcd.fillRect(0, 226, 319, 14,TFT_GREY);
MA.Lcd.setTextColor(TFT_BLACK,TFT_RED);
MA.Lcd.drawCentreString("* TFT_eSPI *", 160, 4, 1);
MA.Lcd.setTextColor(TFT_YELLOW,TFT_GREY);
MA.Lcd.drawCentreString("Adapted by Bodmer", 160, 228,1);
MA.Lcd.drawRect(0, 14, 319, 211, TFT_BLUE);
// Draw crosshairs
MA.Lcd.drawLine(159, 15, 159, 224,TFT_BLUE);
MA.Lcd.drawLine(1, 119, 318, 119,TFT_BLUE);
for (int i=9; i<310; i+=10)
MA.Lcd.drawLine(i, 117, i, 121,TFT_BLUE);
for (int i=19; i<220; i+=10)
MA.Lcd.drawLine(157, i, 161, i,TFT_BLUE);
// Draw sin-, cos- and tan-lines
MA.Lcd.setTextColor(TFT_CYAN);
MA.Lcd.drawString("Sin", 5, 15,2);
for (int i=1; i<318; i++)
{
MA.Lcd.drawPixel(i,119+(sin(((i*1.13)*3.14)/180)*95),TFT_CYAN);
}
MA.Lcd.setTextColor(TFT_RED);
MA.Lcd.drawString("Cos", 5, 30,2);
for (int i=1; i<318; i++)
{
MA.Lcd.drawPixel(i,119+(cos(((i*1.13)*3.14)/180)*95),TFT_RED);
}
MA.Lcd.setTextColor(TFT_YELLOW);
MA.Lcd.drawString("Tan", 5, 45,2);
for (int i=1; i<318; i++)
{
MA.Lcd.drawPixel(i,119+(tan(((i*1.13)*3.14)/180)),TFT_YELLOW);
}
delay(1000);
MA.Lcd.fillRect(1,15,317,209,TFT_BLACK);
MA.Lcd.drawLine(159, 15, 159, 224,TFT_BLUE);
MA.Lcd.drawLine(1, 119, 318, 119,TFT_BLUE);
int col = 0;
// Draw a moving sinewave
x=1;
for (int i=1; i<(317*20); i++)
{
x++;
if (x==318)
x=1;
if (i>318)
{
if ((x==159)||(buf[x-1]==119))
col = TFT_BLUE;
else
MA.Lcd.drawPixel(x,buf[x-1],TFT_BLACK);
}
y=119+(sin(((i*1.1)*3.14)/180)*(90-(i / 100)));
MA.Lcd.drawPixel(x,y,TFT_BLUE);
buf[x-1]=y;
}
delay(1000);
MA.Lcd.fillRect(1,15,317,209,TFT_BLACK);
// Draw some filled rectangles
for (int i=1; i<6; i++)
{
switch (i)
{
case 1:
col = TFT_MAGENTA;
break;
case 2:
col = TFT_RED;
break;
case 3:
col = TFT_GREEN;
break;
case 4:
col = TFT_BLUE;
break;
case 5:
col = TFT_YELLOW;
break;
}
MA.Lcd.fillRect(70+(i*20), 30+(i*20), 60, 60,col);
}
delay(1000);
MA.Lcd.fillRect(1,15,317,209,TFT_BLACK);
// Draw some filled, rounded rectangles
for (int i=1; i<6; i++)
{
switch (i)
{
case 1:
col = TFT_MAGENTA;
break;
case 2:
col = TFT_RED;
break;
case 3:
col = TFT_GREEN;
break;
case 4:
col = TFT_BLUE;
break;
case 5:
col = TFT_YELLOW;
break;
}
MA.Lcd.fillRoundRect(190-(i*20), 30+(i*20), 60,60, 3,col);
}
delay(1000);
MA.Lcd.fillRect(1,15,317,209,TFT_BLACK);
// Draw some filled circles
for (int i=1; i<6; i++)
{
switch (i)
{
case 1:
col = TFT_MAGENTA;
break;
case 2:
col = TFT_RED;
break;
case 3:
col = TFT_GREEN;
break;
case 4:
col = TFT_BLUE;
break;
case 5:
col = TFT_YELLOW;
break;
}
MA.Lcd.fillCircle(100+(i*20),60+(i*20), 30,col);
}
delay(1000);
MA.Lcd.fillRect(1,15,317,209,TFT_BLACK);
// Draw some lines in a pattern
for (int i=15; i<224; i+=5)
{
MA.Lcd.drawLine(1, i, (i*1.44)-10, 223,TFT_RED);
}
for (int i=223; i>15; i-=5)
{
MA.Lcd.drawLine(317, i, (i*1.44)-11, 15,TFT_RED);
}
for (int i=223; i>15; i-=5)
{
MA.Lcd.drawLine(1, i, 331-(i*1.44), 15,TFT_CYAN);
}
for (int i=15; i<224; i+=5)
{
MA.Lcd.drawLine(317, i, 330-(i*1.44), 223,TFT_CYAN);
}
delay(1000);
MA.Lcd.fillRect(1,15,317,209,TFT_BLACK);
// Draw some random circles
for (int i=0; i<100; i++)
{
x=32+random(256);
y=45+random(146);
r=random(30);
MA.Lcd.drawCircle(x, y, r,random(0xFFFF));
}
delay(1000);
MA.Lcd.fillRect(1,15,317,209,TFT_BLACK);
// Draw some random rectangles
for (int i=0; i<100; i++)
{
x=2+random(316);
y=16+random(207);
x2=2+random(316);
y2=16+random(207);
if (x2<x) {
r=x;x=x2;x2=r;
}
if (y2<y) {
r=y;y=y2;y2=r;
}
MA.Lcd.drawRect(x, y, x2-x, y2-y,random(0xFFFF));
}
delay(1000);
MA.Lcd.fillRect(1,15,317,209,TFT_BLACK);
// Draw some random rounded rectangles
for (int i=0; i<100; i++)
{
x=2+random(316);
y=16+random(207);
x2=2+random(316);
y2=16+random(207);
// We need to get the width and height and do some window checking
if (x2<x) {
r=x;x=x2;x2=r;
}
if (y2<y) {
r=y;y=y2;y2=r;
}
// We need a minimum size of 6
if((x2-x)<6) x2=x+6;
if((y2-y)<6) y2=y+6;
MA.Lcd.drawRoundRect(x, y, x2-x,y2-y, 3,random(0xFFFF));
}
delay(1000);
MA.Lcd.fillRect(1,15,317,209,TFT_BLACK);
//randomSeed(1234);
int colour = 0;
for (int i=0; i<100; i++)
{
x=2+random(316);
y=16+random(209);
x2=2+random(316);
y2=16+random(209);
colour=random(0xFFFF);
MA.Lcd.drawLine(x, y, x2, y2,colour);
}
delay(1000);
MA.Lcd.fillRect(1,15,317,209,TFT_BLACK);
// This test has been modified as it takes more time to calculate the random numbers
// than to draw the pixels (3 seconds to produce 30,000 randoms)!
for (int i=0; i<10000; i++)
{
MA.Lcd.drawPixel(2+random(316), 16+random(209),random(0xFFFF));
}
// Draw 10,000 pixels to fill a 100x100 pixel box
// use the coords as the colour to produce the banding
//byte i = 100;
//while (i--) {
// byte j = 100;
// while (j--) MA.Lcd.drawPixel(i+110,j+70,i+j);
// //while (j--) MA.Lcd.drawPixel(i+110,j+70,0xFFFF);
//}
delay(1000);
MA.Lcd.fillScreen(TFT_BLUE);
MA.Lcd.fillRoundRect(80, 70, 239-80,169-70, 3,TFT_RED);
MA.Lcd.setTextColor(TFT_WHITE,TFT_RED);
MA.Lcd.drawCentreString("That's it!", 160, 93,2);
MA.Lcd.drawCentreString("Restarting in a", 160, 119,2);
MA.Lcd.drawCentreString("few seconds...", 160, 132,2);
runTime = millis()-runTime;
MA.Lcd.setTextColor(TFT_GREEN,TFT_BLUE);
MA.Lcd.drawCentreString("Runtime: (msecs)", 160, 210,2);
MA.Lcd.setTextDatum(TC_DATUM);
MA.Lcd.drawNumber(runTime, 160, 225,2);
delay (5000);
}
| [
"[email protected]"
] | |
351df11b35b05c1a9134770f71a3a679e69feec2 | bc92c058b0c2dd2877648e30156245e36ee571a4 | /source/common/xproto/framework/third_party/aarch64/opencv/include/opencv2/core/hal/intrin_neon.hpp | 6eb43abc6e2a4fc5c0f791e5ddfe87d30db7496a | [
"BSD-2-Clause"
] | permissive | robort-yuan/AI-EXPRESS | c1783f5f155b918dcc6da11956c842ae5467de8e | 56f86d03afbb09f42c21958c8cd9f2f1c6437f48 | refs/heads/master | 2023-02-09T03:51:44.775020 | 2021-01-02T15:15:37 | 2021-01-02T15:15:37 | 309,591,131 | 0 | 0 | BSD-2-Clause | 2020-12-08T07:48:54 | 2020-11-03T06:11:06 | null | UTF-8 | C++ | false | false | 64,403 | hpp | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Copyright (C) 2015, Itseez Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifndef OPENCV_HAL_INTRIN_NEON_HPP
#define OPENCV_HAL_INTRIN_NEON_HPP
#include <algorithm>
#include "opencv2/core/utility.hpp"
namespace cv
{
//! @cond IGNORED
CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN
#define CV_SIMD128 1
#if defined(__aarch64__)
#define CV_SIMD128_64F 1
#else
#define CV_SIMD128_64F 0
#endif
#if CV_SIMD128_64F
#define OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv, suffix) \
template <typename T> static inline \
_Tpv vreinterpretq_##suffix##_f64(T a) { return (_Tpv) a; } \
template <typename T> static inline \
float64x2_t vreinterpretq_f64_##suffix(T a) { return (float64x2_t) a; }
OPENCV_HAL_IMPL_NEON_REINTERPRET(uint8x16_t, u8)
OPENCV_HAL_IMPL_NEON_REINTERPRET(int8x16_t, s8)
OPENCV_HAL_IMPL_NEON_REINTERPRET(uint16x8_t, u16)
OPENCV_HAL_IMPL_NEON_REINTERPRET(int16x8_t, s16)
OPENCV_HAL_IMPL_NEON_REINTERPRET(uint32x4_t, u32)
OPENCV_HAL_IMPL_NEON_REINTERPRET(int32x4_t, s32)
OPENCV_HAL_IMPL_NEON_REINTERPRET(uint64x2_t, u64)
OPENCV_HAL_IMPL_NEON_REINTERPRET(int64x2_t, s64)
OPENCV_HAL_IMPL_NEON_REINTERPRET(float32x4_t, f32)
#endif
struct v_uint8x16
{
typedef uchar lane_type;
enum { nlanes = 16 };
v_uint8x16() {}
explicit v_uint8x16(uint8x16_t v) : val(v) {}
v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7,
uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15)
{
uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15};
val = vld1q_u8(v);
}
uchar get0() const
{
return vgetq_lane_u8(val, 0);
}
uint8x16_t val;
};
struct v_int8x16
{
typedef schar lane_type;
enum { nlanes = 16 };
v_int8x16() {}
explicit v_int8x16(int8x16_t v) : val(v) {}
v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7,
schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15)
{
schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15};
val = vld1q_s8(v);
}
schar get0() const
{
return vgetq_lane_s8(val, 0);
}
int8x16_t val;
};
struct v_uint16x8
{
typedef ushort lane_type;
enum { nlanes = 8 };
v_uint16x8() {}
explicit v_uint16x8(uint16x8_t v) : val(v) {}
v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7)
{
ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7};
val = vld1q_u16(v);
}
ushort get0() const
{
return vgetq_lane_u16(val, 0);
}
uint16x8_t val;
};
struct v_int16x8
{
typedef short lane_type;
enum { nlanes = 8 };
v_int16x8() {}
explicit v_int16x8(int16x8_t v) : val(v) {}
v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7)
{
short v[] = {v0, v1, v2, v3, v4, v5, v6, v7};
val = vld1q_s16(v);
}
short get0() const
{
return vgetq_lane_s16(val, 0);
}
int16x8_t val;
};
struct v_uint32x4
{
typedef unsigned lane_type;
enum { nlanes = 4 };
v_uint32x4() {}
explicit v_uint32x4(uint32x4_t v) : val(v) {}
v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3)
{
unsigned v[] = {v0, v1, v2, v3};
val = vld1q_u32(v);
}
unsigned get0() const
{
return vgetq_lane_u32(val, 0);
}
uint32x4_t val;
};
struct v_int32x4
{
typedef int lane_type;
enum { nlanes = 4 };
v_int32x4() {}
explicit v_int32x4(int32x4_t v) : val(v) {}
v_int32x4(int v0, int v1, int v2, int v3)
{
int v[] = {v0, v1, v2, v3};
val = vld1q_s32(v);
}
int get0() const
{
return vgetq_lane_s32(val, 0);
}
int32x4_t val;
};
struct v_float32x4
{
typedef float lane_type;
enum { nlanes = 4 };
v_float32x4() {}
explicit v_float32x4(float32x4_t v) : val(v) {}
v_float32x4(float v0, float v1, float v2, float v3)
{
float v[] = {v0, v1, v2, v3};
val = vld1q_f32(v);
}
float get0() const
{
return vgetq_lane_f32(val, 0);
}
float32x4_t val;
};
struct v_uint64x2
{
typedef uint64 lane_type;
enum { nlanes = 2 };
v_uint64x2() {}
explicit v_uint64x2(uint64x2_t v) : val(v) {}
v_uint64x2(uint64 v0, uint64 v1)
{
uint64 v[] = {v0, v1};
val = vld1q_u64(v);
}
uint64 get0() const
{
return vgetq_lane_u64(val, 0);
}
uint64x2_t val;
};
struct v_int64x2
{
typedef int64 lane_type;
enum { nlanes = 2 };
v_int64x2() {}
explicit v_int64x2(int64x2_t v) : val(v) {}
v_int64x2(int64 v0, int64 v1)
{
int64 v[] = {v0, v1};
val = vld1q_s64(v);
}
int64 get0() const
{
return vgetq_lane_s64(val, 0);
}
int64x2_t val;
};
#if CV_SIMD128_64F
struct v_float64x2
{
typedef double lane_type;
enum { nlanes = 2 };
v_float64x2() {}
explicit v_float64x2(float64x2_t v) : val(v) {}
v_float64x2(double v0, double v1)
{
double v[] = {v0, v1};
val = vld1q_f64(v);
}
double get0() const
{
return vgetq_lane_f64(val, 0);
}
float64x2_t val;
};
#endif
#if CV_FP16
// Workaround for old compilers
static inline int16x4_t vreinterpret_s16_f16(float16x4_t a) { return (int16x4_t)a; }
static inline float16x4_t vreinterpret_f16_s16(int16x4_t a) { return (float16x4_t)a; }
static inline float16x4_t cv_vld1_f16(const void* ptr)
{
#ifndef vld1_f16 // APPLE compiler defines vld1_f16 as macro
return vreinterpret_f16_s16(vld1_s16((const short*)ptr));
#else
return vld1_f16((const __fp16*)ptr);
#endif
}
static inline void cv_vst1_f16(void* ptr, float16x4_t a)
{
#ifndef vst1_f16 // APPLE compiler defines vst1_f16 as macro
vst1_s16((short*)ptr, vreinterpret_s16_f16(a));
#else
vst1_f16((__fp16*)ptr, a);
#endif
}
#ifndef vdup_n_f16
#define vdup_n_f16(v) (float16x4_t){v, v, v, v}
#endif
#endif // CV_FP16
#if CV_FP16
inline v_float32x4 v128_load_fp16_f32(const short* ptr)
{
float16x4_t a = cv_vld1_f16((const __fp16*)ptr);
return v_float32x4(vcvt_f32_f16(a));
}
inline void v_store_fp16(short* ptr, const v_float32x4& a)
{
float16x4_t fp16 = vcvt_f16_f32(a.val);
cv_vst1_f16((short*)ptr, fp16);
}
#endif
#define OPENCV_HAL_IMPL_NEON_INIT(_Tpv, _Tp, suffix) \
inline v_##_Tpv v_setzero_##suffix() { return v_##_Tpv(vdupq_n_##suffix((_Tp)0)); } \
inline v_##_Tpv v_setall_##suffix(_Tp v) { return v_##_Tpv(vdupq_n_##suffix(v)); } \
inline _Tpv##_t vreinterpretq_##suffix##_##suffix(_Tpv##_t v) { return v; } \
inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16(vreinterpretq_u8_##suffix(v.val)); } \
inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16(vreinterpretq_s8_##suffix(v.val)); } \
inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8(vreinterpretq_u16_##suffix(v.val)); } \
inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(vreinterpretq_s16_##suffix(v.val)); } \
inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4(vreinterpretq_u32_##suffix(v.val)); } \
inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4(vreinterpretq_s32_##suffix(v.val)); } \
inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2(vreinterpretq_u64_##suffix(v.val)); } \
inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2(vreinterpretq_s64_##suffix(v.val)); } \
inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4(vreinterpretq_f32_##suffix(v.val)); }
OPENCV_HAL_IMPL_NEON_INIT(uint8x16, uchar, u8)
OPENCV_HAL_IMPL_NEON_INIT(int8x16, schar, s8)
OPENCV_HAL_IMPL_NEON_INIT(uint16x8, ushort, u16)
OPENCV_HAL_IMPL_NEON_INIT(int16x8, short, s16)
OPENCV_HAL_IMPL_NEON_INIT(uint32x4, unsigned, u32)
OPENCV_HAL_IMPL_NEON_INIT(int32x4, int, s32)
OPENCV_HAL_IMPL_NEON_INIT(uint64x2, uint64, u64)
OPENCV_HAL_IMPL_NEON_INIT(int64x2, int64, s64)
OPENCV_HAL_IMPL_NEON_INIT(float32x4, float, f32)
#if CV_SIMD128_64F
#define OPENCV_HAL_IMPL_NEON_INIT_64(_Tpv, suffix) \
inline v_float64x2 v_reinterpret_as_f64(const v_##_Tpv& v) { return v_float64x2(vreinterpretq_f64_##suffix(v.val)); }
OPENCV_HAL_IMPL_NEON_INIT(float64x2, double, f64)
OPENCV_HAL_IMPL_NEON_INIT_64(uint8x16, u8)
OPENCV_HAL_IMPL_NEON_INIT_64(int8x16, s8)
OPENCV_HAL_IMPL_NEON_INIT_64(uint16x8, u16)
OPENCV_HAL_IMPL_NEON_INIT_64(int16x8, s16)
OPENCV_HAL_IMPL_NEON_INIT_64(uint32x4, u32)
OPENCV_HAL_IMPL_NEON_INIT_64(int32x4, s32)
OPENCV_HAL_IMPL_NEON_INIT_64(uint64x2, u64)
OPENCV_HAL_IMPL_NEON_INIT_64(int64x2, s64)
OPENCV_HAL_IMPL_NEON_INIT_64(float32x4, f32)
OPENCV_HAL_IMPL_NEON_INIT_64(float64x2, f64)
#endif
#define OPENCV_HAL_IMPL_NEON_PACK(_Tpvec, _Tp, hreg, suffix, _Tpwvec, pack, mov, rshr) \
inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \
{ \
hreg a1 = mov(a.val), b1 = mov(b.val); \
return _Tpvec(vcombine_##suffix(a1, b1)); \
} \
inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \
{ \
hreg a1 = mov(a.val); \
vst1_##suffix(ptr, a1); \
} \
template<int n> inline \
_Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \
{ \
hreg a1 = rshr(a.val, n); \
hreg b1 = rshr(b.val, n); \
return _Tpvec(vcombine_##suffix(a1, b1)); \
} \
template<int n> inline \
void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \
{ \
hreg a1 = rshr(a.val, n); \
vst1_##suffix(ptr, a1); \
}
OPENCV_HAL_IMPL_NEON_PACK(v_uint8x16, uchar, uint8x8_t, u8, v_uint16x8, pack, vqmovn_u16, vqrshrn_n_u16)
OPENCV_HAL_IMPL_NEON_PACK(v_int8x16, schar, int8x8_t, s8, v_int16x8, pack, vqmovn_s16, vqrshrn_n_s16)
OPENCV_HAL_IMPL_NEON_PACK(v_uint16x8, ushort, uint16x4_t, u16, v_uint32x4, pack, vqmovn_u32, vqrshrn_n_u32)
OPENCV_HAL_IMPL_NEON_PACK(v_int16x8, short, int16x4_t, s16, v_int32x4, pack, vqmovn_s32, vqrshrn_n_s32)
OPENCV_HAL_IMPL_NEON_PACK(v_uint32x4, unsigned, uint32x2_t, u32, v_uint64x2, pack, vmovn_u64, vrshrn_n_u64)
OPENCV_HAL_IMPL_NEON_PACK(v_int32x4, int, int32x2_t, s32, v_int64x2, pack, vmovn_s64, vrshrn_n_s64)
OPENCV_HAL_IMPL_NEON_PACK(v_uint8x16, uchar, uint8x8_t, u8, v_int16x8, pack_u, vqmovun_s16, vqrshrun_n_s16)
OPENCV_HAL_IMPL_NEON_PACK(v_uint16x8, ushort, uint16x4_t, u16, v_int32x4, pack_u, vqmovun_s32, vqrshrun_n_s32)
// pack boolean
inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b)
{
uint8x16_t ab = vcombine_u8(vmovn_u16(a.val), vmovn_u16(b.val));
return v_uint8x16(ab);
}
inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b,
const v_uint32x4& c, const v_uint32x4& d)
{
uint16x8_t nab = vcombine_u16(vmovn_u32(a.val), vmovn_u32(b.val));
uint16x8_t ncd = vcombine_u16(vmovn_u32(c.val), vmovn_u32(d.val));
return v_uint8x16(vcombine_u8(vmovn_u16(nab), vmovn_u16(ncd)));
}
inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c,
const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f,
const v_uint64x2& g, const v_uint64x2& h)
{
uint32x4_t ab = vcombine_u32(vmovn_u64(a.val), vmovn_u64(b.val));
uint32x4_t cd = vcombine_u32(vmovn_u64(c.val), vmovn_u64(d.val));
uint32x4_t ef = vcombine_u32(vmovn_u64(e.val), vmovn_u64(f.val));
uint32x4_t gh = vcombine_u32(vmovn_u64(g.val), vmovn_u64(h.val));
uint16x8_t abcd = vcombine_u16(vmovn_u32(ab), vmovn_u32(cd));
uint16x8_t efgh = vcombine_u16(vmovn_u32(ef), vmovn_u32(gh));
return v_uint8x16(vcombine_u8(vmovn_u16(abcd), vmovn_u16(efgh)));
}
inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0,
const v_float32x4& m1, const v_float32x4& m2,
const v_float32x4& m3)
{
float32x2_t vl = vget_low_f32(v.val), vh = vget_high_f32(v.val);
float32x4_t res = vmulq_lane_f32(m0.val, vl, 0);
res = vmlaq_lane_f32(res, m1.val, vl, 1);
res = vmlaq_lane_f32(res, m2.val, vh, 0);
res = vmlaq_lane_f32(res, m3.val, vh, 1);
return v_float32x4(res);
}
inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0,
const v_float32x4& m1, const v_float32x4& m2,
const v_float32x4& a)
{
float32x2_t vl = vget_low_f32(v.val), vh = vget_high_f32(v.val);
float32x4_t res = vmulq_lane_f32(m0.val, vl, 0);
res = vmlaq_lane_f32(res, m1.val, vl, 1);
res = vmlaq_lane_f32(res, m2.val, vh, 0);
res = vaddq_f32(res, a.val);
return v_float32x4(res);
}
#define OPENCV_HAL_IMPL_NEON_BIN_OP(bin_op, _Tpvec, intrin) \
inline _Tpvec operator bin_op (const _Tpvec& a, const _Tpvec& b) \
{ \
return _Tpvec(intrin(a.val, b.val)); \
} \
inline _Tpvec& operator bin_op##= (_Tpvec& a, const _Tpvec& b) \
{ \
a.val = intrin(a.val, b.val); \
return a; \
}
OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_uint8x16, vqaddq_u8)
OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_uint8x16, vqsubq_u8)
OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_int8x16, vqaddq_s8)
OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_int8x16, vqsubq_s8)
OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_uint16x8, vqaddq_u16)
OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_uint16x8, vqsubq_u16)
OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_int16x8, vqaddq_s16)
OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_int16x8, vqsubq_s16)
OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_int32x4, vaddq_s32)
OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_int32x4, vsubq_s32)
OPENCV_HAL_IMPL_NEON_BIN_OP(*, v_int32x4, vmulq_s32)
OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_uint32x4, vaddq_u32)
OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_uint32x4, vsubq_u32)
OPENCV_HAL_IMPL_NEON_BIN_OP(*, v_uint32x4, vmulq_u32)
OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_float32x4, vaddq_f32)
OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_float32x4, vsubq_f32)
OPENCV_HAL_IMPL_NEON_BIN_OP(*, v_float32x4, vmulq_f32)
OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_int64x2, vaddq_s64)
OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_int64x2, vsubq_s64)
OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_uint64x2, vaddq_u64)
OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_uint64x2, vsubq_u64)
#if CV_SIMD128_64F
OPENCV_HAL_IMPL_NEON_BIN_OP(/, v_float32x4, vdivq_f32)
OPENCV_HAL_IMPL_NEON_BIN_OP(+, v_float64x2, vaddq_f64)
OPENCV_HAL_IMPL_NEON_BIN_OP(-, v_float64x2, vsubq_f64)
OPENCV_HAL_IMPL_NEON_BIN_OP(*, v_float64x2, vmulq_f64)
OPENCV_HAL_IMPL_NEON_BIN_OP(/, v_float64x2, vdivq_f64)
#else
inline v_float32x4 operator / (const v_float32x4& a, const v_float32x4& b)
{
float32x4_t reciprocal = vrecpeq_f32(b.val);
reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal);
reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal);
return v_float32x4(vmulq_f32(a.val, reciprocal));
}
inline v_float32x4& operator /= (v_float32x4& a, const v_float32x4& b)
{
float32x4_t reciprocal = vrecpeq_f32(b.val);
reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal);
reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal);
a.val = vmulq_f32(a.val, reciprocal);
return a;
}
#endif
// saturating multiply 8-bit, 16-bit
#define OPENCV_HAL_IMPL_NEON_MUL_SAT(_Tpvec, _Tpwvec) \
inline _Tpvec operator * (const _Tpvec& a, const _Tpvec& b) \
{ \
_Tpwvec c, d; \
v_mul_expand(a, b, c, d); \
return v_pack(c, d); \
} \
inline _Tpvec& operator *= (_Tpvec& a, const _Tpvec& b) \
{ a = a * b; return a; }
OPENCV_HAL_IMPL_NEON_MUL_SAT(v_int8x16, v_int16x8)
OPENCV_HAL_IMPL_NEON_MUL_SAT(v_uint8x16, v_uint16x8)
OPENCV_HAL_IMPL_NEON_MUL_SAT(v_int16x8, v_int32x4)
OPENCV_HAL_IMPL_NEON_MUL_SAT(v_uint16x8, v_uint32x4)
// Multiply and expand
inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b,
v_int16x8& c, v_int16x8& d)
{
c.val = vmull_s8(vget_low_s8(a.val), vget_low_s8(b.val));
d.val = vmull_s8(vget_high_s8(a.val), vget_high_s8(b.val));
}
inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b,
v_uint16x8& c, v_uint16x8& d)
{
c.val = vmull_u8(vget_low_u8(a.val), vget_low_u8(b.val));
d.val = vmull_u8(vget_high_u8(a.val), vget_high_u8(b.val));
}
inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b,
v_int32x4& c, v_int32x4& d)
{
c.val = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val));
d.val = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val));
}
inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b,
v_uint32x4& c, v_uint32x4& d)
{
c.val = vmull_u16(vget_low_u16(a.val), vget_low_u16(b.val));
d.val = vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val));
}
inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b,
v_uint64x2& c, v_uint64x2& d)
{
c.val = vmull_u32(vget_low_u32(a.val), vget_low_u32(b.val));
d.val = vmull_u32(vget_high_u32(a.val), vget_high_u32(b.val));
}
inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b)
{
return v_int16x8(vcombine_s16(
vshrn_n_s32(vmull_s16( vget_low_s16(a.val), vget_low_s16(b.val)), 16),
vshrn_n_s32(vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)), 16)
));
}
inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b)
{
return v_uint16x8(vcombine_u16(
vshrn_n_u32(vmull_u16( vget_low_u16(a.val), vget_low_u16(b.val)), 16),
vshrn_n_u32(vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val)), 16)
));
}
inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b)
{
int32x4_t c = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val));
int32x4_t d = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val));
int32x4x2_t cd = vuzpq_s32(c, d);
return v_int32x4(vaddq_s32(cd.val[0], cd.val[1]));
}
inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c)
{
v_int32x4 s = v_dotprod(a, b);
return v_int32x4(vaddq_s32(s.val , c.val));
}
#define OPENCV_HAL_IMPL_NEON_LOGIC_OP(_Tpvec, suffix) \
OPENCV_HAL_IMPL_NEON_BIN_OP(&, _Tpvec, vandq_##suffix) \
OPENCV_HAL_IMPL_NEON_BIN_OP(|, _Tpvec, vorrq_##suffix) \
OPENCV_HAL_IMPL_NEON_BIN_OP(^, _Tpvec, veorq_##suffix) \
inline _Tpvec operator ~ (const _Tpvec& a) \
{ \
return _Tpvec(vreinterpretq_##suffix##_u8(vmvnq_u8(vreinterpretq_u8_##suffix(a.val)))); \
}
OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint8x16, u8)
OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int8x16, s8)
OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint16x8, u16)
OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int16x8, s16)
OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint32x4, u32)
OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int32x4, s32)
OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint64x2, u64)
OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int64x2, s64)
#define OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(bin_op, intrin) \
inline v_float32x4 operator bin_op (const v_float32x4& a, const v_float32x4& b) \
{ \
return v_float32x4(vreinterpretq_f32_s32(intrin(vreinterpretq_s32_f32(a.val), vreinterpretq_s32_f32(b.val)))); \
} \
inline v_float32x4& operator bin_op##= (v_float32x4& a, const v_float32x4& b) \
{ \
a.val = vreinterpretq_f32_s32(intrin(vreinterpretq_s32_f32(a.val), vreinterpretq_s32_f32(b.val))); \
return a; \
}
OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(&, vandq_s32)
OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(|, vorrq_s32)
OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(^, veorq_s32)
inline v_float32x4 operator ~ (const v_float32x4& a)
{
return v_float32x4(vreinterpretq_f32_s32(vmvnq_s32(vreinterpretq_s32_f32(a.val))));
}
#if CV_SIMD128_64F
inline v_float32x4 v_sqrt(const v_float32x4& x)
{
return v_float32x4(vsqrtq_f32(x.val));
}
inline v_float32x4 v_invsqrt(const v_float32x4& x)
{
v_float32x4 one = v_setall_f32(1.0f);
return one / v_sqrt(x);
}
#else
inline v_float32x4 v_sqrt(const v_float32x4& x)
{
float32x4_t x1 = vmaxq_f32(x.val, vdupq_n_f32(FLT_MIN));
float32x4_t e = vrsqrteq_f32(x1);
e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x1, e), e), e);
e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x1, e), e), e);
return v_float32x4(vmulq_f32(x.val, e));
}
inline v_float32x4 v_invsqrt(const v_float32x4& x)
{
float32x4_t e = vrsqrteq_f32(x.val);
e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x.val, e), e), e);
e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x.val, e), e), e);
return v_float32x4(e);
}
#endif
#define OPENCV_HAL_IMPL_NEON_ABS(_Tpuvec, _Tpsvec, usuffix, ssuffix) \
inline _Tpuvec v_abs(const _Tpsvec& a) { return v_reinterpret_as_##usuffix(_Tpsvec(vabsq_##ssuffix(a.val))); }
OPENCV_HAL_IMPL_NEON_ABS(v_uint8x16, v_int8x16, u8, s8)
OPENCV_HAL_IMPL_NEON_ABS(v_uint16x8, v_int16x8, u16, s16)
OPENCV_HAL_IMPL_NEON_ABS(v_uint32x4, v_int32x4, u32, s32)
inline v_float32x4 v_abs(v_float32x4 x)
{ return v_float32x4(vabsq_f32(x.val)); }
#if CV_SIMD128_64F
#define OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(bin_op, intrin) \
inline v_float64x2 operator bin_op (const v_float64x2& a, const v_float64x2& b) \
{ \
return v_float64x2(vreinterpretq_f64_s64(intrin(vreinterpretq_s64_f64(a.val), vreinterpretq_s64_f64(b.val)))); \
} \
inline v_float64x2& operator bin_op##= (v_float64x2& a, const v_float64x2& b) \
{ \
a.val = vreinterpretq_f64_s64(intrin(vreinterpretq_s64_f64(a.val), vreinterpretq_s64_f64(b.val))); \
return a; \
}
OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(&, vandq_s64)
OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(|, vorrq_s64)
OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(^, veorq_s64)
inline v_float64x2 operator ~ (const v_float64x2& a)
{
return v_float64x2(vreinterpretq_f64_s32(vmvnq_s32(vreinterpretq_s32_f64(a.val))));
}
inline v_float64x2 v_sqrt(const v_float64x2& x)
{
return v_float64x2(vsqrtq_f64(x.val));
}
inline v_float64x2 v_invsqrt(const v_float64x2& x)
{
v_float64x2 one = v_setall_f64(1.0f);
return one / v_sqrt(x);
}
inline v_float64x2 v_abs(v_float64x2 x)
{ return v_float64x2(vabsq_f64(x.val)); }
#endif
// TODO: exp, log, sin, cos
#define OPENCV_HAL_IMPL_NEON_BIN_FUNC(_Tpvec, func, intrin) \
inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \
{ \
return _Tpvec(intrin(a.val, b.val)); \
}
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_min, vminq_u8)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_max, vmaxq_u8)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_min, vminq_s8)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_max, vmaxq_s8)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_min, vminq_u16)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_max, vmaxq_u16)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_min, vminq_s16)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_max, vmaxq_s16)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_min, vminq_u32)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_max, vmaxq_u32)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int32x4, v_min, vminq_s32)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int32x4, v_max, vmaxq_s32)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_min, vminq_f32)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_max, vmaxq_f32)
#if CV_SIMD128_64F
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_min, vminq_f64)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_max, vmaxq_f64)
#endif
#if CV_SIMD128_64F
inline int64x2_t vmvnq_s64(int64x2_t a)
{
int64x2_t vx = vreinterpretq_s64_u32(vdupq_n_u32(0xFFFFFFFF));
return veorq_s64(a, vx);
}
inline uint64x2_t vmvnq_u64(uint64x2_t a)
{
uint64x2_t vx = vreinterpretq_u64_u32(vdupq_n_u32(0xFFFFFFFF));
return veorq_u64(a, vx);
}
#endif
#define OPENCV_HAL_IMPL_NEON_INT_CMP_OP(_Tpvec, cast, suffix, not_suffix) \
inline _Tpvec operator == (const _Tpvec& a, const _Tpvec& b) \
{ return _Tpvec(cast(vceqq_##suffix(a.val, b.val))); } \
inline _Tpvec operator != (const _Tpvec& a, const _Tpvec& b) \
{ return _Tpvec(cast(vmvnq_##not_suffix(vceqq_##suffix(a.val, b.val)))); } \
inline _Tpvec operator < (const _Tpvec& a, const _Tpvec& b) \
{ return _Tpvec(cast(vcltq_##suffix(a.val, b.val))); } \
inline _Tpvec operator > (const _Tpvec& a, const _Tpvec& b) \
{ return _Tpvec(cast(vcgtq_##suffix(a.val, b.val))); } \
inline _Tpvec operator <= (const _Tpvec& a, const _Tpvec& b) \
{ return _Tpvec(cast(vcleq_##suffix(a.val, b.val))); } \
inline _Tpvec operator >= (const _Tpvec& a, const _Tpvec& b) \
{ return _Tpvec(cast(vcgeq_##suffix(a.val, b.val))); }
OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint8x16, OPENCV_HAL_NOP, u8, u8)
OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int8x16, vreinterpretq_s8_u8, s8, u8)
OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint16x8, OPENCV_HAL_NOP, u16, u16)
OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int16x8, vreinterpretq_s16_u16, s16, u16)
OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint32x4, OPENCV_HAL_NOP, u32, u32)
OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int32x4, vreinterpretq_s32_u32, s32, u32)
OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_float32x4, vreinterpretq_f32_u32, f32, u32)
#if CV_SIMD128_64F
OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint64x2, OPENCV_HAL_NOP, u64, u64)
OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int64x2, vreinterpretq_s64_u64, s64, u64)
OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_float64x2, vreinterpretq_f64_u64, f64, u64)
#endif
inline v_float32x4 v_not_nan(const v_float32x4& a)
{ return v_float32x4(vreinterpretq_f32_u32(vceqq_f32(a.val, a.val))); }
#if CV_SIMD128_64F
inline v_float64x2 v_not_nan(const v_float64x2& a)
{ return v_float64x2(vreinterpretq_f64_u64(vceqq_f64(a.val, a.val))); }
#endif
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_add_wrap, vaddq_u8)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_add_wrap, vaddq_s8)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_add_wrap, vaddq_u16)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_add_wrap, vaddq_s16)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_sub_wrap, vsubq_u8)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_sub_wrap, vsubq_s8)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_sub_wrap, vsubq_u16)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_sub_wrap, vsubq_s16)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_mul_wrap, vmulq_u8)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_mul_wrap, vmulq_s8)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_mul_wrap, vmulq_u16)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_mul_wrap, vmulq_s16)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_absdiff, vabdq_u8)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_absdiff, vabdq_u16)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_absdiff, vabdq_u32)
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_absdiff, vabdq_f32)
#if CV_SIMD128_64F
OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_absdiff, vabdq_f64)
#endif
/** Saturating absolute difference **/
inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b)
{ return v_int8x16(vqabsq_s8(vqsubq_s8(a.val, b.val))); }
inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b)
{ return v_int16x8(vqabsq_s16(vqsubq_s16(a.val, b.val))); }
#define OPENCV_HAL_IMPL_NEON_BIN_FUNC2(_Tpvec, _Tpvec2, cast, func, intrin) \
inline _Tpvec2 func(const _Tpvec& a, const _Tpvec& b) \
{ \
return _Tpvec2(cast(intrin(a.val, b.val))); \
}
OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int8x16, v_uint8x16, vreinterpretq_u8_s8, v_absdiff, vabdq_s8)
OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int16x8, v_uint16x8, vreinterpretq_u16_s16, v_absdiff, vabdq_s16)
OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int32x4, v_uint32x4, vreinterpretq_u32_s32, v_absdiff, vabdq_s32)
inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b)
{
v_float32x4 x(vmlaq_f32(vmulq_f32(a.val, a.val), b.val, b.val));
return v_sqrt(x);
}
inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b)
{
return v_float32x4(vmlaq_f32(vmulq_f32(a.val, a.val), b.val, b.val));
}
inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c)
{
#if CV_SIMD128_64F
// ARMv8, which adds support for 64-bit floating-point (so CV_SIMD128_64F is defined),
// also adds FMA support both for single- and double-precision floating-point vectors
return v_float32x4(vfmaq_f32(c.val, a.val, b.val));
#else
return v_float32x4(vmlaq_f32(c.val, a.val, b.val));
#endif
}
inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c)
{
return v_int32x4(vmlaq_s32(c.val, a.val, b.val));
}
inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c)
{
return v_fma(a, b, c);
}
inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c)
{
return v_fma(a, b, c);
}
#if CV_SIMD128_64F
inline v_float64x2 v_magnitude(const v_float64x2& a, const v_float64x2& b)
{
v_float64x2 x(vaddq_f64(vmulq_f64(a.val, a.val), vmulq_f64(b.val, b.val)));
return v_sqrt(x);
}
inline v_float64x2 v_sqr_magnitude(const v_float64x2& a, const v_float64x2& b)
{
return v_float64x2(vaddq_f64(vmulq_f64(a.val, a.val), vmulq_f64(b.val, b.val)));
}
inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c)
{
return v_float64x2(vfmaq_f64(c.val, a.val, b.val));
}
inline v_float64x2 v_muladd(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c)
{
return v_fma(a, b, c);
}
#endif
// trade efficiency for convenience
#define OPENCV_HAL_IMPL_NEON_SHIFT_OP(_Tpvec, suffix, _Tps, ssuffix) \
inline _Tpvec operator << (const _Tpvec& a, int n) \
{ return _Tpvec(vshlq_##suffix(a.val, vdupq_n_##ssuffix((_Tps)n))); } \
inline _Tpvec operator >> (const _Tpvec& a, int n) \
{ return _Tpvec(vshlq_##suffix(a.val, vdupq_n_##ssuffix((_Tps)-n))); } \
template<int n> inline _Tpvec v_shl(const _Tpvec& a) \
{ return _Tpvec(vshlq_n_##suffix(a.val, n)); } \
template<int n> inline _Tpvec v_shr(const _Tpvec& a) \
{ return _Tpvec(vshrq_n_##suffix(a.val, n)); } \
template<int n> inline _Tpvec v_rshr(const _Tpvec& a) \
{ return _Tpvec(vrshrq_n_##suffix(a.val, n)); }
OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint8x16, u8, schar, s8)
OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int8x16, s8, schar, s8)
OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint16x8, u16, short, s16)
OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int16x8, s16, short, s16)
OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint32x4, u32, int, s32)
OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int32x4, s32, int, s32)
OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint64x2, u64, int64, s64)
OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int64x2, s64, int64, s64)
#define OPENCV_HAL_IMPL_NEON_ROTATE_OP(_Tpvec, suffix) \
template<int n> inline _Tpvec v_rotate_right(const _Tpvec& a) \
{ return _Tpvec(vextq_##suffix(a.val, vdupq_n_##suffix(0), n)); } \
template<int n> inline _Tpvec v_rotate_left(const _Tpvec& a) \
{ return _Tpvec(vextq_##suffix(vdupq_n_##suffix(0), a.val, _Tpvec::nlanes - n)); } \
template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \
{ return a; } \
template<int n> inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \
{ return _Tpvec(vextq_##suffix(a.val, b.val, n)); } \
template<int n> inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \
{ return _Tpvec(vextq_##suffix(b.val, a.val, _Tpvec::nlanes - n)); } \
template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \
{ CV_UNUSED(b); return a; }
OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint8x16, u8)
OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int8x16, s8)
OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint16x8, u16)
OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int16x8, s16)
OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint32x4, u32)
OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int32x4, s32)
OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_float32x4, f32)
OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint64x2, u64)
OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int64x2, s64)
#if CV_SIMD128_64F
OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_float64x2, f64)
#endif
#define OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(_Tpvec, _Tp, suffix) \
inline _Tpvec v_load(const _Tp* ptr) \
{ return _Tpvec(vld1q_##suffix(ptr)); } \
inline _Tpvec v_load_aligned(const _Tp* ptr) \
{ return _Tpvec(vld1q_##suffix(ptr)); } \
inline _Tpvec v_load_low(const _Tp* ptr) \
{ return _Tpvec(vcombine_##suffix(vld1_##suffix(ptr), vdup_n_##suffix((_Tp)0))); } \
inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \
{ return _Tpvec(vcombine_##suffix(vld1_##suffix(ptr0), vld1_##suffix(ptr1))); } \
inline void v_store(_Tp* ptr, const _Tpvec& a) \
{ vst1q_##suffix(ptr, a.val); } \
inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \
{ vst1q_##suffix(ptr, a.val); } \
inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \
{ vst1q_##suffix(ptr, a.val); } \
inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \
{ vst1q_##suffix(ptr, a.val); } \
inline void v_store_low(_Tp* ptr, const _Tpvec& a) \
{ vst1_##suffix(ptr, vget_low_##suffix(a.val)); } \
inline void v_store_high(_Tp* ptr, const _Tpvec& a) \
{ vst1_##suffix(ptr, vget_high_##suffix(a.val)); }
OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint8x16, uchar, u8)
OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int8x16, schar, s8)
OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint16x8, ushort, u16)
OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int16x8, short, s16)
OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint32x4, unsigned, u32)
OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int32x4, int, s32)
OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint64x2, uint64, u64)
OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int64x2, int64, s64)
OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_float32x4, float, f32)
#if CV_SIMD128_64F
OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_float64x2, double, f64)
#endif
#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \
inline scalartype v_reduce_##func(const _Tpvec& a) \
{ \
_Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \
a0 = vp##vectorfunc##_##suffix(a0, a0); \
return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, a0),0); \
}
OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, unsigned short, sum, add, u16)
OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, unsigned short, max, max, u16)
OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, unsigned short, min, min, u16)
OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, short, sum, add, s16)
OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, short, max, max, s16)
OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, short, min, min, s16)
#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \
inline scalartype v_reduce_##func(const _Tpvec& a) \
{ \
_Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \
return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, vget_high_##suffix(a.val)),0); \
}
OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, sum, add, u32)
OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, max, max, u32)
OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, min, min, u32)
OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, sum, add, s32)
OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, max, max, s32)
OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, min, min, s32)
OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, sum, add, f32)
OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, max, max, f32)
OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, min, min, f32)
#if CV_SIMD128_64F
inline double v_reduce_sum(const v_float64x2& a)
{
return vgetq_lane_f64(a.val, 0) + vgetq_lane_f64(a.val, 1);
}
#endif
inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b,
const v_float32x4& c, const v_float32x4& d)
{
float32x4x2_t ab = vtrnq_f32(a.val, b.val);
float32x4x2_t cd = vtrnq_f32(c.val, d.val);
float32x4_t u0 = vaddq_f32(ab.val[0], ab.val[1]); // a0+a1 b0+b1 a2+a3 b2+b3
float32x4_t u1 = vaddq_f32(cd.val[0], cd.val[1]); // c0+c1 d0+d1 c2+c3 d2+d3
float32x4_t v0 = vcombine_f32(vget_low_f32(u0), vget_low_f32(u1));
float32x4_t v1 = vcombine_f32(vget_high_f32(u0), vget_high_f32(u1));
return v_float32x4(vaddq_f32(v0, v1));
}
inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b)
{
uint32x4_t t0 = vpaddlq_u16(vpaddlq_u8(vabdq_u8(a.val, b.val)));
uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0));
return vget_lane_u32(vpadd_u32(t1, t1), 0);
}
inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b)
{
uint32x4_t t0 = vpaddlq_u16(vpaddlq_u8(vreinterpretq_u8_s8(vabdq_s8(a.val, b.val))));
uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0));
return vget_lane_u32(vpadd_u32(t1, t1), 0);
}
inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b)
{
uint32x4_t t0 = vpaddlq_u16(vabdq_u16(a.val, b.val));
uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0));
return vget_lane_u32(vpadd_u32(t1, t1), 0);
}
inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b)
{
uint32x4_t t0 = vpaddlq_u16(vreinterpretq_u16_s16(vabdq_s16(a.val, b.val)));
uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0));
return vget_lane_u32(vpadd_u32(t1, t1), 0);
}
inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b)
{
uint32x4_t t0 = vabdq_u32(a.val, b.val);
uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0));
return vget_lane_u32(vpadd_u32(t1, t1), 0);
}
inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b)
{
uint32x4_t t0 = vreinterpretq_u32_s32(vabdq_s32(a.val, b.val));
uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0));
return vget_lane_u32(vpadd_u32(t1, t1), 0);
}
inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b)
{
float32x4_t t0 = vabdq_f32(a.val, b.val);
float32x2_t t1 = vpadd_f32(vget_low_f32(t0), vget_high_f32(t0));
return vget_lane_f32(vpadd_f32(t1, t1), 0);
}
#define OPENCV_HAL_IMPL_NEON_POPCOUNT(_Tpvec, cast) \
inline v_uint32x4 v_popcount(const _Tpvec& a) \
{ \
uint8x16_t t = vcntq_u8(cast(a.val)); \
uint16x8_t t0 = vpaddlq_u8(t); /* 16 -> 8 */ \
uint32x4_t t1 = vpaddlq_u16(t0); /* 8 -> 4 */ \
return v_uint32x4(t1); \
}
OPENCV_HAL_IMPL_NEON_POPCOUNT(v_uint8x16, OPENCV_HAL_NOP)
OPENCV_HAL_IMPL_NEON_POPCOUNT(v_uint16x8, vreinterpretq_u8_u16)
OPENCV_HAL_IMPL_NEON_POPCOUNT(v_uint32x4, vreinterpretq_u8_u32)
OPENCV_HAL_IMPL_NEON_POPCOUNT(v_int8x16, vreinterpretq_u8_s8)
OPENCV_HAL_IMPL_NEON_POPCOUNT(v_int16x8, vreinterpretq_u8_s16)
OPENCV_HAL_IMPL_NEON_POPCOUNT(v_int32x4, vreinterpretq_u8_s32)
inline int v_signmask(const v_uint8x16& a)
{
int8x8_t m0 = vcreate_s8(CV_BIG_UINT(0x0706050403020100));
uint8x16_t v0 = vshlq_u8(vshrq_n_u8(a.val, 7), vcombine_s8(m0, m0));
uint64x2_t v1 = vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(v0)));
return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 8);
}
inline int v_signmask(const v_int8x16& a)
{ return v_signmask(v_reinterpret_as_u8(a)); }
inline int v_signmask(const v_uint16x8& a)
{
int16x4_t m0 = vcreate_s16(CV_BIG_UINT(0x0003000200010000));
uint16x8_t v0 = vshlq_u16(vshrq_n_u16(a.val, 15), vcombine_s16(m0, m0));
uint64x2_t v1 = vpaddlq_u32(vpaddlq_u16(v0));
return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 4);
}
inline int v_signmask(const v_int16x8& a)
{ return v_signmask(v_reinterpret_as_u16(a)); }
inline int v_signmask(const v_uint32x4& a)
{
int32x2_t m0 = vcreate_s32(CV_BIG_UINT(0x0000000100000000));
uint32x4_t v0 = vshlq_u32(vshrq_n_u32(a.val, 31), vcombine_s32(m0, m0));
uint64x2_t v1 = vpaddlq_u32(v0);
return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 2);
}
inline int v_signmask(const v_int32x4& a)
{ return v_signmask(v_reinterpret_as_u32(a)); }
inline int v_signmask(const v_float32x4& a)
{ return v_signmask(v_reinterpret_as_u32(a)); }
#if CV_SIMD128_64F
inline int v_signmask(const v_uint64x2& a)
{
int64x1_t m0 = vdup_n_s64(0);
uint64x2_t v0 = vshlq_u64(vshrq_n_u64(a.val, 63), vcombine_s64(m0, m0));
return (int)vgetq_lane_u64(v0, 0) + ((int)vgetq_lane_u64(v0, 1) << 1);
}
inline int v_signmask(const v_float64x2& a)
{ return v_signmask(v_reinterpret_as_u64(a)); }
#endif
#define OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(_Tpvec, suffix, shift) \
inline bool v_check_all(const v_##_Tpvec& a) \
{ \
_Tpvec##_t v0 = vshrq_n_##suffix(vmvnq_##suffix(a.val), shift); \
uint64x2_t v1 = vreinterpretq_u64_##suffix(v0); \
return (vgetq_lane_u64(v1, 0) | vgetq_lane_u64(v1, 1)) == 0; \
} \
inline bool v_check_any(const v_##_Tpvec& a) \
{ \
_Tpvec##_t v0 = vshrq_n_##suffix(a.val, shift); \
uint64x2_t v1 = vreinterpretq_u64_##suffix(v0); \
return (vgetq_lane_u64(v1, 0) | vgetq_lane_u64(v1, 1)) != 0; \
}
OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint8x16, u8, 7)
OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint16x8, u16, 15)
OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint32x4, u32, 31)
#if CV_SIMD128_64F
OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint64x2, u64, 63)
#endif
inline bool v_check_all(const v_int8x16& a)
{ return v_check_all(v_reinterpret_as_u8(a)); }
inline bool v_check_all(const v_int16x8& a)
{ return v_check_all(v_reinterpret_as_u16(a)); }
inline bool v_check_all(const v_int32x4& a)
{ return v_check_all(v_reinterpret_as_u32(a)); }
inline bool v_check_all(const v_float32x4& a)
{ return v_check_all(v_reinterpret_as_u32(a)); }
inline bool v_check_any(const v_int8x16& a)
{ return v_check_any(v_reinterpret_as_u8(a)); }
inline bool v_check_any(const v_int16x8& a)
{ return v_check_any(v_reinterpret_as_u16(a)); }
inline bool v_check_any(const v_int32x4& a)
{ return v_check_any(v_reinterpret_as_u32(a)); }
inline bool v_check_any(const v_float32x4& a)
{ return v_check_any(v_reinterpret_as_u32(a)); }
#if CV_SIMD128_64F
inline bool v_check_all(const v_int64x2& a)
{ return v_check_all(v_reinterpret_as_u64(a)); }
inline bool v_check_all(const v_float64x2& a)
{ return v_check_all(v_reinterpret_as_u64(a)); }
inline bool v_check_any(const v_int64x2& a)
{ return v_check_any(v_reinterpret_as_u64(a)); }
inline bool v_check_any(const v_float64x2& a)
{ return v_check_any(v_reinterpret_as_u64(a)); }
#endif
#define OPENCV_HAL_IMPL_NEON_SELECT(_Tpvec, suffix, usuffix) \
inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \
{ \
return _Tpvec(vbslq_##suffix(vreinterpretq_##usuffix##_##suffix(mask.val), a.val, b.val)); \
}
OPENCV_HAL_IMPL_NEON_SELECT(v_uint8x16, u8, u8)
OPENCV_HAL_IMPL_NEON_SELECT(v_int8x16, s8, u8)
OPENCV_HAL_IMPL_NEON_SELECT(v_uint16x8, u16, u16)
OPENCV_HAL_IMPL_NEON_SELECT(v_int16x8, s16, u16)
OPENCV_HAL_IMPL_NEON_SELECT(v_uint32x4, u32, u32)
OPENCV_HAL_IMPL_NEON_SELECT(v_int32x4, s32, u32)
OPENCV_HAL_IMPL_NEON_SELECT(v_float32x4, f32, u32)
#if CV_SIMD128_64F
OPENCV_HAL_IMPL_NEON_SELECT(v_float64x2, f64, u64)
#endif
#define OPENCV_HAL_IMPL_NEON_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix) \
inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \
{ \
b0.val = vmovl_##suffix(vget_low_##suffix(a.val)); \
b1.val = vmovl_##suffix(vget_high_##suffix(a.val)); \
} \
inline _Tpwvec v_expand_low(const _Tpvec& a) \
{ \
return _Tpwvec(vmovl_##suffix(vget_low_##suffix(a.val))); \
} \
inline _Tpwvec v_expand_high(const _Tpvec& a) \
{ \
return _Tpwvec(vmovl_##suffix(vget_high_##suffix(a.val))); \
} \
inline _Tpwvec v_load_expand(const _Tp* ptr) \
{ \
return _Tpwvec(vmovl_##suffix(vld1_##suffix(ptr))); \
}
OPENCV_HAL_IMPL_NEON_EXPAND(v_uint8x16, v_uint16x8, uchar, u8)
OPENCV_HAL_IMPL_NEON_EXPAND(v_int8x16, v_int16x8, schar, s8)
OPENCV_HAL_IMPL_NEON_EXPAND(v_uint16x8, v_uint32x4, ushort, u16)
OPENCV_HAL_IMPL_NEON_EXPAND(v_int16x8, v_int32x4, short, s16)
OPENCV_HAL_IMPL_NEON_EXPAND(v_uint32x4, v_uint64x2, uint, u32)
OPENCV_HAL_IMPL_NEON_EXPAND(v_int32x4, v_int64x2, int, s32)
inline v_uint32x4 v_load_expand_q(const uchar* ptr)
{
uint8x8_t v0 = vcreate_u8(*(unsigned*)ptr);
uint16x4_t v1 = vget_low_u16(vmovl_u8(v0));
return v_uint32x4(vmovl_u16(v1));
}
inline v_int32x4 v_load_expand_q(const schar* ptr)
{
int8x8_t v0 = vcreate_s8(*(unsigned*)ptr);
int16x4_t v1 = vget_low_s16(vmovl_s8(v0));
return v_int32x4(vmovl_s16(v1));
}
#if defined(__aarch64__)
#define OPENCV_HAL_IMPL_NEON_UNPACKS(_Tpvec, suffix) \
inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \
{ \
b0.val = vzip1q_##suffix(a0.val, a1.val); \
b1.val = vzip2q_##suffix(a0.val, a1.val); \
} \
inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \
{ \
return v_##_Tpvec(vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val))); \
} \
inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \
{ \
return v_##_Tpvec(vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val))); \
} \
inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \
{ \
c.val = vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val)); \
d.val = vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val)); \
}
#else
#define OPENCV_HAL_IMPL_NEON_UNPACKS(_Tpvec, suffix) \
inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \
{ \
_Tpvec##x2_t p = vzipq_##suffix(a0.val, a1.val); \
b0.val = p.val[0]; \
b1.val = p.val[1]; \
} \
inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \
{ \
return v_##_Tpvec(vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val))); \
} \
inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \
{ \
return v_##_Tpvec(vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val))); \
} \
inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \
{ \
c.val = vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val)); \
d.val = vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val)); \
}
#endif
OPENCV_HAL_IMPL_NEON_UNPACKS(uint8x16, u8)
OPENCV_HAL_IMPL_NEON_UNPACKS(int8x16, s8)
OPENCV_HAL_IMPL_NEON_UNPACKS(uint16x8, u16)
OPENCV_HAL_IMPL_NEON_UNPACKS(int16x8, s16)
OPENCV_HAL_IMPL_NEON_UNPACKS(uint32x4, u32)
OPENCV_HAL_IMPL_NEON_UNPACKS(int32x4, s32)
OPENCV_HAL_IMPL_NEON_UNPACKS(float32x4, f32)
#if CV_SIMD128_64F
OPENCV_HAL_IMPL_NEON_UNPACKS(float64x2, f64)
#endif
#define OPENCV_HAL_IMPL_NEON_EXTRACT(_Tpvec, suffix) \
template <int s> \
inline v_##_Tpvec v_extract(const v_##_Tpvec& a, const v_##_Tpvec& b) \
{ \
return v_##_Tpvec(vextq_##suffix(a.val, b.val, s)); \
}
OPENCV_HAL_IMPL_NEON_EXTRACT(uint8x16, u8)
OPENCV_HAL_IMPL_NEON_EXTRACT(int8x16, s8)
OPENCV_HAL_IMPL_NEON_EXTRACT(uint16x8, u16)
OPENCV_HAL_IMPL_NEON_EXTRACT(int16x8, s16)
OPENCV_HAL_IMPL_NEON_EXTRACT(uint32x4, u32)
OPENCV_HAL_IMPL_NEON_EXTRACT(int32x4, s32)
OPENCV_HAL_IMPL_NEON_EXTRACT(uint64x2, u64)
OPENCV_HAL_IMPL_NEON_EXTRACT(int64x2, s64)
OPENCV_HAL_IMPL_NEON_EXTRACT(float32x4, f32)
#if CV_SIMD128_64F
OPENCV_HAL_IMPL_NEON_EXTRACT(float64x2, f64)
#endif
#if CV_SIMD128_64F
inline v_int32x4 v_round(const v_float32x4& a)
{
float32x4_t a_ = a.val;
int32x4_t result;
__asm__ ("fcvtns %0.4s, %1.4s"
: "=w"(result)
: "w"(a_)
: /* No clobbers */);
return v_int32x4(result);
}
#else
inline v_int32x4 v_round(const v_float32x4& a)
{
static const int32x4_t v_sign = vdupq_n_s32(1 << 31),
v_05 = vreinterpretq_s32_f32(vdupq_n_f32(0.5f));
int32x4_t v_addition = vorrq_s32(v_05, vandq_s32(v_sign, vreinterpretq_s32_f32(a.val)));
return v_int32x4(vcvtq_s32_f32(vaddq_f32(a.val, vreinterpretq_f32_s32(v_addition))));
}
#endif
inline v_int32x4 v_floor(const v_float32x4& a)
{
int32x4_t a1 = vcvtq_s32_f32(a.val);
uint32x4_t mask = vcgtq_f32(vcvtq_f32_s32(a1), a.val);
return v_int32x4(vaddq_s32(a1, vreinterpretq_s32_u32(mask)));
}
inline v_int32x4 v_ceil(const v_float32x4& a)
{
int32x4_t a1 = vcvtq_s32_f32(a.val);
uint32x4_t mask = vcgtq_f32(a.val, vcvtq_f32_s32(a1));
return v_int32x4(vsubq_s32(a1, vreinterpretq_s32_u32(mask)));
}
inline v_int32x4 v_trunc(const v_float32x4& a)
{ return v_int32x4(vcvtq_s32_f32(a.val)); }
#if CV_SIMD128_64F
inline v_int32x4 v_round(const v_float64x2& a)
{
static const int32x2_t zero = vdup_n_s32(0);
return v_int32x4(vcombine_s32(vmovn_s64(vcvtaq_s64_f64(a.val)), zero));
}
inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b)
{
return v_int32x4(vcombine_s32(vmovn_s64(vcvtaq_s64_f64(a.val)), vmovn_s64(vcvtaq_s64_f64(b.val))));
}
inline v_int32x4 v_floor(const v_float64x2& a)
{
static const int32x2_t zero = vdup_n_s32(0);
int64x2_t a1 = vcvtq_s64_f64(a.val);
uint64x2_t mask = vcgtq_f64(vcvtq_f64_s64(a1), a.val);
a1 = vaddq_s64(a1, vreinterpretq_s64_u64(mask));
return v_int32x4(vcombine_s32(vmovn_s64(a1), zero));
}
inline v_int32x4 v_ceil(const v_float64x2& a)
{
static const int32x2_t zero = vdup_n_s32(0);
int64x2_t a1 = vcvtq_s64_f64(a.val);
uint64x2_t mask = vcgtq_f64(a.val, vcvtq_f64_s64(a1));
a1 = vsubq_s64(a1, vreinterpretq_s64_u64(mask));
return v_int32x4(vcombine_s32(vmovn_s64(a1), zero));
}
inline v_int32x4 v_trunc(const v_float64x2& a)
{
static const int32x2_t zero = vdup_n_s32(0);
return v_int32x4(vcombine_s32(vmovn_s64(vcvtaq_s64_f64(a.val)), zero));
}
#endif
#define OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(_Tpvec, suffix) \
inline void v_transpose4x4(const v_##_Tpvec& a0, const v_##_Tpvec& a1, \
const v_##_Tpvec& a2, const v_##_Tpvec& a3, \
v_##_Tpvec& b0, v_##_Tpvec& b1, \
v_##_Tpvec& b2, v_##_Tpvec& b3) \
{ \
/* m00 m01 m02 m03 */ \
/* m10 m11 m12 m13 */ \
/* m20 m21 m22 m23 */ \
/* m30 m31 m32 m33 */ \
_Tpvec##x2_t t0 = vtrnq_##suffix(a0.val, a1.val); \
_Tpvec##x2_t t1 = vtrnq_##suffix(a2.val, a3.val); \
/* m00 m10 m02 m12 */ \
/* m01 m11 m03 m13 */ \
/* m20 m30 m22 m32 */ \
/* m21 m31 m23 m33 */ \
b0.val = vcombine_##suffix(vget_low_##suffix(t0.val[0]), vget_low_##suffix(t1.val[0])); \
b1.val = vcombine_##suffix(vget_low_##suffix(t0.val[1]), vget_low_##suffix(t1.val[1])); \
b2.val = vcombine_##suffix(vget_high_##suffix(t0.val[0]), vget_high_##suffix(t1.val[0])); \
b3.val = vcombine_##suffix(vget_high_##suffix(t0.val[1]), vget_high_##suffix(t1.val[1])); \
}
OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(uint32x4, u32)
OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(int32x4, s32)
OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(float32x4, f32)
#define OPENCV_HAL_IMPL_NEON_INTERLEAVED(_Tpvec, _Tp, suffix) \
inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b) \
{ \
_Tpvec##x2_t v = vld2q_##suffix(ptr); \
a.val = v.val[0]; \
b.val = v.val[1]; \
} \
inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \
{ \
_Tpvec##x3_t v = vld3q_##suffix(ptr); \
a.val = v.val[0]; \
b.val = v.val[1]; \
c.val = v.val[2]; \
} \
inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \
v_##_Tpvec& c, v_##_Tpvec& d) \
{ \
_Tpvec##x4_t v = vld4q_##suffix(ptr); \
a.val = v.val[0]; \
b.val = v.val[1]; \
c.val = v.val[2]; \
d.val = v.val[3]; \
} \
inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \
hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \
{ \
_Tpvec##x2_t v; \
v.val[0] = a.val; \
v.val[1] = b.val; \
vst2q_##suffix(ptr, v); \
} \
inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \
const v_##_Tpvec& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \
{ \
_Tpvec##x3_t v; \
v.val[0] = a.val; \
v.val[1] = b.val; \
v.val[2] = c.val; \
vst3q_##suffix(ptr, v); \
} \
inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \
const v_##_Tpvec& c, const v_##_Tpvec& d, \
hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \
{ \
_Tpvec##x4_t v; \
v.val[0] = a.val; \
v.val[1] = b.val; \
v.val[2] = c.val; \
v.val[3] = d.val; \
vst4q_##suffix(ptr, v); \
}
#define OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(tp, suffix) \
inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, v_##tp##x2& b ) \
{ \
tp##x1_t a0 = vld1_##suffix(ptr); \
tp##x1_t b0 = vld1_##suffix(ptr + 1); \
tp##x1_t a1 = vld1_##suffix(ptr + 2); \
tp##x1_t b1 = vld1_##suffix(ptr + 3); \
a = v_##tp##x2(vcombine_##suffix(a0, a1)); \
b = v_##tp##x2(vcombine_##suffix(b0, b1)); \
} \
\
inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, \
v_##tp##x2& b, v_##tp##x2& c ) \
{ \
tp##x1_t a0 = vld1_##suffix(ptr); \
tp##x1_t b0 = vld1_##suffix(ptr + 1); \
tp##x1_t c0 = vld1_##suffix(ptr + 2); \
tp##x1_t a1 = vld1_##suffix(ptr + 3); \
tp##x1_t b1 = vld1_##suffix(ptr + 4); \
tp##x1_t c1 = vld1_##suffix(ptr + 5); \
a = v_##tp##x2(vcombine_##suffix(a0, a1)); \
b = v_##tp##x2(vcombine_##suffix(b0, b1)); \
c = v_##tp##x2(vcombine_##suffix(c0, c1)); \
} \
\
inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, v_##tp##x2& b, \
v_##tp##x2& c, v_##tp##x2& d ) \
{ \
tp##x1_t a0 = vld1_##suffix(ptr); \
tp##x1_t b0 = vld1_##suffix(ptr + 1); \
tp##x1_t c0 = vld1_##suffix(ptr + 2); \
tp##x1_t d0 = vld1_##suffix(ptr + 3); \
tp##x1_t a1 = vld1_##suffix(ptr + 4); \
tp##x1_t b1 = vld1_##suffix(ptr + 5); \
tp##x1_t c1 = vld1_##suffix(ptr + 6); \
tp##x1_t d1 = vld1_##suffix(ptr + 7); \
a = v_##tp##x2(vcombine_##suffix(a0, a1)); \
b = v_##tp##x2(vcombine_##suffix(b0, b1)); \
c = v_##tp##x2(vcombine_##suffix(c0, c1)); \
d = v_##tp##x2(vcombine_##suffix(d0, d1)); \
} \
\
inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, const v_##tp##x2& b, \
hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \
{ \
vst1_##suffix(ptr, vget_low_##suffix(a.val)); \
vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \
vst1_##suffix(ptr + 2, vget_high_##suffix(a.val)); \
vst1_##suffix(ptr + 3, vget_high_##suffix(b.val)); \
} \
\
inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, \
const v_##tp##x2& b, const v_##tp##x2& c, \
hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \
{ \
vst1_##suffix(ptr, vget_low_##suffix(a.val)); \
vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \
vst1_##suffix(ptr + 2, vget_low_##suffix(c.val)); \
vst1_##suffix(ptr + 3, vget_high_##suffix(a.val)); \
vst1_##suffix(ptr + 4, vget_high_##suffix(b.val)); \
vst1_##suffix(ptr + 5, vget_high_##suffix(c.val)); \
} \
\
inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, const v_##tp##x2& b, \
const v_##tp##x2& c, const v_##tp##x2& d, \
hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \
{ \
vst1_##suffix(ptr, vget_low_##suffix(a.val)); \
vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \
vst1_##suffix(ptr + 2, vget_low_##suffix(c.val)); \
vst1_##suffix(ptr + 3, vget_low_##suffix(d.val)); \
vst1_##suffix(ptr + 4, vget_high_##suffix(a.val)); \
vst1_##suffix(ptr + 5, vget_high_##suffix(b.val)); \
vst1_##suffix(ptr + 6, vget_high_##suffix(c.val)); \
vst1_##suffix(ptr + 7, vget_high_##suffix(d.val)); \
}
OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint8x16, uchar, u8)
OPENCV_HAL_IMPL_NEON_INTERLEAVED(int8x16, schar, s8)
OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint16x8, ushort, u16)
OPENCV_HAL_IMPL_NEON_INTERLEAVED(int16x8, short, s16)
OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint32x4, unsigned, u32)
OPENCV_HAL_IMPL_NEON_INTERLEAVED(int32x4, int, s32)
OPENCV_HAL_IMPL_NEON_INTERLEAVED(float32x4, float, f32)
#if CV_SIMD128_64F
OPENCV_HAL_IMPL_NEON_INTERLEAVED(float64x2, double, f64)
#endif
OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(int64, s64)
OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(uint64, u64)
inline v_float32x4 v_cvt_f32(const v_int32x4& a)
{
return v_float32x4(vcvtq_f32_s32(a.val));
}
#if CV_SIMD128_64F
inline v_float32x4 v_cvt_f32(const v_float64x2& a)
{
float32x2_t zero = vdup_n_f32(0.0f);
return v_float32x4(vcombine_f32(vcvt_f32_f64(a.val), zero));
}
inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b)
{
return v_float32x4(vcombine_f32(vcvt_f32_f64(a.val), vcvt_f32_f64(b.val)));
}
inline v_float64x2 v_cvt_f64(const v_int32x4& a)
{
return v_float64x2(vcvt_f64_f32(vcvt_f32_s32(vget_low_s32(a.val))));
}
inline v_float64x2 v_cvt_f64_high(const v_int32x4& a)
{
return v_float64x2(vcvt_f64_f32(vcvt_f32_s32(vget_high_s32(a.val))));
}
inline v_float64x2 v_cvt_f64(const v_float32x4& a)
{
return v_float64x2(vcvt_f64_f32(vget_low_f32(a.val)));
}
inline v_float64x2 v_cvt_f64_high(const v_float32x4& a)
{
return v_float64x2(vcvt_f64_f32(vget_high_f32(a.val)));
}
#endif
////////////// Lookup table access ////////////////////
inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec)
{
int CV_DECL_ALIGNED(32) elems[4] =
{
tab[vgetq_lane_s32(idxvec.val, 0)],
tab[vgetq_lane_s32(idxvec.val, 1)],
tab[vgetq_lane_s32(idxvec.val, 2)],
tab[vgetq_lane_s32(idxvec.val, 3)]
};
return v_int32x4(vld1q_s32(elems));
}
inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec)
{
float CV_DECL_ALIGNED(32) elems[4] =
{
tab[vgetq_lane_s32(idxvec.val, 0)],
tab[vgetq_lane_s32(idxvec.val, 1)],
tab[vgetq_lane_s32(idxvec.val, 2)],
tab[vgetq_lane_s32(idxvec.val, 3)]
};
return v_float32x4(vld1q_f32(elems));
}
inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y)
{
/*int CV_DECL_ALIGNED(32) idx[4];
v_store(idx, idxvec);
float32x4_t xy02 = vcombine_f32(vld1_f32(tab + idx[0]), vld1_f32(tab + idx[2]));
float32x4_t xy13 = vcombine_f32(vld1_f32(tab + idx[1]), vld1_f32(tab + idx[3]));
float32x4x2_t xxyy = vuzpq_f32(xy02, xy13);
x = v_float32x4(xxyy.val[0]);
y = v_float32x4(xxyy.val[1]);*/
int CV_DECL_ALIGNED(32) idx[4];
v_store_aligned(idx, idxvec);
x = v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]);
y = v_float32x4(tab[idx[0]+1], tab[idx[1]+1], tab[idx[2]+1], tab[idx[3]+1]);
}
#if CV_SIMD128_64F
inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec)
{
double CV_DECL_ALIGNED(32) elems[2] =
{
tab[vgetq_lane_s32(idxvec.val, 0)],
tab[vgetq_lane_s32(idxvec.val, 1)],
};
return v_float64x2(vld1q_f64(elems));
}
inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y)
{
int CV_DECL_ALIGNED(32) idx[4];
v_store_aligned(idx, idxvec);
x = v_float64x2(tab[idx[0]], tab[idx[1]]);
y = v_float64x2(tab[idx[0]+1], tab[idx[1]+1]);
}
#endif
////// FP16 suport ///////
#if CV_FP16
inline v_float32x4 v_load_expand(const float16_t* ptr)
{
float16x4_t v =
#ifndef vld1_f16 // APPLE compiler defines vld1_f16 as macro
(float16x4_t)vld1_s16((const short*)ptr);
#else
vld1_f16((const __fp16*)ptr);
#endif
return v_float32x4(vcvt_f32_f16(v));
}
inline void v_pack_store(float16_t* ptr, const v_float32x4& v)
{
float16x4_t hv = vcvt_f16_f32(v.val);
#ifndef vst1_f16 // APPLE compiler defines vst1_f16 as macro
vst1_s16((short*)ptr, (int16x4_t)hv);
#else
vst1_f16((__fp16*)ptr, hv);
#endif
}
#else
inline v_float32x4 v_load_expand(const float16_t* ptr)
{
const int N = 4;
float buf[N];
for( int i = 0; i < N; i++ ) buf[i] = (float)ptr[i];
return v_load(buf);
}
inline void v_pack_store(float16_t* ptr, const v_float32x4& v)
{
const int N = 4;
float buf[N];
v_store(buf, v);
for( int i = 0; i < N; i++ ) ptr[i] = float16_t(buf[i]);
}
#endif
inline void v_cleanup() {}
//! @name Check SIMD support
//! @{
//! @brief Check CPU capability of SIMD operation
static inline bool hasSIMD128()
{
return (CV_CPU_HAS_SUPPORT_NEON) ? true : false;
}
//! @}
CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END
//! @endcond
}
#endif
| [
"[email protected]"
] | |
6ebc73bb273052d61f2941d3fe2646d9eed2ea9c | f131f99c2410c2c84bfa8cd3ae1bc035048ebe48 | /axe.mod/angle.mod/src/libGLESv2/renderer/d3d/d3d11/PixelTransfer11.h | ed1a3ae1d0a43a47661971e4b0811b92419ae48b | [] | no_license | nitrologic/mod | b2a81e44db5ef85a573187c27b634eb393c1ca0c | f4f1e3c5e6af0890dc9b81eea17513e9a2f29916 | refs/heads/master | 2021-05-15T01:39:21.181554 | 2018-03-16T21:16:56 | 2018-03-16T21:16:56 | 38,656,465 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,479 | h | //
// Copyright (c) 2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// PixelTransfer11.h:
// Buffer-to-Texture and Texture-to-Buffer data transfers.
// Used to implement pixel unpack and pixel pack buffers in ES3.
#ifndef LIBGLESV2_PIXELTRANSFER11_H_
#define LIBGLESV2_PIXELTRANSFER11_H_
#include "common/platform.h"
#include <GLES2/gl2.h>
#include <map>
namespace gl
{
class Buffer;
struct Box;
struct Extents;
struct PixelUnpackState;
}
namespace rx
{
class Renderer11;
class RenderTarget;
class PixelTransfer11
{
public:
explicit PixelTransfer11(Renderer11 *renderer);
~PixelTransfer11();
static bool supportsBufferToTextureCopy(GLenum internalFormat);
// unpack: the source buffer is stored in the unpack state, and buffer strides
// offset: the start of the data within the unpack buffer
// destRenderTarget: individual slice/layer of a target texture
// destinationFormat/sourcePixelsType: determines shaders + shader parameters
// destArea: the sub-section of destRenderTarget to copy to
bool copyBufferToTexture(const gl::PixelUnpackState &unpack, unsigned int offset, RenderTarget *destRenderTarget,
GLenum destinationFormat, GLenum sourcePixelsType, const gl::Box &destArea);
private:
struct CopyShaderParams
{
unsigned int FirstPixelOffset;
unsigned int PixelsPerRow;
unsigned int RowStride;
unsigned int RowsPerSlice;
float PositionOffset[2];
float PositionScale[2];
int TexLocationOffset[2];
int TexLocationScale[2];
};
static void setBufferToTextureCopyParams(const gl::Box &destArea, const gl::Extents &destSize, GLenum internalFormat,
const gl::PixelUnpackState &unpack, unsigned int offset, CopyShaderParams *parametersOut);
void buildShaderMap();
ID3D11PixelShader *findBufferToTexturePS(GLenum internalFormat) const;
Renderer11 *mRenderer;
std::map<GLenum, ID3D11PixelShader *> mBufferToTexturePSMap;
ID3D11VertexShader *mBufferToTextureVS;
ID3D11GeometryShader *mBufferToTextureGS;
ID3D11Buffer *mParamsConstantBuffer;
CopyShaderParams mParamsData;
ID3D11RasterizerState *mCopyRasterizerState;
ID3D11DepthStencilState *mCopyDepthStencilState;
};
}
#endif // LIBGLESV2_PIXELTRANSFER11_H_
| [
"nitrologic@548b755b-aa20-0410-b24a-7f7e2b255a79"
] | nitrologic@548b755b-aa20-0410-b24a-7f7e2b255a79 |
b70fab9e23853c653aefbd9acb43978bdd93f8b8 | 9d8629da31c36bc1a7a527bff2d2a706fcb2ffff | /ClientList.h | f7625f22f1a7bf7c90eed4500fabd4d0345ed489 | [] | no_license | Kostizer/work | a587bd7b06beef83207ef6c7bfa50882e05e18f6 | 502d207110f7814353b96867b3d8a43700a3b562 | refs/heads/main | 2023-02-06T09:43:11.033616 | 2020-12-28T16:42:42 | 2020-12-28T16:42:42 | 324,889,176 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 469 | h | #ifndef CLIENTLIST_H
#define CLIENTLIST_H
#include <list>
#include "Client.h"
class ClientList //список клиентов
{
private:
list <Client*> setPtrsClients; // контейнер список клиентов
list <Client*>::iterator iter; //итератор
public: ~ClientList();
void insertClient(Client*); //внесение клиента в список
void display(); //отображение на экране
};
#endif | [
"[email protected]"
] | |
2a4c22eb9d41d7343e0e3eb83a824e1ae063b130 | 15fd495f617071de89a066f7d13199a0eca45be5 | /old2/initial_separation.hpp | b0b23de445a89adc20f980e497617e772ee9a866 | [] | no_license | V-Italy/optical_flow | 5176f221a4822398cacc0ce98cc968970a3955e3 | 5b07f43a5e76136283ab471b85d29fc351725042 | refs/heads/master | 2021-01-16T19:33:58.171269 | 2015-05-15T17:30:36 | 2015-05-15T17:30:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,111 | hpp | #ifndef INITIAL_SEPARATION_HPP
#define INITIAL_SEPARATION_HPP
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "types.hpp"
#include <iostream>
#include <string>
#include <unordered_map>
#include "tensor_computation.hpp"
#include "misc.hpp"
void initial_segmentation(const cv::Mat_<cv::Vec2d> &flowfield,
cv::Mat_<double> &phi,
const std::unordered_map<std::string, parameter> ¶meters,
cv::Vec6d &dominantmotion
);
void segementFlowfield(const cv::Mat_<cv::Vec2d> &f, cv::Mat_<double> &phi, const std::unordered_map<std::string, parameter> ¶meters, cv::Vec6d &dominantmotion);
bool are_close_blocks(cv::Vec6d a1, cv::Vec6d a2, double Tm, double r);
void choose_better_affine(
const cv::Mat_<bool> &merged_blocks,
const cv::Vec6d &p_new,
cv::Vec6d &p_old,
const cv::Mat_<cv::Vec2d> &f,
int blocksize
);
double error_block(int i, int j, int blocksize, const cv::Vec6d &a_p, const cv::Mat_<cv::Vec2d> &flow);
#endif
| [
"[email protected]"
] | |
1d4f4d0cc45c957d1f2deac425720308b4f8f8b2 | 73b8d67dcf86c4aaa8b005e4f270c62c60c2cdba | /Combinatorics/排列的逆序.cpp | cb788973c12cdcdc432422d489ed2f8e2e8ed89b | [] | no_license | DaDaMrX/Sophomore | 822b750c8bff0490a7f200facd907e8e854ccaaa | bf724064f6a3ca107c0f950042d681f265b00a2f | refs/heads/master | 2021-01-12T04:34:24.793104 | 2017-04-02T11:33:18 | 2017-04-02T11:33:18 | 83,888,762 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 601 | cpp | #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
const int N = 15;
int a[N], b[N];
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
int n;
ll k;
scanf("%d%lld", &n, &k);
k--;
for (int i = 1; i <= n; i++)
{
b[n + 1 - i] = k % i;
k /= i;
}
memset(a, 0, sizeof(a));
for (int i = 1; i <= n; i++)
{
int j = 0, s = 0;
while (s <= b[i])
{
j++;
if (a[j] == 0) s++;
}
a[j] = i;
}
for (int i = 1; i < n; i++) printf("%d ", a[i]);
printf("%d\n", a[n]);
}
return 0;
}
| [
"[email protected]"
] | |
d33b32c9b4a47b6af5dff5e0e5a9538cd1c20814 | 1cc44526fe719ddb807241e873b536c22fa0d1bf | /Src/Representations/Infrastructure/IntegralImage.h | 905d5ce8458bf640470368ee81f5137c6a558063 | [
"BSD-2-Clause"
] | permissive | Handsome-Computer-Organization/nao | 55e188276a7ba82631bc6283d18db89f2b688c75 | d7bbac09355e5f8f719acb4b65b39bc7975878ca | refs/heads/main | 2023-04-26T12:24:59.944423 | 2021-05-14T12:53:10 | 2021-05-14T12:53:10 | 367,357,552 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,364 | h | /**
* @file InegralImage.h
*
* Declaration of struct IntegralImage.
*/
#pragma once
#include "Tools/Streams/AutoStreamable.h"
#include "Image.h"
#include "SobelImage.h"
#include "Tools/Math/BHMath.h"
STREAMABLE(IntegralImage,
{
IntegralImage(const int w = 320, const int h = 240)
{
init(w,h);
}
void init(const int w = 320, const int h = 240)
{
width = w; height = h;
image.reserve(width * height);
ySum.reserve(width * height);
for (unsigned int x = 0; x < width; x++)
for (unsigned int y = 0; y < height; y++)
{
ySum.push_back(0);
image.push_back(0);
}
}
int getPixelAt(const int x, const int y) const { return (int)image[y * width + x]; }
void createIntegralImage(const Image &source);
void createIntegralImageDiffFromGray(const Image &source, const unsigned grayValue);
void createIntegralImageSobel(const SobelImage &source);
void createIntegralImageDiffFromGraySobel(const SobelImage &source, const unsigned grayValue);
,
(unsigned) width,
(unsigned) height,
(std::vector<unsigned>) image,
(std::vector<unsigned>) ySum,
});
struct IntegralImageUpper : public IntegralImage
{
IntegralImageUpper() : IntegralImage(640, 480) {}
private:
void serialize(In* in, Out* out)
{
STREAM_REGISTER_BEGIN;
STREAM_BASE(IntegralImage);
STREAM_REGISTER_FINISH;
}
}; | [
"[email protected]"
] | |
75c791d96d328bde914eede19276e9f4751d49c0 | 67efc5a1259f2ea7f592bbf37f05e0cd5542cea6 | /PA9_KendraKendall/Square.cpp | 54ac4c0bf4bb9bdb466459507ab58450e4ef0a91 | [] | no_license | kylerlittle/worlds-hardest-game | c96e7a7ed7a618c7609232ea9727e1a8e35b5c9d | 403be2795a984982e7bd5d9da7945b48f4f8e74c | refs/heads/master | 2021-07-06T14:44:04.622126 | 2017-09-26T22:58:27 | 2017-09-26T22:58:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 212 | cpp | #include "Square.h"
/*Default constructor*/
Square::Square() : RectangleShape(sf::Vector2f(SQUARE_LEN, SQUARE_LEN))
{
setFillColor(sf::Color::Red);
setOutlineThickness(1);
setOutlineColor(sf::Color::Black);
} | [
"Kyler Little@DESKTOP-KQ9SPFN"
] | Kyler Little@DESKTOP-KQ9SPFN |
f5e5fbaec7699770d69f36d7f0405fe2cc42c653 | abf463fdb8a7c7631fb1db4380807e336f039ea6 | /c++/pointerstofunction.cpp | 93ed02f826d163fb363b2f16df12b66e61fa70d2 | [] | no_license | Jayad/Program_practise | ea1a16bf17519e581d75978c062c2f31a960c7a2 | 6de6f5cf8ebb24b264f999853cb11925c00ac746 | refs/heads/master | 2021-06-16T08:33:50.630104 | 2017-03-27T16:12:41 | 2017-03-27T16:12:41 | 8,859,196 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 580 | cpp | #include<iostream>
using namespace std;
int addition(int a, int b)
{
return (a+b);
}
int subtraction(int a, int b)
{
return (a-b);
}
int operation(int a, int b, int (*func)(int a, int b))
{
int g;
g=(*func)(a,b);
return g;
}
int main()
{
int m,n,p;
//minus is a pointer to a function that has two parameters of type int. It is immediately assigned to point to the function subtraction, all in a single line:
int (*minus)(int,int) =subtraction;
m=operation(5,6,addition);
n=operation(25,m,minus);
p=operation(25,m,subtraction);
cout << n <<endl;
cout << p <<endl;
return 0;
}
| [
"[email protected]"
] | |
4add068c487baff7302a727264b819bddc447e3e | ff3683f5507e90cc04aef75fc467504e4a77c8fc | /pjsip_android/build/platforms/android-3/arch-arm/usr/include/media/AudioSystem.h | 77c90ba7fc1fef4d31d6d29d9cb2e2cb0e398f4f | [] | no_license | zzjs2001702/csip | f23ecad4e17aedc5e12a71fbedc1001a48bcabc0 | 83d75fd556e4146d9df5a95b8e23587238637337 | refs/heads/master | 2021-12-30T07:43:11.356552 | 2013-02-02T19:35:14 | 2013-02-02T19:35:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,389 | h | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_AUDIOSYSTEM_H_
#define ANDROID_AUDIOSYSTEM_H_
#include <utils/RefBase.h>
#include <utils/threads.h>
#include <media/IAudioFlinger.h>
namespace android {
typedef void (*audio_error_callback)(status_t err);
class AudioSystem
{
public:
enum stream_type {
DEFAULT =-1,
VOICE_CALL = 0,
SYSTEM = 1,
RING = 2,
MUSIC = 3,
ALARM = 4,
NOTIFICATION = 5,
BLUETOOTH_SCO = 6,
NUM_STREAM_TYPES
};
enum audio_output_type {
AUDIO_OUTPUT_DEFAULT =-1,
AUDIO_OUTPUT_HARDWARE = 0,
AUDIO_OUTPUT_A2DP = 1,
NUM_AUDIO_OUTPUT_TYPES
};
enum audio_format {
FORMAT_DEFAULT = 0,
PCM_16_BIT,
PCM_8_BIT,
INVALID_FORMAT
};
enum audio_mode {
MODE_INVALID = -2,
MODE_CURRENT = -1,
MODE_NORMAL = 0,
MODE_RINGTONE,
MODE_IN_CALL,
NUM_MODES // not a valid entry, denotes end-of-list
};
enum audio_routes {
ROUTE_EARPIECE = (1 << 0),
ROUTE_SPEAKER = (1 << 1),
ROUTE_BLUETOOTH_SCO = (1 << 2),
ROUTE_HEADSET = (1 << 3),
ROUTE_BLUETOOTH_A2DP = (1 << 4),
ROUTE_ALL = -1UL,
};
enum audio_in_acoustics {
AGC_ENABLE = 0x0001,
AGC_DISABLE = 0,
NS_ENABLE = 0x0002,
NS_DISABLE = 0,
TX_IIR_ENABLE = 0x0004,
TX_DISABLE = 0
};
/* These are static methods to control the system-wide AudioFlinger
* only privileged processes can have access to them
*/
// routing helper functions
static status_t speakerphone(bool state);
static status_t isSpeakerphoneOn(bool* state);
static status_t bluetoothSco(bool state);
static status_t isBluetoothScoOn(bool* state);
static status_t muteMicrophone(bool state);
static status_t isMicrophoneMuted(bool *state);
static status_t setMasterVolume(float value);
static status_t setMasterMute(bool mute);
static status_t getMasterVolume(float* volume);
static status_t getMasterMute(bool* mute);
static status_t setStreamVolume(int stream, float value);
static status_t setStreamMute(int stream, bool mute);
static status_t getStreamVolume(int stream, float* volume);
static status_t getStreamMute(int stream, bool* mute);
static status_t setMode(int mode);
static status_t getMode(int* mode);
static status_t setRouting(int mode, uint32_t routes, uint32_t mask);
static status_t getRouting(int mode, uint32_t* routes);
static status_t isMusicActive(bool *state);
// Temporary interface, do not use
// TODO: Replace with a more generic key:value get/set mechanism
static status_t setParameter(const char* key, const char* value);
static void setErrorCallback(audio_error_callback cb);
// helper function to obtain AudioFlinger service handle
static const sp<IAudioFlinger>& get_audio_flinger();
static float linearToLog(int volume);
static int logToLinear(float volume);
static status_t getOutputSamplingRate(int* samplingRate, int stream = DEFAULT);
static status_t getOutputFrameCount(int* frameCount, int stream = DEFAULT);
static status_t getOutputLatency(uint32_t* latency, int stream = DEFAULT);
static bool routedToA2dpOutput(int streamType);
static status_t getInputBufferSize(uint32_t sampleRate, int format, int channelCount,
size_t* buffSize);
// ----------------------------------------------------------------------------
private:
class AudioFlingerClient: public IBinder::DeathRecipient, public BnAudioFlingerClient
{
public:
AudioFlingerClient() {
}
// DeathRecipient
virtual void binderDied(const wp<IBinder>& who);
// IAudioFlingerClient
virtual void a2dpEnabledChanged(bool enabled);
};
static int getOutput(int streamType);
static sp<AudioFlingerClient> gAudioFlingerClient;
friend class AudioFlingerClient;
static Mutex gLock;
static sp<IAudioFlinger> gAudioFlinger;
static audio_error_callback gAudioErrorCallback;
static int gOutSamplingRate[NUM_AUDIO_OUTPUT_TYPES];
static int gOutFrameCount[NUM_AUDIO_OUTPUT_TYPES];
static uint32_t gOutLatency[NUM_AUDIO_OUTPUT_TYPES];
static bool gA2dpEnabled;
static size_t gInBuffSize;
// previous parameters for recording buffer size queries
static uint32_t gPrevInSamplingRate;
static int gPrevInFormat;
static int gPrevInChannelCount;
};
}; // namespace android
#endif /*ANDROID_AUDIOSYSTEM_H_*/
| [
"r3gis3r@9f815046-5998-e9c0-b7e2-ac03a23edfa4"
] | r3gis3r@9f815046-5998-e9c0-b7e2-ac03a23edfa4 |
fb2f013c32dab39a97caef773ef5ba626ae401ec | e50b5f066628ef65fd7f79078b4b1088f9d11e87 | /llvm/tools/clang/test/CodeGenObjCXX/block-nested-in-lambda.cpp | 7c9714584ae4154586106fb09845266cc5a24e23 | [
"NCSA"
] | permissive | uzleo/coast | 1471e03b2a1ffc9883392bf80711e6159917dca1 | 04bd688ac9a18d2327c59ea0c90f72e9b49df0f4 | refs/heads/master | 2020-05-16T11:46:24.870750 | 2019-04-23T13:57:53 | 2019-04-23T13:57:53 | 183,025,687 | 0 | 0 | null | 2019-04-23T13:52:28 | 2019-04-23T13:52:27 | null | UTF-8 | C++ | false | false | 1,213 | cpp | // RUN: %clang_cc1 -triple=x86_64-apple-darwin10 -emit-llvm -std=c++11 -fblocks -o - %s | FileCheck %s
// CHECK: %[[BLOCK_CAPTURED0:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, i32*, i32* }>, <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, i32*, i32* }>* %[[BLOCK:.*]], i32 0, i32 5
// CHECK: %[[V0:.*]] = getelementptr inbounds %[[LAMBDA_CLASS:.*]], %[[LAMBDA_CLASS]]* %[[THIS:.*]], i32 0, i32 0
// CHECK: %[[V1:.*]] = load i32*, i32** %[[V0]], align 8
// CHECK: store i32* %[[V1]], i32** %[[BLOCK_CAPTURED0]], align 8
// CHECK: %[[BLOCK_CAPTURED1:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, i32*, i32* }>, <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, i32*, i32* }>* %[[BLOCK]], i32 0, i32 6
// CHECK: %[[V2:.*]] = getelementptr inbounds %[[LAMBDA_CLASS]], %[[LAMBDA_CLASS]]* %[[THIS]], i32 0, i32 1
// CHECK: %[[V3:.*]] = load i32*, i32** %[[V2]], align 8
// CHECK: store i32* %[[V3]], i32** %[[BLOCK_CAPTURED1]], align 8
void foo1(int &, int &);
void block_in_lambda(int &s1, int &s2) {
auto lambda = [&s1, &s2]() {
auto block = ^{
foo1(s1, s2);
};
block();
};
lambda();
}
| [
"[email protected]"
] | |
dd3ab9dbbfdc817ace282aa442f3d1fa37a845a9 | 1349bac38d0c70d2d4abf45adb5ce08423b128f2 | /Proyecto/4-Sistema-utilizando-clases/clientes.h | 89be9e081145309926ee08fca459dcd219e46b8c | [
"MIT"
] | permissive | jdelcidz/cpp-1 | 4c5cac6bc35bbbee07cdabc4d1636348bbbc1a53 | 47562fac7939ac0e942f5ad29a08d6405996c9a0 | refs/heads/master | 2022-10-22T13:01:43.299891 | 2020-06-13T15:01:48 | 2020-06-13T15:01:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | h | #include <iostream>
using namespace std;
class Cliente {
public:
string Codigo;
string Nombre;
string Telefono;
Cliente() {
}
Cliente(string codigo, string nombre, string telefono) {
Codigo = codigo;
Nombre = nombre;
Telefono = telefono;
}
};
void inicializarDatosdeClientes();
void clientes();
bool buscarCliente(string &codigo, string &nombreCliente);
| [
"[email protected]"
] | |
5b5df4f93f44ec357943180ec7d2252b49f66c31 | 99d3c5d09886c1d45cc7eed7a6dcce3548ac4da3 | /nebula/doc/old/RCS/Samples/SampleFramework/renderer/drivers/d3d9/D3D9RendererTarget.cpp | 54121c655b907bce59a20369ccfc296a67989aa0 | [] | no_license | nebula-engine/nebula_old | 1e49843c7c8a4915d0303cca5b8067d6e62de4fb | d61f91140b6ac5334a8292bfece97092a99c53b0 | refs/heads/master | 2021-01-23T13:49:01.855177 | 2015-03-05T04:07:06 | 2015-03-05T04:07:06 | 29,644,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,024 | cpp | /*
* Copyright 2008-2012 NVIDIA Corporation. All rights reserved.
*
* NOTICE TO USER:
*
* This source code is subject to NVIDIA ownership rights under U.S. and
* international Copyright laws. Users and possessors of this source code
* are hereby granted a nonexclusive, royalty-free license to use this code
* in individual and commercial software.
*
* NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE
* CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR
* IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
* IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL,
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
* OR PERFORMANCE OF THIS SOURCE CODE.
*
* U.S. Government End Users. This source code is a "commercial item" as
* that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of
* "commercial computer software" and "commercial computer software
* documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995)
* and is provided to the U.S. Government only as a commercial end item.
* Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through
* 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the
* source code with only those rights set forth herein.
*
* Any use of this source code in individual and commercial software must
* include, in the user documentation and internal comments to the code,
* the above Disclaimer and U.S. Government End Users Notice.
*/
// suppress LNK4221 on Xbox
namespace {char dummySymbol; }
#include <RendererConfig.h>
#include "D3D9RendererTarget.h"
#if defined(RENDERER_ENABLE_DIRECT3D9) && defined(RENDERER_ENABLE_DIRECT3D9_TARGET)
#include <RendererTargetDesc.h>
#include "D3D9RendererTexture2D.h"
using namespace SampleRenderer;
D3D9RendererTarget::D3D9RendererTarget(IDirect3DDevice9 &d3dDevice, const RendererTargetDesc &desc) :
m_d3dDevice(d3dDevice)
{
m_d3dLastSurface = 0;
m_d3dLastDepthStencilSurface = 0;
m_d3dDepthStencilSurface = 0;
for(PxU32 i=0; i<desc.numTextures; i++)
{
D3D9RendererTexture2D &texture = *static_cast<D3D9RendererTexture2D*>(desc.textures[i]);
m_textures.push_back(&texture);
}
m_depthStencilSurface = static_cast<D3D9RendererTexture2D*>(desc.depthStencilSurface);
RENDERER_ASSERT(m_depthStencilSurface && m_depthStencilSurface->m_d3dTexture, "Invalid Target Depth Stencil Surface!");
onDeviceReset();
}
D3D9RendererTarget::~D3D9RendererTarget(void)
{
if(m_d3dDepthStencilSurface) m_d3dDepthStencilSurface->Release();
}
void D3D9RendererTarget::bind(void)
{
RENDERER_ASSERT(m_d3dLastSurface==0 && m_d3dLastDepthStencilSurface==0, "Render Target in bad state!");
if(m_d3dDepthStencilSurface && !m_d3dLastSurface && !m_d3dLastDepthStencilSurface)
{
m_d3dDevice.GetRenderTarget(0, &m_d3dLastSurface);
m_d3dDevice.GetDepthStencilSurface(&m_d3dLastDepthStencilSurface);
const PxU32 numTextures = (PxU32)m_textures.size();
for(PxU32 i=0; i<numTextures; i++)
{
IDirect3DSurface9 *d3dSurcace = 0;
D3D9RendererTexture2D &texture = *m_textures[i];
/* HRESULT result = */ texture.m_d3dTexture->GetSurfaceLevel(0, &d3dSurcace);
RENDERER_ASSERT(d3dSurcace, "Cannot get Texture Surface!");
if(d3dSurcace)
{
m_d3dDevice.SetRenderTarget(i, d3dSurcace);
d3dSurcace->Release();
}
}
m_d3dDevice.SetDepthStencilSurface(m_d3dDepthStencilSurface);
const DWORD flags = D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER;
m_d3dDevice.Clear(0, 0, flags, 0x00000000, 1.0f, 0);
}
float depthBias = 0.0001f;
float biasSlope = 1.58f;
#if RENDERER_ENABLE_DRESSCODE
depthBias = dcParam("depthBias", depthBias, 0.0f, 0.01f);
biasSlope = dcParam("biasSlope", biasSlope, 0.0f, 5.0f);
#endif
m_d3dDevice.SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
m_d3dDevice.SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&biasSlope);
}
void D3D9RendererTarget::unbind(void)
{
RENDERER_ASSERT(m_d3dLastSurface && m_d3dLastDepthStencilSurface, "Render Target in bad state!");
if(m_d3dDepthStencilSurface && m_d3dLastSurface && m_d3dLastDepthStencilSurface)
{
m_d3dDevice.SetDepthStencilSurface(m_d3dLastDepthStencilSurface);
m_d3dDevice.SetRenderTarget(0, m_d3dLastSurface);
const PxU32 numTextures = (PxU32)m_textures.size();
for(PxU32 i=1; i<numTextures; i++)
{
m_d3dDevice.SetRenderTarget(i, 0);
}
m_d3dLastSurface->Release();
m_d3dLastSurface = 0;
m_d3dLastDepthStencilSurface->Release();
m_d3dLastDepthStencilSurface = 0;
}
float depthBias = 0;
float biasSlope = 0;
m_d3dDevice.SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias);
m_d3dDevice.SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&biasSlope);
}
void D3D9RendererTarget::onDeviceLost(void)
{
RENDERER_ASSERT(m_d3dLastDepthStencilSurface==0, "Render Target in bad state!");
RENDERER_ASSERT(m_d3dDepthStencilSurface, "Render Target in bad state!");
if(m_d3dDepthStencilSurface)
{
m_d3dDepthStencilSurface->Release();
m_d3dDepthStencilSurface = 0;
}
}
void D3D9RendererTarget::onDeviceReset(void)
{
RENDERER_ASSERT(m_d3dDepthStencilSurface==0, "Render Target in bad state!");
if(!m_d3dDepthStencilSurface && m_depthStencilSurface && m_depthStencilSurface->m_d3dTexture)
{
bool ok = m_depthStencilSurface->m_d3dTexture->GetSurfaceLevel(0, &m_d3dDepthStencilSurface) == D3D_OK;
if(!ok)
{
RENDERER_ASSERT(ok, "Failed to create Render Target Depth Stencil Surface.");
}
}
}
#endif //#if defined(RENDERER_ENABLE_DIRECT3D9) && defined(RENDERER_ENABLE_DIRECT3D9_TARGET)
| [
"[email protected]"
] | |
763c5199c8d7ff0bad12e10db4cfaf0c56e7d0f4 | 6f525b3061951e1e6604bcf8d10f6ad6a733d8d6 | /main.cpp | bb9c643771668251894ffe3aa177b5a5ad0b41eb | [] | no_license | Zheny-mc/- | 93239e4ac8da420c340e98d5225c3e85001c8370 | f01ce6a83239b7098be0f2d7e559f092c9b828b7 | refs/heads/master | 2022-12-04T13:00:34.487558 | 2020-08-27T15:09:34 | 2020-08-27T15:09:34 | 288,446,291 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,191 | cpp | #include "zipper.h"
using std::cout;
using std::endl;
class Power
{
public:
int argc; //количество аргументов
string* argv; //аргументы
string mode; //режим запуска
string name; //имя архива
vector<string> FileNames;
Power(int _argc, const char** _argv) : argc(_argc-1), argv(new string[_argc-1])
{
for(int i = 0; i < argc; i++)
argv[i] = _argv[i+1];
}
~Power()
{
delete[] argv;
}
bool check_args();
void poll();
void run();
};
bool Power::check_args()
{
// -c - создание архива
// -x - распаковка архива
string KeyWords[] = {"-c", "-cz", "-x", "-xz", ".zip", ".zip.z"};
if (argc >= 2)
{
if ((argv[0] == KeyWords[0] || argv[0] == KeyWords[1] ||
argv[0] == KeyWords[2] || argv[0] == KeyWords[3]) &&
(argv[1].find(KeyWords[4]) != -1 || argv[1].find(KeyWords[5]) != -1))
{
if ((argv[0] == KeyWords[0] || argv[0] == KeyWords[1]) && argc == 2)
{
cout << "Nothing packing... Input files" << endl;
return false;
}
}
else
{
cout << "Dont know 1 and 2 arguments" << endl;
return false;
}
}
else
{
cout << "It is little count argumets" << endl;
return false;
}
return true;
}
void Power::poll()
{
mode = argv[0];
name = argv[1];
if (mode == "-c" || mode == "-cz")
{
for (int i = 2; i < argc; i++)
FileNames.push_back(argv[i]);
}
}
void Power::run()
{
Zipper archive(name, FileNames);
if (name.find(".z") != -1) archive.set_HaveKey();
if (mode == "-c")
{
//создание архива
archive.help();
}
else if (mode == "-x")
{
//распаковка архива
archive.UnPack();
}
}
int main()
{
/*
string name = "test.zip";
vector<string> args = {"file1.dat", "file2.dat"};
string Key = "123";
Zipper arch2(name, args);
arch2.Pack();
arch2.UnPack();
*/
int argc = 5;
const char* argv[] = {"./zipper", "-c", "name.zip.z", "file1.dat", "file2.dat"};
Power R(argc, argv);
if (R.check_args()) //проверка правильности аргументов
{
R.poll(); //заполнение аргументов
R.run(); //запуск
}
return 0;
}
| [
"[email protected]"
] | |
b3a9f06a2beb496a368a28c02dc9d5a72e5c81d4 | a84730d2a6666e7d7deb86ac939876ecf4397502 | /littl/Unicode.hpp | f8a41c1783f57e7fbf742c91aac6cd76edcc432e | [] | no_license | minexew/littl | 44587a113fceb5ef761139c3c94e10d168ce1918 | 7889fbc515a088f9ade6ccb8772aaff9c62dfe79 | refs/heads/master | 2021-06-06T05:03:59.158975 | 2020-02-04T10:03:01 | 2020-02-04T10:05:25 | 23,193,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,249 | hpp | /*
Copyright (C) 2011, 2012, 2013 Xeatheran Minexew
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.
*/
#pragma once
#include "Base.hpp"
namespace li
{
class Unicode
{
public:
typedef char32_t Char;
static const Char backspaceChar = 0x00000008;
static const Char tabChar = 0x00000009;
static const Char lineFeedChar = 0x0000000A;
static const Char invalidChar = 0xFFFFFFFF;
static bool isAlpha( Char c )
{
return ( c >= 'A' && c <= 'Z' ) || ( c >= 'a' && c <= 'z' );
}
static bool isAlphaNumeric( Char c )
{
return isAlpha( c ) || isNumeric( c );
}
static bool isNumeric( Char c )
{
return c >= '0' && c <= '9';
}
};
struct UnicodeChar
{
Unicode::Char c;
UnicodeChar( Unicode::Char c = Unicode::invalidChar ) : c( c ) {}
UnicodeChar& operator = ( Unicode::Char c ) { this->c = c; return *this; }
operator Unicode::Char& () { return c; }
operator const Unicode::Char& () const { return c; }
};
}
| [
"[email protected]"
] | |
bd23a417f929fbe61f9532b724581b0b5138391c | cd99ca9461435d1417cb146d966e54272fbcc7ad | /3rd party/maxsdk/samples/systems/sunlight/PhysicalSunSkyEnv_UI.h | 835e3a73d76e02d0da3b8f152ec6c1e6b49f011e | [] | no_license | mortany/xray15 | eacce7965e785dd71d1877eae25c1f9eff680eec | 72a13fb24e9b388850bc769427c231da8f599228 | refs/heads/master | 2020-08-02T20:45:23.493981 | 2019-10-14T18:48:48 | 2019-10-14T18:48:48 | 211,499,718 | 0 | 0 | null | 2019-09-28T12:50:47 | 2019-09-28T12:50:46 | null | UTF-8 | C++ | false | false | 1,664 | h | //////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
//
//////////////////////////////////////////////////////////////////////////////
#pragma once
// local
#include "PhysicalSunSkyEnv.h"
// Max SDK
#include <Qt/QMaxParamBlockWidget.h>
// Qt
#include "ui_PhysSunSky.h"
#include <QtWidgets/QWidget>
//==================================================================================================
// class PhysicalSunSkyEnv::MainPanelWidget
//
// Qt widget that implements the UI for the main panel of the physical sun & sky environment.
//
class PhysicalSunSkyEnv::MainPanelWidget :
public MaxSDK::QMaxParamBlockWidget
{
Q_OBJECT
public:
explicit MainPanelWidget(IParamBlock2& param_block);
~MainPanelWidget();
// -- inherited from QMaxParamBlockWidget
virtual void SetParamBlock(ReferenceMaker* owner, IParamBlock2* const param_block) override;
virtual void UpdateUI(const TimeValue t) override;
virtual void UpdateParameterUI(const TimeValue t, const ParamID param_id, const int tab_index) override;
protected slots:
void create_sun_positioner_button_clicked();
private:
void update_illuminance_model_controls(const TimeValue t);
private:
// UI designer object
Ui_PhysSunSky m_ui_builder;
IParamBlock2* m_param_block;
};
| [
"[email protected]"
] | |
07737784510130c542c5f91c387a0d793b1f688f | 070d630a312f393372d9264089329120186a8f3a | /Galatea/Bomb.h | 144e62037e0c30159b751816de6b1b5e1004b7f5 | [] | no_license | peersmg/WW2ShooterGame | 35ca31078e0ee205cddc399bc7ae5f6b0d29d440 | 7980af2c4ff980651f74f6f18d0b8c4a57bde4de | refs/heads/master | 2021-01-11T10:50:01.099834 | 2016-12-13T18:53:34 | 2016-12-13T18:53:34 | 76,181,606 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 959 | h |
//Title : Bomb.h
//Purpose : Bomb header.
//Author : Matthew Peers
//Date : 05/12/16
#pragma once
#include "GameObject.h"
class Bomb : public GameObject
{
private:
Rectangle2D collisionShape; // Objects collision shape
Vector2D m_velocity; // The velocity of the bomb
Vector2D m_imageSize; // The size of the bomb graphic within the image file
float m_speed; // How fast the bomb should fall
public:
// Constructor
Bomb();
// Set up the bomb
void Initialise(float angle, Vector2D position);
// Process the collisions of this gameobject
void ProcessCollision(GameObject &other);
// Update the gameobject logic, called every frame
void Update(float deltaTime);
// Deactivate this game object and create an explosion effect
void Explode();
// Returns the collision shape
IShape2D& GetCollisionShape();
// Recieves and handles events
void HandleEvent(Event evt);
};
| [
"[email protected]"
] | |
50c61de1f90a8ba7f4f42745acee1e69b6e3bd9c | 6556148eec751962b54c5b9a619bbebae2c4119d | / robocupsslclient/Tactics/DisperseTactic.h | 6641afd259abd5aac2de1e6a5ca95b80162ebfe0 | [] | no_license | Hannna/robocupsslclient | 947fe9ccb2f6101b60dc711166d7d91435bc624d | 4009fce4bba34f9e8083645c8ee88dc8d975986c | refs/heads/master | 2020-06-03T11:57:58.539558 | 2012-02-28T23:39:42 | 2012-02-28T23:39:42 | 33,896,893 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 423 | h | /*
* DIsperseTactic.h
*
* Created on: Aug 9, 2011
* Author: maciek
*/
#ifndef DISPERSETACTIC_H_
#define DISPERSETACTIC_H_
#include "Tactic.h"
class Robot;
class DisperseTactic: public Tactic {
public:
DisperseTactic( Robot & robot );
virtual bool isFinish();
virtual ~DisperseTactic();
protected:
virtual void execute(void *);
private:
DisperseTactic();
};
#endif /* DISPERSETACTIC_H_ */
| [
"mgabka@48f5bffa-9504-1908-88fd-a439b3b414de"
] | mgabka@48f5bffa-9504-1908-88fd-a439b3b414de |
4a875cef049e86b3d405a51174546f8ce2c76b73 | 5f67df4e0d6d82b6877e4f899dd6395850ca3604 | /Hackerrank/Miser-Nim.cpp | 6871314b85c7309cb80f77b54e0c0b6fe812b1e0 | [
"MIT"
] | permissive | dfm066/Programming | c27115bffed568fa1fe05a5448a7a82042451415 | 53d28460cd40b966cca1d4695d9dc6792ced4c6f | refs/heads/master | 2021-07-03T17:40:22.010361 | 2020-09-14T19:59:03 | 2020-09-14T19:59:03 | 63,838,561 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t,n,s,flg;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(int i = 0; i < n; i++){
scanf("%d",&s);
if(i!=0)
flg ^= s;
else
flg=s;
}
if(n==1&&s==1)
printf("Second\n");
else if((n%2==0&&flg==0)||(n%2!=0&&flg!=0))
printf("First\n");
else
printf("Second\n");
}
return 0;
}
| [
"[email protected]"
] | |
fbd95e919280ee7cda0bda642c89214ab67cb77f | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/107/405/CWE590_Free_Memory_Not_on_Heap__delete_int64_t_placement_new_63b.cpp | 4f1509d3599a480515654a657f303a28fafea0b3 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,241 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_int64_t_placement_new_63b.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete.pointer.label.xml
Template File: sources-sink-63b.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: placement_new Data buffer is declared on the stack
* GoodSource: Allocate memory on the heap
* Sinks:
* BadSink : Print then free data
* Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE590_Free_Memory_Not_on_Heap__delete_int64_t_placement_new_63
{
#ifndef OMITBAD
void badSink(int64_t * * dataPtr)
{
int64_t * data = *dataPtr;
printLongLongLine(*data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(int64_t * * dataPtr)
{
int64_t * data = *dataPtr;
printLongLongLine(*data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete data;
}
#endif /* OMITGOOD */
} /* close namespace */
| [
"[email protected]"
] | |
c3f7d961b7690ecc82fbb80bdfe88010c2f688df | f9fed164f610b5ce23c5e56f0b0ebdaa7f0ca6e7 | /oj/1683/1683/main.cpp | d3799d4eae23ff019386f0cf88e2f6e9fbe4c935 | [] | no_license | lszr-x/MiscellaneousAlgorithmOfC- | b0f4bc53ee191d31b66425ff83fbb26d7c470fde | a4b1af0e3935616e136f9e3d37eaf9728b846f8a | refs/heads/master | 2021-04-15T14:18:17.640846 | 2018-03-27T13:27:34 | 2018-03-27T13:27:34 | 126,178,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 673 | cpp | //
// main.cpp
// 1683
//
// Created by apple on 2017/3/20.
// Copyright © 2017年 apple. All rights reserved.
//
#include <iostream>
#include <set>
#include <cstdio>
using namespace std;
int main(int argc, const char * argv[]) {
set<string> s;
string a,b;
char x;
while(~scanf("%c",&x)){
if(x=='A'){
b.resize(1000);
scanf("%s",&b[0]);
if(s.count(b)){
printf("他得奖了\n");
}
else printf("没有快滚\n");
}
if(x=='B'){
b.resize(1000);
scanf("%s",&b[0]);
s.insert(b);
}
}
return 0;
}
| [
"[email protected]"
] | |
007afcd159ffcc5116171b1c538e46556afa5ff5 | 1942a0d16bd48962e72aa21fad8d034fa9521a6c | /aws-cpp-sdk-cloudtrail/include/aws/cloudtrail/model/PutEventSelectorsRequest.h | 63ba924f8dac3ec11c50d390820f5155086beb9e | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | yecol/aws-sdk-cpp | 1aff09a21cfe618e272c2c06d358cfa0fb07cecf | 0b1ea31e593d23b5db49ee39d0a11e5b98ab991e | refs/heads/master | 2021-01-20T02:53:53.557861 | 2018-02-11T11:14:58 | 2018-02-11T11:14:58 | 83,822,910 | 0 | 1 | null | 2017-03-03T17:17:00 | 2017-03-03T17:17:00 | null | UTF-8 | C++ | false | false | 9,978 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/cloudtrail/CloudTrail_EXPORTS.h>
#include <aws/cloudtrail/CloudTrailRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/cloudtrail/model/EventSelector.h>
namespace Aws
{
namespace CloudTrail
{
namespace Model
{
/**
*/
class AWS_CLOUDTRAIL_API PutEventSelectorsRequest : public CloudTrailRequest
{
public:
PutEventSelectorsRequest();
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code> </p>
*/
inline const Aws::String& GetTrailName() const{ return m_trailName; }
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code> </p>
*/
inline void SetTrailName(const Aws::String& value) { m_trailNameHasBeenSet = true; m_trailName = value; }
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code> </p>
*/
inline void SetTrailName(Aws::String&& value) { m_trailNameHasBeenSet = true; m_trailName = value; }
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code> </p>
*/
inline void SetTrailName(const char* value) { m_trailNameHasBeenSet = true; m_trailName.assign(value); }
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code> </p>
*/
inline PutEventSelectorsRequest& WithTrailName(const Aws::String& value) { SetTrailName(value); return *this;}
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code> </p>
*/
inline PutEventSelectorsRequest& WithTrailName(Aws::String&& value) { SetTrailName(value); return *this;}
/**
* <p>Specifies the name of the trail or trail ARN. If you specify a trail name,
* the string must meet the following requirements:</p> <ul> <li> <p>Contain only
* ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes
* (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or
* number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have
* no adjacent periods, underscores or dashes. Names like
* <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li>
* <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul>
* <p>If you specify a trail ARN, it must be in the format:</p> <p>
* <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code> </p>
*/
inline PutEventSelectorsRequest& WithTrailName(const char* value) { SetTrailName(value); return *this;}
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline const Aws::Vector<EventSelector>& GetEventSelectors() const{ return m_eventSelectors; }
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline void SetEventSelectors(const Aws::Vector<EventSelector>& value) { m_eventSelectorsHasBeenSet = true; m_eventSelectors = value; }
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline void SetEventSelectors(Aws::Vector<EventSelector>&& value) { m_eventSelectorsHasBeenSet = true; m_eventSelectors = value; }
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline PutEventSelectorsRequest& WithEventSelectors(const Aws::Vector<EventSelector>& value) { SetEventSelectors(value); return *this;}
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline PutEventSelectorsRequest& WithEventSelectors(Aws::Vector<EventSelector>&& value) { SetEventSelectors(value); return *this;}
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline PutEventSelectorsRequest& AddEventSelectors(const EventSelector& value) { m_eventSelectorsHasBeenSet = true; m_eventSelectors.push_back(value); return *this; }
/**
* <p>Specifies the settings for your event selectors. You can configure up to five
* event selectors for a trail.</p>
*/
inline PutEventSelectorsRequest& AddEventSelectors(EventSelector&& value) { m_eventSelectorsHasBeenSet = true; m_eventSelectors.push_back(value); return *this; }
private:
Aws::String m_trailName;
bool m_trailNameHasBeenSet;
Aws::Vector<EventSelector> m_eventSelectors;
bool m_eventSelectorsHasBeenSet;
};
} // namespace Model
} // namespace CloudTrail
} // namespace Aws
| [
"[email protected]"
] | |
840dcf27278063660fa44194e5b89fdda06ad237 | 5c3f6bdd0aa5446a78372c967d5a642c429b8eda | /src/versionbits.h | a9e0c63d836f63cecba02a2e2110b6be67fd9289 | [
"MIT"
] | permissive | GlobalBoost/GlobalBoost-Y | defeb2f930222d8b78447a9440d03cce9d8d602c | b4c8f1bb88ebbfa5016376fee9a00ae98902133f | refs/heads/master | 2023-08-11T12:04:12.578240 | 2023-07-11T03:56:18 | 2023-07-11T03:56:18 | 23,804,954 | 20 | 22 | MIT | 2023-07-11T03:56:19 | 2014-09-08T19:26:43 | C++ | UTF-8 | C++ | false | false | 3,223 | h | // Copyright (c) 2016-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef GLOBALBOOST_VERSIONBITS_H
#define GLOBALBOOST_VERSIONBITS_H
#include <chain.h>
#include <map>
/** What block version to use for new blocks (pre versionbits) */
static const int32_t VERSIONBITS_LAST_OLD_BLOCK_VERSION = 4;
/** What bits to set in version for versionbits blocks */
static const int32_t VERSIONBITS_TOP_BITS = 0x20000000UL;
/** What bitmask determines whether versionbits is in use */
static const int32_t VERSIONBITS_TOP_MASK = 0xE0000000UL;
/** Total bits available for versionbits */
static const int32_t VERSIONBITS_NUM_BITS = 29;
enum class ThresholdState {
DEFINED,
STARTED,
LOCKED_IN,
ACTIVE,
FAILED,
};
// A map that gives the state for blocks whose height is a multiple of Period().
// The map is indexed by the block's parent, however, so all keys in the map
// will either be nullptr or a block with (height + 1) % Period() == 0.
typedef std::map<const CBlockIndex*, ThresholdState> ThresholdConditionCache;
struct VBDeploymentInfo {
/** Deployment name */
const char *name;
/** Whether GBT clients can safely ignore this rule in simplified usage */
bool gbt_force;
};
struct BIP9Stats {
int period;
int threshold;
int elapsed;
int count;
bool possible;
};
extern const struct VBDeploymentInfo VersionBitsDeploymentInfo[];
/**
* Abstract class that implements BIP9-style threshold logic, and caches results.
*/
class AbstractThresholdConditionChecker {
protected:
virtual bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const =0;
virtual int64_t BeginTime(const Consensus::Params& params) const =0;
virtual int64_t EndTime(const Consensus::Params& params) const =0;
virtual int Period(const Consensus::Params& params) const =0;
virtual int Threshold(const Consensus::Params& params) const =0;
public:
BIP9Stats GetStateStatisticsFor(const CBlockIndex* pindex, const Consensus::Params& params) const;
// Note that the functions below take a pindexPrev as input: they compute information for block B based on its parent.
ThresholdState GetStateFor(const CBlockIndex* pindexPrev, const Consensus::Params& params, ThresholdConditionCache& cache) const;
int GetStateSinceHeightFor(const CBlockIndex* pindexPrev, const Consensus::Params& params, ThresholdConditionCache& cache) const;
};
struct VersionBitsCache
{
ThresholdConditionCache caches[Consensus::MAX_VERSION_BITS_DEPLOYMENTS];
void Clear();
};
ThresholdState VersionBitsState(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos, VersionBitsCache& cache);
BIP9Stats VersionBitsStatistics(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos);
int VersionBitsStateSinceHeight(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos, VersionBitsCache& cache);
uint32_t VersionBitsMask(const Consensus::Params& params, Consensus::DeploymentPos pos);
#endif // GLOBALBOOST_VERSIONBITS_H
| [
"null"
] | null |
fb08c0d2636672b54a4222a71083226d91ea9697 | e1071cd8065ed01b8bc42f5f47f964837ec723b8 | /src/ripple/ledger/ApplyView.h | 8c90ab09e0cde9dd2d05e251d724b2d31b69d0ec | [
"MIT-Wu",
"MIT",
"ISC",
"BSL-1.0"
] | permissive | SAN-CHAIN/sand | 07355acf0ba4607a5cb1408a1d86d87f03e3a317 | 1c51a7d1b215a7a2e1e06bd3b87a7e1da7239664 | refs/heads/master | 2020-06-22T01:27:21.168067 | 2016-10-15T11:22:18 | 2016-10-15T11:22:18 | 94,208,495 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 6,190 | h | //------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef RIPPLE_LEDGER_APPLYVIEW_H_INCLUDED
#define RIPPLE_LEDGER_APPLYVIEW_H_INCLUDED
#include <ripple/ledger/RawView.h>
#include <ripple/ledger/ReadView.h>
namespace ripple {
enum ApplyFlags
{
tapNONE = 0x00,
// Signature already checked
tapNO_CHECK_SIGN = 0x01,
// Enable supressed features for testing.
// This lets unit tests exercise code that
// is not turned on for production.
//
tapENABLE_TESTING = 0x02,
// This is not the transaction's last pass
// Transaction can be retried, soft failures allowed
tapRETRY = 0x20,
// Transaction came from a privileged source
tapADMIN = 0x400,
};
inline
ApplyFlags
operator|(ApplyFlags const& lhs,
ApplyFlags const& rhs)
{
return static_cast<ApplyFlags>(
static_cast<int>(lhs) |
static_cast<int>(rhs));
}
inline
ApplyFlags
operator&(ApplyFlags const& lhs,
ApplyFlags const& rhs)
{
return static_cast<ApplyFlags>(
static_cast<int>(lhs) &
static_cast<int>(rhs));
}
//------------------------------------------------------------------------------
/** Writeable view to a ledger, for applying a transaction.
This refinement of ReadView provides an interface where
the SLE can be "checked out" for modifications and put
back in an updated or removed state. Also added is an
interface to provide contextual information necessary
to calculate the results of transaction processing,
including the metadata if the view is later applied to
the parent (using an interface in the derived class).
The context info also includes values from the base
ledger such as sequence number and the network time.
This allows implementations to journal changes made to
the state items in a ledger, with the option to apply
those changes to the base or discard the changes without
affecting the base.
Typical usage is to call read() for non-mutating
operations.
For mutating operations the sequence is as follows:
// Add a new value
v.insert(sle);
// Check out a value for modification
sle = v.peek(k);
// Indicate that changes were made
v.update(sle)
// Or, erase the value
v.erase(sle)
The invariant is that insert, update, and erase may not
be called with any SLE which belongs to different view.
*/
class ApplyView
: public ReadView
{
public:
/** Returns the tx apply flags.
Flags can affect the outcome of transaction
processing. For example, transactions applied
to an open ledger generate "local" failures,
while transactions applied to the consensus
ledger produce hard failures (and claim a fee).
*/
virtual
ApplyFlags
flags() const = 0;
/** Prepare to modify the SLE associated with key.
Effects:
Gives the caller ownership of a modifiable
SLE associated with the specified key.
The returned SLE may be used in a subsequent
call to erase or update.
The SLE must not be passed to any other ApplyView.
@return `nullptr` if the key is not present
*/
virtual
std::shared_ptr<SLE>
peek (Keylet const& k) = 0;
/** Remove a peeked SLE.
Requirements:
`sle` was obtained from prior call to peek()
on this instance of the RawView.
Effects:
The key is no longer associated with the SLE.
*/
virtual
void
erase (std::shared_ptr<SLE> const& sle) = 0;
/** Insert a new state SLE
Requirements:
`sle` was not obtained from any calls to
peek() on any instances of RawView.
The SLE's key must not already exist.
Effects:
The key in the state map is associated
with the SLE.
The RawView acquires ownership of the shared_ptr.
@note The key is taken from the SLE
*/
virtual
void
insert (std::shared_ptr<SLE> const& sle) = 0;
/** Indicate changes to a peeked SLE
Requirements:
The SLE's key must exist.
`sle` was obtained from prior call to peek()
on this instance of the RawView.
Effects:
The SLE is updated
@note The key is taken from the SLE
*/
/** @{ */
virtual
void
update (std::shared_ptr<SLE> const& sle) = 0;
/** Get the number of modified entries
*/
virtual
std::size_t
size () = 0;
//--------------------------------------------------------------------------
// Called when a credit is made to an account
// This is required to support PaymentSandbox
virtual
void
creditHook (AccountID const& from,
AccountID const& to,
STAmount const& amount)
{
}
};
} // ripple
#endif
| [
"[email protected]"
] | |
710cc5465a8f1005f68b2025d414f2f897935b04 | 31ac07ecd9225639bee0d08d00f037bd511e9552 | /externals/OCCTLib/inc/StepVisual_ColourRgb.hxx | 314f72478c4c2ef2fc33810c2d891c44006b7f05 | [] | no_license | litao1009/SimpleRoom | 4520e0034e4f90b81b922657b27f201842e68e8e | 287de738c10b86ff8f61b15e3b8afdfedbcb2211 | refs/heads/master | 2021-01-20T19:56:39.507899 | 2016-07-29T08:01:57 | 2016-07-29T08:01:57 | 64,462,604 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,916 | hxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#ifndef _StepVisual_ColourRgb_HeaderFile
#define _StepVisual_ColourRgb_HeaderFile
#ifndef _Standard_HeaderFile
#include <Standard.hxx>
#endif
#ifndef _Standard_DefineHandle_HeaderFile
#include <Standard_DefineHandle.hxx>
#endif
#ifndef _Handle_StepVisual_ColourRgb_HeaderFile
#include <Handle_StepVisual_ColourRgb.hxx>
#endif
#ifndef _Standard_Real_HeaderFile
#include <Standard_Real.hxx>
#endif
#ifndef _StepVisual_ColourSpecification_HeaderFile
#include <StepVisual_ColourSpecification.hxx>
#endif
#ifndef _Handle_TCollection_HAsciiString_HeaderFile
#include <Handle_TCollection_HAsciiString.hxx>
#endif
class TCollection_HAsciiString;
class StepVisual_ColourRgb : public StepVisual_ColourSpecification {
public:
//! Returns a ColourRgb <br>
Standard_EXPORT StepVisual_ColourRgb();
Standard_EXPORT virtual void Init(const Handle(TCollection_HAsciiString)& aName) ;
Standard_EXPORT virtual void Init(const Handle(TCollection_HAsciiString)& aName,const Standard_Real aRed,const Standard_Real aGreen,const Standard_Real aBlue) ;
Standard_EXPORT void SetRed(const Standard_Real aRed) ;
Standard_EXPORT Standard_Real Red() const;
Standard_EXPORT void SetGreen(const Standard_Real aGreen) ;
Standard_EXPORT Standard_Real Green() const;
Standard_EXPORT void SetBlue(const Standard_Real aBlue) ;
Standard_EXPORT Standard_Real Blue() const;
DEFINE_STANDARD_RTTI(StepVisual_ColourRgb)
protected:
private:
Standard_Real red;
Standard_Real green;
Standard_Real blue;
};
// other Inline functions and methods (like "C++: function call" methods)
#endif
| [
"[email protected]"
] | |
b968362744c2d2e1d65238878d04021c9e45ecfb | 96d44e7e9ba85a38d44c204c58e93bf5fc4a546c | /for_spectra/auau15gev/tpcAnal/StRoot/StRefMultCorr/StRefMultCorr.h | 0b4f560303156126792af9651819524e068a19a5 | [] | no_license | ManukhovStepan/Aparin-laboratory | 00abfcb53d634de6026fbfa98009113db13a45f7 | b1072a7eb036e5cadf3388b8511f755c039dbb37 | refs/heads/master | 2022-11-28T01:17:57.519553 | 2020-08-11T08:59:47 | 2020-08-11T08:59:47 | 255,908,201 | 0 | 2 | null | 2020-08-11T08:59:49 | 2020-04-15T12:21:54 | C++ | UTF-8 | C++ | false | false | 8,217 | h | //------------------------------------------------------------------------------
// $Id: StRefMultCorr.h,v 1.1 2018/09/07 10:49:45 nasim Exp $
// $Log: StRefMultCorr.h,v $
// Revision 1.1 2018/09/07 10:49:45 nasim
// *** empty log message ***
//
// Revision 1.9 2015/05/22 06:52:07 hmasui
// Add grefmult for Run14 Au+Au 200 GeV
//
// Revision 1.8 2013/05/10 18:33:33 hmasui
// Add TOF tray mult, preliminary update for Run12 U+U
//
// Revision 1.7 2012/05/08 03:19:51 hmasui
// Move parameters to Centrality_def_refmult.txt
//
// Revision 1.6 2012/04/23 21:29:33 hmasui
// Added isBadRun() function for outlier rejection, getBeginRun() and getEndRun() to obtain the run range for a given (energy,year)
//
// Revision 1.5 2011/11/08 19:11:03 hmasui
// Add luminosity corrections for 200 GeV
//
// Revision 1.4 2011/10/11 19:35:18 hmasui
// Fix typo. Add z-vertex check in getWeight() function
//
// Revision 1.3 2011/10/10 21:30:34 hmasui
// Replaced hard coded parameters for z-vertex and weight corrections by input parameters from text file
//
// Revision 1.2 2011/08/12 20:28:04 hmasui
// Avoid varying corrected refmult in the same event by random number
//
// Revision 1.1 2011/08/11 18:38:36 hmasui
// First version of Refmult correction class
//
//------------------------------------------------------------------------------
// StRefMultCorr class
// - Provide centrality bins based on multiplicity (refmult, refmult2, tof tray mulitplicity etc)
// * 5% increment centrality bins (16 bins)
// * 5% increment in 0-10%, and 10% increment in 10-80% (9 bins)
// - Provide corrected multiplicity (z-vertex dependence)
// - Provide "re-weighting" correction, only relevant to the peripheral bins
//
// Centrality binning:
// Bin Centrality (16) Centrality (9)
// 0 75-80% 70-80%
// 1 70-75% 60-70%
// 2 65-70% 50-60%
// 3 60-65% 40-50%
// 4 55-60% 30-40%
// 5 50-55% 20-30%
// 6 45-50% 10-20%
// 7 40-45% 5-10%
// 8 35-40% 0- 5%
// 9 30-35%
// 10 25-30%
// 11 20-25%
// 12 15-20%
// 13 10-15%
// 14 5-10%
// 15 0- 5%
//
// See how to use this class in StRefMultCorr/macros/getCentralityBins.C
//
// authors: Alexander Schmah, Hiroshi Masui
//------------------------------------------------------------------------------
#ifndef __StRefMultCorr_h__
#define __StRefMultCorr_h__
#include <vector>
#include <map>
#include "TString.h"
//______________________________________________________________________________
// Class to correct z-vertex dependence, luminosity dependence of multiplicity
class StRefMultCorr {
public:
// Specify the type of multiplicity (default is refmult)
// "refmult" - reference multiplicity defined in |eta|<0.5
// "refmult2" - reference multiplicity defined in 0.5<|eta|<1.0
// "refmult3" - reference multiplicity defined in |eta|<0.5 without protons
// "toftray" - TOF tray multiplicity
// "grefmult" - global reference multiplicity defined in |eta|<0.5,dca<3,nHitsFit>10
StRefMultCorr(const TString name="refmult");
virtual ~StRefMultCorr(); /// Default destructor
// Bad run rejection
Bool_t isBadRun(const Int_t RunId) ;
// Event-by-event initialization. Call this function event-by-event
// * Default ZDC coincidence rate = 0 to make the function backward compatible
// --> i.e. no correction will be applied unless users set the values for 200 GeV
void initEvent(const UShort_t RefMult, const Double_t z,
const Double_t zdcCoincidenceRate=0.0) ; // Set multiplicity, vz and zdc coincidence rate
/// Get corrected multiplicity, correction as a function of primary z-vertex
Double_t getRefMultCorr() const;
// Corrected multiplity
// flag=0: Luminosity only
// flag=1: z-vertex only
// flag=2: full correction (default)
Double_t getRefMultCorr(const UShort_t RefMult, const Double_t z,
const Double_t zdcCoincidenceRate, const UInt_t flag=2) const ;
/// Get 16 centrality bins (5% increment, 0-5, 5-10, ..., 75-80)
Int_t getCentralityBin16() const;
/// Get 9 centrality bins (10% increment except for 0-5 and 5-10)
Int_t getCentralityBin9() const;
/// Re-weighting correction, correction is only applied up to mNormalize_step (energy dependent)
Double_t getWeight() const;
// Initialization of centrality bins etc
void init(const Int_t RunId);
// Read scale factor from text file
void setVzForWeight(const Int_t nbin, const Double_t min, const Double_t max) ;
void readScaleForWeight(const Char_t* input) ;
// Return begin/end run from energy and year
Int_t getBeginRun(const Double_t energy, const Int_t year) ;
Int_t getEndRun(const Double_t energy, const Int_t year) ;
// Print all parameters
void print(const Option_t* option="") const ;
private:
const TString mName ; // refmult, refmult2, refmult3 or toftray (case insensitive)
// Functions
void read() ; /// Read input parameters from text file StRoot/StRefMultCorr/Centrality_def.txt
void readBadRuns() ; /// Read bad run numbers
void clear() ; /// Clear all arrays
Bool_t isIndexOk() const ; /// 0 <= mParameterIndex < maxArraySize
Bool_t isZvertexOk() const ; /// mStart_zvertex < z < mStop_zvertex
Bool_t isRefMultOk() const ; /// 0-80%, (corrected multiplicity) > mCentrality_bins[0]
Bool_t isCentralityOk(const Int_t icent) const ; /// centrality bin check
Int_t setParameterIndex(const Int_t RunId) ; /// Parameter index from run id (return mParameterIndex)
// Special scale factor for Run14 to take into account the weight
// between different triggers
// - return 1 for all the other runs
Double_t getScaleForWeight() const ;
// Get table name based on the input multiplicity definition
const Char_t* getTable() const ;
// Data members
enum {
mNCentrality = 16, /// 16 centrality bins, starting from 75-80% with 5% bin width
mNPar_z_vertex = 8,
mNPar_weight = 8,
mNPar_luminosity = 2
};
// Use these variables to avoid varying the corrected multiplicity
// in the same event by random numbers
UShort_t mRefMult ; /// Current multiplicity
Double_t mVz ; /// Current primary z-vertex
Double_t mZdcCoincidenceRate ; /// Current ZDC coincidence rate
Double_t mRefMult_corr; /// Corrected refmult
std::vector<Int_t> mYear ; /// Year
std::vector<Int_t> mStart_runId ; /// Start run id
std::vector<Int_t> mStop_runId ; /// Stop run id
std::vector<Double_t> mStart_zvertex ; /// Start z-vertex (cm)
std::vector<Double_t> mStop_zvertex ; /// Stop z-vertex (cm)
std::vector<Double_t> mNormalize_stop ; /// Normalization between MC and data (normalized in refmult>mNormalize_stop)
std::vector<Int_t> mCentrality_bins[mNCentrality+1] ; /// Centrality bins (last value is set to 5000)
std::vector<Double_t> mPar_z_vertex[mNPar_z_vertex] ; /// parameters for z-vertex correction
std::vector<Double_t> mPar_weight[mNPar_weight] ; /// parameters for weight correction
std::vector<Double_t> mPar_luminosity[mNPar_luminosity] ; /// parameters for luminosity correction (valid only for 200 GeV)
Int_t mParameterIndex; /// Index of correction parameters
std::multimap<std::pair<Double_t, Int_t>, Int_t> mBeginRun ; /// Begin run number for a given (energy, year)
std::multimap<std::pair<Double_t, Int_t>, Int_t> mEndRun ; /// End run number for a given (energy, year)
std::vector<Int_t> mBadRun ; /// Bad run number list
// [6][680];
Int_t mnVzBinForWeight ; /// vz bin size for scale factor
std::vector<Double_t> mVzEdgeForWeight ; /// vz edge value
std::vector<Double_t> mgRefMultTriggerCorrDiffVzScaleRatio ; /// Scale factor for global refmult
ClassDef(StRefMultCorr, 0)
};
#endif
| [
"[email protected]"
] | |
9f30de5b08b44027dc3b197a5a0d3a685aebc4c0 | fb57dc0efeab3e51e6c59c8d58c654ac253c3ba9 | /Sharing/Src/Source/Common/Private/json/json_parsing.cpp | a47f3378e2a6f0cb628b8d34bffae5eddd693588 | [
"MIT"
] | permissive | microsoft/MixedRealityToolkit | aa7eddbeb36cbb5894beea32e2ff91cef29afcdf | 8454abcce504effd83c9d6e20725f6037c11e2b4 | refs/heads/main | 2023-07-08T11:15:38.879033 | 2023-06-28T19:21:12 | 2023-06-28T19:21:12 | 46,008,487 | 251 | 61 | MIT | 2023-06-28T19:21:13 | 2015-11-11T20:37:59 | C++ | UTF-8 | C++ | false | false | 31,445 | cpp | /***
* ==++==
*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ==--==
* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*
* json_parsing.cpp
*
* HTTP Library: JSON parser and writer
*
* For the latest on this and related APIs, please see http://casablanca.codeplex.com.
*
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
****/
#include "stdafx.h"
#include "./cpprest/json.h"
#include <vector>
#pragma warning(disable : 4127) // allow expressions like while(true) pass
using namespace web;
using namespace web::json;
using namespace utility;
using namespace utility::conversions;
int _hexval [] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 };
namespace web {
namespace json
{
namespace details
{
//
// JSON Parsing
//
template <typename Token>
#ifdef _MS_WINDOWS
__declspec(noreturn)
#else
__attribute__((noreturn))
#endif
void CreateError(const Token &tk, const utility::string_t &message)
{
utility::ostringstream_t os;
os << _XPLATSTR("* Line ") << tk.start.m_line << _XPLATSTR(", Column ") << tk.start.m_column << _XPLATSTR(" Syntax error: ") << message;
throw web::json::json_exception(os.str().c_str());
}
template <typename CharType>
class JSON_Parser
{
public:
JSON_Parser()
: m_currentLine(1),
m_eof(std::char_traits<CharType>::eof()),
m_currentColumn(1),
m_currentParsingDepth(0)
{ }
struct Location
{
size_t m_line;
size_t m_column;
};
struct Token
{
enum Kind
{
TKN_EOF,
TKN_OpenBrace,
TKN_CloseBrace,
TKN_OpenBracket,
TKN_CloseBracket,
TKN_Comma,
TKN_Colon,
TKN_StringLiteral,
TKN_NumberLiteral,
TKN_IntegerLiteral,
TKN_BooleanLiteral,
TKN_NullLiteral,
TKN_Comment
};
Token() : kind(TKN_EOF) {}
Kind kind;
std::basic_string<CharType> string_val;
typename JSON_Parser<CharType>::Location start;
union
{
double double_val;
int64_t int64_val;
uint64_t uint64_val;
bool boolean_val;
bool has_unescape_symbol;
};
bool signed_number;
};
void GetNextToken(Token &);
web::json::value ParseValue(typename JSON_Parser<CharType>::Token &first)
{
auto _value = _ParseValue(first);
#ifdef ENABLE_JSON_VALUE_VISUALIZER
auto type = _value->type();
#endif
return web::json::value(std::move(_value)
#ifdef ENABLE_JSON_VALUE_VISUALIZER
,type
#endif
);
}
protected:
virtual CharType NextCharacter() = 0;
virtual CharType PeekCharacter() = 0;
virtual bool CompleteComment(Token &token);
virtual bool CompleteStringLiteral(Token &token);
bool handle_unescape_char(Token &token);
private:
bool CompleteNumberLiteral(CharType first, Token &token);
bool ParseInt64(CharType first, uint64_t& value);
bool CompleteKeywordTrue(Token &token);
bool CompleteKeywordFalse(Token &token);
bool CompleteKeywordNull(Token &token);
std::unique_ptr<web::json::details::_Value> _ParseValue(typename JSON_Parser<CharType>::Token &first);
std::unique_ptr<web::json::details::_Object> _ParseObject(typename JSON_Parser<CharType>::Token &tkn);
std::unique_ptr<web::json::details::_Array> _ParseArray(typename JSON_Parser<CharType>::Token &tkn);
JSON_Parser& operator=(const JSON_Parser&);
CharType EatWhitespace();
void CreateToken(typename JSON_Parser<CharType>::Token& tk, typename Token::Kind kind, Location &start)
{
tk.kind = kind;
tk.start = start;
tk.string_val.clear();
}
void CreateToken(typename JSON_Parser<CharType>::Token& tk, typename Token::Kind kind)
{
tk.kind = kind;
tk.start.m_line = m_currentLine;
tk.start.m_column = m_currentColumn;
tk.string_val.clear();
}
protected:
size_t m_currentLine;
size_t m_currentColumn;
size_t m_currentParsingDepth;
#ifndef __APPLE__
static const size_t maxParsingDepth = 128;
#else
static const size_t maxParsingDepth = 32;
#endif
const typename std::char_traits<CharType>::int_type m_eof;
};
template <typename CharType>
class JSON_StreamParser : public JSON_Parser<CharType>
{
public:
JSON_StreamParser(std::basic_istream<CharType> &stream)
: m_streambuf(stream.rdbuf())
{
}
protected:
virtual CharType NextCharacter();
virtual CharType PeekCharacter();
private:
typename std::basic_streambuf<CharType, std::char_traits<CharType>>* m_streambuf;
};
template <typename CharType>
class JSON_StringParser : public JSON_Parser<CharType>
{
public:
JSON_StringParser(const std::basic_string<CharType>& string)
: m_position(&string[0])
{
m_startpos = m_position;
m_endpos = m_position+string.size();
}
protected:
virtual CharType NextCharacter();
virtual CharType PeekCharacter();
virtual bool CompleteComment(typename JSON_Parser<CharType>::Token &token);
virtual bool CompleteStringLiteral(typename JSON_Parser<CharType>::Token &token);
private:
bool finish_parsing_string_with_unescape_char(typename JSON_Parser<CharType>::Token &token);
const CharType* m_position;
const CharType* m_startpos;
const CharType* m_endpos;
};
template <typename CharType>
CharType JSON_StreamParser<CharType>::NextCharacter()
{
CharType ch = (CharType) m_streambuf->sbumpc();
if (ch == '\n')
{
this->m_currentLine += 1;
this->m_currentColumn = 0;
}
else
{
this->m_currentColumn += 1;
}
return (CharType)ch;
}
template <typename CharType>
CharType JSON_StreamParser<CharType>::PeekCharacter()
{
return (CharType)m_streambuf->sgetc();
}
template <typename CharType>
CharType JSON_StringParser<CharType>::NextCharacter()
{
if (m_position == m_endpos)
return (CharType)this->m_eof;
CharType ch = *m_position;
m_position += 1;
if ( ch == '\n' )
{
this->m_currentLine += 1;
this->m_currentColumn = 0;
}
else
{
this->m_currentColumn += 1;
}
return (CharType)ch;
}
template <typename CharType>
CharType JSON_StringParser<CharType>::PeekCharacter()
{
if ( m_position == m_endpos ) return (CharType)this->m_eof;
return (CharType)*m_position;
}
//
// Consume whitespace characters and return the first non-space character or EOF
//
template <typename CharType>
CharType JSON_Parser<CharType>::EatWhitespace()
{
CharType ch = NextCharacter();
while ( ch != this->m_eof && iswspace((int)ch) )
{
ch = NextCharacter();
}
return ch;
}
template <typename CharType>
bool JSON_Parser<CharType>::CompleteKeywordTrue(Token &token)
{
if (NextCharacter() != 'r')
return false;
if (NextCharacter() != 'u')
return false;
if (NextCharacter() != 'e')
return false;
token.kind = Token::TKN_BooleanLiteral;
token.boolean_val = true;
return true;
}
template <typename CharType>
bool JSON_Parser<CharType>::CompleteKeywordFalse(Token &token)
{
if (NextCharacter() != 'a')
return false;
if (NextCharacter() != 'l')
return false;
if (NextCharacter() != 's')
return false;
if (NextCharacter() != 'e')
return false;
token.kind = Token::TKN_BooleanLiteral;
token.boolean_val = false;
return true;
}
template <typename CharType>
bool JSON_Parser<CharType>::CompleteKeywordNull(Token &token)
{
if (NextCharacter() != 'u')
return false;
if (NextCharacter() != 'l')
return false;
if (NextCharacter() != 'l')
return false;
token.kind = Token::TKN_NullLiteral;
return true;
}
// Returns false only on overflow
template <typename CharType>
inline bool JSON_Parser<CharType>::ParseInt64(CharType first, uint64_t& value)
{
value = first - '0';
CharType ch = PeekCharacter();
while (ch >= '0' && ch <= '9')
{
int next_digit = ch - '0';
if (value > (ULLONG_MAX / 10) || (value == ULLONG_MAX/10 && next_digit > ULLONG_MAX%10))
return false;
NextCharacter();
value *= 10;
value += next_digit;
ch = PeekCharacter();
}
return true;
}
// This namespace hides the x-plat helper functions
namespace
{
#ifdef _MS_WINDOWS
static int print_llu(char* ptr, size_t n, uint64_t val64)
{
return _snprintf_s(ptr, n, _TRUNCATE, "%I64u", val64);
}
static int print_llu(wchar_t* ptr, size_t n, uint64_t val64)
{
return _snwprintf_s(ptr, n, _TRUNCATE, L"%I64u", val64);
}
static double anystod(const wchar_t* str) { return wcstod(str, nullptr); }
#else
static int print_llu(char* ptr, size_t n, unsigned long long val64)
{
return snprintf(ptr, n, "%llu", val64);
}
#endif
static double anystod(const char* str) { return strtod(str, nullptr); }
}
template <typename CharType>
bool JSON_Parser<CharType>::CompleteNumberLiteral(CharType first, Token &token)
{
bool minus_sign;
if (first == '-')
{
minus_sign = true;
first = NextCharacter();
}
else
{
minus_sign = false;
}
if (first < '0' || first > '9')
return false;
CharType ch = PeekCharacter();
//Check for two (or more) zeros at the begining
if (first == '0' && ch == '0')
return false;
// Parse the number assuming its integer
uint64_t val64;
bool complete = ParseInt64(first, val64);
ch = PeekCharacter();
if (complete && ch!='.' && ch!='E' && ch!='e')
{
if (minus_sign)
{
if (val64 > static_cast<uint64_t>(1) << 63 )
{
// It is negative and cannot be represented in int64, so we resort to double
token.double_val = 0 - static_cast<double>(val64);
token.signed_number = true;
token.kind = JSON_Parser<CharType>::Token::TKN_NumberLiteral;
return true;
}
// It is negative, but fits into int64
token.int64_val = 0 - static_cast<int64_t>(val64);
token.kind = JSON_Parser<CharType>::Token::TKN_IntegerLiteral;
token.signed_number = true;
return true;
}
// It is positive so we use unsigned int64
token.uint64_val = val64;
token.kind = JSON_Parser<CharType>::Token::TKN_IntegerLiteral;
token.signed_number = false;
return true;
}
// Magic number 5 leaves room for decimal point, null terminator, etc (in most cases)
::std::vector<CharType> buf(::std::numeric_limits<uint64_t>::digits10 + 5);
int count = print_llu(buf.data(), buf.size(), val64);
_ASSERTE(count >= 0);
_ASSERTE((size_t)count < buf.size());
// Resize to cut off the null terminator
buf.resize(count);
bool decimal = false;
while (ch != this->m_eof)
{
// Digit encountered?
if (ch >= '0' && ch <= '9')
{
buf.push_back(ch);
NextCharacter();
ch = PeekCharacter();
}
// Decimal dot?
else if (ch == '.')
{
if (decimal)
return false;
decimal = true;
buf.push_back(ch);
NextCharacter();
ch = PeekCharacter();
// Check that the following char is a digit
if (ch < '0' || ch > '9')
return false;
buf.push_back(ch);
NextCharacter();
ch = PeekCharacter();
}
// Exponent?
else if (ch == 'E' || ch == 'e')
{
buf.push_back(ch);
NextCharacter();
ch = PeekCharacter();
// Check for the exponent sign
if (ch == '+')
{
buf.push_back(ch);
NextCharacter();
ch = PeekCharacter();
}
else if (ch == '-')
{
buf.push_back(ch);
NextCharacter();
ch = PeekCharacter();
}
// First number of the exponent
if (ch >= '0' && ch <= '9')
{
buf.push_back(ch);
NextCharacter();
ch = PeekCharacter();
}
else return false;
// The rest of the exponent
while (ch >= '0' && ch <= '9')
{
buf.push_back(ch);
NextCharacter();
ch = PeekCharacter();
}
// The peeked character is not a number, so we can break from the loop and construct the number
break;
}
else
{
// Not expected number character?
break;
}
};
buf.push_back('\0');
token.double_val = anystod(buf.data());
if (minus_sign)
{
token.double_val = -token.double_val;
}
token.kind = (JSON_Parser<CharType>::Token::TKN_NumberLiteral);
return true;
}
template <typename CharType>
bool JSON_Parser<CharType>::CompleteComment(Token &token)
{
// We already found a '/' character as the first of a token -- what kind of comment is it?
CharType ch = NextCharacter();
if ( ch == this->m_eof || (ch != '/' && ch != '*') )
return false;
if ( ch == '/' )
{
// Line comment -- look for a newline or EOF to terminate.
ch = NextCharacter();
while ( ch != this->m_eof && ch != '\n')
{
ch = NextCharacter();
}
}
else
{
// Block comment -- look for a terminating "*/" sequence.
ch = NextCharacter();
while ( true )
{
if ( ch == this->m_eof )
return false;
if ( ch == '*' )
{
CharType ch1 = PeekCharacter();
if ( ch1 == this->m_eof )
return false;
if ( ch1 == '/' )
{
// Consume the character
NextCharacter();
break;
}
ch = ch1;
}
ch = NextCharacter();
}
}
token.kind = Token::TKN_Comment;
return true;
}
template <typename CharType>
bool JSON_StringParser<CharType>::CompleteComment(typename JSON_Parser<CharType>::Token &token)
{
// This function is specialized for the string parser, since we can be slightly more
// efficient in copying data from the input to the token: do a memcpy() rather than
// one character at a time.
CharType ch = JSON_StringParser<CharType>::NextCharacter();
if ( ch == this->m_eof || (ch != '/' && ch != '*') )
return false;
if ( ch == '/' )
{
// Line comment -- look for a newline or EOF to terminate.
ch = JSON_StringParser<CharType>::NextCharacter();
while ( ch != this->m_eof && ch != '\n')
{
ch = JSON_StringParser<CharType>::NextCharacter();
}
}
else
{
// Block comment -- look for a terminating "*/" sequence.
ch = JSON_StringParser<CharType>::NextCharacter();
while ( true )
{
if ( ch == this->m_eof )
return false;
if ( ch == '*' )
{
ch = JSON_StringParser<CharType>::PeekCharacter();
if ( ch == this->m_eof )
return false;
if ( ch == '/' )
{
// Consume the character
JSON_StringParser<CharType>::NextCharacter();
break;
}
}
ch = JSON_StringParser<CharType>::NextCharacter();
}
}
token.kind = JSON_Parser<CharType>::Token::TKN_Comment;
return true;
}
template <typename CharType>
inline bool JSON_Parser<CharType>::handle_unescape_char(Token &token)
{
// This function converts unescape character pairs (e.g. "\t") into their ASCII or UNICODE representations (e.g. tab sign)
// Also it handles \u + 4 hexadecimal digits
CharType ch = NextCharacter();
switch (ch)
{
case '\"':
token.string_val.push_back('\"');
return true;
case '\\':
token.string_val.push_back('\\');
return true;
case '/':
token.string_val.push_back('/');
return true;
case 'b':
token.string_val.push_back('\b');
return true;
case 'f':
token.string_val.push_back('\f');
return true;
case 'r':
token.string_val.push_back('\r');
return true;
case 'n':
token.string_val.push_back('\n');
return true;
case 't':
token.string_val.push_back('\t');
return true;
case 'u':
{
// A four-hexdigit unicode character
int decoded = 0;
for (int i = 0; i < 4; ++i)
{
ch = NextCharacter();
if (!isxdigit((unsigned char) (ch)))
return false;
int val = _hexval[ch];
_ASSERTE(val != -1);
// Add the input char to the decoded number
decoded |= (val << (4 * (3 - i)));
}
// Construct the character based on the decoded number
ch = static_cast<CharType>(decoded & 0xFFFF);
token.string_val.push_back(ch);
return true;
}
default:
return false;
}
}
template <typename CharType>
bool JSON_Parser<CharType>::CompleteStringLiteral(Token &token)
{
CharType ch = NextCharacter();
while ( ch != '"' )
{
if ( ch == '\\' )
{
handle_unescape_char(token);
}
else if (ch >= CharType(0x0) && ch < CharType(0x20))
{
return false;
}
else
{
if (ch == this->m_eof)
return false;
token.string_val.push_back(ch);
}
ch = NextCharacter();
}
if ( ch == '"' )
{
token.kind = Token::TKN_StringLiteral;
}
else
{
return false;
}
return true;
}
template <typename CharType>
bool JSON_StringParser<CharType>::CompleteStringLiteral(typename JSON_Parser<CharType>::Token &token)
{
// This function is specialized for the string parser, since we can be slightly more
// efficient in copying data from the input to the token: do a memcpy() rather than
// one character at a time.
auto start = m_position;
token.has_unescape_symbol = false;
CharType ch = JSON_StringParser<CharType>::NextCharacter();
while (ch != '"')
{
if (ch == this->m_eof)
return false;
if (ch == '\\')
{
token.string_val.resize(m_position - start - 1);
if (token.string_val.size() > 0)
memcpy(&token.string_val[0], start, (m_position - start - 1)*sizeof(CharType));
token.has_unescape_symbol = true;
return finish_parsing_string_with_unescape_char(token);
}
else if (ch >= CharType(0x0) && ch < CharType(0x20))
{
return false;
}
ch = JSON_StringParser<CharType>::NextCharacter();
}
token.string_val.resize(m_position - start - 1);
if (token.string_val.size() > 0)
memcpy(&token.string_val[0], start, (m_position - start - 1)*sizeof(CharType));
token.kind = JSON_Parser<CharType>::Token::TKN_StringLiteral;
return true;
}
template <typename CharType>
bool JSON_StringParser<CharType>::finish_parsing_string_with_unescape_char(typename JSON_Parser<CharType>::Token &token)
{
// This function handles parsing the string when an unescape character is encountered.
// It is called once the part before the unescape char is copied to the token.string_val string
CharType ch;
if (!JSON_StringParser<CharType>::handle_unescape_char(token))
return false;
while ((ch = JSON_StringParser<CharType>::NextCharacter()) != '"')
{
if (ch == '\\')
{
if (!JSON_StringParser<CharType>::handle_unescape_char(token))
return false;
}
else
{
if (ch == this->m_eof)
return false;
token.string_val.push_back(ch);
}
}
token.kind = JSON_StringParser<CharType>::Token::TKN_StringLiteral;
return true;
}
template <typename CharType>
void JSON_Parser<CharType>::GetNextToken(typename JSON_Parser<CharType>::Token& result)
{
try_again:
CharType ch = EatWhitespace();
CreateToken(result, Token::TKN_EOF);
if (ch == this->m_eof) return;
switch (ch)
{
case '{':
case '[':
{
if(++m_currentParsingDepth > JSON_Parser<CharType>::maxParsingDepth)
{
CreateError(result, _XPLATSTR("Nesting too deep!"));
break;
}
typename JSON_Parser<CharType>::Token::Kind tk = ch == '{' ? Token::TKN_OpenBrace : Token::TKN_OpenBracket;
CreateToken(result, tk, result.start);
break;
}
case '}':
case ']':
{
if((signed int)(--m_currentParsingDepth) < 0)
{
CreateError(result, _XPLATSTR("Mismatched braces!"));
break;
}
typename JSON_Parser<CharType>::Token::Kind tk = ch == '}' ? Token::TKN_CloseBrace : Token::TKN_CloseBracket;
CreateToken(result, tk, result.start);
break;
}
case ',':
CreateToken(result, Token::TKN_Comma, result.start);
break;
case ':':
CreateToken(result, Token::TKN_Colon, result.start);
break;
case 't':
if (!CompleteKeywordTrue(result)) CreateError(result, _XPLATSTR("Malformed literal"));
break;
case 'f':
if (!CompleteKeywordFalse(result)) CreateError(result, _XPLATSTR("Malformed literal"));
break;
case 'n':
if (!CompleteKeywordNull(result)) CreateError(result, _XPLATSTR("Malformed literal"));
break;
case '/':
if ( !CompleteComment(result) ) CreateError(result, _XPLATSTR("Malformed comment"));
// For now, we're ignoring comments.
goto try_again;
case '"':
if ( !CompleteStringLiteral(result) ) CreateError(result, _XPLATSTR("Malformed string literal"));
break;
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if ( !CompleteNumberLiteral(ch, result) ) CreateError(result, _XPLATSTR("Malformed numeric literal"));
break;
default:
CreateError(result, _XPLATSTR("Malformed token"));
break;
}
}
template <typename CharType>
std::unique_ptr<web::json::details::_Object> JSON_Parser<CharType>::_ParseObject(typename JSON_Parser<CharType>::Token &tkn)
{
GetNextToken(tkn);
auto obj = utility::details::make_unique<web::json::details::_Object>(g_keep_json_object_unsorted);
auto& elems = obj->m_object.m_elements;
if ( tkn.kind != JSON_Parser<CharType>::Token::TKN_CloseBrace )
{
while ( true )
{
// State 1: New field or end of object, looking for field name or closing brace
std::basic_string<CharType> fieldName;
switch ( tkn.kind )
{
case JSON_Parser<CharType>::Token::TKN_StringLiteral:
fieldName = std::move(tkn.string_val);
break;
default:
goto error;
}
GetNextToken(tkn);
// State 2: Looking for a colon.
if ( tkn.kind != JSON_Parser<CharType>::Token::TKN_Colon ) goto done;
GetNextToken(tkn);
// State 3: Looking for an expression.
#ifdef ENABLE_JSON_VALUE_VISUALIZER
auto fieldValue = _ParseValue(tkn);
auto type = fieldValue->type();
elems.emplace_back(utility::conversions::to_string_t(std::move(fieldName)), json::value(std::move(fieldValue), type));
#else
elems.emplace_back(utility::conversions::to_string_t(std::move(fieldName)), json::value(_ParseValue(tkn)));
#endif
// State 4: Looking for a comma or a closing brace
switch (tkn.kind)
{
case JSON_Parser<CharType>::Token::TKN_Comma:
GetNextToken(tkn);
break;
case JSON_Parser<CharType>::Token::TKN_CloseBrace:
goto done;
default:
goto error;
}
}
}
done:
GetNextToken(tkn);
if (!g_keep_json_object_unsorted) {
::std::sort(elems.begin(), elems.end(), json::object::compare_pairs);
}
return obj;
error:
CreateError(tkn, _XPLATSTR("Malformed object literal"));
}
template <typename CharType>
std::unique_ptr<web::json::details::_Array> JSON_Parser<CharType>::_ParseArray(typename JSON_Parser<CharType>::Token &tkn)
{
GetNextToken(tkn);
auto result = utility::details::make_unique<web::json::details::_Array>();
if ( tkn.kind != JSON_Parser<CharType>::Token::TKN_CloseBracket )
{
while ( true )
{
// State 1: Looking for an expression.
result->m_array.m_elements.emplace_back(ParseValue(tkn));
// State 4: Looking for a comma or a closing bracket
switch (tkn.kind)
{
case JSON_Parser<CharType>::Token::TKN_Comma:
GetNextToken(tkn);
break;
case JSON_Parser<CharType>::Token::TKN_CloseBracket:
GetNextToken(tkn);
return result;
default:
CreateError(tkn, _XPLATSTR("Malformed array literal"));
}
}
}
GetNextToken(tkn);
return result;
}
template <typename CharType>
std::unique_ptr<web::json::details::_Value> JSON_Parser<CharType>::_ParseValue(typename JSON_Parser<CharType>::Token &tkn)
{
switch (tkn.kind)
{
case JSON_Parser<CharType>::Token::TKN_OpenBrace:
return _ParseObject(tkn);
case JSON_Parser<CharType>::Token::TKN_OpenBracket:
return _ParseArray(tkn);
case JSON_Parser<CharType>::Token::TKN_StringLiteral:
{
auto value = utility::details::make_unique<web::json::details::_String>(std::move(tkn.string_val), tkn.has_unescape_symbol);
GetNextToken(tkn);
return std::move(value);
}
case JSON_Parser<CharType>::Token::TKN_IntegerLiteral:
{
std::unique_ptr<web::json::details::_Number> value;
if (tkn.signed_number)
value = utility::details::make_unique<web::json::details::_Number>(tkn.int64_val);
else
value = utility::details::make_unique<web::json::details::_Number>(tkn.uint64_val);
GetNextToken(tkn);
return std::move(value);
}
case JSON_Parser<CharType>::Token::TKN_NumberLiteral:
{
auto value = utility::details::make_unique<web::json::details::_Number>(tkn.double_val);
GetNextToken(tkn);
return std::move(value);
}
case JSON_Parser<CharType>::Token::TKN_BooleanLiteral:
{
auto value = utility::details::make_unique<web::json::details::_Boolean>(tkn.boolean_val);
GetNextToken(tkn);
return std::move(value);
}
case JSON_Parser<CharType>::Token::TKN_NullLiteral:
{
GetNextToken(tkn);
return utility::details::make_unique<web::json::details::_Null>();
}
default:
CreateError(tkn, _XPLATSTR("Unexpected token"));
}
}
}}}
static web::json::value _parse_stream(utility::istream_t &stream)
{
web::json::details::JSON_StreamParser<utility::char_t> parser(stream);
web::json::details::JSON_Parser<utility::char_t>::Token tkn;
parser.GetNextToken(tkn);
auto value = parser.ParseValue(tkn);
if ( tkn.kind != web::json::details::JSON_Parser<utility::char_t>::Token::TKN_EOF )
{
web::json::details::CreateError(tkn, _XPLATSTR("Left-over characters in stream after parsing a JSON value"));
}
return value;
}
#ifdef _MS_WINDOWS
static web::json::value _parse_narrow_stream(std::istream &stream)
{
web::json::details::JSON_StreamParser<char> parser(stream);
web::json::details::JSON_StreamParser<char>::Token tkn;
parser.GetNextToken(tkn);
auto value = parser.ParseValue(tkn);
if ( tkn.kind != web::json::details::JSON_Parser<char>::Token::TKN_EOF )
{
web::json::details::CreateError(tkn, _XPLATSTR("Left-over characters in stream after parsing a JSON value"));
}
return value;
}
#endif
web::json::value web::json::value::parse(const utility::string_t& str)
{
web::json::details::JSON_StringParser<utility::char_t> parser(str);
web::json::details::JSON_Parser<utility::char_t>::Token tkn;
parser.GetNextToken(tkn);
auto value = parser.ParseValue(tkn);
if (tkn.kind != web::json::details::JSON_Parser<utility::char_t>::Token::TKN_EOF)
{
web::json::details::CreateError(tkn, _XPLATSTR("Left-over characters in stream after parsing a JSON value"));
}
return value;
}
web::json::value web::json::value::parse(utility::istream_t &stream)
{
return _parse_stream(stream);
}
#ifdef _MS_WINDOWS
web::json::value web::json::value::parse(std::istream& stream)
{
return _parse_narrow_stream(stream);
}
#endif
| [
"[email protected]"
] | |
79f0b9167ead7bc77891775ab3a98bbe58afec88 | fc2d01d1afa08ffc46c23901163c37e679c3beaf | /Core/StdFile.cpp | 533d3729043f127ca134fd910935909cd517be4f | [] | no_license | seblef/ShadowEngine | a9428607b49cdd41eb22dcbd8504555454e26a0c | fba95e910c63269bfe0a05ab639dc78b6c16ab8b | refs/heads/master | 2023-02-14T19:08:25.878492 | 2021-01-08T16:16:44 | 2021-01-08T16:16:44 | 113,681,956 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 297 | cpp |
#include "StdFile.h"
using namespace Core;
bool StdFile::seek(size_t offset, FileSeek fs)
{
ios::seekdir sd;
switch(fs)
{
case FS_START: sd=ios::beg; break;
case FS_END: sd=ios::end; break;
default: sd=ios::cur;
}
_fs.seekp(offset,sd);
return _fs.good();
}
| [
"[email protected]"
] | |
673a7db6492227e1c1996b24178c3487367db332 | f75d79c35ee9c42213837405efb0489ef95dff4a | /C867/securityStudent.h | 94e4da17a8c4d659bd59057e518d829c7cacb8c9 | [] | no_license | djok1/C867 | 398951964038a6a9c1c4b95fa008ae21bd7901f1 | b8234c59c361757709da95ec964ceb3a5b767f9c | refs/heads/master | 2022-10-29T10:13:27.146076 | 2019-09-09T04:58:59 | 2019-09-09T04:58:59 | 202,541,307 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 414 | h | #pragma once
#include "student.h"
class securityStudent :
public student
{
private:
DegreeType degreeType = security;
public:
string getDegreeType()
{
return "Security";
}
securityStudent(string StudentID, string FirstName, string LastName, string Email, string Age, string Days1, string Days2, string Days3) :student(StudentID, FirstName, LastName, Email, Age, Days1, Days2, Days3)
{
}
};
| [
"[email protected]"
] | |
cbb5ea0f6eadede1af2ce6a67dcdc7b751de9331 | eabffc4df9bcb5b98a64242c544f45be4bfe85f3 | /Project_Uno/Project_Uno_Tos/Uno_V14/main.cpp | 6b64bc2e2fab20f79e72f32b95c13d6d37f425a9 | [] | no_license | Dredz223/Fall_Class_2018_Csc5 | 7d1086a8fc31a6cd3151bc5adfd68a9f247575a9 | 8c404cbfd560293b3558b474bc10d2fd961eae48 | refs/heads/master | 2020-04-04T22:33:47.099653 | 2018-12-15T02:51:18 | 2018-12-15T02:51:18 | 156,328,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,609 | cpp | /*
* File: main.cpp
* Author: Andres Guerrero Maldonado
* Created on December 9th, 2018 8:40PM
* Purpose: Uno Project_V14
*
*/
//System Libraries
#include <iostream> //I/O Library -> cout,endl
#include <cstdlib> //Random Library
#include <cstring> //String Library
#include <ctime> //Time Library
#include <fstream> //Stream Library
#include <iomanip> //I/o Manip Library
#include <cmath> //Math Library
using namespace std;//namespace I/O stream library created
//User Libraries
//Global Constants
//Math, Physics, Science, Conversions, 2-D Array Columns
//Function Prototypes
void Rules(); //Rules function
void filDeck(string [],int); //Fill the deck 1-9, Red, Green, Blue, Yellow
void prnDeck(string [],int,int); //Print the Deck of Cards
void shuffle(string [],int,int); //Shuffle the Deck
//Execution Begins Here!
int main(int argc, char** argv) {
//Initialize random seed
srand(static_cast<unsigned int>(time(0)));
//Declare Variables
const int NUMCRDS=72; //Size of the Deck
const int NUMCRDZ=57; //Size of the Deck that will be randomized
int n2Shufl=7; //How many times to Shuffle the Deck
string deck[NUMCRDS]; //72 Cards represented as a string Face|Suit
string hand1; //Hand 1 display 7 cards
string strtCD,tempCD; //Starting card where we compare to other hands
string player1,player2;//Player Names
string tempN,tempC;
string null[NUMCRDS]; //array with no values
int numhnd=7,tempH1,tempH2;
bool end, //End Condition
turn, //Used when player 1 is skipped and to not repeat p2's turn
lturn; //Used to not repeat p2's turn after already played
int count=2; //used to force end game
float pnts; //Points awarded
//Displays Rules
Rules();
cout<<endl;
//Ask the players for their name
cout<<"This is a game of UNO!"<<endl;
cout<<"Enter the names of the 2 players!"<<endl;
cin>>player1>>player2;//Insert the names of the players
//Initial Variables
filDeck(deck,NUMCRDS);
//Print the Cards
cout<<"Fresh Deck of Cards before Shuffling"<<endl;
prnDeck(deck,NUMCRDS,NUMCRDS/8);
//Print the Cards
shuffle(deck,NUMCRDS,n2Shufl);
//Print the Cards
cout<<"Deck of Cards after Shuffling"<<endl;
prnDeck(deck,NUMCRDS,NUMCRDS/8);
//Getting Starting card
strtCD=deck[14+rand()%(NUMCRDZ)];
cout<<"The starting card is: "<<strtCD<<endl;
//Hand 1 display 7 cards
cout<<"============================================="<<endl;
cout<<player1<<"'s hand is: "<<endl;
for(int i=0;i<7;i++){
cout<<"Card "<<i+1<<": "<<deck[i]<<endl;
}
string card1 = deck[0];
string card2 = deck[1];
string card3 = deck[2];
string card4 = deck[3];
string card5 = deck[4];
string card6 = deck[5];
string card7 = deck[6];
cout<<"============================================="<<endl;
//Hand 2 display 7 cards
cout<<player2<<"'s hand is: "<<endl;
for(int i=7;i<14;i++){
cout<<"Card "<<i-6<<": "<<deck[i]<<endl;
}
string card8 = deck[7];
string card9 = deck[8];
string card10 = deck[9];
string card11 = deck[10];
string card12 = deck[11];
string card13 = deck[12];
string card14 = deck[13];
cout<<"============================================="<<endl;
//return 0;
//Initialize Variables
end = false; //condition to end the game
//Map/Process Inputs to Outputs
//Display Player names
cout<<"Players: "<<player1<<", "<<player2<<endl;
//Display starting deck
cout<<"The starting card for the game is: "<<strtCD<<endl;
cout<<"============================================="<<endl;
//Player one goes first card 1-7 check
//Start if statement with a color check
//card[1] represents color, cards[0] represents number
//Player 1 goes first
cout<<player1<<"'s turn"<<endl;
if(card1[1] == strtCD[1] || card1[0] == strtCD[0]){
tempN = card1[0];
tempC = card1[1];
tempCD = card1;
card1 = null[0];
tempH1 = numhnd -1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player1<<"'s hand is "
<<tempH1<<endl;
cout<<"============================================="<<endl;
}
else if(card2[1] == strtCD[1] || card2[0] == strtCD[0]){
tempN = card2[0];
tempC = card2[1];
tempCD = card2;
card2 = null[1];
tempH1 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player1<<"'s hand is "
<<tempH1<<endl;
cout<<"============================================="<<endl;
}
else if(card3[1] == strtCD[1] || card3[0] == strtCD[0]){
tempN = card3[0];
tempC = card3[1];
tempCD = card3;
card3 = null[2];
tempH1 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player1<<"'s hand is "
<<tempH1<<endl;
cout<<"============================================="<<endl;
}
else if(card4[1] == strtCD[1] || card4[0] == strtCD[0]){
tempN = card4[0];
tempC = card4[1];
tempCD = card4;
card4 = null[3];
tempH1 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player1<<"'s hand is "
<<tempH1<<endl;
cout<<"============================================="<<endl;
}
else if(card5[1] == strtCD[1] || card5[0] == strtCD[0]){
tempN = card5[0];
tempC = card5[1];
tempCD = card5;
card5 = null[4];
tempH1 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player1<<"'s hand is "
<<tempH1<<endl;
cout<<"============================================="<<endl;
}
else if(card6[1] == strtCD[1] || card6[0] == strtCD[0]){
tempN = card6[0];
tempC = card6[1];
tempCD = card6;
card6 = null[5];
tempH1 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player1<<"'s hand is "
<<tempH1<<endl;
cout<<"============================================="<<endl;
}
else if(card7[1] == strtCD[1] || card7[0] == strtCD[0]){
tempN = card7[0];
tempC = card7[1];
tempCD = card7;
card7 = null[6];
tempH1 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player1<<"'s hand is "
<<tempH1<<endl;
cout<<"============================================="<<endl;
}
else{
cout<<"No cards available to play!!!"<<endl;
cout<<"The number of cards left in "<<player1<<"'s current hand is "
<<numhnd<<endl;
cout<<"============================================="<<endl;
cout<<player1<<"'s turn is skipped"<<endl;
//Player 2's turn if player 1 was skipped
cout<<player2<<"'s turn"<<endl;
if(card8[1] == strtCD[1] || card8[0] == strtCD[0]){
tempN = card8[0];
tempC = card8[1];
tempCD = card8;
card8 = null[7];
tempH2 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
cout<<"============================================="<<endl;
turn = false;
}
else if(card9[1] == strtCD[1] || card9[0] == strtCD[0]){
tempN = card9[0];
tempC = card9[1];
tempCD = card9;
card9 = null[8];
tempH2 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
cout<<"============================================="<<endl;
turn = false;
}
else if(card10[1] == strtCD[1] || card10[0] == strtCD[0]){
tempN = card10[0];
tempC = card10[1];
tempCD = card10;
card10 = null[9];
tempH2 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
cout<<"============================================="<<endl;
turn = false;
}
else if(card11[1] == strtCD[1] || card11[0] == strtCD[0]){
tempN = card11[0];
tempC = card11[1];
tempCD = card11;
card11 = null[10];
tempH2 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
cout<<"============================================="<<endl;
turn = false;
}
else if(card12[1] == strtCD[1] || card12[0] == strtCD[0]){
tempN = card12[0];
tempC = card12[1];
tempCD = card12;
card12 = null[11];
tempH2 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
cout<<"============================================="<<endl;
turn = false;
}
else if(card13[1] == strtCD[1] || card13[0] == strtCD[0]){
tempN = card13[0];
tempC = card13[1];
tempCD = card13;
card13 = null[12];
tempH2 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
cout<<"============================================="<<endl;
turn = false;
}
else if(card14[1] == strtCD[1] || card14[0] == strtCD[0]){
tempN = card14[0];
tempC = card14[1];
tempCD = card14;
card14 = null[13];
tempH2 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
cout<<"============================================="<<endl;
turn = false;
}
else{
cout<<"No cards available!!!"<<endl;
//cout<<player2<<"'s current hand is "<<hand<<endl;
cout<<player2<<"'s turn skipped"<<endl;
cout<<"============================================="<<endl;
turn = false;
}
}
//Player 2 after player 1 had played a card
cout<<player2<<"'s turn"<<endl;
do{
if(card8[1] == tempCD[1] || card8[0] == tempCD[0]){
tempN = card8[0];
tempC = card8[1];
tempCD = card8;
card8 = null[0];
tempH2 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
turn = false;
cout<<"============================================="<<endl;
}
else if(card9[1] == tempCD[1] || card9[0] == tempCD[0]){
tempN = card9[0];
tempC = card9[1];
tempCD = card9;
card9 = null[0];
tempH2 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
turn = false;
cout<<"============================================="<<endl;
}
else if(card10[1] == tempCD[1] || card10[0] == tempCD[0]){
tempN = card10[0];
tempC = card10[1];
tempCD = card10;
card10 = null[0];
tempH2 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
turn = false;
cout<<"============================================="<<endl;
}
else if(card11[1] == tempCD[1] || card11[0] == tempCD[0]){
tempN = card11[0];
tempC = card11[1];
tempCD = card11;
card11 = null[0];
tempH2 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
turn = false;
cout<<"============================================="<<endl;
}
else if(card12[1] == tempCD[1] || card12[0] == tempCD[0]){
tempN = card12[0];
tempC = card12[1];
tempCD = card12;
card12 = null[0];
tempH2 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
turn = false;
cout<<"============================================="<<endl;
}
else if(card13[1] == tempCD[1] || card13[0] == tempCD[0]){
tempN = card13[0];
tempC = card13[1];
tempCD = card13;
card13 = null[0];
tempH2 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
turn = false;
cout<<"============================================="<<endl;
}
else if(card14[1] == tempCD[1] || card14[0] == tempCD[0]){
tempN = card14[0];
tempC = card14[1];
tempCD = card14;
card14 = null[0];
tempH2 = numhnd - 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
turn = false;
cout<<"============================================="<<endl;
}
else{
cout<<"No cards available!!!"<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
turn = false;
cout<<"============================================="<<endl;
cout<<player2<<"'s turn skipped"<<endl;
}
}while(turn);
//MAJOR DO WHILE LOOP AHEAD
//Repeat loop turn 2 and beyond until player a has 1 card and says "UNO"
do{
cout<<player1<<"'s turn"<<endl;
if(card1[1] == tempCD[1] || card1[0] == tempCD[0]){
tempN = card1[0];
tempC = card1[1];
tempCD = card1;
card1 = null[0];
tempH1 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player1<<"'s hand is "
<<tempH1<<endl;
cout<<"============================================="<<endl;
}
else if(card2[1] == tempCD[1] || card2[0] == tempCD[0]){
tempN = card2[0];
tempC = card2[1];
tempCD = card2;
card2 = null[0];
tempH1 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player1<<"'s hand is "
<<tempH1<<endl;
cout<<"============================================="<<endl;
}
else if(card3[1] == tempCD[1] || card3[0] == tempCD[0]){
tempN = card3[0];
tempC = card3[1];
tempCD = card3;
card3 = null[0];
tempH1 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player1<<"'s hand is "
<<tempH1<<endl;
cout<<"============================================="<<endl;
}
else if(card4[1] == tempCD[1] || card4[0] == tempCD[0]){
tempN = card4[0];
tempC = card4[1];
tempCD= card4;
tempH1 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player1<<"'s hand is "
<<tempH1<<endl;
cout<<"============================================="<<endl;
}
else if(card5[1] == tempCD[1] || card5[0] == tempCD[0]){
tempN = card5[0];
tempC = card5[1];
tempCD = card5;
card5 = null[0];
tempH1 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player1<<"'s hand is "
<<tempH1<<endl;
cout<<"============================================="<<endl;
}
else if(card6[1] == tempCD[1] || card6[0] == tempCD[0]){
tempN = card6[0];
tempC = card6[1];
tempCD = card6;
card6 = null[0];
tempH1 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player1<<"'s hand is "
<<tempH1<<endl;;
cout<<"============================================="<<endl;
}
else if(card7[1] == tempCD[1] || card7[0] == tempCD[0]){
tempN = card7[0];
tempC = card7[1];
tempCD = card7;
card7 = null[0];
tempH1 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player1<<"'s hand is "
<<tempH1<<endl;
cout<<"============================================="<<endl;
}
else{
cout<<"No cards available to play!!!"<<endl;
//cout<<player1<<"'s current hand is "<<hand<<endl;
cout<<player1<<"'s turn is skipped"<<endl;
cout<<"============================================="<<endl;
//Player 2's turn if player 1 was skipped
cout<<player2<<"'s turn"<<endl;
if(card8[1] == tempCD[1] || card8[0] == tempCD[0]){
tempN = card8[0];
tempC = card8[1];
tempCD = card8;
card8 = null[0];
tempH2 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
lturn = false;
cout<<"============================================="<<endl;
}
else if(card9[1] == tempCD[1] || card9[0] == tempCD[0]){
tempN = card9[0];
tempC = card9[1];
tempCD = card9;
card9 = null[0];
tempH2 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
lturn = false;
cout<<"============================================="<<endl;
}
else if(card10[1] == tempCD[1] || card10[0] == tempCD[0]){
tempN = card10[0];
tempC = card10[1];
tempCD = card10;
card10 = null[0];
tempH2 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
lturn = false;
cout<<"============================================="<<endl;
}
else if(card11[1] == tempCD[1] || card11[0] == tempCD[0]){
tempN = card11[0];
tempC = card11[1];
tempCD = card11;
card11 = null[0];
tempH2 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
lturn = false;
cout<<"============================================="<<endl;
}
else if(card12[1] == tempCD[1] || card12[0] == tempCD[0]){
tempN = card12[0];
tempC = card12[1];
tempCD = card12;
card12 = null[0];
tempH2 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
lturn = false;
cout<<"============================================="<<endl;
}
else if(card13[1] == tempCD[1] || card13[0] == tempCD[0]){
tempN = card13[0];
tempC = card13[1];
tempCD = card13;
card13 = null[0];
tempH2 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
lturn = false;
cout<<"============================================="<<endl;
}
else if(card14[1] == tempCD[1] || card14[0] == tempCD[0]){
tempN = card14[0];
tempC = card14[1];
tempCD = card14;
card14 = null[0];
tempH2 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
lturn = false;
cout<<"============================================="<<endl;
}
else{
cout<<"No cards available!!!"<<endl;
//cout<<player2<<"'s current hand is "<<hand<<endl;
cout<<player2<<"'s turn skipped"<<endl;
cout<<"============================================="<<endl;
}
}
//says uno for player 1
if(tempH1 == 1){
cout<<player1<<" UNO!!!"<<endl;
cout<<"============================================="<<endl;
}
//Player 2 if player 1 plays a card
cout<<player2<<"'s turn"<<endl;
do{
if(card8[1] == tempCD[1] || card8[0] == tempCD[0]){
tempN = card8[0];
tempC = card8[1];
tempCD = card8;
card8 = null[0];
tempH2 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
cout<<"============================================="<<endl;
}
else if(card9[1] == tempCD[1] || card9[0] == tempCD[0]){
tempN = card9[0];
tempC = card9[1];
tempCD = card9;
card9 = null[0];
tempH2 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
cout<<"============================================="<<endl;
}
else if(card10[1] == tempCD[1] || card10[0] == tempCD[0]){
tempN = card10[0];
tempC = card10[1];
tempCD = card10;
card10 = null[0];
tempH2 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
cout<<"============================================="<<endl;
}
else if(card11[1] == tempCD[1] || card11[0] == tempCD[0]){
tempN = card11[0];
tempC = card11[1];
tempCD = card11;
card11 = null[0];
tempH2 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
cout<<"============================================="<<endl;
}
else if(card12[1] == tempCD[1] || card12[0] == tempCD[0]){
tempN = card12[0];
tempC = card12[1];
tempCD = card12;
card12 = null[0];
tempH2 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
cout<<"============================================="<<endl;
}
else if(card13[1] == tempCD[1] || card13[0] == tempCD[0]){
tempN = card13[0];
tempC = card13[1];
tempCD = card13;
card13 = null[0];
tempH2 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
cout<<"============================================="<<endl;
}
else if(card14[1] == tempCD[1] || card14[0] == tempCD[0]){
tempN = card14[0];
tempC = card14[1];
tempCD = card14;
card14 = null[0];
tempH2 -= 1;
cout<<"The new deck is: "<<tempCD<<endl;
cout<<"The number of cards left in "<<player2<<"'s hand is "
<<tempH2<<endl;
cout<<"============================================="<<endl;
}
else{
cout<<"No cards available!!!"<<endl;
cout<<player2<<"'s turn skipped"<<endl;
cout<<"============================================="<<endl;
}
}while(lturn);
//Player hands used to display UNO!!! and end game
//Ends game player 1 wins
if(tempH1 == 0){
end = true;
cout<<player1<<" Wins! Congratulations! "<<endl;
cout<<"============================================="<<endl;
}
//Says Uno
if(tempH2 == 1){
cout<<player2<<" UNO!!!"<<endl;
cout<<"============================================="<<endl;
}
//Ends game player 2 wins
if(tempH2 == 0){
end = true;
cout<<player2<<" Wins! Congratulations! "<<endl;
cout<<"============================================="<<endl;
}
//Counter used to end game where the game cannot be finished
count++;
if(count==15){
cout<<"Game cannot be finished!!!"<<endl;
end = true;
}
}while (end == false);
//Exit program!
return 0;
}
void Rules(){
string line;
fstream inputFile;
//open file
inputFile.open("Rules.txt");
if(inputFile.is_open()){
while(getline(inputFile,line)){
cout<<line<<"\n";
}
inputFile.close();
}
}
void shuffle(string c[],int nCrd,int nShuf){
for(int shuf=1;shuf<=nShuf;shuf++){
for(int card=0;card<nCrd;card++){
int indx=rand()%nCrd;
string temp=c[card];
c[card]=c[indx];
c[indx]=temp;
}
}
}
void prnDeck(string c[],int n,int perLine){
for(int i=0;i<n;i++){
cout<<c[i]<<" ";
if(i%perLine==(perLine-1))cout<<endl;
}
cout<<endl;
}
void filDeck(string c[],int n){
//Red, Blue, Green, Yellow
char suit[]={'R','B','G','Y'};
char face[]={'1','2','3','4','5','6','7','8','9',
'1','2','3','4','5','6','7','8','9'};
for(int i=0;i<n;i++){
c[i]=face[i%18];
c[i]+=suit[i/18];
}
}
| [
"[email protected]"
] | |
c3f31821e15b08d46f6e86b6d01868c3fb114d02 | 2b9cc67d4bbb5257b4c64bf6437bf7c589300c06 | /scripts/NuisanceChecks/AutoDict_binary_function_TString_TString_bool_.cxx | 8b9b688dc17be4a4d24fd0070b0e23bb186c3bf2 | [] | no_license | gerbaudo/hlfv-fitmodel | 81bfe391a4a19af5268fa056319dc552f6b9e1cf | 17a44604fa860382f72e27a5ee5c1432677e40cd | refs/heads/master | 2020-06-07T09:34:42.487189 | 2015-05-25T09:44:23 | 2015-05-25T09:44:23 | 35,870,053 | 1 | 0 | null | 2015-05-25T09:05:46 | 2015-05-19T08:43:13 | C | UTF-8 | C++ | false | false | 275 | cxx | #include "map"
#include "TString.h"
#include "TString.h"
#ifdef __CINT__
#pragma link C++ nestedclasses;
#pragma link C++ nestedtypedefs;
#pragma link C++ class binary_function<TString,TString,bool>+;
#pragma link C++ class binary_function<TString,TString,bool>::*+;
#endif
| [
"avitald@883ba7d9-fdd0-4202-9341-49aa55999ad8"
] | avitald@883ba7d9-fdd0-4202-9341-49aa55999ad8 |
3386100488410794c0ee148f203fed290ff288cf | e7e245b6f266ab277997b06e9d334f62fd67494e | /BUG_2.CPP | 421c404df325589e4d931622ed78917408f64bc6 | [] | no_license | amankumarkeshu/Spoj-Questions | 22c2ec58db9ca4ce02c106629018edc1633ecc5f | 29c9f16fb028979e7bfa5b7bf9091715290a0afd | refs/heads/master | 2020-03-28T17:51:49.314185 | 2019-04-17T10:06:24 | 2019-04-17T10:06:24 | 148,829,949 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,204 | cpp |
#include<bits/stdc++.h>
#define ll long long
#define ld long double
#define tt(t) read(t); while(t--)
#define endl '\n'
#define vll vector<ll>
#define vvll vector< vll >
#define pll pair<ll ,ll >
#define pss pair < string , string >
#define vpll vector< pll >
#define vpss vector< pss >
#define mp make_pair
#define pb push_back
#define MOD 1000000007
#define inf 1e18;
#define find(v,x) ((v).find(x) != (v).end())
#define vfind(v,x) (find(all(v),x) != (v).end())
#define clr(c) (c).clear()
#define cres(c,n) (c).clear(),(c).resize(n)
#define ios ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL)
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define fst first
#define scd second
#define fr(i,n) for(ll (i) = 0 ; (i) < (n) ; ++(i))
#define fr1(i,n) for(ll (i) = 1 ; (i) <= (n) ; ++(i))
#define frr(i,n) for(ll (i) = (n)-1 ; (i)>=0 ; --(i))
#define frab(i,a,b,c) for(ll (i) = a ; (i) <= (b) ; (i)+=(c))
#define mst(A) memset( (A) , 0 , sizeof(A) );
template< class T > void setmax(T &a, T b) { if(a < b) a = b; }
template< class T > void setmin(T &a, T b) { if(b < a) a = b; }
using namespace std;
void read(ll &x){
scanf("%lld",&x);
}
void read(ll &x,ll &y){
scanf("%lld %lld",&x,&y);
}
void read(ll &x,ll &y,ll &z){
scanf("%lld %lld %lld",&x,&y,&z);
}
void read(ll &x,ll &y,ll &z,ll &w){
scanf("%lld %lld %lld %lld",&x,&y,&z,&w);
}
void read(vll &oneD){
for(ll i=0;i<oneD.size();i++){
read(oneD[i]);
}
}
void read(vvll &twoD){
for(ll i=0;i<twoD.size();i++){
read(twoD[i]);
}
}
void write(vll &oneD){
for(ll i=0;i<oneD.size();i++){
printf("%lld ",oneD[i]);
}
printf("\n");
}
void write(vvll &twoD){
for(ll i=0;i<twoD.size();i++){
write(twoD[i]);
}
}
void write(vpll &oneDP){
fr(i,oneDP.size()){
printf("%lld %lld\n" , oneDP[i].fst , oneDP[i].scd);
}
cout<<"\n";
}
void write(map< ll , ll > &mpp){
for(map<ll , ll >::iterator it = mpp.begin() ; it != mpp.end() ; it++){
cout<<it->fst<<" : "<<it->scd<<endl;
}
cout<<endl;
}
bool cmp(const pair<ll,ll> &a,const pair<ll,ll> &b)
{
if(a.first == b.first)
return (a.scd >= b.scd);
return (a.first < b.first);
}
vll seive;
vll primes;
void Seive(){
const ll maxn = 100005;
seive.resize(maxn);
fr(i,maxn) seive[i] = 1;
//seive[1] = 0;
//seive[0] = 0;
for(ll i=2;i*i<maxn;i++)
{
if(seive[i]==1 )
{
for(ll j = i*i ; j <maxn ; j+=i)
{
seive[j] = 0;
}
}
}
primes.pb(2);
for(ll i=3;i<maxn;i+=2)
{
if(seive[i])
primes.pb(i);
}
}
void printprime(ll l,ll r)
{
if(l<2)
l=2;
bool isprime[r-l+1];
fr(i,r-l+1)
isprime[i]=true;
for( int i =0; primes[i]*primes[i] <= r; i++)
{
// Smaller or equal value to l
//cout<<primes[i]<<"primes[i] ";
ll base = (l/primes[i])*primes[i];
if(base < l)
{
base =base + primes[i];
}
//Mark all multiples of primes [i] as false
for( ll j= base ;j<=r; j+=primes[i])
{
isprime[j-l]= false;
}
// There may be a case where base itsef a prime
if(base == primes[i])
isprime[base-l]=true;
}
for( int i=0; i<r-l+1; i++)
{
if(isprime[i]==true)
cout<<i+l<<endl;
}
}
ll isprime(ll N){
if(N<2 || (!(N&1) && N!=2))
return 0;
for(ll i=3; i*i<=N; i+=2){
if(!(N%i))
return 0;
}
return 1;
}
ll mulmod(ll a, ll b, ll mod)
{
ll res = 0; // Initialize result
a = a % mod;
while (b > 0)
{
// If b is odd, add 'a' to result
if (b % 2 == 1)
res = (res + a) % mod;
// Multiply 'a' with 2
a = (a * 2) % mod;
// Divide b by 2
b /= 2;
}
// Return result
return res % mod;
}
ll power(ll x, ll y , ll m){
long long int res = 1;
x = x % m;
while (y > 0)
{
// If y is odd, multiply x with result
if (y & 1)
res = mulmod(res,x,m);
// y must be even now
y = y>>1; // y = y/2
x = mulmod(x,x, m);
}
return res;
}
ll modinv(ll x , ll mod = MOD){
return power(x , mod - 2 , mod);
}
//////////////////////////////////////////////////////////////////////////////////////
int main()
{
ll a,b,c,d;
ll k,l,m,n,p,q,r,s,t;
vpll v;
v.clear();
//Seive();
tt(t)
{
ll A[127]={0},B[127]={0};
string s1,s2;
cin>>s1>>s2;
n=s1.length();
m=s2.length();
ll flag=0;
fr(i,n)
{
A[s1[i]]++;
}
fr(i,m)
{
B[s2[i]]++;
}
fr1(i,123)
{
if(B[i]>=A[i])
{
//cout<<(char)i+96<<" ";
}
else
{
//cout<<i<<" ";
//cout<<B[i]<<" "<<A[i]<<endl;
flag=1;
}
}
if(flag) cout<<"No\n";
else cout<<"Yes\n";
}
}
| [
"[email protected]"
] | |
e5031dbebf3a2c7f67a0e11f0cdb81242aafd0c2 | 7e5be101928eb7ea43bc1a335d3475536f8a5bb2 | /2016 Training/7.24/E.cpp | 93b0907a0e3a12e39f6cf75f5d0d0d4a4a2ef55b | [] | no_license | TaoSama/ICPC-Code-Library | f94d4df0786a8a1c175da02de0a3033f9bd103ec | ec80ec66a94a5ea1d560c54fe08be0ecfcfc025e | refs/heads/master | 2020-04-04T06:19:21.023777 | 2018-11-05T18:22:32 | 2018-11-05T18:22:32 | 54,618,194 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,005 | cpp | //
// Created by TaoSama on 2016-07-24
// Copyright (c) 2016 TaoSama. All rights reserved.
//
#pragma comment(linker, "/STACK:102400000,102400000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>
using namespace std;
#define pr(x) cout << #x << " = " << x << " "
#define prln(x) cout << #x << " = " << x << endl
const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;
int n, a[N], b[N];
void solve(vector<int>& ans, bool rev) {
map<int, int> mp;
int sum = 0;
for(int i = 1; i <= n; ++i) {
sum += a[i] - b[i + rev];
++mp[sum];
}
int last = 0;
for(auto& p : mp) {
int tmp = p.second;
p.second += last;
last = tmp;
}
int delta = 0;
for(int i = 1; i <= n; ++i) {
auto iter = mp.lower_bound(delta);
if(iter == mp.begin()) ans.push_back(rev ? n - i + 1 : i);
delta += a[i] - b[i + rev];
}
}
int main() {
#ifdef LOCAL
freopen("C:\\Users\\TaoSama\\Desktop\\in.txt", "r", stdin);
// freopen("C:\\Users\\TaoSama\\Desktop\\out.txt","w",stdout);
#endif
ios_base::sync_with_stdio(0);
clock_t _ = clock();
while(scanf("%d", &n) == 1) {
for(int i = 1; i <= n; ++i) scanf("%d", a + i);
for(int i = 1; i <= n; ++i) scanf("%d", b + i);
vector<int> ans;
solve(ans, 0);
reverse(a + 1, a + 1 + n);
reverse(b + 1, b + 1 + n);
b[n + 1] = b[1];
solve(ans, 1);
sort(ans.begin(), ans.end());
ans.resize(unique(ans.begin(), ans.end()) - ans.begin());
printf("%d\n", ans.size());
for(int i = 0; i < ans.size(); ++i)
printf("%d%c", ans[i], " \n"[i == ans.size() - 1]);
}
#ifdef LOCAL
printf("\nTime cost: %.2fs\n", 1.0 * (clock() - _) / CLOCKS_PER_SEC);
#endif
return 0;
}
| [
"[email protected]"
] | |
f2875b792519f990a2bb56acc2de73a1a2ca58a0 | 44ab5e73bae277f1078dbe73fd0f99a7f0c98fa6 | /include/MacroSupplyManager.h | d8afce8137869f38a5d7a81c4378058e35e81a64 | [] | no_license | albertouri/dementor-bot | f66dfb00f1391a7457d07cf136eee086b5cdfd29 | b62de93062767943bb8a6c30aaa825ddd31198be | refs/heads/master | 2021-01-20T09:36:41.993561 | 2015-07-23T19:26:08 | 2015-07-23T19:26:08 | 39,587,387 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 427 | h | #pragma once
#include <Arbitrator.h>
#include <BWAPI.h>
#include <MacroManager.h>
class MacroSupplyManager
{
public:
static MacroSupplyManager* create();
static void destroy();
void update();
int lastFrameCheck;
int initialSupplyTotal;
int initialSupplyProviderCount;
private:
MacroSupplyManager();
~MacroSupplyManager();
};
extern MacroSupplyManager* TheMacroSupplyManager; | [
"[email protected]"
] | |
1aef01f180436c891cb128393d345da60a8b8b8d | 5971ac054f281c79989f29765443b7aa510650d7 | /src/standard/bits/DD_replace.hpp | a716ddf6fcab6421ce38cdff9987b7a475e7f37e | [
"BSD-3-Clause"
] | permissive | ArshartCloud/libDDCPP | 41c01b5f88912b7af49387b54d2cd2854616f0e0 | e9e717794c38fe8a9e1098cd4892f01df1594889 | refs/heads/master | 2021-01-15T11:08:06.050206 | 2015-09-29T09:05:30 | 2015-09-29T09:05:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,063 | hpp | // DDCPP/standard/bits/DD_replace.hpp
#ifndef DD_REPLACE_HPP_INCLUDED_
# define DD_REPLACE_HPP_INCLUDED_ 1
# include "DD_global_definitions.hpp"
DD_BEGIN_
template <typename UndirectionalIteratorT_, typename ValueT1_, typename ValueT2_>
ProcessType replace(
UndirectionalIteratorT_ begin__,
UndirectionalIteratorT_ const& end__,
ValueT1_ const& old__,
ValueT2_ value__
) DD_NOEXCEPT_AS(*++begin__ = value__ DD_COMMA begin__ != end__ && *begin__ == old__) {
for (; begin__ != end__; ++begin__) {
if (*begin__ == old__) {
*begin__ = value__;
}
}
}
template <typename UndirectionalIteratorT_, typename ValueT1_, typename BinaryPredicatorT_, typename ValueT2_>
ProcessType replace(
UndirectionalIteratorT_ begin__,
UndirectionalIteratorT_ const& end__,
ValueT1_ old__,
BinaryPredicatorT_ const& equal__,
ValueT2_ value__
) DD_NOEXCEPT_AS(*++begin__ = value__ DD_COMMA begin__ != end__ && equal__(*begin__, old__)) {
for (; begin__ != end__; ++begin__) {
if (equal__(*begin__, old__)) {
*begin__ = value__;
}
}
}
DD_END_
#endif
| [
"[email protected]"
] | |
6ad15fed7348b9c02a45ce67d575780989be98d5 | 753244933fc4465b0047821aea81c311738e1732 | /culture/target/cpp-O3/ts2/src/__boot__.cpp | 4b1c891c0f75dfc3b8fbfa4ada38343b16600895 | [] | no_license | mboussaa/HXvariability | abfaba5452fecb1b83bc595dc3ed942a126510b8 | ea32b15347766b6e414569b19cbc113d344a56d9 | refs/heads/master | 2021-01-01T17:45:54.656971 | 2017-07-26T01:27:49 | 2017-07-26T01:27:49 | 98,127,672 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 6,348 | cpp | // Generated by Haxe 3.3.0
#include <hxcpp.h>
#ifndef INCLUDED_utest_ui_common_SuccessResultsDisplayMode
#include <utest/ui/common/SuccessResultsDisplayMode.h>
#endif
#ifndef INCLUDED_utest_ui_common_HeaderDisplayMode
#include <utest/ui/common/HeaderDisplayMode.h>
#endif
#ifndef INCLUDED_utest__Dispatcher_EventException
#include <utest/_Dispatcher/EventException.h>
#endif
#ifndef INCLUDED_utest_Assertation
#include <utest/Assertation.h>
#endif
#ifndef INCLUDED_haxe_StackItem
#include <haxe/StackItem.h>
#endif
#ifndef INCLUDED_ValueType
#include <ValueType.h>
#endif
#ifndef INCLUDED_utest_TestHandler
#include <utest/TestHandler.h>
#endif
#ifndef INCLUDED_utest_Assert
#include <utest/Assert.h>
#endif
#ifndef INCLUDED_thx_culture_DateFormatInfo
#include <thx/culture/DateFormatInfo.h>
#endif
#ifndef INCLUDED_haxe_MainLoop
#include <haxe/MainLoop.h>
#endif
#ifndef INCLUDED_haxe_Log
#include <haxe/Log.h>
#endif
#ifndef INCLUDED_haxe_EntryPoint
#include <haxe/EntryPoint.h>
#endif
#ifndef INCLUDED_utest_ui_text_PrintReport
#include <utest/ui/text/PrintReport.h>
#endif
#ifndef INCLUDED_utest_ui_text_PlainTextReport
#include <utest/ui/text/PlainTextReport.h>
#endif
#ifndef INCLUDED_utest_ui_common_ResultStats
#include <utest/ui/common/ResultStats.h>
#endif
#ifndef INCLUDED_utest_ui_common_ResultAggregator
#include <utest/ui/common/ResultAggregator.h>
#endif
#ifndef INCLUDED_utest_ui_common_ReportTools
#include <utest/ui/common/ReportTools.h>
#endif
#ifndef INCLUDED_utest_ui_common_PackageResult
#include <utest/ui/common/PackageResult.h>
#endif
#ifndef INCLUDED_utest_ui_common_IReport
#include <utest/ui/common/IReport.h>
#endif
#ifndef INCLUDED_utest_ui_common_FixtureResult
#include <utest/ui/common/FixtureResult.h>
#endif
#ifndef INCLUDED_utest_ui_common_ClassResult
#include <utest/ui/common/ClassResult.h>
#endif
#ifndef INCLUDED_utest_ui_Report
#include <utest/ui/Report.h>
#endif
#ifndef INCLUDED_utest_TestResult
#include <utest/TestResult.h>
#endif
#ifndef INCLUDED_utest_TestFixture
#include <utest/TestFixture.h>
#endif
#ifndef INCLUDED_utest_Runner
#include <utest/Runner.h>
#endif
#ifndef INCLUDED_utest_Notifier
#include <utest/Notifier.h>
#endif
#ifndef INCLUDED_utest_Dispatcher
#include <utest/Dispatcher.h>
#endif
#ifndef INCLUDED_thx_culture_TestDateFormatInfo
#include <thx/culture/TestDateFormatInfo.h>
#endif
#ifndef INCLUDED_haxe_io_Eof
#include <haxe/io/Eof.h>
#endif
#ifndef INCLUDED_haxe_io_Bytes
#include <haxe/io/Bytes.h>
#endif
#ifndef INCLUDED_haxe_ds_StringMap
#include <haxe/ds/StringMap.h>
#endif
#ifndef INCLUDED_haxe_Timer
#include <haxe/Timer.h>
#endif
#ifndef INCLUDED_haxe_MainEvent
#include <haxe/MainEvent.h>
#endif
#ifndef INCLUDED_haxe_IMap
#include <haxe/IMap.h>
#endif
#ifndef INCLUDED_haxe_CallStack
#include <haxe/CallStack.h>
#endif
#ifndef INCLUDED_cpp_vm_Thread
#include <cpp/vm/Thread.h>
#endif
#ifndef INCLUDED_cpp_vm_Mutex
#include <cpp/vm/Mutex.h>
#endif
#ifndef INCLUDED_cpp_vm_Lock
#include <cpp/vm/Lock.h>
#endif
#ifndef INCLUDED_cpp_Lib
#include <cpp/Lib.h>
#endif
#ifndef INCLUDED_Type
#include <Type.h>
#endif
#ifndef INCLUDED_TS2
#include <TS2.h>
#endif
#ifndef INCLUDED_Sys
#include <Sys.h>
#endif
#ifndef INCLUDED_StringTools
#include <StringTools.h>
#endif
#ifndef INCLUDED_StringBuf
#include <StringBuf.h>
#endif
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_Reflect
#include <Reflect.h>
#endif
#ifndef INCLUDED__List_ListIterator
#include <_List/ListIterator.h>
#endif
#ifndef INCLUDED__List_ListNode
#include <_List/ListNode.h>
#endif
#ifndef INCLUDED_List
#include <List.h>
#endif
#ifndef INCLUDED_Lambda
#include <Lambda.h>
#endif
#ifndef INCLUDED_EReg
#include <EReg.h>
#endif
#ifndef INCLUDED_Date
#include <Date.h>
#endif
void __files__boot();
void __boot_all()
{
__files__boot();
hx::RegisterResources( hx::GetResources() );
::utest::ui::common::SuccessResultsDisplayMode_obj::__register();
::utest::ui::common::HeaderDisplayMode_obj::__register();
::utest::_Dispatcher::EventException_obj::__register();
::utest::Assertation_obj::__register();
::haxe::StackItem_obj::__register();
::ValueType_obj::__register();
::utest::TestHandler_obj::__register();
::utest::Assert_obj::__register();
::thx::culture::DateFormatInfo_obj::__register();
::haxe::MainLoop_obj::__register();
::haxe::Log_obj::__register();
::haxe::EntryPoint_obj::__register();
::utest::ui::text::PrintReport_obj::__register();
::utest::ui::text::PlainTextReport_obj::__register();
::utest::ui::common::ResultStats_obj::__register();
::utest::ui::common::ResultAggregator_obj::__register();
::utest::ui::common::ReportTools_obj::__register();
::utest::ui::common::PackageResult_obj::__register();
::utest::ui::common::IReport_obj::__register();
::utest::ui::common::FixtureResult_obj::__register();
::utest::ui::common::ClassResult_obj::__register();
::utest::ui::Report_obj::__register();
::utest::TestResult_obj::__register();
::utest::TestFixture_obj::__register();
::utest::Runner_obj::__register();
::utest::Notifier_obj::__register();
::utest::Dispatcher_obj::__register();
::thx::culture::TestDateFormatInfo_obj::__register();
::haxe::io::Eof_obj::__register();
::haxe::io::Bytes_obj::__register();
::haxe::ds::StringMap_obj::__register();
::haxe::Timer_obj::__register();
::haxe::MainEvent_obj::__register();
::haxe::IMap_obj::__register();
::haxe::CallStack_obj::__register();
::cpp::vm::Thread_obj::__register();
::cpp::vm::Mutex_obj::__register();
::cpp::vm::Lock_obj::__register();
::cpp::Lib_obj::__register();
::Type_obj::__register();
::TS2_obj::__register();
::Sys_obj::__register();
::StringTools_obj::__register();
::StringBuf_obj::__register();
::Std_obj::__register();
::Reflect_obj::__register();
::_List::ListIterator_obj::__register();
::_List::ListNode_obj::__register();
::List_obj::__register();
::Lambda_obj::__register();
::EReg_obj::__register();
::Date_obj::__register();
::utest::ui::common::SuccessResultsDisplayMode_obj::__boot();
::utest::ui::common::HeaderDisplayMode_obj::__boot();
::utest::_Dispatcher::EventException_obj::__boot();
::utest::Assertation_obj::__boot();
::haxe::StackItem_obj::__boot();
::ValueType_obj::__boot();
::haxe::Log_obj::__boot();
::haxe::EntryPoint_obj::__boot();
::haxe::MainLoop_obj::__boot();
::thx::culture::DateFormatInfo_obj::__boot();
::utest::Assert_obj::__boot();
::utest::TestHandler_obj::__boot();
}
| [
"[email protected]"
] | |
146667344c2c1171d15ff754316cad6a1370c9ce | ce152a04306cf4ae69ff0c462e7016de376eba47 | /1062.cpp | aba7355190855a4f174b0265e5da66afcde522a3 | [] | no_license | the-badcoder/UVA-Solutions | 9038384e657acf810bd2eb6e356d4b8c47117c73 | b061787a998d4456fec290f896f80c12590eb256 | refs/heads/master | 2018-09-22T11:23:22.380688 | 2018-09-15T14:32:14 | 2018-09-15T14:32:14 | 105,517,803 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,445 | cpp | /// Bismillah Hir Rahmanir Rahim
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using ii = pair <int, int>;
using vii = vector<ii>;
#define ff first
#define ss second
#define sz(x) (x).size()
#define space " "
#define all(x) (x).begin(), (x).end()
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
/*
template <class T> T gcd(T a,T b){ if(b == 0) return a; return gcd( b,a % b ); }
template <class T> T lcm(T a, T b ){ return ( a / gcd( a,b ) ) * b; }
template<class T> string ToString(const T &x){ stringstream s; s << x; return s.str(); }
template<class T> int ToInteger(const T &x){ stringstream s; s << x; int r; s >> r; return r; }
*/
template<class T1> void deb(T1 e1)
{
cout << e1 << endl;
}
template<class T1,class T2> void deb(T1 e1, T2 e2)
{
cout << e1 << space << e2 << endl;
}
template<class T1,class T2,class T3> void deb(T1 e1, T2 e2, T3 e3)
{
cout << e1 << space << e2 << space << e3 << endl;
}
#define pf printf
#define sf1(a) scanf("%d", &a)
#define sf2(a,b) scanf("%d %d",&a, &b)
#define sf3(a,b,c) scanf("%d %d %d", &a, &b, &c)
#define sf4(a,b,c,d) scanf("%d %d %d %d", &a, &b, &c, &d)
#define sf1ll(a) scanf("%lld", &a)
#define sf2ll(a,b) scanf("%lld %lld", &a, &b)
#define sf3ll(a,b,c) scanf("%lld %lld %lld", &a, &b, &c)
#define sf4ll(a,b,c,d) scanf("%lld %lld %lld %lld", &a, &b, &c, &d)
#define READ freopen("in.txt", "r", stdin);
#define WRITE freopen("out.txt", "w", stdout);
/// The End.
const int res = 1e6 + 10;
const ll mod = 1e9 + 7;
stack <char> st;
vector < stack <char> > vs;
string s;
int loop = 0;
int check( int x )
{
for( int i = 0; i < vs.size(); i++ )
{
if( s[ x ] <= vs[ i ].top() )
{
vs[ i ].push( s[ x ] );
return 0;
}
}
vs.push_back( st );
vs[ vs.size() - 1 ].push( s[ x ] );
return 1;
}
int main()
{
while( cin >> s )
{
int ans = 0;
vs.clear();
if( s == "end" )
{
break;
}
int len = s.size();
for( int i = 0; i < len; i++ )
{
ans += check( i );
}
printf("Case %d: %d\n", ++loop, ans );
}
return 0;
}
| [
"[email protected]"
] | |
1f4d72ceb37d50dd8a694c5d49e2f087f583b158 | 6ca4d5f12e9a3839e70163856ff29220f63375f9 | /dependencies/thermite3d/include/scriptable/RenderComponent.h | cea8e0b67c70db2e50e5b99078cf3c9b0fec1585 | [
"MIT"
] | permissive | weflowers/voxeliens | 8d75f304067cea534cd906c86715f08207496640 | 64322d13d1661b6d5f88032b16f410516b9690b8 | refs/heads/master | 2023-01-31T21:22:55.461634 | 2020-12-11T19:35:47 | 2020-12-11T19:35:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 492 | h | #ifndef RENDER_COMPONENT_H_
#define RENDER_COMPONENT_H_
#include "Component.h"
#include "OgreSceneNode.h"
namespace Thermite
{
class RenderComponent : public Component
{
public:
RenderComponent(Object* parent);
~RenderComponent(void);
void onEnabled(bool enabled);
void update(void);
public:
Ogre::SceneManager* mSceneManager;
Ogre::SceneNode* mOgreSceneNode;
bool mIsVisible;
bool mUpdateIsVisible;
};
}
#endif //RENDER_COMPONENT_H_
| [
"[email protected]"
] | |
90a04ac4cf8490b973d3f872556115bfce48e3fb | c2bbe165858014ea7fd226710fa3dc1f4af36fe8 | /src/utilities.hpp | 6d2a191684e3a236196738757b0907d78bf3e144 | [] | no_license | tonymugen/GWAlikeMeth | 5781bb71e0ac79d6772d405a025f4379a52453cc | 8245a7224ba4253681f54aaedd17a60b4520bedf | refs/heads/master | 2020-04-16T00:34:56.464885 | 2020-01-31T22:28:18 | 2020-01-31T22:28:18 | 165,144,017 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,541 | hpp | //
// utilities.hpp
//
//
// Created by Tony Greenberg on 12/21/16.
// Copyright © 2016 Tony Greenberg. All rights reserved.
//
/// Miscellaneous functions and algorithms
/** \file
* \author Anthony J. Greenberg
* \copyright Copyright (c) 2016 Anthony J. Greenberg
* \version 0.1
*
* This is the project header file containing function definitions and constants.
*
*/
#ifndef utilities_hpp
#define utilities_hpp
#include <vector>
#include <string>
#include <utility>
#include <limits>
#include <cmath>
#include <cstdint> // for uint64_t
#include <stack>
using std::vector;
using std::string;
using std::swap;
using std::numeric_limits;
using std::signbit;
using std::stack;
namespace BayesicSpace {
/// The definition of \f$\pi\f$
const double BS_PI = 3.14159265358979323846264338328;
/// Machine \f$\epsilon\f$
const double BS_EPS = numeric_limits<double>::epsilon();
/// Tiny value to guard agains underflow
const double BS_FPMIN = numeric_limits<double>::min()/BS_EPS;
/** \brief Swap two `uint64_t` values
*
* Uses the three XORs trick to swap two integers. Safe if the variables happen to refer to the same address.
*
* \param[in,out] i first integer
* \param[in,out] j second integer
*/
void swapXOR(uint64_t &i, uint64_t &j){
if (&i != &j) { // no move needed if this is actually the same variable
i ^= j;
j ^= i;
i ^= j;
}
}
/** \brief Swap two `in64_t` values
*
* Uses the three XORs trick to swap two integers. Safe if the variables happen to refer to the same address.
*
* \param[in,out] i first integer
* \param[in,out] j second integer
*/
void swapXOR(int64_t &i, int64_t &j){
if (&i != &j) { // no move needed if this is actually the same variable
i ^= j;
j ^= i;
i ^= j;
}
}
/** \brief Swap two `uint32_t` values
*
* Uses the three XORs trick to swap two integers. Safe if the variables happen to refer to the same address.
*
* \param[in,out] i first integer
* \param[in,out] j second integer
*/
void swapXOR(uint32_t &i, uint32_t &j){
if (&i != &j) { // no move needed if this is actually the same variable
i ^= j;
j ^= i;
i ^= j;
}
}
/** \brief Swap two `int32_t` values
*
* Uses the three XORs trick to swap two integers. Safe if the variables happen to refer to the same address.
*
* \param[in,out] i first integer
* \param[in,out] j second integer
*/
void swapXOR(int32_t &i, int32_t &j){
if (&i != &j) { // no move needed if this is actually the same variable
i ^= j;
j ^= i;
i ^= j;
}
}
/** \brief Mean of a C array
*
* Calculates a mean of an array. Uses the recursive algorithm for numerical stability.
*
* \param[in] arr array to average
* \param[in] len array length
*
*/
double mean(const double *arr, const size_t &len){
double mean = 0.0;
for (size_t i = 0; i < len; i++) {
mean += (arr[i] - mean)/static_cast<double>(i + 1);
}
return mean;
}
/** \brief Mean of a C array with stride
*
* Calculates a mean of an array with stride (i.e., using every _stride_ element). Uses the recursive algorithm for numerical stability.
*
* \param[in] arr array to average
* \param[in] len array length
* \param[in] stride stride
*
*/
double mean(const double *arr, const size_t &len, const size_t &stride){
double mean = 0.0;
size_t nSteps = len/stride; // floor is what I want
for (size_t i = 0; i < nSteps; i++) {
mean += (arr[i * stride] - mean)/static_cast<double>(i + 1);
}
return mean;
}
/** \brief Mean of a C++ vector
*
* Calculates a mean of a vector. Uses the recursive algorithm for numerical stability.
*
* \param[in] vec vector to average
*
*/
double mean(const vector<double> &vec){
double mean = 0.0;
for (size_t i = 0; i < vec.size(); i++) {
mean += (vec[i] - mean)/static_cast<double>(i + 1);
}
return mean;
}
/** \brief Mean of a C++ vector with stride
*
* Calculates a mean of a vector with stride (i.e., using every _stride_ element). Uses the recursive algorithm for numerical stability.
*
* \param[in] vec vector to average
* \param[in] stride stride
*
*/
double mean(const vector<double> &vec, const size_t &stride){
double mean = 0.0;
size_t nSteps = vec.size()/stride; // floor is what I want
for (size_t i = 0; i < nSteps; i++) {
mean += (vec[i * stride] - mean)/static_cast<double>(i + 1);
}
return mean;
}
/** \brief Square of a double
*
* \param[in] x value to square
* \return double square of the input
*/
inline double pow2(const double &x) {return x*x; };
/** \brief Shift three values left
*
* Shifts a new value, moving the old to the left. The first value is discarded.
*
* \param[in,out] a first value (becomes _b_)
* \param[in,out] b second value (becomes _c_)
* \param[in,out] c third value (becomes _d_)
* \param[in] d unchanged fourth value (shifted to _c_)
*
*/
inline void shft3(double &a, double &b, double &c, const double &d){
a = b;
b = c;
c = d;
}
/** \brief Bracket a maximum
*
* Brackets a maximum of a function given two initial guesses. Based on the Numerical Recipes in C++ function. Using max rather than min because max is more important in statistical applications.
* The resulting bracketing values are candA < candB < candC.
*
* \param[in] func function to maximize. Has to take a double and return a double
* \param[in] startA starting value A
* \param[in] startB starting value B
* \param[out] candA first bracketing value
* \param[out] candB second bracketing value
* \param[out] candC third breacketing value
*
*/
template<class T>
void bracketMax(T &func, const double &startA, const double &startB, double &candA, double &candB, double &candC);
// body of the function has to be in the header file because of template stuff
template<class T>
void bracketMax(T &func, const double &startA, const double &startB, double &candA, double &candB, double &candC){
// set up constants
const double GOLD = 1.618034; // default successive magnification ratio
const double GLIMIT = 100.0; // maximum magnification allowed for the parabolic fit
const double TINY = 1.0e-20; // tiny value to assure no division by zero
// set the initial values
candA = startA;
candB = startB;
double fa = func(candA);
double fb = func(candB);
// test if the function changes value at all (or at least a little over epsilon)
if (fabs(fa - fb) < 1.001*BS_EPS) {
candB += 100.0; // maybe just unlucky; change candB
fb = func(candB);
if (fabs(fa - fb) < 1.001*BS_EPS) { // now for sure there is a problem
throw string("ERROR: function does not change over the candidate interval");
}
}
// want to keep going uphill, so reverse order if b takes us down
if (fb < fa) {
swap(candA, candB);
swap(fa, fb);
}
// first guess at candC
candC = candB + GOLD*(candB - candA);
double fc = func(candC);
while (fb < fc) { // stop when we bracket (func(candC) drops below func(candB)); will not execute if our first guess at candC hit the jackpot
// parabolic extrapolation from a,b,c to find a new candidate u
// note that parabolic extrapolation works the same for min and max
double r = (candB-candA)*(fb-fc);
double q = (candB-candC)*(fb-fa);
// NOTE: signbit() is C++11; true if negative
double qrDiff = (signbit(q-r) ? -fmax(fabs(q-r), TINY) : fmax(fabs(q-r), TINY)); // using TINY to guard against division by zero
double u = candB - ((candB-candC)*q-(candB-candA)*r)/(2.0*qrDiff);
double ulim = candB + GLIMIT*(candC-candB);
double fu;
if (!signbit((candB - u)*(u - candC))) { // u is between b and c; try it
fu = func(u);
if (fu > fc) { // maximum between b and c
candA = candB;
candB = u;
break;
} else if (fu < fb){ // maximum between a and u
candC = u;
break;
}
// Nothing good found; revert to golden rule magnification
u = candC + GOLD*(candC-candB);
fu = func(u);
} else if (!signbit((candC-u)*(u-ulim))){ // u is between c and limit
fu = func(u);
if (fu > fc) {
shft3(candB, candC, u, u+GOLD*(u-candC));
shft3(fb, fc, fu, func(u)); // u has changed in the previous shift
}
} else if ((u-ulim)*(ulim-candC) >= 0.0) { // limit u to maximum allowed value if it is closer than c
u = ulim;
fu = func(u);
} else { // reject the parabolic approach and use golden rule magnification
u = candC + GOLD*(candC-candB);
fu = func(u);
}
// did not bracket yet; eliminate the oldest point and continue
shft3(candA, candB, candC, u);
shft3(fa, fb, fc, fu);
}
}
/** \brief Find the value that maximizes a function
*
* Uses the Brent method to find the value of \f$x\f$ that maximizes a function. Modification of the implementation found in Numerical Recipes in C++. Maximizing rather than minimizing because that is the most common application in statistics.
* Tolerance is set at \f$1.001 \times \sqrt{\epsilon}\f$, where \f$\epsilon\f$ is machine floating-point precision for _double_. This is just above the theoretical limit of precision.
*
* \param[in] func functor that represents the function to be maximized
* \param[in] startX starting value
* \param[out] xMax value of \f$x\f$ at maximum
* \param[out] fMax function value at maximum
*
*/
template<class T>
void maximizer(T &func, const double &startX, double &xMax, double &fMax);
// Template function. Body has to be in the .hpp file.
template<class T>
void maximizer(T &func, const double &startX, double &xMax, double &fMax){
const double tol = 1.001 * sqrt(BS_EPS); // set the tolerance just above the theoretical limit
const unsigned int ITMAX = 1000; // maximum number of iterations
const double CGOLD = 0.3819660; // golden ratio for when we abandon parabolic interpolation
const double ZEPS = 1e-3 * BS_EPS; // small number to protect against numerical problems when the maximum is zero and we are trying to achieve a certain fractional accuracy
// misc. parameters; named the same as the ones in Numerical Recipes Chapter 10.3
double d = 0.0;
double e = 0.0; // the distance moved in the step before last
double etemp;
double fu;
double fv;
double fw;
double fx;
double u;
double v;
double w;
double x;
double xm;
double p;
double q;
double r;
double tol1;
double mtol1;
double tol2;
// start by bracketing
const double startB = startX + 100.0;
double ax;
double bx;
double cx;
bracketMax(func, startX, startB, ax, bx, cx);
double a = (ax < cx ? ax : cx);
double b = (ax > cx ? ax : cx); // a and b (but not necessarily func(a) and func(b)) must be ascending order
// initialize
x = w = v = bx;
fw = fv = fx = func(x);
unsigned int iter;
for (iter = 0; iter < ITMAX; iter++) {
xm = 0.5 * (a + b); // xm is the midpoint between a and b
tol1 = tol * fabs(x) + ZEPS;
tol2 = 2.0 * tol1;
mtol1 = -tol1;
// test for doneness
if (fabs(x - xm) <= (tol2 - 0.5*(b-a))) {
fMax = fx;
xMax = x;
break;
}
if (fabs(e) > tol1) { // construct parabolic fit; not happening for the first round since e is set to 0.0 to begin with
r = (x-w)*(fx-fv);
q = (x-v)*(fx-fw);
p = (x-v)*q-(x-w)*r;
q = 2.0*(q-r);
if (q > 0.0) {
p = -p;
}
q = fabs(q);
etemp = e;
e = d;
// Test the parabolic fit for acceptability.
// The parabolic step has to be (1) in the (a,b) interval and (2) the movement has to be smaller than 0.5*(the one before last)
if ((fabs(p) >= fabs(0.5*q*etemp)) || (p <= q*(a-x)) || (p >= q*(b-x))) {
// parabolic step no good; take golden section into the larger segment
e = (x >= xm ? a-x : b-x);
d = CGOLD*e;
} else { // take the parabolic step
d = p/q;
u = x+d;
if ((u-a < tol2) || (b-u < tol2)) {
d = (signbit(xm - x) ? mtol1 : tol1);
}
}
} else {
e = (x >= xm ? a-x : b-x);
d = CGOLD * e;
}
u = (fabs(d) >= tol1 ? x+d : x+(signbit(d) ? mtol1 : tol1));
fu = func(u); // our one function evaluation
// once we have our function evaluation, we decide what to do with it
if (fu >= fx) {
if (u >= x) {
a = x;
} else {
b = x;
}
shft3(v,w,x,u);
shft3(fv,fw,fx,fu);
} else {
if (u < x) {
a = u;
} else {
b = u;
}
if ((fu >= fw) || (w == x)) {
v = w;
w = u;
fv = fw;
fw = fu;
} else if ((fu >= fv) || (v == x) || (v == w)) {
v = u;
fv = fu;
}
}
}
// if we did not get there after max # of iterations
if (iter + 1 >= ITMAX) {
xMax = x;
fMax = nan("");
}
}
/** \brief Logarithm of the Gamma function
*
* The log of the \f$ \Gamma(x) \f$ function. Implementing the Lanczos algorythm following Numerical Recipes in C++.
*
* \param[in] x value
* \return \f$ \log \Gamma(x) \f$
*
*/
double lnGamma(const double &x){
if (x <= 0.0) return nan("");
// define the weird magical coefficients
const double coeff[14] {57.1562356658629235,-59.5979603554754912,14.1360979747417471,-0.491913816097620199,0.339946499848118887e-4,0.465236289270485756e-4,-0.983744753048795646e-4,0.158088703224912494e-3,-0.210264441724104883e-3,0.217439618115212643e-3,-0.164318106536763890e-3,0.844182239838527433e-4,-0.261908384015814087e-4,0.368991826595316234e-5};
// save a copy of x for incrementing
double y = x;
double gamma = 5.24218750000000000; // 671/128
double tmp = x + gamma;
tmp = (x + 0.5)*log(tmp) - tmp;
double logPi = 0.91893853320467267; // 0.5*log(2.0*pi)
tmp += logPi;
double cZero = 0.999999999999997092; // c_0
for (size_t i = 0; i < 14; i++) {
cZero += coeff[i]/(++y);
}
return tmp + log(cZero/x);
}
/** \brief Continued fraction of the Beta function
*
* Computes the continued fraction of the Beta function following the Lenz method (see Numerical Recipes in C++). To be used in the _betai_ function.
*
* \param[in] x value
* \param[in] a shape parameter \f$a\f$
* \param[in] b shape parameter \f$b\f$
*
* \return continued fraction value
*
*/
double betacf(const double &x, const double &a, const double &b){
const unsigned int maxIter = 10000;
const double aPb = a + b;
const double aPo = a + 1.0;
const double aMo = a - 1.0;
double numer = 1.0; // first step of Lentz's method; define first continued fraction numerator
double denom = 1.0 - aPb*x/aPo; // define the denominator to start
if (fabs(denom) < BS_FPMIN) denom = BS_FPMIN; // set d to something resonalbly small if it is too close to 0
denom = 1.0/denom;
double cFrac = denom; // will become the continued fraction
for (unsigned int m = 1; m < maxIter; m++) {
double dm = static_cast<double>(m);
double m2 = 2.0*dm;
double aa = dm*(b-dm)*x/( (aMo+m2)*(a+m2) );
// even step of the recurrence
denom = 1.0 + aa*denom;
numer = 1.0 + aa/numer;
if (fabs(denom) < BS_FPMIN) denom = BS_FPMIN;
if (fabs(numer) < BS_FPMIN) numer = BS_FPMIN;
denom = 1.0/denom;
cFrac *= denom*numer;
aa = -(a+dm)*(aPb+dm)*x/( (a+m2)*(aPo+m2) );
// odd step of the recurrence
denom = 1.0 + aa*denom;
numer = 1.0 + aa/numer;
if (fabs(denom) < BS_FPMIN) denom = BS_FPMIN;
if (fabs(numer) < BS_FPMIN) numer = BS_FPMIN;
denom = 1.0/denom;
double del = denom*numer;
cFrac *= del;
if (fabs(del-1.0) <= BS_EPS) break; // done if within epsilon
}
return cFrac;
}
/** \brief Regularized incomplete Beta function
*
* Computes a quadrature approximatino of the regularized incomplete Beta function following the method in Numerical Recipes in C++. To be used in the _betai_ function.
*
* \param[in] x value
* \param[in] a shape parameter \f$a\f$
* \param[in] b shape parameter \f$b\f$
*
* \return approximate \f$ I_x(a, b) \f$
*s
*/
double betaiapprox(const double &x, const double &a, const double &b){
// Gauss-Legendre abscissas and weights. Magic numbers copied from Numerical Recipes in C++
const double y[18] {0.0021695375159141994,0.011413521097787704,0.027972308950302116,0.051727015600492421,0.082502225484340941, 0.12007019910960293,
0.16415283300752470,0.21442376986779355, 0.27051082840644336,0.33199876341447887,0.39843234186401943, 0.46931971407375483, 0.54413605556657973,
0.62232745288031077,0.70331500465597174, 0.78649910768313447,0.87126389619061517, 0.95698180152629142};
const double w[18] {0.0055657196642445571,0.012915947284065419,0.020181515297735382,0.027298621498568734,0.034213810770299537,0.040875750923643261,
0.047235083490265582,0.053244713977759692,0.058860144245324798,0.064039797355015485,0.068745323835736408,0.072941885005653087,0.076598410645870640,
0.079687828912071670,0.082187266704339706,0.084078218979661945,0.085346685739338721,0.085983275670394821};
double res;
double xu;
const double aMo = a - 1.0;
const double bMo = b - 1.0;
const double mu = a/(a+b);
const double lnMu = log(mu);
const double lnOMU = log(1.0 - mu);
double t = sqrt(a*b/(pow2(a+b)*(a+b+1.0)));
// set the extent of tail integration
if (x > mu) {
if (x > 1.0) return 1.0;
xu = fmax(mu + 10.0*t, x + 5.0*t);
xu = fmin(1.0, xu);
} else {
if (x < 0.0) return 0.0;
xu = fmin(mu - 10.0*t, x - 5.0*t);
xu = fmax(0.0, xu);
}
double sum = 0.0;
// Gauss-Legendre accumulation
for (size_t i = 0; i < 18; i++) {
t = x + (xu-x)*y[i];
sum += w[i]*exp(aMo*(log(t)-lnMu)+bMo*(log(1-t)-lnOMU));
}
res = sum*(xu-x)*exp(aMo*lnMu-lnGamma(a)+bMo*lnOMU-lnGamma(b)+lnGamma(a+b));
return res > 0.0 ? 1.0-res : -res;
}
/** \brief Regularized incomplete Beta function
*
* Computes the regularized incomplete Beta function following the method in Numerical Recipes in C++.
*
* \param[in] x value
* \param[in] a shape parameter \f$a\f$
* \param[in] b shape parameter \f$b\f$
*
* \return \f$ I_x(a, b) \f$
*
*/
double betai(const double &x, const double &a, const double &b){
if ( (a <= 0.0) || (b <= 0.0) ) return nan("");
if ( (x < 0.0) || (x > 1.0) ) return nan("");
if ( (x == 0.0) || (x == 1.0) ) return x;
const double doApprox = 3000.0; // when to do the quadrature approximation
if ( (a > doApprox) && (b > doApprox) ) return betaiapprox(x, a, b);
double bt = exp(lnGamma(a+b) - lnGamma(a) - lnGamma(b) + a*log(x) + b*log(1.0 - x));
if (x < (a+1.0)/(a+b+2.0)) {
return bt*betacf(x,a,b)/a;
} else {
return 1.0 - bt*betacf(1.0-x,b,a)/b;
}
}
/** \brief Shell sort
*
* Sorts the provided vector in ascending order using Shell's method. Rather than move the elements themselves, save their indexes to the output vector. The first element of the index vector points to the smallest element of the input vector etc. The implementation is modified from code in Numerical Recipes in C++.
* NOTE: This algorithm is too slow for vectors of \f$ > 50\f$ elements. I am using it to finish off the quickSort, this is why I am giving it a range within a larger vector.
*
* \param[in] target vector to be sorted
* \param[in] beg index of the first element
* \param[in] end index of one past the last element to be included
* \param[out] outIdx vector of indexes
*/
void shellSort(const vector<double> &target, const size_t &beg, const size_t &end, vector<size_t> &outIdx){
if (target.size() < end) {
throw string("Target vector size smaller than end index in shellSort()");
} else if (outIdx.size() < end) {
throw string("Output vector size smaller than end index in shellSort()");
} else if (end < beg) {
throw string("End index smaller than beginning index in shellSort()");
} else if (target.size() != outIdx.size()) {
throw string("Target and output vectors must be of the same size in shellSort()");
}
// set up the initial output index values
//for (size_t i = beg; i < end; i++) {
// outIdx[i] = i;
//}
// pick the initial increment
size_t inc = 1;
do {
inc = inc*3 + 1;
} while (inc <= end - beg);
// start the sort
do { // loop over partial sorts, decreasing the increment each time
inc /= 3;
const size_t bottom = beg + inc;
for (size_t iOuter = bottom; iOuter < end; iOuter++) { // outer loop of the insertion sort, going over the indexes
if (outIdx[iOuter] >= target.size()) {
throw string("outIdx value out of bounds for target vector in shellSort()");
}
const size_t curInd = outIdx[iOuter]; // save the current value of the index
size_t jInner = iOuter;
while (target[ outIdx[jInner - inc] ] > target[ curInd ]) { // Straight insertion inner loop; looking for a place to insert the current value
if (outIdx[jInner-inc] >= target.size()) {
throw string("outIdx value out of bounds for target vector in shellSort()");
}
outIdx[jInner] = outIdx[jInner-inc];
jInner -= inc;
if (jInner < bottom) {
break;
}
}
outIdx[jInner] = curInd;
}
} while (inc > 1);
}
/** Quicksort
*
* This function implements the Quicksort algorithm, taking the Numerical Recipes implementation as a base. It re-arranges the indexes in the output vector rather than move around the elements of the target vector. The output index must be the same size as the target (this is checked and exception thown if the condidition is not met). The output index is initialized with the correct index values.
*
* \param[in] target vector to be sorted
* \param[in] beg index of the first element
* \param[in] end index of one past the last element to be included
* \param[out] outIdx vector of indexes
*
*/
void quickSort(const vector<double> &target, const size_t &beg, const size_t &end, vector<size_t> &outIdx){
if (target.size() < end) {
throw string("Target vector size smaller than end index in quickSort()");
} else if (outIdx.size() < end) {
throw string("Output vector size smaller than end index in quickSort()");
} else if (end < beg) {
throw string("End index smaller than beginning index in quickSort()");
} else if (target.size() != outIdx.size()) {
throw string("Target and output vectors must be of the same size in quickSort()");
}
for (size_t i = beg; i < end; i++) {
outIdx[i] = i;
}
// stacks to keep the l and ir values of the sub-vectors that are not being worked on
stack<size_t> lStack;
stack<size_t> irStack;
const size_t m = 15; // the size of the sub-vectors that will be sorted by shellSort
size_t l = beg; // left side of the sub-vector to be bisected
size_t ir = end - 1; // right side of the sub-vector to be bisected
while(true){
if (ir-l < m) { // the current sub-vector is small enough for shellSort
shellSort(target, l, ir+1, outIdx);
if (lStack.empty()) {
break;
}
l = lStack.top();
lStack.pop();
ir = irStack.top();
irStack.pop();
} else {
const size_t k = (l+ir) >> 1; // median between l and ir
swapXOR(outIdx[k], outIdx[l+1]);
// rearrange the vector region so that target[outIdx[l]] <= target[outIdx[l+1]] <= target[outIdx[ir]]
if (target[ outIdx[l] ] > target[ outIdx[ir] ]) {
swapXOR(outIdx[l], outIdx[ir]);
}
if (target[ outIdx[l+1] ] > target[ outIdx[ir] ]) {
swapXOR(outIdx[l+1], outIdx[ir]);
}
if (target[ outIdx[l] ] > target[ outIdx[l+1] ]) {
swapXOR(outIdx[l], outIdx[l+1]);
}
// set the range for partitioning
size_t i = l+1;
size_t j = ir;
size_t ip = outIdx[l+1]; // index of the pivot (partitioning element)
while(true){ // inner loop
do {
i++;
} while(target[ outIdx[i] ] < target[ ip ]); // scan forward to find element > pivot
do {
j--;
} while(target[ outIdx[j] ] > target[ ip ]); // scan backwards to find element < pivot
if (j < i) { // stop the scans if the indexes crossed
break;
}
swapXOR(outIdx[i], outIdx[j]); // exchange elements unless the indexes have crossed
}
outIdx[l+1] = outIdx[j]; // insert the index of the pivot
outIdx[j] = ip;
// push the indexes of defining the larger sub-vector to the stacks; the smaller sub-vector will be processed in the next iteration of the loop
if ( (ir-i+1) > (j-l) ) {
lStack.push(i);
irStack.push(ir);
ir = j - 1;
} else {
lStack.push(l);
irStack.push(j-1);
l = i;
}
}
}
}
}
#endif /* utilities_hpp */
| [
"[email protected]"
] | |
ea8aced1719207ae48408b8c869b1b39321b001f | 2cf838b54b556987cfc49f42935f8aa7563ea1f4 | /aws-cpp-sdk-awstransfer/include/aws/awstransfer/model/Protocol.h | b916cbb80e3b96b2cd32a08683e2afe256637a6f | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | QPC-database/aws-sdk-cpp | d11e9f0ff6958c64e793c87a49f1e034813dac32 | 9f83105f7e07fe04380232981ab073c247d6fc85 | refs/heads/main | 2023-06-14T17:41:04.817304 | 2021-07-09T20:28:20 | 2021-07-09T20:28:20 | 384,714,703 | 1 | 0 | Apache-2.0 | 2021-07-10T14:16:41 | 2021-07-10T14:16:41 | null | UTF-8 | C++ | false | false | 617 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/awstransfer/Transfer_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace Transfer
{
namespace Model
{
enum class Protocol
{
NOT_SET,
SFTP,
FTP,
FTPS
};
namespace ProtocolMapper
{
AWS_TRANSFER_API Protocol GetProtocolForName(const Aws::String& name);
AWS_TRANSFER_API Aws::String GetNameForProtocol(Protocol value);
} // namespace ProtocolMapper
} // namespace Model
} // namespace Transfer
} // namespace Aws
| [
"[email protected]"
] | |
e3a3dc2a7e4e45b67c3de0e0411b68caea317f92 | d6f182688087f16a6c174e01638de38266fe5459 | /工作目录/称重项目/20170723/WeighSensor/shuruxishu.cpp | b13ef2876704aae58a5c70f600791acf1cd7a903 | [] | no_license | xsw258x2s5w8/WorkDir1 | ad1c9f1c30233ab74094a0b89e5db831b0e6cf8f | 83fd028bea424c11e9068cf6d1cebc0091584d3d | refs/heads/master | 2021-01-01T18:20:41.799845 | 2017-07-27T11:38:00 | 2017-07-27T11:38:00 | 98,314,467 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 655 | cpp | #include "shuruxishu.h"
#include "ui_shuruxishu.h"
#include "index.h"
#include "shuruxishutioajiao.h"
Shuruxishu::Shuruxishu(QWidget *parent) :
QWidget(parent),
ui(new Ui::Shuruxishu)
{
ui->setupUi(this);
connect(ui->returnIndex,SIGNAL(clicked()),this,SLOT(returnIndex()));
connect(ui->returnPage,SIGNAL(clicked()),this,SLOT(returnPage()));
}
Shuruxishu::~Shuruxishu()
{
delete ui;
}
void Shuruxishu::returnIndex()
{
// Index *menu=new Index();
// menu->show();
this->close();
}
void Shuruxishu::returnPage()
{
Shuruxishutioajiao *returnPage=new Shuruxishutioajiao();
returnPage->show();
this->close();
}
| [
"[email protected]"
] | |
c134767e7d527dc572391ed3114e0f0079e401c3 | c2233b9d54688c32836dea72b6c9ac3306d37213 | /analyzer/analyzer.cpp | d0b1527cad1147c97616398264cea045dbd47a65 | [
"MIT"
] | permissive | zarath/AntScope2 | 64f404acdad819aa886d63c259513cf9fb5e47b9 | 259f0d36e82384487ca214bfc793cb0097e28f5c | refs/heads/master | 2022-11-17T23:32:59.507981 | 2020-07-14T20:13:50 | 2020-07-14T20:13:50 | 279,683,944 | 0 | 0 | MIT | 2020-07-14T20:14:14 | 2020-07-14T20:14:14 | null | UTF-8 | C++ | false | false | 34,902 | cpp | #include "analyzer.h"
#include "popupindicator.h"
#include "customanalyzer.h"
#include <QDateTime>
#include "Notification.h"
Analyzer::Analyzer(QObject *parent) : QObject(parent),
m_hidAnalyzer(nullptr),
m_comAnalyzer(nullptr),
m_analyzerModel(0),
m_comAnalyzerFound(false),
m_hidAnalyzerFound(false),
m_nanovnaAnalyzerFound(false),
m_chartCounter(0),
m_isMeasuring(false),
m_isContinuos(false),
m_dotsNumber(100),
m_downloader(nullptr),
m_updateDialog(nullptr),
m_pfw(nullptr),
m_INFOSIZE(512),
m_MAGICAA230Z(0xFE02A185),
m_MAGICHID(0x5c620202),
m_INTERNALMAGICAA230Z(0x87654321),
m_MAGICAA30ZERO(0x5c623002),
m_calibrationMode(false)
{
m_pfw = new QByteArray;
}
Analyzer::~Analyzer()
{
if(m_downloader)
{
delete m_downloader;
m_downloader = nullptr;
}
delete m_pfw;
if(m_hidAnalyzer)
{
delete m_hidAnalyzer;
m_hidAnalyzer = nullptr;
}
if(m_comAnalyzer)
{
comAnalyzer* tmp = m_comAnalyzer;
m_comAnalyzer = nullptr;
delete tmp;
}
}
double Analyzer::getVersion() const
{
if(m_comAnalyzerFound && m_comAnalyzer != nullptr)
{
return m_comAnalyzer->getVersion().toDouble();
}else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr)
{
return m_hidAnalyzer->getVersion().toDouble();
}
return 0;
}
void Analyzer::on_downloadInfoComplete()
{
QString ver = m_downloader->version();
if (m_bManualUpdate)
{
if(ver.isEmpty())
{
QMessageBox::information(nullptr, tr("Latest version"),
tr("Can not get the latest version.\nPlease try later."));
}else
{
double internetVersion = ver.toDouble();//ver.remove(".").toInt();
m_updateDialog = new UpdateDialog();
m_updateDialog->setAttribute(Qt::WA_DeleteOnClose);
m_updateDialog->setWindowTitle(tr("Updating"));
connect(m_updateDialog,SIGNAL(update()),this,SLOT(on_internetUpdate()));
connect(this, SIGNAL(updatePercentChanged(int)),m_updateDialog,SLOT(on_percentChanged(qint32)));
if(internetVersion > getVersion())
{
m_updateDialog->setMainText(tr("New version of firmware is available now!"));
}else
{
m_updateDialog->setMainText(tr("You have the latest version of firmware."));
}
m_updateDialog->exec();
}
} else { // auto check for new firmvare
if (!ver.isEmpty())
{
double internetVersion = ver.toDouble();
if(internetVersion > getVersion())
{
const qint64 interval = 24*60*60;
QString serialNumber = getSerialNumber();
QString key = "firmware_" + serialNumber;
QSettings settings(Settings::setIniFile(), QSettings::IniFormat);
settings.beginGroup("Update");
qint64 last_notify = settings.value(key, 0).toLongLong();
QDateTime last_dt;
last_dt.setMSecsSinceEpoch(last_notify);
QDateTime current_dt = QDateTime::currentDateTime();
if (last_dt.secsTo(current_dt) > interval)
{
settings.setValue(key, QDateTime::currentMSecsSinceEpoch());
emit showNotification(
QString(tr("New version of firmware is available now!")),
m_downloader->downloadLink());
}
settings.endGroup();
}
}
}
}
bool Analyzer::needCheckForUpdate()
{
const qint64 interval = 24*60*60;
QString serialNumber = getSerialNumber();
QString key = "firmware_" + serialNumber;
QSettings settings(Settings::setIniFile(), QSettings::IniFormat);
settings.beginGroup("Update");
qint64 last_notify = settings.value(key, 0).toLongLong();
QDateTime last_dt;
last_dt.setMSecsSinceEpoch(last_notify);
QDateTime current_dt = QDateTime::currentDateTime();
return last_dt.secsTo(current_dt) > interval;
}
void Analyzer::on_downloadFileComplete()
{
*m_pfw = m_downloader->file();
QBuffer fwdata(m_pfw);
fwdata.open(QIODevice::ReadOnly);
fwdata.seek(m_INFOSIZE);
updateFirmware(&fwdata);
}
void Analyzer::on_internetUpdate()
{
m_downloader->startDownloadFw();
m_updateDialog->setStatusText(tr("Downloading firmware..."));
}
void Analyzer::readFile(QString pathToFw)
{
QFile file(pathToFw);
bool state = true;
if(!file.open(QIODevice::ReadOnly))
{
QMessageBox::warning(nullptr, tr("Warning"), tr("Can not open firmware file."));
return;
}
*m_pfw = file.readAll();
if (m_pfw->isEmpty())
{
QMessageBox::warning(nullptr, tr("Warning"), tr("Can not read firmware file."));
state = false;
}
file.close();
if(state)
{
//m_updateDialog->setStatusText(tr("Updating, please wait..."));
QBuffer fwdata(m_pfw);
fwdata.open(QIODevice::ReadOnly);
fwdata.seek(m_INFOSIZE);
updateFirmware(&fwdata);
}
}
bool Analyzer::checkFile(QString path)
{
QFile fwfile(path);
QByteArray arr;
QByteArray fw;
quint32 magic = 0;
quint32 len = 0;
quint32 readCrc = 0;
quint32 revision = 0;
const char *pd;
if (!fwfile.open(QIODevice::ReadOnly)) {
QMessageBox::warning(nullptr, tr("Warning"),
tr("Firmware file can not open"));
return false;
}
arr = fwfile.read(m_INFOSIZE);
if ((qint32)arr.length() < m_INFOSIZE)
{
fwfile.close();
return false;
}
pd = arr.constData();
magic = qFromLittleEndian<quint32>(*((quint32*)pd));
len = qFromLittleEndian<quint32>(*((quint32*)&pd[4]));
readCrc = qFromLittleEndian<quint32>(*((quint32*)&pd[8]));
revision = qFromLittleEndian<quint32>(*((quint32*)&pd[20]));
if(m_hidAnalyzer)
{
//m_hidAnalyzer->setRevision(revision); // old
m_hidAnalyzer->setRevision(QString::number(revision));
}
QString prototype = CustomAnalyzer::currentPrototype();
if(((names[getAnalyzerModel()] == "AA-230 ZOOM" || prototype == "AA-230 ZOOM") && (magic == m_MAGICAA230Z)) ||
((names[getAnalyzerModel()] == "AA-650 ZOOM" || prototype == "AA-650 ZOOM") && (magic == m_MAGICAA230Z)) ||
((names[getAnalyzerModel()] == "AA-55 ZOOM" || prototype == "AA-55 ZOOM") && (magic == m_MAGICHID)) ||
((names[getAnalyzerModel()] == "AA-35 ZOOM" || prototype == "AA-35 ZOOM") && (magic == m_MAGICHID)) ||
((names[getAnalyzerModel()] == "AA-30 ZERO" || prototype == "AA-30 ZERO") && (magic == m_MAGICAA30ZERO)) ||
((names[getAnalyzerModel()] == "AA-30.ZERO" || prototype == "AA-30.ZERO") && (magic == m_MAGICAA30ZERO)))
{
}else
{
QMessageBox::warning(nullptr, tr("Warning"),
tr("Firmware file has wrong format"));
fwfile.close();
return false;
}
if (!fwfile.seek(m_INFOSIZE))
{
QMessageBox::warning(nullptr, tr("Warning"),
tr("Firmware file is too short."));
fwfile.close();
return false;
}
fw = fwfile.readAll();
fwfile.close();
if ((quint32)fw.length() != len) {
QMessageBox::warning(nullptr, tr("Warning"),
tr("Firmware file has wrong length."));
return false;
}
if (readCrc != CRC32::crc(0xffffffff, fw)) {
QMessageBox::warning(nullptr, tr("Warning"),
tr("Firmware file has wrong CRC."));
return false;
}
return true;
}
QString Analyzer::getModelString( void )
{
return CustomAnalyzer::customized() ? CustomAnalyzer::currentPrototype() : names[m_analyzerModel];
}
quint32 Analyzer::getModel( void )
{
return m_analyzerModel;
}
quint32 Analyzer::getHidModel( void )
{
return m_hidAnalyzer->getModel();
}
QString Analyzer::getSerialNumber(void) const
{
if(m_hidAnalyzerFound && m_hidAnalyzer != nullptr)
{
return m_hidAnalyzer->getSerial();
}else if(m_comAnalyzerFound && m_comAnalyzer != nullptr)
{
return m_comAnalyzer->getSerial();
}
return QString();
}
void Analyzer::on_measure (qint64 fqFrom, qint64 fqTo, qint32 dotsNumber)
{
m_getAnalyzerData = false;
if(!m_isMeasuring)
{
m_isMeasuring = true;
QDateTime datetime = QDateTime::currentDateTime();
QString name = datetime.toString("##dd.MM.yyyy-hh:mm:ss");
emit newMeasurement(name, fqFrom, fqTo, dotsNumber);
//emit newMeasurement(name);
m_dotsNumber = dotsNumber;
m_chartCounter = 0;
if (m_nanovnaAnalyzerFound && m_NanovnaAnalyzer != nullptr)
{
m_dotsNumber = 101;
m_NanovnaAnalyzer->startMeasure(fqFrom, fqTo, m_dotsNumber);
} else if(m_comAnalyzerFound && m_comAnalyzer != nullptr)
{
m_comAnalyzer->setIsFRXMode(true);
m_comAnalyzer->startMeasure(fqFrom,fqTo,m_dotsNumber);
}else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr)
{
m_hidAnalyzer->setIsFRXMode(true);
m_hidAnalyzer->startMeasure(fqFrom,fqTo,m_dotsNumber);
}
PopUpIndicator::setIndicatorVisible(true);
} else {
on_stopMeasure();
}
}
void Analyzer::on_measureContinuous(qint64 fqFrom, qint64 fqTo, qint32 dotsNumber)
{
if(!m_isMeasuring)
{
qDebug() << "Analyzer::on_measureContinuous" << fqFrom << fqTo << dotsNumber;
m_isMeasuring = true;
//QThread::msleep(500);
emit continueMeasurement(fqFrom, fqTo, dotsNumber);
m_dotsNumber = dotsNumber;
m_chartCounter = 0;
if (m_nanovnaAnalyzerFound && m_NanovnaAnalyzer != nullptr)
{
//m_NanovnaAnalyzer->startMeasure(fqFrom, fqTo, dotsNumber);
} else if(m_comAnalyzerFound && m_comAnalyzer != nullptr)
{
m_comAnalyzer->startMeasure(fqFrom,fqTo,dotsNumber);
}else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr)
{
//m_hidAnalyzer->setIsFRXMode(true);
m_hidAnalyzer->startMeasure(fqFrom,fqTo,dotsNumber);
}
PopUpIndicator::setIndicatorVisible(true);
} else {
qDebug() << "Analyzer::on_measureContinuous STOP";
on_stopMeasure();
}
}
void Analyzer::on_measureUser (qint64 fqFrom, qint64 fqTo, qint32 dotsNumber)
{
if(!m_isMeasuring)
{
m_isMeasuring = true;
QDateTime datetime = QDateTime::currentDateTime();
QString name = datetime.toString("##dd.MM.yyyy-hh:mm:ss");
emit newMeasurement(name, fqFrom, fqTo, dotsNumber);
m_dotsNumber = dotsNumber;
m_chartCounter = 0;
if(m_comAnalyzerFound && m_comAnalyzer != nullptr)
{
m_comAnalyzer->setIsFRXMode(false);
m_comAnalyzer->startMeasure(fqFrom,fqTo,dotsNumber);
}else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr)
{
m_hidAnalyzer->setIsFRXMode(false);
m_hidAnalyzer->startMeasure(fqFrom,fqTo,dotsNumber);
}
PopUpIndicator::setIndicatorVisible(true);
} else {
on_stopMeasure();
}
}
void Analyzer::on_measureOneFq(QWidget* /*parent*/, qint64 fqFrom, qint32 /*dotsNumber*/)
{
m_isMeasuring = true;
m_dotsNumber = 100000;
m_chartCounter = 0;
if(m_comAnalyzerFound && m_comAnalyzer != nullptr)
{
m_comAnalyzer->setIsFRXMode(true);
m_comAnalyzer->startMeasureOneFq(fqFrom,m_dotsNumber);
}else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr)
{
m_hidAnalyzer->setIsFRXMode(true);
m_hidAnalyzer->startMeasureOneFq(fqFrom,m_dotsNumber);
}
}
void Analyzer::on_stopMeasure()
{
PopUpIndicator::setIndicatorVisible(false);
m_isMeasuring = false;
m_chartCounter = 0;
if (m_nanovnaAnalyzerFound && m_NanovnaAnalyzer != nullptr)
{
m_NanovnaAnalyzer->stopMeasure();
} else if(m_comAnalyzerFound && m_comAnalyzer != nullptr)
{
m_comAnalyzer->stopMeasure();
}else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr)
{
m_hidAnalyzer->stopMeasure();
}
emit measurementComplete();
}
void Analyzer::updateFirmware (QIODevice *fw)
{
if(m_comAnalyzerFound && m_comAnalyzer != nullptr)
{
m_comAnalyzer->update(fw);
}else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr)
{
m_hidAnalyzer->update(fw);
}
}
void Analyzer::setAutoCheckUpdate( bool state)
{
m_autoCheckUpdate = state;
}
void Analyzer::makeScreenshot()
{
if(!m_isMeasuring)
{
if(m_comAnalyzerFound && m_comAnalyzer != nullptr)
{
QTimer::singleShot(100, m_comAnalyzer, SLOT(makeScreenshot()));
}else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr)
{
QTimer::singleShot(100, m_hidAnalyzer, SLOT(makeScreenshot()));
}
}
}
void Analyzer::on_hidAnalyzerFound (quint32 analyzerNumber)
{
if(m_comAnalyzer)
{
comAnalyzer* tmp = m_comAnalyzer;
m_comAnalyzer = nullptr;
delete tmp;
}
m_hidAnalyzerFound = true;
m_analyzerModel = analyzerNumber;
QString str = CustomAnalyzer::customized() ? CustomAnalyzer::currentAlias() : names[m_analyzerModel];
emit analyzerFound(str);
//if(m_autoCheckUpdate)
extern bool g_developerMode;
if (!g_developerMode)
{
QTimer::singleShot(5000, [this]() {
this->checkFirmwareUpdate();
});
}
}
void Analyzer::on_hidAnalyzerDisconnected ()
{
if(!m_comAnalyzer)
{
m_comAnalyzer = new comAnalyzer(this);
connect(m_comAnalyzer,SIGNAL(newData(rawData)),this,SLOT(on_newData(rawData)));
connect(m_comAnalyzer,SIGNAL(newUserData(rawData,UserData)),this,SLOT(on_newUserData(rawData,UserData)));
connect(m_comAnalyzer,SIGNAL(newUserDataHeader(QStringList)),this,SLOT(on_newUserDataHeader(QStringList)));
connect(m_comAnalyzer,SIGNAL(analyzerFound(quint32)),this,SLOT(on_comAnalyzerFound(quint32)));
connect(m_comAnalyzer,SIGNAL(analyzerDisconnected()),this,SLOT(on_comAnalyzerDisconnected()));
connect(m_comAnalyzer,SIGNAL(analyzerDataStringArrived(QString)),this,SLOT(on_analyzerDataStringArrived(QString)));
connect(m_comAnalyzer,SIGNAL(analyzerScreenshotDataArrived(QByteArray)),this,SLOT(on_analyzerScreenshotDataArrived(QByteArray)));
connect(m_comAnalyzer,SIGNAL(updatePercentChanged(int)),this,SLOT(on_updatePercentChanged(int)));
connect(this, SIGNAL(screenshotComplete()),m_comAnalyzer,SLOT(on_screenshotComplete()));
connect(this, SIGNAL(measurementComplete()), m_comAnalyzer, SLOT(on_measurementComplete()));//, Qt::QueuedConnection);
connect(m_comAnalyzer,SIGNAL(aa30bootFound()),this,SIGNAL(aa30bootFound()));
connect(m_comAnalyzer, SIGNAL(aa30updateComplete()), this, SIGNAL(aa30updateComplete()));
connect(m_comAnalyzer, &comAnalyzer::signalFullInfo, this, &Analyzer::slotFullInfo);
connect(m_comAnalyzer, &comAnalyzer::signalMeasurementError, this, &Analyzer::signalMeasurementError);
}
m_hidAnalyzerFound = false;
m_analyzerModel = 0;
emit analyzerDisconnected();
}
void Analyzer::on_comAnalyzerFound (quint32 analyzerNumber)
{
if(m_hidAnalyzer)
{
delete m_hidAnalyzer;
m_hidAnalyzer = nullptr;
}
m_comAnalyzerFound = true;
m_analyzerModel = analyzerNumber;
QString str = CustomAnalyzer::customized() ? CustomAnalyzer::currentPrototype() : names[m_analyzerModel];
emit analyzerFound(str);
// //if(m_autoCheckUpdate)
// {
// QString url = "https://www.rigexpert.com/getfirmware?model=";
// url += names[m_analyzerModel].toLower().remove(" ").remove("-");
// url += "&sn=";
// url += m_hidAnalyzer->getSerial();
// url += "&revision=";
// url += "1";
// m_downloader->startDownloadInfo(QUrl(url));
// }
//if(m_autoCheckUpdate)
extern bool g_developerMode;
if (!g_developerMode)
{
QTimer::singleShot(5000, [this]() {
this->checkFirmwareUpdate();
});
}
}
void Analyzer::on_comAnalyzerDisconnected ()
{
if(!m_hidAnalyzer)
{
m_hidAnalyzer = new hidAnalyzer(this);
connect(m_hidAnalyzer,SIGNAL(newData(rawData)),this,SLOT(on_newData(rawData)));
connect(m_hidAnalyzer,SIGNAL(newUserData(rawData,UserData)),this,SLOT(on_newUserData(rawData,UserData)));
connect(m_hidAnalyzer,SIGNAL(newUserDataHeader(QStringList)),this,SLOT(on_newUserDataHeader(QStringList)));
connect(m_hidAnalyzer,SIGNAL(analyzerFound(quint32)),this,SLOT(on_hidAnalyzerFound(quint32)));
connect(m_hidAnalyzer,SIGNAL(analyzerDisconnected()),this,SLOT(on_hidAnalyzerDisconnected()));
connect(m_hidAnalyzer,SIGNAL(analyzerDataStringArrived(QString)),this,SLOT(on_analyzerDataStringArrived(QString)));
connect(m_hidAnalyzer,SIGNAL(analyzerScreenshotDataArrived(QByteArray)),this,SLOT(on_analyzerScreenshotDataArrived(QByteArray)));
connect(this, SIGNAL(screenshotComplete()),m_hidAnalyzer,SLOT(on_screenshotComplete()));
connect(this, SIGNAL(measurementComplete()), m_hidAnalyzer, SLOT(on_measurementComplete()));//, Qt::QueuedConnection);
connect(m_hidAnalyzer, &hidAnalyzer::signalFullInfo, this, &Analyzer::slotFullInfo);
connect(m_hidAnalyzer, &hidAnalyzer::signalMeasurementError, this, &Analyzer::signalMeasurementError);
}
m_comAnalyzerFound = false;
m_analyzerModel = 0;
if(m_comAnalyzer != nullptr)
{
m_comAnalyzer->setAnalyzerModel(0);
}
emit analyzerDisconnected();
}
void Analyzer::on_nanovnaAnalyzerFound (QString name)
{
if(m_hidAnalyzer)
{
delete m_hidAnalyzer;
m_hidAnalyzer = nullptr;
}
if(m_comAnalyzer)
{
delete m_comAnalyzer;
m_comAnalyzer = nullptr;
}
m_hidAnalyzerFound = false;
m_comAnalyzerFound = false;
m_nanovnaAnalyzerFound = true;
for (int i=0; i<QUANTITY; i++) {
if (names[i] == "NanoVNA") {
m_analyzerModel = i;
break;
}
}
emit analyzerFound(name);
}
void Analyzer::on_nanovnaAnalyzerDisconnected()
{
if(!m_comAnalyzer)
{
m_comAnalyzer = new comAnalyzer(this);
connect(m_comAnalyzer,SIGNAL(newData(rawData)),this,SLOT(on_newData(rawData)));
connect(m_comAnalyzer,SIGNAL(newUserData(rawData,UserData)),this,SLOT(on_newUserData(rawData,UserData)));
connect(m_comAnalyzer,SIGNAL(newUserDataHeader(QStringList)),this,SLOT(on_newUserDataHeader(QStringList)));
connect(m_comAnalyzer,SIGNAL(analyzerFound(quint32)),this,SLOT(on_comAnalyzerFound(quint32)));
connect(m_comAnalyzer,SIGNAL(analyzerDisconnected()),this,SLOT(on_comAnalyzerDisconnected()));
connect(m_comAnalyzer,SIGNAL(analyzerDataStringArrived(QString)),this,SLOT(on_analyzerDataStringArrived(QString)));
connect(m_comAnalyzer,SIGNAL(analyzerScreenshotDataArrived(QByteArray)),this,SLOT(on_analyzerScreenshotDataArrived(QByteArray)));
connect(m_comAnalyzer,SIGNAL(updatePercentChanged(int)),this,SLOT(on_updatePercentChanged(int)));
connect(this, SIGNAL(screenshotComplete()),m_comAnalyzer,SLOT(on_screenshotComplete()));
connect(this, SIGNAL(measurementComplete()), m_comAnalyzer, SLOT(on_measurementComplete()));//, Qt::QueuedConnection);
connect(m_comAnalyzer,SIGNAL(aa30bootFound()),this,SIGNAL(aa30bootFound()));
connect(m_comAnalyzer, SIGNAL(aa30updateComplete()), this, SIGNAL(aa30updateComplete()));
connect(m_comAnalyzer, &comAnalyzer::signalFullInfo, this, &Analyzer::slotFullInfo);
connect(m_comAnalyzer, &comAnalyzer::signalMeasurementError, this, &Analyzer::signalMeasurementError);
}
if(!m_hidAnalyzer)
{
m_hidAnalyzer = new hidAnalyzer(this);
connect(m_hidAnalyzer,SIGNAL(newData(rawData)),this,SLOT(on_newData(rawData)));
connect(m_hidAnalyzer,SIGNAL(newUserData(rawData,UserData)),this,SLOT(on_newUserData(rawData,UserData)));
connect(m_hidAnalyzer,SIGNAL(newUserDataHeader(QStringList)),this,SLOT(on_newUserDataHeader(QStringList)));
connect(m_hidAnalyzer,SIGNAL(analyzerFound(quint32)),this,SLOT(on_hidAnalyzerFound(quint32)));
connect(m_hidAnalyzer,SIGNAL(analyzerDisconnected()),this,SLOT(on_hidAnalyzerDisconnected()));
connect(m_hidAnalyzer,SIGNAL(analyzerDataStringArrived(QString)),this,SLOT(on_analyzerDataStringArrived(QString)));
connect(m_hidAnalyzer,SIGNAL(analyzerScreenshotDataArrived(QByteArray)),this,SLOT(on_analyzerScreenshotDataArrived(QByteArray)));
connect(this, SIGNAL(screenshotComplete()),m_hidAnalyzer,SLOT(on_screenshotComplete()));
connect(this, SIGNAL(measurementComplete()), m_hidAnalyzer, SLOT(on_measurementComplete()));//, Qt::QueuedConnection);
connect(m_hidAnalyzer, &hidAnalyzer::signalFullInfo, this, &Analyzer::slotFullInfo);
connect(m_hidAnalyzer, &hidAnalyzer::signalMeasurementError, this, &Analyzer::signalMeasurementError);
}
m_nanovnaAnalyzerFound = false;
m_analyzerModel = 0;
emit analyzerDisconnected();
}
void Analyzer::on_newData(rawData _rawData)
{
if (m_getAnalyzerData) {
emit newAnalyzerData (_rawData);
} else {
emit newData (_rawData);
}
if(++m_chartCounter >= m_dotsNumber+1 || !m_isMeasuring)
{
m_isMeasuring = false;
m_chartCounter = 0;
PopUpIndicator::setIndicatorVisible(false);
if(!m_calibrationMode)
{
emit measurementComplete();
}
}
}
void Analyzer::on_newUserData(rawData _rawData, UserData _userData)
{
if(++m_chartCounter == m_dotsNumber+1 || !m_isMeasuring)
{
emit newUserData (_rawData, _userData);
m_isMeasuring = false;
m_chartCounter = 0;
PopUpIndicator::setIndicatorVisible(false);
if(!m_calibrationMode)
{
emit measurementComplete();
}
}else
{
emit newUserData (_rawData, _userData);
}
}
void Analyzer::on_newUserDataHeader(QStringList fields)
{
emit newUserDataHeader (fields);
}
void Analyzer::on_analyzerDataStringArrived(QString str)
{
emit analyzerDataStringArrived(str);
}
void Analyzer::getAnalyzerData()
{
if(!m_isMeasuring)
{
if(m_comAnalyzerFound && m_comAnalyzer != nullptr)
{
QTimer::singleShot(100, m_comAnalyzer, SLOT(getAnalyzerData()));
}else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr)
{
QTimer::singleShot(100, m_hidAnalyzer, SLOT(getAnalyzerData()));
}
}
}
void Analyzer::on_itemDoubleClick(QString number, QString dotsNumber, QString name)
{
setIsMeasuring(true);
if (name.trimmed().isEmpty()) {
name = number;
}
m_getAnalyzerData = true;
if(m_comAnalyzerFound && m_comAnalyzer != nullptr)
{
m_chartCounter = 0;
m_dotsNumber = dotsNumber.toInt();
emit newMeasurement(name);
m_comAnalyzer->getAnalyzerData(number);
}else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr)
{
m_chartCounter = 0;
m_dotsNumber = dotsNumber.toInt();
emit newMeasurement(name);
m_hidAnalyzer->getAnalyzerData(number);
}
}
void Analyzer::on_dialogClosed()
{
//setIsMeasuring(false);
}
void Analyzer::on_stopMeasuring()
{
setIsMeasuring(false);
}
void Analyzer::on_analyzerScreenshotDataArrived(QByteArray arr)
{
emit analyzerScreenshotDataArrived(arr);
}
void Analyzer::on_screenshotComplete(void)
{
emit screenshotComplete();
}
void Analyzer::on_updatePercentChanged(int number)
{
if (m_updateDialog != nullptr)
m_updateDialog->on_percentChanged(number);
emit updatePercentChanged(number);
}
void Analyzer::checkFirmwareUpdate()
{
if (needCheckForUpdate())
{
on_checkUpdatesBtn_clicked();
m_bManualUpdate = false;
}
}
void Analyzer::on_checkUpdatesBtn_clicked()
{
m_bManualUpdate = true;
if(m_downloader == nullptr)
{
m_downloader = new Downloader();
connect(m_downloader, SIGNAL(downloadInfoComplete()),
this, SLOT(on_downloadInfoComplete()));
connect(m_downloader, SIGNAL(downloadFileComplete()),
this, SLOT(on_downloadFileComplete()));
connect(m_downloader, SIGNAL(progress(qint64,qint64)),
this, SLOT(on_progress(qint64,qint64)));
}
QString url = "https://www.rigexpert.com/getfirmware?model=";
QString prototype = CustomAnalyzer::customized() ? CustomAnalyzer::currentPrototype() : names[m_analyzerModel];
//url += names[m_analyzerModel].toLower().remove(" ").remove("-");
url += prototype.toLower().remove(" ").remove("-");
url += "&sn=";
if(m_hidAnalyzerFound && m_hidAnalyzer != nullptr)
{
url += m_hidAnalyzer->getSerial();
url += "&revision=";
url += m_hidAnalyzer->getRevision();
}else if (m_comAnalyzerFound && m_comAnalyzer != nullptr)
{
url += m_comAnalyzer->getSerial();
url += "&revision=";
url += m_comAnalyzer->getRevision();
}
if (m_mapFullInfo.contains("MAC"))
{
url += "&mac=" + m_mapFullInfo["MAC"];
}
if (m_mapFullInfo.contains("SN"))
{
url += "&s_n=" + m_mapFullInfo["SN"];
}
m_downloader->startDownloadInfo(QUrl(url));
}
void Analyzer::on_progress(qint64 downloaded,qint64 total)
{
int percent = downloaded*100/total;
if (percent == 100)
{
emit updatePercentChanged(0);
m_updateDialog->setStatusText(tr("Updating, please wait..."));
}else
{
emit updatePercentChanged(percent);
}
}
bool Analyzer::openComPort(const QString& portName, quint32 portSpeed)
{
return (m_comAnalyzer == nullptr ? false : m_comAnalyzer->openComPort(portName, portSpeed));
}
void Analyzer::closeComPort()
{
if(m_comAnalyzer != nullptr)
{
m_comAnalyzer->closeComPort();
}
}
void Analyzer::setAnalyzerModel (int model)
{
if(m_comAnalyzerFound && m_comAnalyzer != nullptr)
{
m_analyzerModel = model;
m_comAnalyzer->setAnalyzerModel(model);
m_comAnalyzer->setIsMeasuring(true);
}
}
void Analyzer::on_measureCalib(int dotsNumber)
{
m_isMeasuring = true;
m_dotsNumber = dotsNumber;
qint64 minFq_ = minFq[m_analyzerModel].toULongLong()*1000;
qint64 maxFq_ = maxFq[m_analyzerModel].toULongLong()*1000;
if (CustomAnalyzer::customized()) {
CustomAnalyzer* ca = CustomAnalyzer::getCurrent();
if (ca != nullptr) {
minFq_ = ca->minFq().toULongLong()*1000;
maxFq_ = ca->maxFq().toULongLong()*1000;
}
}
if(m_comAnalyzerFound && m_comAnalyzer != nullptr)
{
m_comAnalyzer->startMeasure(minFq_, maxFq_, dotsNumber);
}else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr)
{
m_hidAnalyzer->startMeasure(minFq_, maxFq_, dotsNumber);
}
}
void Analyzer::setCalibrationMode(bool enabled)
{
m_calibrationMode = enabled;
}
void Analyzer::on_changedAutoDetectMode(bool state)
{
if(state)
{
if(m_hidAnalyzer == nullptr)
{
m_hidAnalyzer = new hidAnalyzer(this);
connect(m_hidAnalyzer,SIGNAL(newData(rawData)),this,SLOT(on_newData(rawData)));
connect(m_hidAnalyzer,SIGNAL(newUserData(rawData,UserData)),this,SLOT(on_newUserData(rawData,UserData)));
connect(m_hidAnalyzer,SIGNAL(newUserDataHeader(QStringList)),this,SLOT(on_newUserDataHeader(QStringList)));
connect(m_hidAnalyzer,SIGNAL(analyzerFound(quint32)),this,SLOT(on_hidAnalyzerFound(quint32)));
connect(m_hidAnalyzer,SIGNAL(analyzerDisconnected()),this,SLOT(on_hidAnalyzerDisconnected()));
connect(m_hidAnalyzer,SIGNAL(analyzerDataStringArrived(QString)),this,SLOT(on_analyzerDataStringArrived(QString)));
connect(m_hidAnalyzer,SIGNAL(analyzerScreenshotDataArrived(QByteArray)),this,SLOT(on_analyzerScreenshotDataArrived(QByteArray)));
connect(m_hidAnalyzer,SIGNAL(updatePercentChanged(int)),this,SLOT(on_updatePercentChanged(int)));
connect(this, SIGNAL(screenshotComplete()),m_hidAnalyzer,SLOT(on_screenshotComplete()));
connect(this, SIGNAL(measurementComplete()), m_hidAnalyzer, SLOT(on_measurementComplete()));//, Qt::QueuedConnection);
connect(m_hidAnalyzer, &hidAnalyzer::signalFullInfo, this, &Analyzer::slotFullInfo);
connect(m_hidAnalyzer, &hidAnalyzer::signalMeasurementError, this, &Analyzer::signalMeasurementError);
}
}else
{
if(m_hidAnalyzer != nullptr)
{
delete m_hidAnalyzer;
m_hidAnalyzer = nullptr;
}
}
if(m_comAnalyzer == nullptr)
{
m_comAnalyzer = new comAnalyzer(this);
connect(m_comAnalyzer,SIGNAL(newData(rawData)),this,SLOT(on_newData(rawData)));
connect(m_comAnalyzer,SIGNAL(newUserData(rawData,UserData)),this,SLOT(on_newUserData(rawData,UserData)));
connect(m_comAnalyzer,SIGNAL(newUserDataHeader(QStringList)),this,SLOT(on_newUserDataHeader(QStringList)));
connect(m_comAnalyzer,SIGNAL(analyzerFound(quint32)),this,SLOT(on_comAnalyzerFound(quint32)));
connect(m_comAnalyzer,SIGNAL(analyzerDisconnected()),this,SLOT(on_comAnalyzerDisconnected()));
connect(m_comAnalyzer,SIGNAL(analyzerDataStringArrived(QString)),this,SLOT(on_analyzerDataStringArrived(QString)));
connect(m_comAnalyzer,SIGNAL(analyzerScreenshotDataArrived(QByteArray)),this,SLOT(on_analyzerScreenshotDataArrived(QByteArray)));
connect(m_comAnalyzer,SIGNAL(updatePercentChanged(int)),this,SLOT(on_updatePercentChanged(int)));
connect(this, SIGNAL(screenshotComplete()),m_comAnalyzer,SLOT(on_screenshotComplete()));
connect(this, SIGNAL(measurementComplete()), m_comAnalyzer, SLOT(on_measurementComplete()));//, Qt::QueuedConnection);
connect(m_comAnalyzer, SIGNAL(aa30bootFound()), this, SIGNAL(aa30bootFound()));
connect(m_comAnalyzer, SIGNAL(aa30updateComplete()), this, SIGNAL(aa30updateComplete()));
connect(m_comAnalyzer, &comAnalyzer::signalFullInfo, this, &Analyzer::slotFullInfo);
connect(m_comAnalyzer, &comAnalyzer::signalMeasurementError, this, &Analyzer::signalMeasurementError);
QTimer::singleShot(1000, m_comAnalyzer, SLOT(searchAnalyzer()));
}
m_comAnalyzer->on_changedAutoDetectMode(state);
}
void Analyzer::on_changedSerialPort(QString portName)
{
if(m_comAnalyzer != nullptr)
{
m_comAnalyzer->on_changedSerialPort(portName);
}
}
void Analyzer::setIsMeasuring (bool _isMeasuring)
{
m_isMeasuring = _isMeasuring;
if(m_comAnalyzer != nullptr)
{
m_comAnalyzer->setIsMeasuring(_isMeasuring);
}
if(m_hidAnalyzer != nullptr)
{
m_hidAnalyzer->setIsMeasuring(_isMeasuring);
}
if(m_NanovnaAnalyzer != nullptr)
{
m_NanovnaAnalyzer->setIsMeasuring(_isMeasuring);
}
PopUpIndicator::setIndicatorVisible(m_isMeasuring);
}
void Analyzer::slotFullInfo(QString str)
{
QStringList list = str.split("\t");
if (list.size() < 2)
return;
m_mapFullInfo.insert(list[0], list[1]);
}
void Analyzer::searchAnalyzer()
{
if (!isMeasuring())
{
if (m_hidAnalyzer != nullptr)
m_hidAnalyzer->searchAnalyzer(true);
if (m_comAnalyzer != nullptr)
m_comAnalyzer->searchAnalyzer();
}
}
bool Analyzer::sendCommand(QString cmd)
{
bool ret = true;
if (getHidAnalyzer() != 0) {
getHidAnalyzer()->sendData(cmd);
} else if (getComAnalyzer() != 0) {
getComAnalyzer()->sendData(cmd);
} else {
ret = false;
}
return ret;
}
void Analyzer::setParseState(int _state)
{
if (getHidAnalyzer() != 0) {
getHidAnalyzer()->setParseState(_state);
} else if (getComAnalyzer() != 0) {
getComAnalyzer()->setParseState(_state);
}
}
int Analyzer::getParseState()
{
int ret = WAIT_NO;
if (getHidAnalyzer() != 0) {
getHidAnalyzer()->getParseState();
} else if (getComAnalyzer() != 0) {
getComAnalyzer()->getParseState();
}
return ret;
}
void Analyzer::on_getLicenses()
{
QString cmd = "LLIC\r\n";
setParseState(WAIT_LICENSE_LIST);
sendCommand(cmd);
}
void Analyzer::on_generateLicence()
{
QString cmd = "GLIC\r\n";
setParseState(WAIT_LICENSE_REQUEST);
sendCommand(cmd);
}
void Analyzer::on_applyLicense(QString& _license)
{
if (getHidAnalyzer() != 0) {
getHidAnalyzer()->applyLicense(_license);
} else if (getComAnalyzer() != 0) {
getComAnalyzer()->applyLicense(_license);
}
}
void Analyzer::on_disconnectNanoNVA()
{
if (m_NanovnaAnalyzer != nullptr) {
m_NanovnaAnalyzer->closeComPort();
m_NanovnaAnalyzer->disconnect();
m_NanovnaAnalyzer->deleteLater();
m_NanovnaAnalyzer = nullptr;
}
}
void Analyzer::on_connectNanoNVA()
{
// TODO disconnect all
// ...
// if (m_NanovnaAnalyzer == nullptr) {
// delete m_NanovnaAnalyzer;
// m_NanovnaAnalyzer = nullptr;
// }
if (NanovnaAnalyzer::portsCount() == 0) {
return;
}
int portIndex = 0;
if (NanovnaAnalyzer::portsCount() > 1) {
// TODO select comport
}
QString portName = NanovnaAnalyzer::availablePorts().at(portIndex).portName();
m_NanovnaAnalyzer = new NanovnaAnalyzer(this);
bool connected = m_NanovnaAnalyzer->openComPort(portName);
if (connected) {
connect(m_NanovnaAnalyzer,SIGNAL(analyzerFound(QString)),this,SLOT(on_nanovnaAnalyzerFound(QString)));
connect(m_NanovnaAnalyzer,SIGNAL(analyzerDisconnected()),this,SLOT(on_nanovnaAnalyzerDisconnected()));
connect(this, SIGNAL(measurementComplete()), m_NanovnaAnalyzer, SLOT(on_measurementComplete()));//, Qt::QueuedConnection);
connect(m_NanovnaAnalyzer, &NanovnaAnalyzer::signalFullInfo, this, &Analyzer::slotFullInfo);
connect(m_NanovnaAnalyzer, &NanovnaAnalyzer::signalMeasurementError, this, &Analyzer::signalMeasurementError);
connect(m_NanovnaAnalyzer,SIGNAL(newData(rawData)),this,SLOT(on_newData(rawData)));
connect(m_NanovnaAnalyzer, &NanovnaAnalyzer::completeMeasurement, this, [=](){
emit measurementCompleteNano();
});
m_NanovnaAnalyzer->checkAnalyzer();
}
}
| [
"[email protected]"
] | |
6709b905feb7467620da6dcd62252ce952f83df2 | 66862c422fda8b0de8c4a6f9d24eced028805283 | /slambook2/3rdparty/Pangolin/external/pybind11/tests/test_constants_and_functions.cpp | f5f9340959b6e1a6caee2ba95e5ed974393256e0 | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | zhh2005757/slambook2_in_Docker | 57ed4af958b730e6f767cd202717e28144107cdb | f0e71327d196cdad3b3c10d96eacdf95240d528b | refs/heads/main | 2023-09-01T03:26:37.542232 | 2021-10-27T11:45:47 | 2021-10-27T11:45:47 | 416,666,234 | 17 | 6 | MIT | 2021-10-13T09:51:00 | 2021-10-13T09:12:15 | null | UTF-8 | C++ | false | false | 3,905 | cpp | /*
tests/test_constants_and_functions.cpp -- global constants and functions, enumerations, raw byte strings
Copyright (c) 2016 Wenzel Jakob <[email protected]>
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"
enum MyEnum { EFirstEntry = 1, ESecondEntry };
std::string test_function1() {
return "test_function()";
}
std::string test_function2(MyEnum k) {
return "test_function(enum=" + std::to_string(k) + ")";
}
std::string test_function3(int i) {
return "test_function(" + std::to_string(i) + ")";
}
py::str test_function4() { return "test_function()"; }
py::str test_function4(char *) { return "test_function(char *)"; }
py::str test_function4(int, float) { return "test_function(int, float)"; }
py::str test_function4(float, int) { return "test_function(float, int)"; }
py::bytes return_bytes() {
const char *data = "\x01\x00\x02\x00";
return std::string(data, 4);
}
std::string print_bytes(py::bytes bytes) {
std::string ret = "bytes[";
const auto value = static_cast<std::string>(bytes);
for (size_t i = 0; i < value.length(); ++i) {
ret += std::to_string(static_cast<int>(value[i])) + " ";
}
ret.back() = ']';
return ret;
}
// Test that we properly handle C++17 exception specifiers (which are part of the function signature
// in C++17). These should all still work before C++17, but don't affect the function signature.
namespace test_exc_sp {
int f1(int x) noexcept { return x+1; }
int f2(int x) noexcept(true) { return x+2; }
int f3(int x) noexcept(false) { return x+3; }
int f4(int x) throw() { return x+4; } // Deprecated equivalent to noexcept(true)
struct C {
int m1(int x) noexcept { return x-1; }
int m2(int x) const noexcept { return x-2; }
int m3(int x) noexcept(true) { return x-3; }
int m4(int x) const noexcept(true) { return x-4; }
int m5(int x) noexcept(false) { return x-5; }
int m6(int x) const noexcept(false) { return x-6; }
int m7(int x) throw() { return x-7; }
int m8(int x) const throw() { return x-8; }
};
}
TEST_SUBMODULE(constants_and_functions, m) {
// test_constants
m.attr("some_constant") = py::int_(14);
// test_function_overloading
m.def("test_function", &test_function1);
m.def("test_function", &test_function2);
m.def("test_function", &test_function3);
#if defined(PYBIND11_OVERLOAD_CAST)
m.def("test_function", py::overload_cast<>(&test_function4));
m.def("test_function", py::overload_cast<char *>(&test_function4));
m.def("test_function", py::overload_cast<int, float>(&test_function4));
m.def("test_function", py::overload_cast<float, int>(&test_function4));
#else
m.def("test_function", static_cast<py::str (*)()>(&test_function4));
m.def("test_function", static_cast<py::str (*)(char *)>(&test_function4));
m.def("test_function", static_cast<py::str (*)(int, float)>(&test_function4));
m.def("test_function", static_cast<py::str (*)(float, int)>(&test_function4));
#endif
py::enum_<MyEnum>(m, "MyEnum")
.value("EFirstEntry", EFirstEntry)
.value("ESecondEntry", ESecondEntry)
.export_values();
// test_bytes
m.def("return_bytes", &return_bytes);
m.def("print_bytes", &print_bytes);
// test_exception_specifiers
using namespace test_exc_sp;
py::class_<C>(m, "C")
.def(py::init<>())
.def("m1", &C::m1)
.def("m2", &C::m2)
.def("m3", &C::m3)
.def("m4", &C::m4)
.def("m5", &C::m5)
.def("m6", &C::m6)
.def("m7", &C::m7)
.def("m8", &C::m8)
;
m.def("f1", f1);
m.def("f2", f2);
m.def("f3", f3);
m.def("f4", f4);
}
| [
"[email protected]"
] | |
8cbeac265cd09daf007ad3a5fb239bc5782e24f8 | 96d9346a16fdbeff7d81cd5344b52d0cc3069c37 | /libs/strong_typedef/tagged_float_example.cpp | 6e0ebfa19e2461f2560758fccdbe0b2b1dd217ef | [] | no_license | schardong/Shand | fbee3d305adeea40bcdb85acad989486a60d5b4c | 8603dbef52f4324cfd16a181a0f58f2642489e61 | refs/heads/master | 2020-12-02T20:58:32.950971 | 2017-03-31T06:07:49 | 2017-03-31T06:07:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,491 | cpp | // Copyright Akira Takahashi 2012
// 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)
#include <boost/math/constants/constants.hpp>
#include <shand/strong_typedef/tagged_float.hpp>
#include <shand/strong_typedef/tagged_float_io.hpp>
struct degree_tag {};
struct radian_tag {};
template <class T>
using degree = shand::tagged_float<T, degree_tag>;
template <class T>
using radian = shand::tagged_float<T, radian_tag>;
template <class T>
radian<T> degree_to_radian(const degree<T>& x)
{
return radian<T>(x.get() * boost::math::constants::pi<T>() / static_cast<T>(180.0));
}
template <class T>
degree<T> radian_to_degree(const radian<T>& x)
{
return degree<T>(x.get() * static_cast<T>(180.0) / boost::math::constants::pi<T>());
}
int main ()
{
// 異なる型(タグ)間での暗黙変換はできない
{
degree<float> deg(90.0f);
// radian<float> rad = deg; // コンパイルエラー!型が違う
}
// degreeからradianへの変換
{
degree<float> deg(90.0f);
radian<float> rad = degree_to_radian(deg);
std::cout << rad << std::endl;
}
// radianからdegreeへの変換
{
radian<float> rad(0.5 * boost::math::constants::pi<float>());
degree<float> deg = radian_to_degree(rad);
std::cout << deg << std::endl;
}
}
/*
output:
1.5708
90
*/
| [
"[email protected]"
] | |
9911eb6635830ceb9819d097f306f33462274b8f | 63cb28e9191fb16bb7940d187595227f81d0e7a4 | /Frequency.cpp | 05c974572cf2992e7c089e992d61f946211c4908 | [] | no_license | Varun2851/CppBasics | b6082c61f3973cc8e9be41ecc7bf05e93fe83a6d | 2e24decd361acc442a1c7c96005fee9b1c100fe6 | refs/heads/main | 2023-07-05T17:09:44.514478 | 2021-08-26T06:38:17 | 2021-08-26T06:38:17 | 389,422,796 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 647 | cpp | #include<iostream>
using namespace std;
void freq(int arr[],int n){
for(int i =0; i<n; i++){
bool flag = false;
for(int j = 0 ; j<i; j++){
if(arr[i] == arr[j]){
flag = true;
break;
}
}
if(flag == true){
continue;
}
int freq1 = 1;
for(int j = i+1; j<n; j++){
if(arr[i] == arr[j]){
freq1++;
}
}
cout<<arr[i]<<" "<<freq1<<endl;
}
}
int main(){
int arr[] = {10,10,10,30,30,70,60,60};
int n = sizeof(arr)/sizeof(int);
freq(arr , n);
return 0;
} | [
"[email protected]"
] | |
41228d315e2b89d6ab69aebf71e914b5b58c34a8 | e796b62a902f609a6f52223bc336a8b81155872a | /semaine 2/Challenges Boucle/challenge5.cpp | 102787249c49754ec4125e1ccdbc6c120f97d75b | [] | no_license | souayrioss/Periode-SAS | 551f28c6cbb672e498e3a14202225e6f301ae163 | 195596fc83083dde248828b7bfb9745bdf70e6cd | refs/heads/main | 2023-09-02T16:53:49.638756 | 2021-11-19T07:49:22 | 2021-11-19T07:49:22 | 426,167,652 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 288 | cpp | #include<stdio.h>
#include<stdlib.h>
int main()
{
int r,a,b;
printf("Donner un entier positif:\n");
scanf("%d",&a);
while(a!=0)
{
r=a%10;
b=10*b+r;
a=a/10;
}
printf("l'inverse de l'entier donne en entrée est %d\n",b);
return 0;
}
| [
"[email protected]"
] | |
4a96122257743f573717ca0f180d4478d508a3ee | 786de89be635eb21295070a6a3452f3a7fe6712c | /pypdsdata/tags/0.8/src/types/pnCCD/ConfigV1.cpp | 454f1aec49bb07e9d902c59cf77e868471c6fcf9 | [] | no_license | connectthefuture/psdmrepo | 85267cfe8d54564f99e17035efe931077c8f7a37 | f32870a987a7493e7bf0f0a5c1712a5a030ef199 | refs/heads/master | 2021-01-13T03:26:35.494026 | 2015-09-03T22:22:11 | 2015-09-03T22:22:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,706 | cpp | //--------------------------------------------------------------------------
// File and Version Information:
// $Id$
//
// Description:
// Class ConfigV1...
//
// Author List:
// Andrei Salnikov
//
//------------------------------------------------------------------------
//-----------------------
// This Class's Header --
//-----------------------
#include "ConfigV1.h"
//-----------------
// C/C++ Headers --
//-----------------
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
#include "Exception.h"
#include "types/TypeLib.h"
#include "types/camera/FrameCoord.h"
//-----------------------------------------------------------------------
// Local Macros, Typedefs, Structures, Unions and Forward Declarations --
//-----------------------------------------------------------------------
namespace {
// methods
FUN0_WRAPPER(pypdsdata::PNCCD::ConfigV1, numLinks)
FUN0_WRAPPER(pypdsdata::PNCCD::ConfigV1, payloadSizePerLink)
PyMethodDef methods[] = {
{"numLinks", numLinks, METH_NOARGS, "Returns number of links." },
{"payloadSizePerLink", payloadSizePerLink, METH_NOARGS, "Returns data size per link." },
{0, 0, 0, 0}
};
char typedoc[] = "Python class wrapping C++ Pds::PNCCD::ConfigV1 class.";
}
// ----------------------------------------
// -- Public Function Member Definitions --
// ----------------------------------------
void
pypdsdata::PNCCD::ConfigV1::initType( PyObject* module )
{
PyTypeObject* type = BaseType::typeObject() ;
type->tp_doc = ::typedoc;
type->tp_methods = ::methods;
BaseType::initType( "ConfigV1", module );
}
| [
"salnikov@b967ad99-d558-0410-b138-e0f6c56caec7"
] | salnikov@b967ad99-d558-0410-b138-e0f6c56caec7 |
9c32880c4500482ea735947486eaac06db6f2553 | abc04815d208c517907228cae60161d6e1d769ef | /inc/IThread.hpp | 60c2720429c78062cf865624ae7cc585bd6d9b04 | [] | no_license | zirkome/plazza | 2f85c474cfa6664f7e496a630f509d805b06facd | 63e8f497fcfa430d107ef181916e0d182afd8316 | refs/heads/master | 2021-05-26T13:52:45.492697 | 2014-04-27T15:46:24 | 2014-04-27T15:46:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 469 | hpp | #ifndef _ITHREAD_H_
# define _ITHREAD_H_
# include "ITask.hpp"
class IThread
{
public:
enum State
{
THR_WAITING,
THR_ALIVE,
THR_DEAD
};
public:
virtual ~IThread() {};
public:
virtual void join(void** retval) = 0;
virtual int cancel() const = 0;
virtual ITask *getTask() const = 0;
virtual void setTask(ITask *) = 0;
virtual State getState() const = 0;
virtual void setState(State state) = 0;
};
#endif /* _ITHREAD_H_ */
| [
"[email protected]"
] | |
28d593a1c7ba0df620033e03fe7c673db2bff6d3 | 87d06658a55119d621cdf154215007ab3d35a2bc | /CORE/src/Scene/Scene.cpp | 55c7645ad0fc975fe293ad9bcd72c7acc0cffeb6 | [
"Apache-2.0"
] | permissive | varomix/orbit-dev | 33ab945d28a82d975080b87df54614392714f06c | 2c0d8586878a1bffc9e778783943dff233972581 | refs/heads/master | 2023-04-15T15:23:48.439292 | 2021-04-30T07:24:59 | 2021-04-30T07:24:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,498 | cpp | #include "pch.h"
#include "Scene.h"
#include "Core/Application.h"
// systems
#include "ECS/Systems/SpotLightSystem.h"
#include "ECS/Systems/PointLightSystem.h"
#include "ECS/Systems/SceneCameraSystem.h"
#include "ECS/Systems/GridRendererSystem.h"
#include "ECS/Systems/MeshRendererSystem.h"
#include "ECS/Systems/EditorCameraSystem.h"
#include "ECS/Systems/DepthSamplingSystem.h"
#include "ECS/Systems/SkyboxRendererSystem.h"
#include "ECS/Systems/DirectionalLightSystem.h"
namespace Orbit {
// define all systems !
static ECS::SpotLightSystem s_SpotLightSystem;
static ECS::PointLightSystem s_PointLightSystem;
static ECS::SceneCameraSystem s_SceneCameraSystem;
static ECS::EditorCameraSystem s_EditorCameraSystem;
static ECS::MeshRendererSystem s_MeshRendererSystem;
static ECS::GridRendererSystem s_GridRendererSystem;
static ECS::DepthSamplingSystem s_DepthSamplingSystem;
static ECS::SkyboxRendererSystem s_SkyboxRendererSystem;
static ECS::DirectionalLightSystem s_DirectionalLightSystem;
void Scene::Init() {
_Registry = MakeUnique<ECS::Registry>();
_Renderer = MakeUnique<PlatformRenderer>(1280, 720);
_Serializer = MakeUnique<SceneSerializer>(_Registry.get(), &_Loader);
// Register all components
_Registry->RegisterComponent<ECS::Common>("Common");
_Registry->RegisterComponent<ECS::Camera>("Camera");
_Registry->RegisterComponent<ECS::Transform>("Transform");
_Registry->RegisterComponent<ECS::SpotLight>("Spot Light");
_Registry->RegisterComponent<ECS::PointLight>("Point Light");
_Registry->RegisterComponent<ECS::MeshRenderer>("MeshRenderer");
_Registry->RegisterComponent<ECS::SkyboxRenderer>("SkyboxRenderer");
_Registry->RegisterComponent<ECS::DirectionalLight>("Directional Light");
// initialise callbacks
auto disp = Application::Dispatcher();
disp->AddListener<OpenSceneEvent>(OB_BIND_FN(Scene::OnOpenScene));
disp->AddListener<AddEntityEvent>(OB_BIND_FN(Scene::OnAddEntity));
disp->AddListener<KeyPressedEvent>(OB_BIND_FN(Scene::OnKeyPressed));
disp->AddListener<AddComponentEvent>(OB_BIND_FN(Scene::OnAddComponent));
disp->AddListener<DestroyEntityEvent>(OB_BIND_FN(Scene::OnDestroyEntity));
disp->AddListener<RemoveComponentEvent>(OB_BIND_FN(Scene::OnRemoveComponent));
// load shaders
_Loader.LoadShader("data/Shaders/PBR");
_Loader.LoadShader("data/Shaders/FLAT");
_Loader.LoadShader("data/Shaders/GRID");
_Loader.LoadShader("data/Shaders/DEPTH");
_Loader.LoadShader("data/Shaders/IRMAP");
_Loader.LoadShader("data/Shaders/SKYBOX");
_Loader.LoadShader("data/Shaders/HDR2MAP");
// meshes
_Loader.LoadMesh("data/Models/Basics/cube.fbx");
_Loader.LoadMesh("data/Models/Basics/sphere.fbx");
// cubemap
const char* faces[6];
faces[CUBEMAP_RIGHT] = "data/Skybox/right.png";
faces[CUBEMAP_LEFT] = "data/Skybox/left.png";
faces[CUBEMAP_TOP] = "data/Skybox/top.png";
faces[CUBEMAP_BOTTOM] = "data/Skybox/bottom.png";
faces[CUBEMAP_FRONT] = "data/Skybox/front.png";
faces[CUBEMAP_BACK] = "data/Skybox/back.png";
_Loader.LoadCubeMap(faces);
// MATERIALS
Material _default;
_default.Name = "default";
_default.Data.Metallic = 0.05;
_default.Data.Roughness = 0.02;
_default.Data.Albedo = vec3f(0.8f, 0.2f, 4.0f);
_Loader.AddMaterial(_default);
// init systems
s_SpotLightSystem.Init();
s_PointLightSystem.Init();
s_SceneCameraSystem.Init();
s_EditorCameraSystem.Init();
s_GridRendererSystem.Init();
s_MeshRendererSystem.Init();
s_SkyboxRendererSystem.Init();
s_DepthSamplingSystem.Init();
s_DirectionalLightSystem.Init();
}
void Scene::Start() {
// start all systems
s_SpotLightSystem.Start();
s_PointLightSystem.Start();
s_SceneCameraSystem.Start();
s_EditorCameraSystem.Start();
s_MeshRendererSystem.Start();
s_SkyboxRendererSystem.Start();
s_DepthSamplingSystem.Start();
s_DirectionalLightSystem.Start();
}
void Scene::Update() {
// lights
s_SpotLightSystem.Update();
s_PointLightSystem.Update();
s_DirectionalLightSystem.Update();
// depth sampling
s_DepthSamplingSystem.Update();
// renderers
_Renderer->GetFrameBuffer()->Clear();
s_MeshRendererSystem.Update();
s_GridRendererSystem.Update();
s_SkyboxRendererSystem.Update();
}
void Scene::DestroyEntity(ECS::EntityID handle) {
_Registry->Destroy(handle);
}
ECS::Entity Scene::AddEntity(std::string name, const vec3f& pos) {
const ECS::EntityID handle = _Registry->AddEntity();
if (name.empty()) { name = "Entity" + std::to_string(handle);}
_Registry->AddComponent<ECS::Transform>(handle, pos);
_Registry->AddComponent<ECS::Common>(handle, name);
return ToEntity(handle);
}
ECS::EntityList Scene::GetEntityList(const ECS::EntitySignature& filter) {
ECS::EntityList list;
for (auto handle : _Registry->GetEntityHandleList(filter)) {
list.push_back(ToEntity(handle));
}
return list;
}
// EVENTS CALLBACKS
void Scene::OnOpenScene(const OpenSceneEvent& e) {
OB_INFO("trying to parse: %s", e.GetFilename().c_str());
_Serializer->Load(e.GetFilename());
Application::Dispatcher()->Prioritize<SceneLoadedEvent>();
}
void Scene::OnSceneResized(const SceneResizedEvent& e) {
int32 w = e.Width();
int32 h = e.Height();
_Renderer->SetViewport(0, 0, w, h);
_Renderer->GetFrameBuffer()->Validate(w, h);
_Renderer->GetDepthBuffer()->Validate(w, h);
}
void Scene::OnAddEntity(const AddEntityEvent& e) {
Application::Dispatcher()->Prioritize<EntityAddedEvent>(this->AddEntity(e.GetName()));
}
void Scene::OnKeyPressed(const KeyPressedEvent& e) {
auto input = Application::Inputs();
if (input->IsKeypress(KEY_LEFT_CONTROL) && input->IsKeypress(KEY_S)) {
_Serializer->Save("Assets/Scenes/project.obproj");
}
}
void Scene::OnAddComponent(const AddComponentEvent& e) {
if (_Registry->IsEntityActive(e.GetEntity())) {
std::string compTypeName = e.GetTypeName();
_Registry->AddComponent(e.GetEntity(), compTypeName);
Application::Dispatcher()->Prioritize<ComponentAddedEvent>(ToEntity(e.GetEntity()), compTypeName);
}
}
void Scene::OnDestroyEntity(const DestroyEntityEvent& e) {
Application::Dispatcher()->Prioritize<EntityDestroyedEvent>(e.GetEntity());
_Registry->Destroy(e.GetEntity());
}
void Scene::OnRemoveComponent(const RemoveComponentEvent& e) {
e.GetEntity().RemoveComponent(e.GetTypeID());
Application::Dispatcher()->Prioritize<RefreshInspectorEvent>(e.GetEntity());
OB_INFO("Component %u removed", e.GetTypeID());
}
} | [
"[email protected]"
] | |
d88a5766093c8014745f471541a3491d9f9bb1ef | 80ee2a0df0ee1c927c2c828dd651793054f68905 | /code/src/caros/components/caros_teleoperation/src/pose_teleoperate.cpp | 26e93981152fd54299c27283dc8fa2e9becb2354 | [] | no_license | ROVI2-SDU-GROUP1/ROVI2 | d92904aff31a28b12c63f42a1a6b51db411f7602 | 93dd07b5815c6da9da3a790d58bd7e16ce55c2db | refs/heads/master | 2021-06-21T15:03:17.935201 | 2017-05-22T10:02:10 | 2017-05-22T10:02:10 | 84,427,466 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,347 | cpp | #include <caros/pose_teleoperate.h>
#include <rw/math/LinearAlgebra.hpp>
#include <ros/ros.h>
#include <std_srvs/Empty.h>
#include <string>
using rw::math::Deg2Rad;
using rw::math::RPY;
using rw::math::Rotation3D;
using rw::math::Transform3D;
using rw::math::Vector3D;
using rw::math::Q;
using rw::math::Quaternion;
namespace caros
{
PoseTeleoperate::PoseTeleoperate(const ros::NodeHandle& nh, const std::string& name)
: caros::CarosNodeServiceInterface(nh, 100), nh_(nh), do_teleoperate_(false)
{
pose_sensor_id1_ = -1;
analog_button_pushed_ = false;
analog_button_ = false;
}
bool PoseTeleoperate::activateHook()
{
std_srvs::Empty::Request request;
std_srvs::Empty::Response response;
if (!initNode())
{
return false;
}
if (!startListening(request, response))
{
return false;
}
return true;
}
bool PoseTeleoperate::recoverHook(const std::string& error_msg, const int64_t error_code)
{
std_srvs::Empty::Request request;
std_srvs::Empty::Response response;
bool resolved = false;
switch (error_code)
{
case TELEOPERATE_MISSING_ROSPARAM_RUNTIME:
if (startListening(request, response))
{
ROS_DEBUG_STREAM("Subscribing to ButtonSensor topic");
button_sensor_state_ = nh_.subscribe(button_sensor_name_, 1, &PoseTeleoperate::handleButtonSensor, this);
if (!button_sensor_state_)
{
CAROS_FATALERROR("Subscribing to ButtonSensor topic failed from recoverhook - FATALERROR",
TELEOPERATE_SUBSCRIPTION_FAILED);
}
resolved = true;
}
if (!pose_array_state_)
{
CAROS_FATALERROR(
"Not able to properly recover from the error condition 'missing rosparam at runtime' - going into "
"FATALERROR",
TELEOPERATE_MISSING_ROSPARAM_RUNTIME);
resolved = false;
ROS_DEBUG_STREAM("Subscribing to pose topic");
pose_array_state_ = nh_.subscribe(pose_array_name_, 1, &PoseTeleoperate::handlePoseArraySensor, this);
if (!button_sensor_state_)
{
CAROS_FATALERROR("Subscribing to pose topic failed from recoverhook - FATALERROR",
TELEOPERATE_SUBSCRIPTION_FAILED);
}
resolved = true;
}
else
{
CAROS_FATALERROR(
"Not able to properly recover from the error condition 'failed subscription' - going into FATALERROR",
TELEOPERATE_SUBSCRIPTION_FAILED);
resolved = false;
}
break;
default:
CAROS_FATALERROR("The provided error code '" << error_code << "' has no recovery functionality! "
<< "- this should be considered a bug!",
TELEOPERATE_INTERNAL_ERROR);
resolved = false;
break;
}
if (resolved)
{
do_teleoperate_ = true;
}
return resolved;
}
void PoseTeleoperate::errorLoopHook()
{
ROS_ERROR_STREAM("Something is wrong. Try calling recoverHook()");
do_teleoperate_ = false;
}
void PoseTeleoperate::fatalErrorLoopHook()
{
ROS_ERROR_STREAM("Fatal error. Shutting down node...");
std_srvs::Empty::Request request;
std_srvs::Empty::Response response;
stopListening(request, response);
}
void PoseTeleoperate::runLoopHook()
{
if (do_teleoperate_)
{
doTeleoperate();
}
}
bool PoseTeleoperate::initNode()
{
// the stuff we need to listen for
std::string dev_name, button_name, pose_sensor_name;
double rate, zoffset, zoffset_tcp;
if (!nh_.getParam("device_name", dev_name))
{
CAROS_FATALERROR("The parameter '" << nh_.getNamespace()
<< "/device_name' was not present on the parameter server! "
<< "This parameter has to be specified for this node to work properly.",
TELEOPERATE_MISSING_ROSPARAM);
return false;
}
nh_.param("rate", rate, 100.0);
nh_.param("zoffset_tcp", zoffset_tcp, 0.0);
nh_.param("zoffset", zoffset, 0.0);
offset_Zpos_.P()[2] = zoffset_tcp;
sensor_offset_.P()[2] = zoffset;
setLoopRateFrequency(rate);
// add some control interface
srv_start_ = nh_.advertiseService("start", &PoseTeleoperate::startListening, this);
srv_stop_ = nh_.advertiseService("stop", &PoseTeleoperate::stopListening, this);
srv_pause_ = nh_.advertiseService("pause", &PoseTeleoperate::pauseListening, this);
// get the workcell
p_workcell_ = caros::getWorkCell();
if (p_workcell_ == NULL)
{
ROS_ERROR("No workcell added to the parameter server!");
CAROS_FATALERROR("No workcell added to the parameter server!", TELEOPERATE_MISSING_ROSPARAM);
return false;
}
// device
dev_ = p_workcell_->findDevice(dev_name);
tmp_state_ = p_workcell_->getDefaultState();
if (dev_ == NULL)
{
ROS_ERROR_STREAM("No device by name " << dev_name << " Possible devices are:");
CAROS_FATALERROR("No device by name found in workcell.", TELEOPERATE_MISSING_DEVICE_IN_WORKCELL);
for (rw::models::Device::Ptr dev : p_workcell_->getDevices())
{
ROS_ERROR_STREAM("dev: " << dev->getName());
}
return false;
}
return true;
}
PoseTeleoperate::~PoseTeleoperate()
{
/* Nothing specific to do */
}
bool PoseTeleoperate::startListening(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response)
{
ROS_DEBUG_STREAM("start: ");
if (do_teleoperate_)
{
ROS_DEBUG_STREAM("Stopping the running teleoperation");
stopListening(request, response);
}
// get pose sensor name
if (!nh_.getParam("PoseArray", pose_array_name_))
{
CAROS_ERROR("No pose sensor topic name defined in parameter server!", TELEOPERATE_MISSING_ROSPARAM_RUNTIME);
return false;
}
if (!nh_.getParam("PushSensor", button_sensor_name_))
{
CAROS_ERROR("No button sensor topic name defined in parameter server!", TELEOPERATE_MISSING_ROSPARAM_RUNTIME);
return false;
}
nh_.param("PoseIdx", pose_sensor_id1_, 0);
// initialize robot arm proxy
ROS_INFO_STREAM("Subscribing to Device proxy, with:" << dev_->getName());
device_sip_ = std::make_shared<caros::SerialDeviceSIProxy>(nh_, dev_->getName());
ROS_INFO_STREAM("Subscribing to Pose Sensor proxy, with: " << pose_array_name_);
pose_sip_ = std::make_shared<caros::PoseSensorSIProxy>(nh_, pose_array_name_);
ROS_INFO_STREAM("Subscribing to ButtonSensor topic, with: " << button_sensor_name_);
button_sensor_state_ = nh_.subscribe(button_sensor_name_, 1, &PoseTeleoperate::handleButtonSensor, this);
if (!button_sensor_state_)
{
CAROS_ERROR("Subscribing to ButtonSensor topic, with: " << button_sensor_name_ << " failed!",
TELEOPERATE_SUBSCRIPTION_FAILED);
return false;
}
pose_array_state_ = nh_.subscribe(pose_array_name_, 1, &PoseTeleoperate::handlePoseArraySensor, this);
ROS_INFO_STREAM("Subscribing to pose topic, with: " << pose_array_name_);
if (!pose_array_state_)
{
CAROS_ERROR("Subscribing to pose topic, with: " << pose_array_name_ << " failed!", TELEOPERATE_SUBSCRIPTION_FAILED);
return false;
}
// initialize doTeleoperate stuff
do_teleoperate_ = true;
return true;
}
void PoseTeleoperate::handleButtonSensor(caros_sensor_msgs::ButtonSensorState btn_state)
{
if (btn_state.analog[0] > 0)
analog_button_pushed_ = true;
else
analog_button_pushed_ = false;
}
void PoseTeleoperate::handlePoseArraySensor(caros_sensor_msgs::PoseSensorState array)
{
poses_.clear();
for (const geometry_msgs::Transform pose : array.poses)
{
Quaternion<> quat(pose.rotation.x, pose.rotation.y, pose.rotation.z, pose.rotation.w);
Vector3D<> pos(pose.translation.x, pose.translation.y, pose.translation.z);
// Quaternion<> quat(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w);
// Vector3D<> pos(pose.position.x, pose.position.y, pose.position.z);
poses_.push_back(Transform3D<>(pos, quat.toRotation3D()));
}
}
bool PoseTeleoperate::pauseListening(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response)
{
/* TODO(any): */
ROS_WARN_STREAM("This method is not implemented!");
return true;
}
bool PoseTeleoperate::stopListening(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response)
{
if (!do_teleoperate_)
{
ROS_DEBUG_STREAM("Already stopped!");
return true;
}
do_teleoperate_ = false;
device_sip_ = NULL;
pose_sip_ = NULL;
return true;
}
void PoseTeleoperate::doTeleoperate()
{
// WARNING SHOULD NOT BLOCK, this should be called from another loop
if (static_cast<signed int>(poses_.size()) <= pose_sensor_id1_)
{
ROS_WARN("no poses yet!");
return;
}
Transform3D<> robotbaseTtrans(RPY<>(180 * Deg2Rad, 0, 0).toRotation3D());
Transform3D<> pose1 = robotbaseTtrans * poses_[pose_sensor_id1_] * sensor_offset_;
Q robQ = device_sip_->getQ();
Q robQd = device_sip_->getQd();
// std::cout << robQ << std::endl;
// servoing of the robot device
if (!analog_button_pushed_)
{
if (analog_button_)
{
ROS_INFO("Released BTN");
}
analog_button_ = false;
}
else if (robQ.size() == 0)
{
ROS_WARN("robQ.size() is 0.... Probably due to read error in Robot State");
}
else
{
dev_->setQ(robQ, tmp_state_);
// if button was not pushed down before then save the tool/sensor transform
if (!analog_button_)
{
ROS_INFO("Pushed BTN");
analog_button_ = true;
initial_sensor_pose_ = pose1; // pose1 * offsetZpos
initial_robotTtool_ = dev_->baseTend(tmp_state_) * offset_Zpos_;
last_target_pose_ = pose1;
}
// calculate the change from initial pose to current pose
// Transform3D<> initialSensorTcurrent = inverse(initialSensorPose_) * pose1;
Vector3D<> relativeMotionPos = pose1.P() - initial_sensor_pose_.P();
Rotation3D<> relativeMotionRot = pose1.R() * inverse(initial_sensor_pose_.R());
Transform3D<> baseTtool_target =
Transform3D<>(initial_robotTtool_.P() + relativeMotionPos, relativeMotionRot * initial_robotTtool_.R());
if (!device_sip_->moveServoT(baseTtool_target * inverse(offset_Zpos_)))
{
ROS_WARN("deviceSIP_->moveServoT(baseTtool_target * inverse(offsetZpos))) failed. Move command to robot failed.");
}
last_target_pose_ = pose1;
}
}
} // namespace caros
| [
"[email protected]"
] | |
6f744e38d05ecd3fe612b9cbe97777cc9ab7995a | 3b9b4049a8e7d38b49e07bb752780b2f1d792851 | /src/components/audio_modem/modem_impl.cc | 447250cad9322254ae692e1137e71662c2210dc7 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | webosce/chromium53 | f8e745e91363586aee9620c609aacf15b3261540 | 9171447efcf0bb393d41d1dc877c7c13c46d8e38 | refs/heads/webosce | 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 | Apache-2.0 | 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null | UTF-8 | C++ | false | false | 11,449 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/audio_modem/modem_impl.h"
#include <stdint.h>
#include <algorithm>
#include <limits>
#include <memory>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/sys_string_conversions.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/audio_modem/audio_modem_switches.h"
#include "components/audio_modem/audio_player_impl.h"
#include "components/audio_modem/audio_recorder_impl.h"
#include "components/audio_modem/public/whispernet_client.h"
#include "content/public/browser/browser_thread.h"
#include "media/audio/audio_manager.h"
#include "media/audio/audio_manager_base.h"
#include "media/base/audio_bus.h"
#include "third_party/webrtc/common_audio/wav_file.h"
namespace audio_modem {
namespace {
const int kMaxSamples = 10000;
const int kTokenTimeoutMs = 2000;
const int kMonoChannelCount = 1;
// UrlSafe is defined as:
// '/' represented by a '_' and '+' represented by a '-'
// TODO(ckehoe): Move this to a central place.
std::string FromUrlSafe(std::string token) {
base::ReplaceChars(token, "-", "+", &token);
base::ReplaceChars(token, "_", "/", &token);
return token;
}
std::string ToUrlSafe(std::string token) {
base::ReplaceChars(token, "+", "-", &token);
base::ReplaceChars(token, "/", "_", &token);
return token;
}
// TODO(ckehoe): Move this to a central place.
std::string AudioTypeToString(AudioType audio_type) {
if (audio_type == AUDIBLE)
return "audible";
if (audio_type == INAUDIBLE)
return "inaudible";
NOTREACHED() << "Got unexpected token type " << audio_type;
return std::string();
}
bool ReadBooleanFlag(const std::string& flag, bool default_value) {
const std::string flag_value = base::ToLowerASCII(
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(flag));
if (flag_value == "true" || flag_value == "1")
return true;
if (flag_value == "false" || flag_value == "0")
return false;
LOG_IF(ERROR, !flag_value.empty())
<< "Unrecognized value \"" << flag_value << " for flag "
<< flag << ". Defaulting to " << default_value;
return default_value;
}
} // namespace
// Public functions.
ModemImpl::ModemImpl() : client_(nullptr), recorder_(nullptr) {
// TODO(rkc): Move all of these into initializer lists once it is allowed.
should_be_playing_[AUDIBLE] = false;
should_be_playing_[INAUDIBLE] = false;
should_be_recording_[AUDIBLE] = false;
should_be_recording_[INAUDIBLE] = false;
player_enabled_[AUDIBLE] = ReadBooleanFlag(
switches::kAudioModemEnableAudibleBroadcast, true);
player_enabled_[INAUDIBLE] = ReadBooleanFlag(
switches::kAudioModemEnableInaudibleBroadcast, true);
player_[AUDIBLE] = nullptr;
player_[INAUDIBLE] = nullptr;
samples_caches_.resize(2);
samples_caches_[AUDIBLE] = new SamplesMap(kMaxSamples);
samples_caches_[INAUDIBLE] = new SamplesMap(kMaxSamples);
}
void ModemImpl::Initialize(WhispernetClient* client,
const TokensCallback& tokens_cb) {
DCHECK(client);
client_ = client;
tokens_cb_ = tokens_cb;
// These will be unregistered on destruction, so unretained is safe to use.
client_->RegisterTokensCallback(
base::Bind(&ModemImpl::OnTokensFound, base::Unretained(this)));
client_->RegisterSamplesCallback(
base::Bind(&ModemImpl::OnTokenEncoded, base::Unretained(this)));
if (!player_[AUDIBLE])
player_[AUDIBLE] = new AudioPlayerImpl();
player_[AUDIBLE]->Initialize();
if (!player_[INAUDIBLE])
player_[INAUDIBLE] = new AudioPlayerImpl();
player_[INAUDIBLE]->Initialize();
decode_cancelable_cb_.Reset(base::Bind(
&ModemImpl::DecodeSamplesConnector, base::Unretained(this)));
if (!recorder_)
recorder_ = new AudioRecorderImpl();
recorder_->Initialize(decode_cancelable_cb_.callback());
dump_tokens_dir_ = base::FilePath(base::CommandLine::ForCurrentProcess()
->GetSwitchValueNative(switches::kAudioModemDumpTokensToDir));
}
ModemImpl::~ModemImpl() {
if (player_[AUDIBLE])
player_[AUDIBLE]->Finalize();
if (player_[INAUDIBLE])
player_[INAUDIBLE]->Finalize();
if (recorder_)
recorder_->Finalize();
// Whispernet initialization may never have completed.
if (client_) {
client_->RegisterTokensCallback(TokensCallback());
client_->RegisterSamplesCallback(SamplesCallback());
}
}
void ModemImpl::StartPlaying(AudioType type) {
DCHECK(type == AUDIBLE || type == INAUDIBLE);
should_be_playing_[type] = true;
// If we don't have our token encoded yet, this check will be false, for now.
// Once our token is encoded, OnTokenEncoded will call UpdateToken, which
// will call this code again (if we're still supposed to be playing).
SamplesMap::iterator samples =
samples_caches_[type]->Get(playing_token_[type]);
if (samples != samples_caches_[type]->end()) {
DCHECK(!playing_token_[type].empty());
if (player_enabled_[type]) {
started_playing_[type] = base::Time::Now();
player_[type]->Play(samples->second);
// If we're playing, we always record to hear what we are playing.
recorder_->Record();
} else {
DVLOG(3) << "Skipping playback for disabled " << AudioTypeToString(type)
<< " player.";
}
}
}
void ModemImpl::StopPlaying(AudioType type) {
DCHECK(type == AUDIBLE || type == INAUDIBLE);
should_be_playing_[type] = false;
player_[type]->Stop();
// If we were only recording to hear our own played tokens, stop.
if (!should_be_recording_[AUDIBLE] && !should_be_recording_[INAUDIBLE])
recorder_->Stop();
playing_token_[type] = std::string();
}
void ModemImpl::StartRecording(AudioType type) {
DCHECK(type == AUDIBLE || type == INAUDIBLE);
should_be_recording_[type] = true;
recorder_->Record();
}
void ModemImpl::StopRecording(AudioType type) {
DCHECK(type == AUDIBLE || type == INAUDIBLE);
should_be_recording_[type] = false;
recorder_->Stop();
}
void ModemImpl::SetToken(AudioType type,
const std::string& url_safe_token) {
DCHECK(type == AUDIBLE || type == INAUDIBLE);
std::string token = FromUrlSafe(url_safe_token);
if (samples_caches_[type]->Get(token) == samples_caches_[type]->end()) {
client_->EncodeToken(token, type, token_params_);
} else {
UpdateToken(type, token);
}
}
const std::string ModemImpl::GetToken(AudioType type) const {
return playing_token_[type];
}
bool ModemImpl::IsPlayingTokenHeard(AudioType type) const {
base::TimeDelta tokenTimeout =
base::TimeDelta::FromMilliseconds(kTokenTimeoutMs);
// This is a bit of a hack. If we haven't been playing long enough,
// return true to avoid tripping an audio fail alarm.
if (base::Time::Now() - started_playing_[type] < tokenTimeout)
return true;
return base::Time::Now() - heard_own_token_[type] < tokenTimeout;
}
void ModemImpl::SetTokenParams(AudioType type, const TokenParameters& params) {
DCHECK_GT(params.length, 0u);
token_params_[type] = params;
// TODO(ckehoe): Make whispernet handle different token lengths
// simultaneously without reinitializing the decoder over and over.
}
// static
std::unique_ptr<Modem> Modem::Create() {
return base::WrapUnique<Modem>(new ModemImpl);
}
// Private functions.
void ModemImpl::OnTokenEncoded(
AudioType type,
const std::string& token,
const scoped_refptr<media::AudioBusRefCounted>& samples) {
samples_caches_[type]->Put(token, samples);
DumpToken(type, token, samples.get());
UpdateToken(type, token);
}
void ModemImpl::OnTokensFound(const std::vector<AudioToken>& tokens) {
std::vector<AudioToken> tokens_to_report;
for (const auto& token : tokens) {
AudioType type = token.audible ? AUDIBLE : INAUDIBLE;
if (playing_token_[type] == token.token)
heard_own_token_[type] = base::Time::Now();
if (should_be_recording_[AUDIBLE] && token.audible) {
tokens_to_report.push_back(token);
} else if (should_be_recording_[INAUDIBLE] && !token.audible) {
tokens_to_report.push_back(token);
}
}
if (!tokens_to_report.empty())
tokens_cb_.Run(tokens_to_report);
}
void ModemImpl::UpdateToken(AudioType type, const std::string& token) {
DCHECK(type == AUDIBLE || type == INAUDIBLE);
if (playing_token_[type] == token)
return;
// Update token.
playing_token_[type] = token;
// If we are supposed to be playing this token type at this moment, switch
// out playback with the new samples.
if (should_be_playing_[type])
RestartPlaying(type);
}
void ModemImpl::RestartPlaying(AudioType type) {
DCHECK(type == AUDIBLE || type == INAUDIBLE);
// We should already have this token in the cache. This function is not
// called from anywhere except update token and only once we have our samples
// in the cache.
DCHECK(samples_caches_[type]->Get(playing_token_[type]) !=
samples_caches_[type]->end());
player_[type]->Stop();
StartPlaying(type);
}
void ModemImpl::DecodeSamplesConnector(const std::string& samples) {
// If we are either supposed to be recording *or* playing, audible or
// inaudible, we should be decoding that type. This is so that if we are
// just playing, we will still decode our recorded token so we can check
// if we heard our own token. Whether or not we report the token to the
// server is checked for and handled in OnTokensFound.
bool decode_audible =
should_be_recording_[AUDIBLE] || should_be_playing_[AUDIBLE];
bool decode_inaudible =
should_be_recording_[INAUDIBLE] || should_be_playing_[INAUDIBLE];
if (decode_audible && decode_inaudible) {
client_->DecodeSamples(BOTH, samples, token_params_);
} else if (decode_audible) {
client_->DecodeSamples(AUDIBLE, samples, token_params_);
} else if (decode_inaudible) {
client_->DecodeSamples(INAUDIBLE, samples, token_params_);
}
}
void ModemImpl::DumpToken(AudioType audio_type,
const std::string& token,
const media::AudioBus* samples) {
if (dump_tokens_dir_.empty())
return;
// Convert the samples to 16-bit integers.
std::vector<int16_t> int_samples;
int_samples.reserve(samples->frames());
for (int i = 0; i < samples->frames(); i++) {
int_samples.push_back(round(
samples->channel(0)[i] * std::numeric_limits<int16_t>::max()));
}
DCHECK_EQ(static_cast<int>(int_samples.size()), samples->frames());
DCHECK_EQ(kMonoChannelCount, samples->channels());
const std::string filename = base::StringPrintf("%s %s.wav",
AudioTypeToString(audio_type).c_str(), ToUrlSafe(token).c_str());
DVLOG(3) << "Dumping token " << filename;
std::string file_str;
#if defined(OS_WIN)
base::FilePath file_path = dump_tokens_dir_.Append(
base::SysNativeMBToWide(filename));
file_str = base::SysWideToNativeMB(file_path.value());
#else
file_str = dump_tokens_dir_.Append(filename).value();
#endif
webrtc::WavWriter writer(file_str, kDefaultSampleRate, kMonoChannelCount);
writer.WriteSamples(int_samples.data(), int_samples.size());
}
} // namespace audio_modem
| [
"[email protected]"
] | |
31223a42c3ed9f7e31ac566031dc8bbcef5334c2 | d93159d0784fc489a5066d3ee592e6c9563b228b | /SimTracker/TrackHistory/interface/HistoryBase.h | f93f8e93cec86e1a76107343ebaadb5ae48e7b4c | [] | permissive | simonecid/cmssw | 86396e31d41a003a179690f8c322e82e250e33b2 | 2559fdc9545b2c7e337f5113b231025106dd22ab | refs/heads/CAallInOne_81X | 2021-08-15T23:25:02.901905 | 2016-09-13T08:10:20 | 2016-09-13T08:53:42 | 176,462,898 | 0 | 1 | Apache-2.0 | 2019-03-19T08:30:28 | 2019-03-19T08:30:24 | null | UTF-8 | C++ | false | false | 4,905 | h | #ifndef HistoryBase_h
#define HistoryBase_h
#include <set>
#include "SimDataFormats/TrackingAnalysis/interface/TrackingParticle.h"
#include "SimDataFormats/TrackingAnalysis/interface/TrackingParticleFwd.h"
#include "SimDataFormats/TrackingAnalysis/interface/TrackingVertex.h"
#include "SimDataFormats/TrackingAnalysis/interface/TrackingVertexContainer.h"
//! Base class to all the history types.
class HistoryBase
{
public:
//! GenParticle trail type.
typedef std::vector<const HepMC::GenParticle *> GenParticleTrail;
//! GenVertex trail type.
typedef std::vector<const HepMC::GenVertex *> GenVertexTrail;
//! GenVertex trail helper type.
typedef std::set<const HepMC::GenVertex *> GenVertexTrailHelper;
//! SimParticle trail type.
typedef std::vector<TrackingParticleRef> SimParticleTrail;
//! SimVertex trail type.
typedef std::vector<TrackingVertexRef> SimVertexTrail;
// Default constructor
HistoryBase()
{
// Default depth
depth_ = -1;
}
//! Set the depth of the history.
/* Set TrackHistory to given depth. Positive values
constrain the number of TrackingVertex visit in the history.
Negatives values set the limit of the iteration over generated
information i.e. (-1 -> status 1 or -2 -> status 2 particles).
/param[in] depth the history
*/
void depth(int d)
{
depth_ = d;
}
//! Return all the simulated vertices in the history.
SimVertexTrail const & simVertexTrail() const
{
return simVertexTrail_;
}
//! Return all the simulated particle in the history.
SimParticleTrail const & simParticleTrail() const
{
return simParticleTrail_;
}
//! Return all generated vertex in the history.
GenVertexTrail const & genVertexTrail() const
{
return genVertexTrail_;
}
//! Return all generated particle in the history.
GenParticleTrail const & genParticleTrail() const
{
return genParticleTrail_;
}
//! Return the initial tracking particle from the history.
const TrackingParticleRef & simParticle() const
{
return simParticleTrail_[0];
}
//! Return the initial tracking vertex from the history.
const TrackingVertexRef & simVertex() const
{
return simVertexTrail_[0];
}
//! Returns a pointer to most primitive status 1 or 2 particle.
const HepMC::GenParticle * genParticle() const
{
if ( genParticleTrail_.empty() ) return 0;
return genParticleTrail_[genParticleTrail_.size()-1];
}
protected:
// History cointainers
GenVertexTrail genVertexTrail_;
GenParticleTrail genParticleTrail_;
SimVertexTrail simVertexTrail_;
SimParticleTrail simParticleTrail_;
// Helper function to speedup search
GenVertexTrailHelper genVertexTrailHelper_;
//! Evaluate track history using a TrackingParticleRef.
/* Return false when the history cannot be determined upto a given depth.
If not depth is pass to the function no restriction are apply to it.
/param[in] TrackingParticleRef of a simulated track
/param[in] depth of the track history
/param[out] boolean that is true when history can be determined
*/
bool evaluate(TrackingParticleRef tpr)
{
resetTrails(tpr);
return traceSimHistory(tpr, depth_);
}
//! Evaluate track history using a TrackingParticleRef.
/* Return false when the history cannot be determined upto a given depth.
If not depth is pass to the function no restriction are apply to it.
/param[in] TrackingVertexRef of a simulated vertex
/param[in] depth of the track history
/param[out] boolean that is true when history can be determined
*/
bool evaluate(TrackingVertexRef tvr)
{
resetTrails();
return traceSimHistory(tvr, depth_);
}
private:
int depth_;
//! Trace all the simulated information for a given reference to a TrackingParticle.
bool traceSimHistory (TrackingParticleRef const &, int);
//! Trace all the simulated information for a given reference to a TrackingVertex.
bool traceSimHistory (TrackingVertexRef const &, int);
//! Trace all the simulated information for a given pointer to a GenParticle.
void traceGenHistory (HepMC::GenParticle const *);
//! Trace all the simulated information for a given pointer to a GenVertex.
void traceGenHistory (HepMC::GenVertex const *);
//! Reset trail functions.
void resetTrails()
{
simParticleTrail_.clear();
simVertexTrail_.clear();
genVertexTrail_.clear();
genParticleTrail_.clear();
genVertexTrailHelper_.clear();
}
void resetTrails(TrackingParticleRef tpr)
{
resetTrails();
simParticleTrail_.push_back(tpr);
}
};
#endif
| [
"[email protected]"
] | |
8bbf23fb186358ddf914798a6f42624299e68764 | 5821d864fb40417184cd37a3ee3c889895d39efb | /manuscript/img-src/lscm/OpenNL_psm.cpp | cf85b3614f3e3d8ca19c2b7de0b4a1a7f7dd554f | [
"WTFPL"
] | permissive | ssloy/least-squares-course | 9c86d8c54894248440fba78206ce253559f4257b | 13692cdfd40a8005893fd33887d6cc743c5f01ec | refs/heads/master | 2022-08-18T15:53:15.313071 | 2021-12-01T12:44:59 | 2021-12-01T12:44:59 | 222,901,933 | 162 | 18 | WTFPL | 2022-07-28T21:16:03 | 2019-11-20T09:38:37 | TeX | UTF-8 | C++ | false | false | 217,065 | cpp | #include "OpenNL_psm.h"
/*
* Copyright (c) 2004-2010, Bruno Levy
* 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 the ALICE Project-Team nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* If you modify this software, you should include a notice giving the
* name of the person performing the modification, the date of modification,
* and the reason for such modification.
*
* Contact: Bruno Levy
*
* [email protected]
*
* ALICE Project
* LORIA, INRIA Lorraine,
* Campus Scientifique, BP 239
* 54506 VANDOEUVRE LES NANCY CEDEX
* FRANCE
*
*/
/*
* This file is a PSM (pluggable software module)
* generated from the distribution of Geogram.
*
* See Geogram documentation on:
* http://alice.loria.fr/software/geogram/doc/html/index.html
*
* See documentation of the functions bundled in this PSM on:
* http://alice.loria.fr/software/geogram/doc/html/nl_8h.html
*/
/******* extracted from nl_private.h *******/
#ifndef OPENNL_PRIVATE_H
#define OPENNL_PRIVATE_H
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#if defined(__APPLE__) && defined(__MACH__)
#define NL_OS_APPLE
#endif
#if defined(__linux__) || defined(__ANDROID__) || defined(NL_OS_APPLE)
#define NL_OS_UNIX
#endif
#if defined(WIN32) || defined(_WIN64)
#define NL_OS_WINDOWS
#endif
#define nl_arg_used(x) (void)x
#if defined(__clang__) || defined(__GNUC__)
#define NL_NORETURN __attribute__((noreturn))
#else
#define NL_NORETURN
#endif
#if defined(_MSC_VER)
#define NL_NORETURN_DECL __declspec(noreturn)
#else
#define NL_NORETURN_DECL
#endif
NL_NORETURN_DECL void nl_assertion_failed(
const char* cond, const char* file, int line
) NL_NORETURN;
NL_NORETURN_DECL void nl_range_assertion_failed(
double x, double min_val, double max_val, const char* file, int line
) NL_NORETURN;
NL_NORETURN_DECL void nl_should_not_have_reached(
const char* file, int line
) NL_NORETURN;
#define nl_assert(x) { \
if(!(x)) { \
nl_assertion_failed(#x,__FILE__, __LINE__) ; \
} \
}
#define nl_range_assert(x,min_val,max_val) { \
if(((x) < (min_val)) || ((x) > (max_val))) { \
nl_range_assertion_failed(x, min_val, max_val, \
__FILE__, __LINE__ \
) ; \
} \
}
#define nl_assert_not_reached { \
nl_should_not_have_reached(__FILE__, __LINE__) ; \
}
#ifdef NL_DEBUG
#define nl_debug_assert(x) nl_assert(x)
#define nl_debug_range_assert(x,min_val,max_val) \
nl_range_assert(x,min_val,max_val)
#else
#define nl_debug_assert(x)
#define nl_debug_range_assert(x,min_val,max_val)
#endif
#ifdef NL_PARANOID
#define nl_parano_assert(x) nl_assert(x)
#define nl_parano_range_assert(x,min_val,max_val) \
nl_range_assert(x,min_val,max_val)
#else
#define nl_parano_assert(x)
#define nl_parano_range_assert(x,min_val,max_val)
#endif
void nlError(const char* function, const char* message) ;
void nlWarning(const char* function, const char* message) ;
NLdouble nlCurrentTime(void);
typedef void* NLdll;
#define NL_LINK_NOW 1
#define NL_LINK_LAZY 2
#define NL_LINK_GLOBAL 4
#define NL_LINK_QUIET 8
#define NL_LINK_USE_FALLBACK 16
NLdll nlOpenDLL(const char* filename, NLenum flags);
void nlCloseDLL(NLdll handle);
NLfunc nlFindFunction(NLdll handle, const char* funcname);
/* classic macros */
#ifndef MIN
#define MIN(x,y) (((x) < (y)) ? (x) : (y))
#endif
#ifndef MAX
#define MAX(x,y) (((x) > (y)) ? (x) : (y))
#endif
#define NL_NEW(T) (T*)(calloc(1, sizeof(T)))
#define NL_NEW_ARRAY(T,NB) (T*)(calloc((size_t)(NB),sizeof(T)))
#define NL_RENEW_ARRAY(T,x,NB) (T*)(realloc(x,(size_t)(NB)*sizeof(T)))
#define NL_DELETE(x) free(x); x = NULL
#define NL_DELETE_ARRAY(x) free(x); x = NULL
#define NL_CLEAR(T, x) memset(x, 0, sizeof(T))
#define NL_CLEAR_ARRAY(T,x,NB) memset(x, 0, (size_t)(NB)*sizeof(T))
#define NL_UINT_MAX 0xffffffff
#define NL_USHORT_MAX 0xffff
extern NLprintfFunc nl_printf;
extern NLfprintfFunc nl_fprintf;
#endif
/******* extracted from nl_blas.h *******/
#ifndef OPENNL_BLAS_H
#define OPENNL_BLAS_H
struct NLBlas;
typedef struct NLBlas* NLBlas_t;
typedef enum {
NoTranspose=0, Transpose=1, ConjugateTranspose=2
} MatrixTranspose ;
typedef enum {
UpperTriangle=0, LowerTriangle=1
} MatrixTriangle ;
typedef enum {
UnitTriangular=0, NotUnitTriangular=1
} MatrixUnitTriangular ;
typedef enum {
NL_HOST_MEMORY, NL_DEVICE_MEMORY
} NLmemoryType;
typedef void* (*FUNPTR_malloc)(
NLBlas_t blas, NLmemoryType type, size_t size
);
typedef void (*FUNPTR_free)(
NLBlas_t blas, NLmemoryType type, size_t size, void* ptr
);
typedef void (*FUNPTR_memcpy)(
NLBlas_t blas,
void* to, NLmemoryType to_type,
void* from, NLmemoryType from_type,
size_t size
);
typedef void (*FUNPTR_dcopy)(
NLBlas_t blas, int n, const double *x, int incx, double *y, int incy
);
typedef void (*FUNPTR_dscal)(
NLBlas_t blas, int n, double a, double *x, int incx
);
typedef double (*FUNPTR_ddot)(
NLBlas_t blas, int n, const double *x, int incx, const double *y, int incy
);
typedef double (*FUNPTR_dnrm2)(NLBlas_t blas, int n, const double *x, int incx);
typedef void (*FUNPTR_daxpy)(
NLBlas_t blas, int n,
double a, const double *x, int incx, double *y, int incy
);
typedef void (*FUNPTR_dgemv)(
NLBlas_t blas, MatrixTranspose trans, int m, int n, double alpha,
const double *A, int ldA, const double *x, int incx,
double beta, double *y, int incy
);
typedef void (*FUNPTR_dtpsv)(
NLBlas_t blas, MatrixTriangle uplo, MatrixTranspose trans,
MatrixUnitTriangular diag, int n, const double *AP,
double *x, int incx
);
struct NLBlas {
FUNPTR_malloc Malloc;
FUNPTR_free Free;
FUNPTR_memcpy Memcpy;
FUNPTR_dcopy Dcopy;
FUNPTR_dscal Dscal;
FUNPTR_ddot Ddot;
FUNPTR_dnrm2 Dnrm2;
FUNPTR_daxpy Daxpy;
FUNPTR_dgemv Dgemv;
FUNPTR_dtpsv Dtpsv;
NLboolean has_unified_memory;
double start_time;
NLulong flops;
NLulong used_ram[2];
NLulong max_used_ram[2];
/*
* Used for stats of the linear solver
* (a bit ugly, should not be here, but
* more convenient for now...)
*/
double sq_rnorm;
double sq_bnorm;
};
NLboolean nlBlasHasUnifiedMemory(NLBlas_t blas);
void nlBlasResetStats(NLBlas_t blas);
double nlBlasGFlops(NLBlas_t blas);
NLulong nlBlasUsedRam(NLBlas_t blas, NLmemoryType type);
NLulong nlBlasMaxUsedRam(NLBlas_t blas, NLmemoryType type);
NLBlas_t nlHostBlas(void);
#define NL_NEW_VECTOR(blas, memtype, dim) \
(double*)blas->Malloc(blas,memtype,(size_t)(dim)*sizeof(double))
#define NL_DELETE_VECTOR(blas, memtype, dim, ptr) \
blas->Free(blas,memtype,(size_t)(dim)*sizeof(double),ptr)
#endif
/******* extracted from nl_matrix.h *******/
#ifndef OPENNL_MATRIX_H
#define OPENNL_MATRIX_H
#ifdef __cplusplus
extern "C" {
#endif
/* Abstract matrix interface */
struct NLMatrixStruct;
typedef struct NLMatrixStruct* NLMatrix;
typedef void(*NLDestroyMatrixFunc)(NLMatrix M);
typedef void(*NLMultMatrixVectorFunc)(NLMatrix M, const double* x, double* y);
#define NL_MATRIX_SPARSE_DYNAMIC 0x1001
#define NL_MATRIX_CRS 0x1002
#define NL_MATRIX_SUPERLU_EXT 0x1003
#define NL_MATRIX_CHOLMOD_EXT 0x1004
#define NL_MATRIX_FUNCTION 0x1005
#define NL_MATRIX_OTHER 0x1006
struct NLMatrixStruct {
NLuint m;
NLuint n;
NLenum type;
NLDestroyMatrixFunc destroy_func;
NLMultMatrixVectorFunc mult_func;
};
NLAPI void NLAPIENTRY nlDeleteMatrix(NLMatrix M);
NLAPI void NLAPIENTRY nlMultMatrixVector(
NLMatrix M, const double* x, double* y
);
/* Dynamic arrays for sparse row/columns */
typedef struct {
NLuint index;
NLdouble value;
} NLCoeff;
typedef struct {
NLuint size;
NLuint capacity;
NLCoeff* coeff;
} NLRowColumn;
NLAPI void NLAPIENTRY nlRowColumnConstruct(NLRowColumn* c);
NLAPI void NLAPIENTRY nlRowColumnDestroy(NLRowColumn* c);
NLAPI void NLAPIENTRY nlRowColumnGrow(NLRowColumn* c);
NLAPI void NLAPIENTRY nlRowColumnAdd(
NLRowColumn* c, NLuint index, NLdouble value
);
NLAPI void NLAPIENTRY nlRowColumnAppend(
NLRowColumn* c, NLuint index, NLdouble value
);
NLAPI void NLAPIENTRY nlRowColumnZero(NLRowColumn* c);
NLAPI void NLAPIENTRY nlRowColumnClear(NLRowColumn* c);
NLAPI void NLAPIENTRY nlRowColumnSort(NLRowColumn* c);
/* Compressed Row Storage */
typedef struct {
NLuint m;
NLuint n;
NLenum type;
NLDestroyMatrixFunc destroy_func;
NLMultMatrixVectorFunc mult_func;
NLdouble* val;
NLuint* rowptr;
NLuint* colind;
NLuint nslices;
NLuint* sliceptr;
NLboolean symmetric_storage;
} NLCRSMatrix;
NLAPI void NLAPIENTRY nlCRSMatrixConstruct(
NLCRSMatrix* M, NLuint m, NLuint n, NLuint nnz, NLuint nslices
);
NLAPI void NLAPIENTRY nlCRSMatrixConstructSymmetric(
NLCRSMatrix* M, NLuint n, NLuint nnz
);
NLAPI NLboolean NLAPIENTRY nlCRSMatrixLoad(
NLCRSMatrix* M, const char* filename
);
NLAPI NLboolean NLAPIENTRY nlCRSMatrixSave(
NLCRSMatrix* M, const char* filename
);
NLAPI NLuint NLAPIENTRY nlCRSMatrixNNZ(NLCRSMatrix* M);
/* SparseMatrix data structure */
#define NL_MATRIX_STORE_ROWS 1
#define NL_MATRIX_STORE_COLUMNS 2
#define NL_MATRIX_STORE_SYMMETRIC 4
typedef struct {
NLuint m;
NLuint n;
NLenum type;
NLDestroyMatrixFunc destroy_func;
NLMultMatrixVectorFunc mult_func;
NLuint diag_size;
NLuint diag_capacity;
NLenum storage;
NLRowColumn* row;
NLRowColumn* column;
NLdouble* diag;
NLuint row_capacity;
NLuint column_capacity;
} NLSparseMatrix;
NLAPI NLMatrix NLAPIENTRY nlSparseMatrixNew(
NLuint m, NLuint n, NLenum storage
);
NLAPI void NLAPIENTRY nlSparseMatrixConstruct(
NLSparseMatrix* M, NLuint m, NLuint n, NLenum storage
);
NLAPI void NLAPIENTRY nlSparseMatrixDestroy(NLSparseMatrix* M);
NLAPI void NLAPIENTRY nlSparseMatrixMult(
NLSparseMatrix* A, const NLdouble* x, NLdouble* y
);
NLAPI void NLAPIENTRY nlSparseMatrixAdd(
NLSparseMatrix* M, NLuint i, NLuint j, NLdouble value
);
NLAPI void NLAPIENTRY nlSparseMatrixAddMatrix(
NLSparseMatrix* M, double mul, const NLMatrix N
);
NLAPI void NLAPIENTRY nlSparseMatrixZero( NLSparseMatrix* M);
NLAPI void NLAPIENTRY nlSparseMatrixClear( NLSparseMatrix* M);
NLAPI NLuint NLAPIENTRY nlSparseMatrixNNZ( NLSparseMatrix* M);
NLAPI void NLAPIENTRY nlSparseMatrixSort( NLSparseMatrix* M);
NLAPI void NLAPIENTRY nlSparseMatrixAddRow( NLSparseMatrix* M);
NLAPI void NLAPIENTRY nlSparseMatrixAddColumn( NLSparseMatrix* M);
NLAPI void NLAPIENTRY nlSparseMatrixMAddRow(
NLSparseMatrix* M, NLuint i1, double s, NLuint i2
);
NLAPI void NLAPIENTRY nlSparseMatrixScaleRow(
NLSparseMatrix* M, NLuint i, double s
);
NLAPI void NLAPIENTRY nlSparseMatrixZeroRow(
NLSparseMatrix* M, NLuint i
);
NLAPI NLMatrix NLAPIENTRY nlCRSMatrixNewFromSparseMatrix(NLSparseMatrix* M);
NLAPI NLMatrix NLAPIENTRY nlCRSMatrixNewFromSparseMatrixSymmetric(
NLSparseMatrix* M
);
NLAPI void NLAPIENTRY nlMatrixCompress(NLMatrix* M);
NLAPI NLuint NLAPIENTRY nlMatrixNNZ(NLMatrix M);
NLAPI NLMatrix NLAPIENTRY nlMatrixFactorize(NLMatrix M, NLenum solver);
typedef void(*NLMatrixFunc)(const double* x, double* y);
NLAPI NLMatrix NLAPIENTRY nlMatrixNewFromFunction(
NLuint m, NLuint n, NLMatrixFunc func
);
NLAPI NLMatrixFunc NLAPIENTRY nlMatrixGetFunction(NLMatrix M);
NLAPI NLMatrix NLAPIENTRY nlMatrixNewFromProduct(
NLMatrix M, NLboolean product_owns_M,
NLMatrix N, NLboolean product_owns_N
);
#ifdef __cplusplus
}
#endif
#endif
/******* extracted from nl_context.h *******/
#ifndef OPENNL_CONTEXT_H
#define OPENNL_CONTEXT_H
/* NLContext data structure */
typedef NLboolean(*NLSolverFunc)(void);
typedef void(*NLProgressFunc)(
NLuint cur_iter, NLuint max_iter, double cur_err, double max_err
);
#define NL_STATE_INITIAL 0
#define NL_STATE_SYSTEM 1
#define NL_STATE_MATRIX 2
#define NL_STATE_ROW 3
#define NL_STATE_MATRIX_CONSTRUCTED 4
#define NL_STATE_SYSTEM_CONSTRUCTED 5
#define NL_STATE_SOLVED 6
typedef struct {
void* base_address;
NLuint stride;
} NLBufferBinding;
#define NL_BUFFER_ITEM(B,i) \
*(double*)((void*)((char*)((B).base_address)+((i)*(B).stride)))
typedef struct {
NLenum state;
NLboolean user_variable_buffers;
NLBufferBinding* variable_buffer;
NLdouble* variable_value;
NLboolean* variable_is_locked;
NLuint* variable_index;
NLuint n;
NLenum matrix_mode;
NLMatrix M;
NLMatrix P;
NLMatrix B;
NLRowColumn af;
NLRowColumn al;
NLdouble* x;
NLdouble* b;
NLdouble* right_hand_side;
NLdouble row_scaling;
NLenum solver;
NLenum preconditioner;
NLboolean preconditioner_defined;
NLuint nb_variables;
NLuint nb_systems;
NLboolean ij_coefficient_called;
NLuint current_row;
NLboolean least_squares;
NLboolean symmetric;
NLuint max_iterations;
NLboolean max_iterations_defined;
NLuint inner_iterations;
NLdouble threshold;
NLboolean threshold_defined;
NLdouble omega;
NLboolean normalize_rows;
NLuint used_iterations;
NLdouble error;
NLdouble start_time;
NLdouble elapsed_time;
NLSolverFunc solver_func;
NLProgressFunc progress_func;
NLboolean verbose;
NLulong flops;
NLenum eigen_solver;
NLdouble eigen_shift;
NLboolean eigen_shift_invert;
NLdouble* eigen_value;
NLdouble* temp_eigen_value;
} NLContextStruct;
extern NLContextStruct* nlCurrentContext;
void nlCheckState(NLenum state);
void nlTransition(NLenum from_state, NLenum to_state);
NLboolean nlDefaultSolver(void);
#endif
/******* extracted from nl_iterative_solvers.h *******/
#ifndef OPENNL_ITERATIVE_SOLVERS_H
#define OPENNL_ITERATIVE_SOLVERS_H
NLAPI NLuint NLAPIENTRY nlSolveSystemIterative(
NLBlas_t blas,
NLMatrix M, NLMatrix P, NLdouble* b, NLdouble* x,
NLenum solver,
double eps, NLuint max_iter, NLuint inner_iter
);
#endif
/******* extracted from nl_preconditioners.h *******/
#ifndef OPENNL_PRECONDITIONERS_H
#define OPENNL_PRECONDITIONERS_H
/* preconditioners */
NLMatrix nlNewJacobiPreconditioner(NLMatrix M);
NLMatrix nlNewSSORPreconditioner(NLMatrix M, double omega);
#endif
/******* extracted from nl_superlu.h *******/
#ifndef OPENNL_SUPERLU_H
#define OPENNL_SUPERLU_H
NLAPI NLMatrix NLAPIENTRY nlMatrixFactorize_SUPERLU(
NLMatrix M, NLenum solver
);
NLboolean nlInitExtension_SUPERLU(void);
NLboolean nlExtensionIsInitialized_SUPERLU(void);
#endif
/******* extracted from nl_cholmod.h *******/
#ifndef OPENNL_CHOLMOD_H
#define OPENNL_CHOLMOD_H
NLAPI NLMatrix NLAPIENTRY nlMatrixFactorize_CHOLMOD(
NLMatrix M, NLenum solver
);
NLboolean nlInitExtension_CHOLMOD(void);
NLboolean nlExtensionIsInitialized_CHOLMOD(void);
#endif
/******* extracted from nl_arpack.h *******/
#ifndef OPENNL_ARPACK_H
#define OPENNL_ARPACK_H
NLboolean nlInitExtension_ARPACK(void);
NLboolean nlExtensionIsInitialized_ARPACK(void);
void nlEigenSolve_ARPACK(void);
#endif
/******* extracted from nl_mkl.h *******/
#ifndef OPENNL_MKL_H
#define OPENNL_MKL_H
NLboolean nlInitExtension_MKL(void);
NLboolean nlExtensionIsInitialized_MKL(void);
extern NLMultMatrixVectorFunc NLMultMatrixVector_MKL;
#endif
/******* extracted from nl_cuda.h *******/
#ifndef OPENNL_CUDA_EXT_H
#define OPENNL_CUDA_EXT_H
NLboolean nlInitExtension_CUDA(void);
NLboolean nlExtensionIsInitialized_CUDA(void);
NLMatrix nlCUDAMatrixNewFromCRSMatrix(NLMatrix M);
NLMatrix nlCUDAJacobiPreconditionerNewFromCRSMatrix(NLMatrix M);
NLBlas_t nlCUDABlas(void);
#endif
/******* extracted from nl_os.c *******/
#if (defined (WIN32) || defined(_WIN64))
#include <windows.h>
#else
#include <sys/types.h>
#include <sys/times.h>
#endif
#if defined(GEO_DYNAMIC_LIBS) && defined(NL_OS_UNIX)
#include <dlfcn.h>
#endif
/* Assertions */
void nl_assertion_failed(const char* cond, const char* file, int line) {
nl_fprintf(
stderr,
"OpenNL assertion failed: %s, file:%s, line:%d\n",
cond,file,line
) ;
abort() ;
}
void nl_range_assertion_failed(
double x, double min_val, double max_val, const char* file, int line
) {
nl_fprintf(
stderr,
"OpenNL range assertion failed: "
"%f in [ %f ... %f ], file:%s, line:%d\n",
x, min_val, max_val, file,line
) ;
abort() ;
}
void nl_should_not_have_reached(const char* file, int line) {
nl_fprintf(
stderr,
"OpenNL should not have reached this point: file:%s, line:%d\n",
file,line
) ;
abort() ;
}
/* Timing */
#ifdef WIN32
NLdouble nlCurrentTime() {
return (NLdouble)GetTickCount() / 1000.0 ;
}
#else
double nlCurrentTime() {
clock_t user_clock ;
struct tms user_tms ;
user_clock = times(&user_tms) ;
return (NLdouble)user_clock / 100.0 ;
}
#endif
/* DLLs/shared objects/dylibs */
#if defined(GEO_DYNAMIC_LIBS)
# if defined(NL_OS_UNIX)
NLdll nlOpenDLL(const char* name, NLenum flags_in) {
void* result = NULL;
int flags = 0;
if((flags_in & NL_LINK_NOW) != 0) {
flags |= RTLD_NOW;
}
if((flags_in & NL_LINK_LAZY) != 0) {
flags |= RTLD_LAZY;
}
if((flags_in & NL_LINK_GLOBAL) != 0) {
flags |= RTLD_GLOBAL;
}
if((flags_in & NL_LINK_QUIET) == 0) {
nl_fprintf(stdout,"Trying to load %s\n", name);
}
result = dlopen(name, flags);
if(result == NULL) {
if((flags_in & NL_LINK_QUIET) == 0) {
nl_fprintf(stderr,"Did not find %s,\n", name);
nl_fprintf(stderr,"Retrying with libgeogram_num_3rdparty.so\n");
}
if((flags_in & NL_LINK_USE_FALLBACK) != 0) {
result=dlopen("libgeogram_num_3rdparty.so", flags);
if(result == NULL) {
if((flags_in & NL_LINK_QUIET) == 0) {
nlError("nlOpenDLL/dlopen",dlerror());
}
}
}
}
if((flags_in & NL_LINK_QUIET) == 0 && result != NULL) {
nl_fprintf(stdout,"Loaded %s\n", name);
}
return result;
}
void nlCloseDLL(void* handle) {
dlclose(handle);
}
NLfunc nlFindFunction(void* handle, const char* name) {
/*
* It is not legal in modern C to cast a void*
* pointer into a function pointer, thus requiring this
* (quite dirty) function that uses a union.
*/
union {
void* ptr;
NLfunc fptr;
} u;
u.ptr = dlsym(handle, name);
return u.fptr;
}
# elif defined(NL_OS_WINDOWS)
NLdll nlOpenDLL(const char* name, NLenum flags) {
/* Note: NL_LINK_LAZY and NL_LINK_GLOBAL are ignored. */
void* result = LoadLibrary(name);
if(result == NULL && ((flags & NL_LINK_USE_FALLBACK) != 0)) {
if((flags & NL_LINK_QUIET) == 0) {
nl_fprintf(stderr,"Did not find %s,\n", name);
nl_fprintf(stderr,"Retrying with geogram_num_3rdparty\n");
}
result=LoadLibrary("geogram_num_3rdparty.dll");
}
return result;
}
void nlCloseDLL(void* handle) {
FreeLibrary((HMODULE)handle);
}
NLfunc nlFindFunction(void* handle, const char* name) {
return (NLfunc)GetProcAddress((HMODULE)handle, name);
}
# endif
#else
NLdll nlOpenDLL(const char* name, NLenum flags) {
nl_arg_used(name);
nl_arg_used(flags);
#ifdef NL_OS_UNIX
nlError("nlOpenDLL","Was not compiled with dynamic linking enabled");
nlError("nlOpenDLL","(see VORPALINE_BUILD_DYNAMIC in CMakeLists.txt)");
#else
nlError("nlOpenDLL","Not implemented");
#endif
return NULL;
}
void nlCloseDLL(void* handle) {
nl_arg_used(handle);
nlError("nlCloseDLL","Not implemented");
}
NLfunc nlFindFunction(void* handle, const char* name) {
nl_arg_used(handle);
nl_arg_used(name);
nlError("nlFindFunction","Not implemented");
return NULL;
}
#endif
/* Error-reporting functions */
NLprintfFunc nl_printf = printf;
NLfprintfFunc nl_fprintf = fprintf;
void nlError(const char* function, const char* message) {
nl_fprintf(stderr, "OpenNL error in %s(): %s\n", function, message) ;
}
void nlWarning(const char* function, const char* message) {
nl_fprintf(stderr, "OpenNL warning in %s(): %s\n", function, message) ;
}
void nlPrintfFuncs(NLprintfFunc f1, NLfprintfFunc f2) {
nl_printf = f1;
nl_fprintf = f2;
}
/******* extracted from nl_matrix.c *******/
/*
Some warnings about const cast in callback for
qsort() function.
*/
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wcast-qual"
#endif
void nlDeleteMatrix(NLMatrix M) {
if(M == NULL) {
return;
}
M->destroy_func(M);
NL_DELETE(M);
}
void nlMultMatrixVector(
NLMatrix M, const double* x, double* y
) {
M->mult_func(M,x,y);
}
void nlRowColumnConstruct(NLRowColumn* c) {
c->size = 0;
c->capacity = 0;
c->coeff = NULL;
}
void nlRowColumnDestroy(NLRowColumn* c) {
NL_DELETE_ARRAY(c->coeff);
c->size = 0;
c->capacity = 0;
}
void nlRowColumnGrow(NLRowColumn* c) {
if(c->capacity != 0) {
c->capacity = 2 * c->capacity;
c->coeff = NL_RENEW_ARRAY(NLCoeff, c->coeff, c->capacity);
} else {
c->capacity = 4;
c->coeff = NL_NEW_ARRAY(NLCoeff, c->capacity);
}
}
void nlRowColumnAdd(NLRowColumn* c, NLuint index, NLdouble value) {
NLuint i;
for(i=0; i<c->size; i++) {
if(c->coeff[i].index == index) {
c->coeff[i].value += value;
return;
}
}
if(c->size == c->capacity) {
nlRowColumnGrow(c);
}
c->coeff[c->size].index = index;
c->coeff[c->size].value = value;
c->size++;
}
/* Does not check whether the index already exists */
void nlRowColumnAppend(NLRowColumn* c, NLuint index, NLdouble value) {
if(c->size == c->capacity) {
nlRowColumnGrow(c);
}
c->coeff[c->size].index = index;
c->coeff[c->size].value = value;
c->size++;
}
void nlRowColumnZero(NLRowColumn* c) {
c->size = 0;
}
void nlRowColumnClear(NLRowColumn* c) {
c->size = 0;
c->capacity = 0;
NL_DELETE_ARRAY(c->coeff);
}
static int nlCoeffCompare(const void* p1, const void* p2) {
return (((NLCoeff*)(p2))->index < ((NLCoeff*)(p1))->index);
}
void nlRowColumnSort(NLRowColumn* c) {
qsort(c->coeff, c->size, sizeof(NLCoeff), nlCoeffCompare);
}
/* CRSMatrix data structure */
static void nlCRSMatrixDestroy(NLCRSMatrix* M) {
NL_DELETE_ARRAY(M->val);
NL_DELETE_ARRAY(M->rowptr);
NL_DELETE_ARRAY(M->colind);
NL_DELETE_ARRAY(M->sliceptr);
M->m = 0;
M->n = 0;
M->nslices = 0;
}
NLboolean nlCRSMatrixSave(NLCRSMatrix* M, const char* filename) {
NLuint nnz = M->rowptr[M->m];
FILE* f = fopen(filename, "rb");
if(f == NULL) {
nlError("nlCRSMatrixSave", "Could not open file");
return NL_FALSE;
}
fwrite(&M->m, sizeof(NLuint), 1, f);
fwrite(&M->n, sizeof(NLuint), 1, f);
fwrite(&nnz, sizeof(NLuint), 1, f);
fwrite(M->rowptr, sizeof(NLuint), M->m+1, f);
fwrite(M->colind, sizeof(NLuint), nnz, f);
fwrite(M->val, sizeof(double), nnz, f);
return NL_TRUE;
}
NLboolean nlCRSMatrixLoad(NLCRSMatrix* M, const char* filename) {
NLuint nnz = 0;
FILE* f = fopen(filename, "rb");
NLboolean truncated = NL_FALSE;
if(f == NULL) {
nlError("nlCRSMatrixLoad", "Could not open file");
return NL_FALSE;
}
truncated = truncated || (
fread(&M->m, sizeof(NLuint), 1, f) != 1 ||
fread(&M->n, sizeof(NLuint), 1, f) != 1 ||
fread(&nnz, sizeof(NLuint), 1, f) != 1
);
if(truncated) {
M->rowptr = NULL;
M->colind = NULL;
M->val = NULL;
} else {
M->rowptr = NL_NEW_ARRAY(NLuint, M->m+1);
M->colind = NL_NEW_ARRAY(NLuint, nnz);
M->val = NL_NEW_ARRAY(double, nnz);
truncated = truncated || (
fread(M->rowptr, sizeof(NLuint), M->m+1, f) != M->m+1 ||
fread(M->colind, sizeof(NLuint), nnz, f) != nnz ||
fread(M->val, sizeof(double), nnz, f) != nnz
);
}
if(truncated) {
nlError("nlCRSMatrixSave", "File appears to be truncated");
NL_DELETE_ARRAY(M->rowptr);
NL_DELETE_ARRAY(M->colind);
NL_DELETE_ARRAY(M->val);
return NL_FALSE;
} else {
M->nslices = 1;
M->sliceptr = NL_NEW_ARRAY(NLuint, M->nslices+1);
M->sliceptr[0] = 0;
M->sliceptr[1] = M->m;
}
fclose(f);
return NL_TRUE;
}
NLuint nlCRSMatrixNNZ(NLCRSMatrix* M) {
return M->rowptr[M->m];
}
static void nlCRSMatrixMultSlice(
NLCRSMatrix* M, const double* x, double* y, NLuint Ibegin, NLuint Iend
) {
NLuint i,j;
for(i=Ibegin; i<Iend; ++i) {
double sum=0.0;
for(j=M->rowptr[i]; j<M->rowptr[i+1]; ++j) {
sum += M->val[j] * x[M->colind[j]];
}
y[i] = sum;
}
}
static void nlCRSMatrixMult(
NLCRSMatrix* M, const double* x, double* y
) {
int slice;
int nslices = (int)(M->nslices);
NLuint i,j,jj;
NLdouble a;
if(M->symmetric_storage) {
for(i=0; i<M->m; ++i) {
y[i] = 0.0;
}
for(i=0; i<M->m; ++i) {
for(jj=M->rowptr[i]; jj<M->rowptr[i+1]; ++jj) {
a = M->val[jj];
j = M->colind[jj];
y[i] += a * x[j];
if(j != i) {
y[j] += a * x[i];
}
}
}
} else {
#if defined(_OPENMP)
#pragma omp parallel for private(slice)
#endif
for(slice=0; slice<nslices; ++slice) {
nlCRSMatrixMultSlice(
M,x,y,M->sliceptr[slice],M->sliceptr[slice+1]
);
}
}
nlHostBlas()->flops += (NLulong)(2*nlCRSMatrixNNZ(M));
}
void nlCRSMatrixConstruct(
NLCRSMatrix* M, NLuint m, NLuint n, NLuint nnz, NLuint nslices
) {
M->m = m;
M->n = n;
M->type = NL_MATRIX_CRS;
M->destroy_func = (NLDestroyMatrixFunc)nlCRSMatrixDestroy;
if(NLMultMatrixVector_MKL != NULL) {
M->mult_func = (NLMultMatrixVectorFunc)NLMultMatrixVector_MKL;
} else {
M->mult_func = (NLMultMatrixVectorFunc)nlCRSMatrixMult;
}
M->nslices = nslices;
M->val = NL_NEW_ARRAY(double, nnz);
M->rowptr = NL_NEW_ARRAY(NLuint, m+1);
M->colind = NL_NEW_ARRAY(NLuint, nnz);
M->sliceptr = NL_NEW_ARRAY(NLuint, nslices+1);
M->symmetric_storage = NL_FALSE;
}
void nlCRSMatrixConstructSymmetric(
NLCRSMatrix* M, NLuint n, NLuint nnz
) {
M->m = n;
M->n = n;
M->type = NL_MATRIX_CRS;
M->destroy_func = (NLDestroyMatrixFunc)nlCRSMatrixDestroy;
M->mult_func = (NLMultMatrixVectorFunc)nlCRSMatrixMult;
M->nslices = 0;
M->val = NL_NEW_ARRAY(double, nnz);
M->rowptr = NL_NEW_ARRAY(NLuint, n+1);
M->colind = NL_NEW_ARRAY(NLuint, nnz);
M->sliceptr = NULL;
M->symmetric_storage = NL_TRUE;
}
/* SparseMatrix data structure */
static void nlSparseMatrixDestroyRowColumns(NLSparseMatrix* M) {
NLuint i;
if(M->storage & NL_MATRIX_STORE_ROWS) {
for(i=0; i<M->m; i++) {
nlRowColumnDestroy(&(M->row[i]));
}
NL_DELETE_ARRAY(M->row);
}
M->storage = (NLenum)((int)(M->storage) & ~NL_MATRIX_STORE_ROWS);
if(M->storage & NL_MATRIX_STORE_COLUMNS) {
for(i=0; i<M->n; i++) {
nlRowColumnDestroy(&(M->column[i]));
}
NL_DELETE_ARRAY(M->column);
}
M->storage = (NLenum)((int)(M->storage) & ~NL_MATRIX_STORE_COLUMNS);
}
void nlSparseMatrixDestroy(NLSparseMatrix* M) {
nl_assert(M->type == NL_MATRIX_SPARSE_DYNAMIC);
nlSparseMatrixDestroyRowColumns(M);
NL_DELETE_ARRAY(M->diag);
#ifdef NL_PARANOID
NL_CLEAR(NLSparseMatrix,M);
#endif
}
void nlSparseMatrixAdd(NLSparseMatrix* M, NLuint i, NLuint j, NLdouble value) {
nl_parano_range_assert(i, 0, M->m - 1);
nl_parano_range_assert(j, 0, M->n - 1);
if((M->storage & NL_MATRIX_STORE_SYMMETRIC) && (j > i)) {
return;
}
if(i == j) {
M->diag[i] += value;
}
if(M->storage & NL_MATRIX_STORE_ROWS) {
nlRowColumnAdd(&(M->row[i]), j, value);
}
if(M->storage & NL_MATRIX_STORE_COLUMNS) {
nlRowColumnAdd(&(M->column[j]), i, value);
}
}
static void nlSparseMatrixAddSparseMatrix(
NLSparseMatrix* M, double mul, const NLSparseMatrix* N
) {
NLuint i,j,ii,jj;
nl_assert(M->m == N->m);
nl_assert(M->n == N->n);
if(N->storage & NL_MATRIX_STORE_SYMMETRIC) {
nl_assert(M->storage & NL_MATRIX_STORE_SYMMETRIC);
}
if(N->storage & NL_MATRIX_STORE_ROWS) {
for(i=0; i<N->m; ++i) {
for(jj=0; jj<N->row[i].size; ++jj) {
nlSparseMatrixAdd(
M,
i, N->row[i].coeff[jj].index,
mul*N->row[i].coeff[jj].value
);
}
}
} else {
nl_assert(N->storage & NL_MATRIX_STORE_COLUMNS);
for(j=0; j<N->n; ++j) {
for(ii=0; ii<N->column[j].size; ++ii) {
nlSparseMatrixAdd(
M,
N->column[j].coeff[ii].index, j,
mul*N->column[j].coeff[ii].value
);
}
}
}
}
static void nlSparseMatrixAddCRSMatrix(
NLSparseMatrix* M, double mul, const NLCRSMatrix* N
) {
NLuint i,jj;
nl_assert(M->m == N->m);
nl_assert(M->n == N->n);
for(i=0; i<M->m; ++i) {
for(jj=N->rowptr[i]; jj<N->rowptr[i+1]; ++jj) {
nlSparseMatrixAdd(
M,
i,
N->colind[jj],
mul*N->val[jj]
);
}
}
}
void nlSparseMatrixAddMatrix(
NLSparseMatrix* M, double mul, const NLMatrix N
) {
nl_assert(M->m == N->m);
nl_assert(M->n == N->n);
if(N->type == NL_MATRIX_SPARSE_DYNAMIC) {
nlSparseMatrixAddSparseMatrix(M, mul, (const NLSparseMatrix*)N);
} else if(N->type == NL_MATRIX_CRS) {
nlSparseMatrixAddCRSMatrix(M, mul, (const NLCRSMatrix*)N);
} else {
nl_assert_not_reached;
}
}
void nlSparseMatrixZero( NLSparseMatrix* M) {
NLuint i;
if(M->storage & NL_MATRIX_STORE_ROWS) {
for(i=0; i<M->m; i++) {
nlRowColumnZero(&(M->row[i]));
}
}
if(M->storage & NL_MATRIX_STORE_COLUMNS) {
for(i=0; i<M->n; i++) {
nlRowColumnZero(&(M->column[i]));
}
}
NL_CLEAR_ARRAY(NLdouble, M->diag, M->diag_size);
}
void nlSparseMatrixClear( NLSparseMatrix* M) {
NLuint i;
if(M->storage & NL_MATRIX_STORE_ROWS) {
for(i=0; i<M->m; i++) {
nlRowColumnClear(&(M->row[i]));
}
}
if(M->storage & NL_MATRIX_STORE_COLUMNS) {
for(i=0; i<M->n; i++) {
nlRowColumnClear(&(M->column[i]));
}
}
NL_CLEAR_ARRAY(NLdouble, M->diag, M->diag_size);
}
/* Returns the number of non-zero coefficients */
NLuint nlSparseMatrixNNZ( NLSparseMatrix* M) {
NLuint nnz = 0;
NLuint i;
if(M->storage & NL_MATRIX_STORE_ROWS) {
for(i = 0; i<M->m; i++) {
nnz += M->row[i].size;
}
} else if (M->storage & NL_MATRIX_STORE_COLUMNS) {
for(i = 0; i<M->n; i++) {
nnz += M->column[i].size;
}
} else {
nl_assert_not_reached;
}
return nnz;
}
void nlSparseMatrixSort( NLSparseMatrix* M) {
NLuint i;
if(M->storage & NL_MATRIX_STORE_ROWS) {
for(i = 0; i<M->m; i++) {
nlRowColumnSort(&(M->row[i]));
}
}
if (M->storage & NL_MATRIX_STORE_COLUMNS) {
for(i = 0; i<M->n; i++) {
nlRowColumnSort(&(M->column[i]));
}
}
}
void nlSparseMatrixMAddRow(
NLSparseMatrix* M, NLuint i1, double s, NLuint i2
) {
NLuint jj;
NLRowColumn* Ri2 = &(M->row[i2]);
NLCoeff* c = NULL;
nl_debug_assert(i1 < M->m);
nl_debug_assert(i2 < M->m);
for(jj=0; jj<Ri2->size; ++jj) {
c = &(Ri2->coeff[jj]);
nlSparseMatrixAdd(M, i1, c->index, s*c->value);
}
}
void nlSparseMatrixScaleRow(
NLSparseMatrix* M, NLuint i, double s
) {
NLuint jj;
NLRowColumn* Ri = &(M->row[i]);
NLCoeff* c = NULL;
nl_assert(M->storage & NL_MATRIX_STORE_ROWS);
nl_assert(!(M->storage & NL_MATRIX_STORE_COLUMNS));
nl_debug_assert(i < M->m);
for(jj=0; jj<Ri->size; ++jj) {
c = &(Ri->coeff[jj]);
c->value *= s;
}
if(i < M->diag_size) {
M->diag[i] *= s;
}
}
void nlSparseMatrixZeroRow(
NLSparseMatrix* M, NLuint i
) {
NLRowColumn* Ri = &(M->row[i]);
nl_debug_assert(i < M->m);
Ri->size = 0;
if(i < M->diag_size) {
M->diag[i] = 0.0;
}
}
/* SparseMatrix x Vector routines, internal helper routines */
static void nlSparseMatrix_mult_rows_symmetric(
NLSparseMatrix* A,
const NLdouble* x,
NLdouble* y
) {
NLuint m = A->m;
NLuint i,ij;
NLCoeff* c = NULL;
for(i=0; i<m; i++) {
NLRowColumn* Ri = &(A->row[i]);
y[i] = 0;
for(ij=0; ij<Ri->size; ++ij) {
c = &(Ri->coeff[ij]);
y[i] += c->value * x[c->index];
if(i != c->index) {
y[c->index] += c->value * x[i];
}
}
}
}
static void nlSparseMatrix_mult_rows(
NLSparseMatrix* A,
const NLdouble* x,
NLdouble* y
) {
/*
* Note: OpenMP does not like unsigned ints
* (causes some floating point exceptions),
* therefore I use here signed ints for all
* indices.
*/
int m = (int)(A->m);
int i,ij;
NLCoeff* c = NULL;
NLRowColumn* Ri = NULL;
#if defined(_OPENMP)
#pragma omp parallel for private(i,ij,c,Ri)
#endif
for(i=0; i<m; i++) {
Ri = &(A->row[i]);
y[i] = 0;
for(ij=0; ij<(int)(Ri->size); ij++) {
c = &(Ri->coeff[ij]);
y[i] += c->value * x[c->index];
}
}
}
static void nlSparseMatrix_mult_cols_symmetric(
NLSparseMatrix* A,
const NLdouble* x,
NLdouble* y
) {
NLuint n = A->n;
NLuint j,ii;
NLCoeff* c = NULL;
for(j=0; j<n; j++) {
NLRowColumn* Cj = &(A->column[j]);
y[j] = 0;
for(ii=0; ii<Cj->size; ii++) {
c = &(Cj->coeff[ii]);
y[c->index] += c->value * x[j];
if(j != c->index) {
y[j] += c->value * x[c->index];
}
}
}
}
static void nlSparseMatrix_mult_cols(
NLSparseMatrix* A,
const NLdouble* x,
NLdouble* y
) {
NLuint n = A->n;
NLuint j,ii;
NLCoeff* c = NULL;
NL_CLEAR_ARRAY(NLdouble, y, A->m);
for(j=0; j<n; j++) {
NLRowColumn* Cj = &(A->column[j]);
for(ii=0; ii<Cj->size; ii++) {
c = &(Cj->coeff[ii]);
y[c->index] += c->value * x[j];
}
}
}
void nlSparseMatrixMult(
NLSparseMatrix* A, const NLdouble* x, NLdouble* y
) {
nl_assert(A->type == NL_MATRIX_SPARSE_DYNAMIC);
if(A->storage & NL_MATRIX_STORE_ROWS) {
if(A->storage & NL_MATRIX_STORE_SYMMETRIC) {
nlSparseMatrix_mult_rows_symmetric(A, x, y);
} else {
nlSparseMatrix_mult_rows(A, x, y);
}
} else {
if(A->storage & NL_MATRIX_STORE_SYMMETRIC) {
nlSparseMatrix_mult_cols_symmetric(A, x, y);
} else {
nlSparseMatrix_mult_cols(A, x, y);
}
}
nlHostBlas()->flops += (NLulong)(2*nlSparseMatrixNNZ(A));
}
NLMatrix nlSparseMatrixNew(
NLuint m, NLuint n, NLenum storage
) {
NLSparseMatrix* result = NL_NEW(NLSparseMatrix);
nlSparseMatrixConstruct(result, m, n, storage);
return (NLMatrix)result;
}
void nlSparseMatrixConstruct(
NLSparseMatrix* M, NLuint m, NLuint n, NLenum storage
) {
NLuint i;
M->m = m;
M->n = n;
M->type = NL_MATRIX_SPARSE_DYNAMIC;
M->destroy_func = (NLDestroyMatrixFunc)nlSparseMatrixDestroy;
M->mult_func = (NLMultMatrixVectorFunc)nlSparseMatrixMult;
M->storage = storage;
if(storage & NL_MATRIX_STORE_ROWS) {
M->row = NL_NEW_ARRAY(NLRowColumn, m);
M->row_capacity = m;
for(i=0; i<n; i++) {
nlRowColumnConstruct(&(M->row[i]));
}
} else {
M->row = NULL;
M->row_capacity = 0;
}
if(storage & NL_MATRIX_STORE_COLUMNS) {
M->column = NL_NEW_ARRAY(NLRowColumn, n);
M->column_capacity = n;
for(i=0; i<n; i++) {
nlRowColumnConstruct(&(M->column[i]));
}
} else {
M->column = NULL;
M->column_capacity = 0;
}
M->diag_size = MIN(m,n);
M->diag_capacity = M->diag_size;
M->diag = NL_NEW_ARRAY(NLdouble, M->diag_size);
}
static void adjust_diag(NLSparseMatrix* M) {
NLuint new_diag_size = MIN(M->m, M->n);
NLuint i;
if(new_diag_size > M->diag_size) {
if(new_diag_size > M->diag_capacity) {
M->diag_capacity *= 2;
if(M->diag_capacity == 0) {
M->diag_capacity = 16;
}
M->diag = NL_RENEW_ARRAY(double, M->diag, M->diag_capacity);
for(i=M->diag_size; i<new_diag_size; ++i) {
M->diag[i] = 0.0;
}
}
M->diag_size= new_diag_size;
}
}
void nlSparseMatrixAddRow( NLSparseMatrix* M) {
++M->m;
if(M->storage & NL_MATRIX_STORE_ROWS) {
if(M->m > M->row_capacity) {
M->row_capacity *= 2;
if(M->row_capacity == 0) {
M->row_capacity = 16;
}
M->row = NL_RENEW_ARRAY(
NLRowColumn, M->row, M->row_capacity
);
}
nlRowColumnConstruct(&(M->row[M->m-1]));
}
adjust_diag(M);
}
void nlSparseMatrixAddColumn( NLSparseMatrix* M) {
++M->n;
if(M->storage & NL_MATRIX_STORE_COLUMNS) {
if(M->n > M->column_capacity) {
M->column_capacity *= 2;
if(M->column_capacity == 0) {
M->column_capacity = 16;
}
M->column = NL_RENEW_ARRAY(
NLRowColumn, M->column, M->column_capacity
);
}
nlRowColumnConstruct(&(M->column[M->n-1]));
}
adjust_diag(M);
}
NLMatrix nlCRSMatrixNewFromSparseMatrix(NLSparseMatrix* M) {
NLuint nnz = nlSparseMatrixNNZ(M);
NLuint nslices = 8; /* TODO: get number of cores */
NLuint slice, cur_bound, cur_NNZ, cur_row;
NLuint i,ij,k;
NLuint slice_size = nnz / nslices;
NLCRSMatrix* CRS = NL_NEW(NLCRSMatrix);
nl_assert(M->storage & NL_MATRIX_STORE_ROWS);
if(M->storage & NL_MATRIX_STORE_SYMMETRIC) {
nl_assert(M->m == M->n);
nlCRSMatrixConstructSymmetric(CRS, M->n, nnz);
} else {
nlCRSMatrixConstruct(CRS, M->m, M->n, nnz, nslices);
}
nlSparseMatrixSort(M);
/* Convert matrix to CRS format */
k=0;
for(i=0; i<M->m; ++i) {
NLRowColumn* Ri = &(M->row[i]);
CRS->rowptr[i] = k;
for(ij=0; ij<Ri->size; ij++) {
NLCoeff* c = &(Ri->coeff[ij]);
CRS->val[k] = c->value;
CRS->colind[k] = c->index;
++k;
}
}
CRS->rowptr[M->m] = k;
/* Create "slices" to be used by parallel sparse matrix vector product */
if(CRS->sliceptr != NULL) {
cur_bound = slice_size;
cur_NNZ = 0;
cur_row = 0;
CRS->sliceptr[0]=0;
for(slice=1; slice<nslices; ++slice) {
while(cur_NNZ < cur_bound && cur_row < M->m) {
++cur_row;
cur_NNZ += CRS->rowptr[cur_row+1] - CRS->rowptr[cur_row];
}
CRS->sliceptr[slice] = cur_row;
cur_bound += slice_size;
}
CRS->sliceptr[nslices]=M->m;
}
return (NLMatrix)CRS;
}
NLMatrix nlCRSMatrixNewFromSparseMatrixSymmetric(NLSparseMatrix* M) {
NLuint nnz;
NLuint i,j,jj,k;
NLCRSMatrix* CRS = NL_NEW(NLCRSMatrix);
nl_assert(M->storage & NL_MATRIX_STORE_ROWS);
nl_assert(M->m == M->n);
nlSparseMatrixSort(M);
if(M->storage & NL_MATRIX_STORE_SYMMETRIC) {
nnz = nlSparseMatrixNNZ(M);
} else {
nnz = 0;
for(i=0; i<M->n; ++i) {
NLRowColumn* Ri = &M->row[i];
for(jj=0; jj<Ri->size; ++jj) {
j = Ri->coeff[jj].index;
if(j <= i) {
++nnz;
}
}
}
}
nlCRSMatrixConstructSymmetric(CRS, M->n, nnz);
k=0;
for(i=0; i<M->m; ++i) {
NLRowColumn* Ri = &(M->row[i]);
CRS->rowptr[i] = k;
for(jj=0; jj<Ri->size; ++jj) {
j = Ri->coeff[jj].index;
if((M->storage & NL_MATRIX_STORE_SYMMETRIC)) {
nl_debug_assert(j <= i);
}
if(j <= i) {
CRS->val[k] = Ri->coeff[jj].value;
CRS->colind[k] = j;
++k;
}
}
}
CRS->rowptr[M->m] = k;
return (NLMatrix)CRS;
}
void nlMatrixCompress(NLMatrix* M) {
NLMatrix CRS = NULL;
if((*M)->type != NL_MATRIX_SPARSE_DYNAMIC) {
return;
}
CRS = nlCRSMatrixNewFromSparseMatrix((NLSparseMatrix*)*M);
nlDeleteMatrix(*M);
*M = CRS;
}
NLuint nlMatrixNNZ(NLMatrix M) {
if(M->type == NL_MATRIX_SPARSE_DYNAMIC) {
return nlSparseMatrixNNZ((NLSparseMatrix*)M);
} else if(M->type == NL_MATRIX_CRS) {
return nlCRSMatrixNNZ((NLCRSMatrix*)M);
}
return M->m * M->n;
}
NLMatrix nlMatrixFactorize(NLMatrix M, NLenum solver) {
NLMatrix result = NULL;
switch(solver) {
case NL_SUPERLU_EXT:
case NL_PERM_SUPERLU_EXT:
case NL_SYMMETRIC_SUPERLU_EXT:
result = nlMatrixFactorize_SUPERLU(M,solver);
break;
case NL_CHOLMOD_EXT:
result = nlMatrixFactorize_CHOLMOD(M,solver);
break;
default:
nlError("nlMatrixFactorize","unknown solver");
}
return result;
}
typedef struct {
NLuint m;
NLuint n;
NLenum type;
NLDestroyMatrixFunc destroy_func;
NLMultMatrixVectorFunc mult_func;
NLMatrixFunc matrix_func;
} NLFunctionMatrix;
static void nlFunctionMatrixDestroy(NLFunctionMatrix* M) {
(void)M; /* to avoid 'unused parameter' warning */
/*
* Nothing special to do,
* there is no dynamic allocated mem.
*/
}
static void nlFunctionMatrixMult(
NLFunctionMatrix* M, const NLdouble* x, NLdouble* y
) {
M->matrix_func(x,y);
}
NLMatrix nlMatrixNewFromFunction(NLuint m, NLuint n, NLMatrixFunc func) {
NLFunctionMatrix* result = NL_NEW(NLFunctionMatrix);
result->m = m;
result->n = n;
result->type = NL_MATRIX_FUNCTION;
result->destroy_func = (NLDestroyMatrixFunc)nlFunctionMatrixDestroy;
result->mult_func = (NLMultMatrixVectorFunc)nlFunctionMatrixMult;
result->matrix_func = func;
return (NLMatrix)result;
}
NLMatrixFunc nlMatrixGetFunction(NLMatrix M) {
if(M == NULL) {
return NULL;
}
if(M->type != NL_MATRIX_FUNCTION) {
return NULL;
}
return ((NLFunctionMatrix*)M)->matrix_func;
}
typedef struct {
NLuint m;
NLuint n;
NLenum type;
NLDestroyMatrixFunc destroy_func;
NLMultMatrixVectorFunc mult_func;
NLMatrixFunc matrix_func;
NLMatrix M;
NLboolean owns_M;
NLMatrix N;
NLboolean owns_N;
NLdouble* work;
} NLMatrixProduct;
static void nlMatrixProductDestroy(NLMatrixProduct* P) {
NL_DELETE_ARRAY(P->work);
if(P->owns_M) {
nlDeleteMatrix(P->M); P->M = NULL;
}
if(P->owns_N) {
nlDeleteMatrix(P->N); P->N = NULL;
}
}
static void nlMatrixProductMult(
NLMatrixProduct* P, const NLdouble* x, NLdouble* y
) {
nlMultMatrixVector(P->N, x, P->work);
nlMultMatrixVector(P->M, P->work, y);
}
NLMatrix nlMatrixNewFromProduct(
NLMatrix M, NLboolean owns_M, NLMatrix N, NLboolean owns_N
) {
NLMatrixProduct* result = NL_NEW(NLMatrixProduct);
nl_assert(M->n == N->m);
result->m = M->m;
result->n = N->n;
result->type = NL_MATRIX_OTHER;
result->work = NL_NEW_ARRAY(NLdouble,N->m);
result->destroy_func = (NLDestroyMatrixFunc)nlMatrixProductDestroy;
result->mult_func = (NLMultMatrixVectorFunc)nlMatrixProductMult;
result->M = M;
result->owns_M = owns_M;
result->N = N;
result->owns_N = owns_N;
return (NLMatrix)result;
}
/******* extracted from nl_context.c *******/
NLContextStruct* nlCurrentContext = NULL;
NLContext nlNewContext() {
NLContextStruct* result = NL_NEW(NLContextStruct);
result->state = NL_STATE_INITIAL;
result->solver = NL_SOLVER_DEFAULT;
result->max_iterations = 100;
result->threshold = 1e-6;
result->omega = 1.5;
result->row_scaling = 1.0;
result->inner_iterations = 5;
result->solver_func = nlDefaultSolver;
result->progress_func = NULL;
result->verbose = NL_FALSE;
result->nb_systems = 1;
result->matrix_mode = NL_STIFFNESS_MATRIX;
nlMakeCurrent(result);
return result;
}
void nlDeleteContext(NLContext context_in) {
NLContextStruct* context = (NLContextStruct*)(context_in);
if(nlCurrentContext == context) {
nlCurrentContext = NULL;
}
nlDeleteMatrix(context->M);
context->M = NULL;
nlDeleteMatrix(context->P);
context->P = NULL;
nlDeleteMatrix(context->B);
context->B = NULL;
nlRowColumnDestroy(&context->af);
nlRowColumnDestroy(&context->al);
NL_DELETE_ARRAY(context->variable_value);
NL_DELETE_ARRAY(context->variable_buffer);
NL_DELETE_ARRAY(context->variable_is_locked);
NL_DELETE_ARRAY(context->variable_index);
NL_DELETE_ARRAY(context->x);
NL_DELETE_ARRAY(context->b);
NL_DELETE_ARRAY(context->right_hand_side);
NL_DELETE_ARRAY(context->eigen_value);
#ifdef NL_PARANOID
NL_CLEAR(NLContextStruct, context);
#endif
NL_DELETE(context);
}
void nlMakeCurrent(NLContext context) {
nlCurrentContext = (NLContextStruct*)(context);
}
NLContext nlGetCurrent() {
return nlCurrentContext;
}
/* Finite state automaton */
void nlCheckState(NLenum state) {
nl_assert(nlCurrentContext->state == state);
}
void nlTransition(NLenum from_state, NLenum to_state) {
nlCheckState(from_state);
nlCurrentContext->state = to_state;
}
/* Preconditioner setup and default solver */
static void nlSetupPreconditioner() {
/* Check compatibility between solver and preconditioner */
if(
nlCurrentContext->solver == NL_BICGSTAB &&
nlCurrentContext->preconditioner == NL_PRECOND_SSOR
) {
nlWarning(
"nlSolve",
"cannot use SSOR preconditioner with non-symmetric matrix, "
"switching to Jacobi"
);
nlCurrentContext->preconditioner = NL_PRECOND_JACOBI;
}
if(
nlCurrentContext->solver == NL_GMRES &&
nlCurrentContext->preconditioner != NL_PRECOND_NONE
) {
nlWarning("nlSolve", "Preconditioner not implemented yet for GMRES");
nlCurrentContext->preconditioner = NL_PRECOND_NONE;
}
if(
nlCurrentContext->solver == NL_SUPERLU_EXT &&
nlCurrentContext->preconditioner != NL_PRECOND_NONE
) {
nlWarning("nlSolve", "Preconditioner not implemented yet for SUPERLU");
nlCurrentContext->preconditioner = NL_PRECOND_NONE;
}
if(
nlCurrentContext->solver == NL_CHOLMOD_EXT &&
nlCurrentContext->preconditioner != NL_PRECOND_NONE
) {
nlWarning("nlSolve", "Preconditioner not implemented yet for CHOLMOD");
nlCurrentContext->preconditioner = NL_PRECOND_NONE;
}
if(
nlCurrentContext->solver == NL_PERM_SUPERLU_EXT &&
nlCurrentContext->preconditioner != NL_PRECOND_NONE
) {
nlWarning(
"nlSolve", "Preconditioner not implemented yet for PERMSUPERLU"
);
nlCurrentContext->preconditioner = NL_PRECOND_NONE;
}
if(
nlCurrentContext->solver == NL_SYMMETRIC_SUPERLU_EXT &&
nlCurrentContext->preconditioner != NL_PRECOND_NONE
) {
nlWarning(
"nlSolve", "Preconditioner not implemented yet for PERMSUPERLU"
);
nlCurrentContext->preconditioner = NL_PRECOND_NONE;
}
nlDeleteMatrix(nlCurrentContext->P);
nlCurrentContext->P = NULL;
switch(nlCurrentContext->preconditioner) {
case NL_PRECOND_NONE:
break;
case NL_PRECOND_JACOBI:
nlCurrentContext->P = nlNewJacobiPreconditioner(nlCurrentContext->M);
break;
case NL_PRECOND_SSOR:
nlCurrentContext->P = nlNewSSORPreconditioner(
nlCurrentContext->M,nlCurrentContext->omega
);
break;
case NL_PRECOND_USER:
break;
default:
nl_assert_not_reached;
}
if(nlCurrentContext->preconditioner != NL_PRECOND_SSOR) {
if(getenv("NL_LOW_MEM") == NULL) {
nlMatrixCompress(&nlCurrentContext->M);
}
}
}
static NLboolean nlSolveDirect() {
NLdouble* b = nlCurrentContext->b;
NLdouble* x = nlCurrentContext->x;
NLuint n = nlCurrentContext->n;
NLuint k;
NLMatrix F = nlMatrixFactorize(
nlCurrentContext->M, nlCurrentContext->solver
);
if(F == NULL) {
return NL_FALSE;
}
for(k=0; k<nlCurrentContext->nb_systems; ++k) {
nlMultMatrixVector(F, b, x);
b += n;
x += n;
}
nlDeleteMatrix(F);
return NL_TRUE;
}
static NLboolean nlSolveIterative() {
NLboolean use_CUDA = NL_FALSE;
NLdouble* b = nlCurrentContext->b;
NLdouble* x = nlCurrentContext->x;
NLuint n = nlCurrentContext->n;
NLuint k;
NLBlas_t blas = nlHostBlas();
NLMatrix M = nlCurrentContext->M;
NLMatrix P = nlCurrentContext->P;
/*
* For CUDA: it is implemented for
* all iterative solvers except GMRES
* Jacobi preconditioner
*/
if(nlExtensionIsInitialized_CUDA() &&
(nlCurrentContext->solver != NL_GMRES) &&
(nlCurrentContext->preconditioner == NL_PRECOND_NONE ||
nlCurrentContext->preconditioner == NL_PRECOND_JACOBI)
) {
if(nlCurrentContext->verbose) {
nl_printf("Using CUDA\n");
}
use_CUDA = NL_TRUE;
blas = nlCUDABlas();
if(nlCurrentContext->preconditioner == NL_PRECOND_JACOBI) {
P = nlCUDAJacobiPreconditionerNewFromCRSMatrix(M);
}
M = nlCUDAMatrixNewFromCRSMatrix(M);
}
/*
* We do not count CUDA transfers and CUDA matrix construction
* when estimating GFlops
*/
nlCurrentContext->start_time = nlCurrentTime();
nlBlasResetStats(blas);
for(k=0; k<nlCurrentContext->nb_systems; ++k) {
nlSolveSystemIterative(
blas,
M,
P,
b,
x,
nlCurrentContext->solver,
nlCurrentContext->threshold,
nlCurrentContext->max_iterations,
nlCurrentContext->inner_iterations
);
b += n;
x += n;
}
nlCurrentContext->flops += blas->flops;
if(use_CUDA) {
nlDeleteMatrix(M);
nlDeleteMatrix(P);
}
return NL_TRUE;
}
NLboolean nlDefaultSolver() {
NLboolean result = NL_TRUE;
nlSetupPreconditioner();
switch(nlCurrentContext->solver) {
case NL_CG:
case NL_BICGSTAB:
case NL_GMRES: {
result = nlSolveIterative();
} break;
case NL_SUPERLU_EXT:
case NL_PERM_SUPERLU_EXT:
case NL_SYMMETRIC_SUPERLU_EXT:
case NL_CHOLMOD_EXT: {
result = nlSolveDirect();
} break;
default:
nl_assert_not_reached;
}
return result;
}
/******* extracted from nl_blas.c *******/
/*
Many warnings about const double* converted to
double* when calling BLAS functions that do not
have the const qualifier in their prototypes.
*/
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wcast-qual"
#pragma GCC diagnostic ignored "-Wcomma"
#endif
#ifndef NL_FORTRAN_WRAP
#define NL_FORTRAN_WRAP(x) x##_
#endif
#ifdef NL_USE_ATLAS
int NL_FORTRAN_WRAP(xerbla)(char *srname, int *info) {
nl_printf(stderr, "** On entry to %6s, parameter number %2d had an illegal value\n",
srname, *info
);
return 0;
}
#ifndef NL_USE_BLAS
#define NL_USE_BLAS
#endif
#endif
#ifdef NL_USE_SUPERLU
#ifndef NL_USE_BLAS
#define NL_USE_BLAS
/*
* The BLAS included in SuperLU does not have DTPSV,
* we use the DTPSV embedded in OpenNL.
*/
#define NEEDS_DTPSV
#endif
#endif
#ifndef NL_USE_BLAS
#define NEEDS_DTPSV
#endif
/* BLAS routines */
/* copy-pasted from CBLAS (i.e. generated from f2c) */
/*
* lsame
* xerbla
* daxpy
* ddot
* dscal
* dnrm2
* dcopy
* dgemv
* dtpsv
*/
typedef NLint integer ;
typedef NLdouble doublereal ;
typedef NLboolean logical ;
typedef NLint ftnlen ;
#ifndef max
#define max(x,y) ((x) > (y) ? (x) : (y))
#endif
#ifndef NL_USE_BLAS
static int NL_FORTRAN_WRAP(lsame)(const char *ca, const char *cb)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
September 30, 1994
Purpose
=======
LSAME returns .TRUE. if CA is the same letter as CB regardless of case.
Arguments
=========
CA (input) CHARACTER*1
CB (input) CHARACTER*1
CA and CB specify the single characters to be compared.
=====================================================================
*/
/* System generated locals */
int ret_val;
/* Local variables */
int inta, intb, zcode;
ret_val = *(unsigned char *)ca == *(unsigned char *)cb;
if (ret_val) {
return ret_val;
}
/* Now test for equivalence if both characters are alphabetic. */
zcode = 'Z';
/* Use 'Z' rather than 'A' so that ASCII can be detected on Prime
machines, on which ICHAR returns a value with bit 8 set.
ICHAR('A') on Prime machines returns 193 which is the same as
ICHAR('A') on an EBCDIC machine. */
inta = *(unsigned char *)ca;
intb = *(unsigned char *)cb;
if (zcode == 90 || zcode == 122) {
/* ASCII is assumed - ZCODE is the ASCII code of either lower or
upper case 'Z'. */
if (inta >= 97 && inta <= 122) inta += -32;
if (intb >= 97 && intb <= 122) intb += -32;
} else if (zcode == 233 || zcode == 169) {
/* EBCDIC is assumed - ZCODE is the EBCDIC code of either lower or
upper case 'Z'. */
if ((inta >= 129 && inta <= 137) ||
(inta >= 145 && inta <= 153) ||
(inta >= 162 && inta <= 169)
)
inta += 64;
if (
(intb >= 129 && intb <= 137) ||
(intb >= 145 && intb <= 153) ||
(intb >= 162 && intb <= 169)
)
intb += 64;
} else if (zcode == 218 || zcode == 250) {
/* ASCII is assumed, on Prime machines - ZCODE is the ASCII code
plus 128 of either lower or upper case 'Z'. */
if (inta >= 225 && inta <= 250) inta += -32;
if (intb >= 225 && intb <= 250) intb += -32;
}
ret_val = inta == intb;
return ret_val;
} /* lsame_ */
/* Subroutine */ static int NL_FORTRAN_WRAP(xerbla)(const char *srname, int *info)
{
/* -- LAPACK auxiliary routine (version 2.0) --
Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University
September 30, 1994
Purpose
=======
XERBLA is an error handler for the LAPACK routines.
It is called by an LAPACK routine if an input parameter has an
invalid value. A message is printed and execution stops.
Installers may consider modifying the STOP statement in order to
call system-specific exception-handling facilities.
Arguments
=========
SRNAME (input) CHARACTER*6
The name of the routine which called XERBLA.
INFO (input) INT
The position of the invalid parameter in the parameter list
of the calling routine.
=====================================================================
*/
nl_fprintf(stderr, "** On entry to %6s, parameter number %2d had an illegal value\n",
srname, *info);
/* End of XERBLA */
return 0;
} /* xerbla_ */
/* Subroutine */ static int NL_FORTRAN_WRAP(daxpy)(integer *n, doublereal *da, doublereal *dx,
integer *incx, doublereal *dy, integer *incy)
{
/* System generated locals */
integer i__1;
/* Local variables */
static integer i, m, ix, iy, mp1;
/* constant times a vector plus a vector.
uses unrolled loops for increments equal to one.
jack dongarra, linpack, 3/11/78.
modified 12/3/93, array(1) declarations changed to array(*)
Parameter adjustments
Function Body */
#define DY(I) dy[(I)-1]
#define DX(I) dx[(I)-1]
if (*n <= 0) {
return 0;
}
if (*da == 0.) {
return 0;
}
if (*incx == 1 && *incy == 1) {
goto L20;
}
/* code for unequal increments or equal increments
not equal to 1 */
ix = 1;
iy = 1;
if (*incx < 0) {
ix = (-(*n) + 1) * *incx + 1;
}
if (*incy < 0) {
iy = (-(*n) + 1) * *incy + 1;
}
i__1 = *n;
for (i = 1; i <= *n; ++i) {
DY(iy) += *da * DX(ix);
ix += *incx;
iy += *incy;
/* L10: */
}
return 0;
/* code for both increments equal to 1
clean-up loop */
L20:
m = *n % 4;
if (m == 0) {
goto L40;
}
i__1 = m;
for (i = 1; i <= m; ++i) {
DY(i) += *da * DX(i);
/* L30: */
}
if (*n < 4) {
return 0;
}
L40:
mp1 = m + 1;
i__1 = *n;
for (i = mp1; i <= *n; i += 4) {
DY(i) += *da * DX(i);
DY(i + 1) += *da * DX(i + 1);
DY(i + 2) += *da * DX(i + 2);
DY(i + 3) += *da * DX(i + 3);
/* L50: */
}
nl_arg_used(i__1);
return 0;
} /* daxpy_ */
#undef DY
#undef DX
static doublereal NL_FORTRAN_WRAP(ddot)(integer *n, doublereal *dx, integer *incx, doublereal *dy,
integer *incy)
{
/* System generated locals */
integer i__1;
doublereal ret_val;
/* Local variables */
static integer i, m;
static doublereal dtemp;
static integer ix, iy, mp1;
/* forms the dot product of two vectors.
uses unrolled loops for increments equal to one.
jack dongarra, linpack, 3/11/78.
modified 12/3/93, array(1) declarations changed to array(*)
Parameter adjustments
Function Body */
#define DY(I) dy[(I)-1]
#define DX(I) dx[(I)-1]
ret_val = 0.;
dtemp = 0.;
if (*n <= 0) {
return ret_val;
}
if (*incx == 1 && *incy == 1) {
goto L20;
}
/* code for unequal increments or equal increments
not equal to 1 */
ix = 1;
iy = 1;
if (*incx < 0) {
ix = (-(*n) + 1) * *incx + 1;
}
if (*incy < 0) {
iy = (-(*n) + 1) * *incy + 1;
}
i__1 = *n;
for (i = 1; i <= *n; ++i) {
dtemp += DX(ix) * DY(iy);
ix += *incx;
iy += *incy;
/* L10: */
}
ret_val = dtemp;
return ret_val;
/* code for both increments equal to 1
clean-up loop */
L20:
m = *n % 5;
if (m == 0) {
goto L40;
}
i__1 = m;
for (i = 1; i <= m; ++i) {
dtemp += DX(i) * DY(i);
/* L30: */
}
if (*n < 5) {
goto L60;
}
L40:
mp1 = m + 1;
i__1 = *n;
for (i = mp1; i <= *n; i += 5) {
dtemp = dtemp + DX(i) * DY(i) + DX(i + 1) * DY(i + 1) + DX(i + 2) *
DY(i + 2) + DX(i + 3) * DY(i + 3) + DX(i + 4) * DY(i + 4);
/* L50: */
}
L60:
ret_val = dtemp;
nl_arg_used(i__1);
return ret_val;
} /* ddot_ */
#undef DY
#undef DX
/* Subroutine */ static int NL_FORTRAN_WRAP(dscal)(integer *n, doublereal *da, doublereal *dx,
integer *incx)
{
/* System generated locals */
integer i__1, i__2;
/* Local variables */
static integer i, m, nincx, mp1;
/* scales a vector by a constant.
uses unrolled loops for increment equal to one.
jack dongarra, linpack, 3/11/78.
modified 3/93 to return if incx .le. 0.
modified 12/3/93, array(1) declarations changed to array(*)
Parameter adjustments
Function Body */
#ifdef DX
#undef DX
#endif
#define DX(I) dx[(I)-1]
if (*n <= 0 || *incx <= 0) {
return 0;
}
if (*incx == 1) {
goto L20;
}
/* code for increment not equal to 1 */
nincx = *n * *incx;
i__1 = nincx;
i__2 = *incx;
for (i = 1; *incx < 0 ? i >= nincx : i <= nincx; i += *incx) {
DX(i) = *da * DX(i);
/* L10: */
}
return 0;
/* code for increment equal to 1
clean-up loop */
L20:
m = *n % 5;
if (m == 0) {
goto L40;
}
i__2 = m;
for (i = 1; i <= m; ++i) {
DX(i) = *da * DX(i);
/* L30: */
}
if (*n < 5) {
return 0;
}
L40:
mp1 = m + 1;
i__2 = *n;
for (i = mp1; i <= *n; i += 5) {
DX(i) = *da * DX(i);
DX(i + 1) = *da * DX(i + 1);
DX(i + 2) = *da * DX(i + 2);
DX(i + 3) = *da * DX(i + 3);
DX(i + 4) = *da * DX(i + 4);
/* L50: */
}
nl_arg_used(i__1);
nl_arg_used(i__2);
return 0;
} /* dscal_ */
#undef DX
static doublereal NL_FORTRAN_WRAP(dnrm2)(integer *n, doublereal *x, integer *incx)
{
/* System generated locals */
integer i__1, i__2;
doublereal ret_val, d__1;
/* Builtin functions */
/* BL: already declared in the included <math.h>,
we do not need it here. */
/*double sqrt(doublereal); */
/* Local variables */
static doublereal norm, scale, absxi;
static integer ix;
static doublereal ssq;
/* DNRM2 returns the euclidean norm of a vector via the function
name, so that
DNRM2 := sqrt( x'*x )
-- This version written on 25-October-1982.
Modified on 14-October-1993 to inline the call to DLASSQ.
Sven Hammarling, Nag Ltd.
Parameter adjustments
Function Body */
#ifdef X
#undef X
#endif
#define X(I) x[(I)-1]
if (*n < 1 || *incx < 1) {
norm = 0.;
} else if (*n == 1) {
norm = fabs(X(1));
} else {
scale = 0.;
ssq = 1.;
/* The following loop is equivalent to this call to the LAPACK
auxiliary routine:
CALL DLASSQ( N, X, INCX, SCALE, SSQ ) */
i__1 = (*n - 1) * *incx + 1;
i__2 = *incx;
for (ix = 1; *incx < 0 ? ix >= (*n-1)**incx+1 : ix <= (*n-1)**incx+1; ix += *incx) {
if (X(ix) != 0.) {
absxi = (d__1 = X(ix), fabs(d__1));
if (scale < absxi) {
/* Computing 2nd power */
d__1 = scale / absxi;
ssq = ssq * (d__1 * d__1) + 1.;
scale = absxi;
} else {
/* Computing 2nd power */
d__1 = absxi / scale;
ssq += d__1 * d__1;
}
}
/* L10: */
}
norm = scale * sqrt(ssq);
}
ret_val = norm;
nl_arg_used(i__1);
nl_arg_used(i__2);
return ret_val;
/* End of DNRM2. */
} /* dnrm2_ */
#undef X
/* Subroutine */ static int NL_FORTRAN_WRAP(dcopy)(integer *n, doublereal *dx, integer *incx,
doublereal *dy, integer *incy)
{
/* System generated locals */
integer i__1;
/* Local variables */
static integer i, m, ix, iy, mp1;
/* copies a vector, x, to a vector, y.
uses unrolled loops for increments equal to one.
jack dongarra, linpack, 3/11/78.
modified 12/3/93, array(1) declarations changed to array(*)
Parameter adjustments
Function Body */
#define DY(I) dy[(I)-1]
#define DX(I) dx[(I)-1]
if (*n <= 0) {
return 0;
}
if (*incx == 1 && *incy == 1) {
goto L20;
}
/* code for unequal increments or equal increments
not equal to 1 */
ix = 1;
iy = 1;
if (*incx < 0) {
ix = (-(*n) + 1) * *incx + 1;
}
if (*incy < 0) {
iy = (-(*n) + 1) * *incy + 1;
}
i__1 = *n;
for (i = 1; i <= *n; ++i) {
DY(iy) = DX(ix);
ix += *incx;
iy += *incy;
/* L10: */
}
return 0;
/* code for both increments equal to 1
clean-up loop */
L20:
m = *n % 7;
if (m == 0) {
goto L40;
}
i__1 = m;
for (i = 1; i <= m; ++i) {
DY(i) = DX(i);
/* L30: */
}
if (*n < 7) {
return 0;
}
L40:
mp1 = m + 1;
i__1 = *n;
for (i = mp1; i <= *n; i += 7) {
DY(i) = DX(i);
DY(i + 1) = DX(i + 1);
DY(i + 2) = DX(i + 2);
DY(i + 3) = DX(i + 3);
DY(i + 4) = DX(i + 4);
DY(i + 5) = DX(i + 5);
DY(i + 6) = DX(i + 6);
/* L50: */
}
nl_arg_used(i__1);
return 0;
} /* dcopy_ */
#undef DX
#undef DY
/* Subroutine */ static int NL_FORTRAN_WRAP(dgemv)(const char *trans, integer *m, integer *n, doublereal *
alpha, doublereal *a, integer *lda, doublereal *x, integer *incx,
doublereal *beta, doublereal *y, integer *incy)
{
/* System generated locals */
/* integer a_dim1, a_offset ; */
integer i__1, i__2;
/* Local variables */
static integer info;
static doublereal temp;
static integer lenx, leny, i, j;
/* extern logical lsame_(char *, char *); */
static integer ix, iy, jx, jy, kx, ky;
/* extern int xerbla_(char *, integer *); */
/* Purpose
=======
DGEMV performs one of the matrix-vector operations
y := alpha*A*x + beta*y, or y := alpha*A'*x + beta*y,
where alpha and beta are scalars, x and y are vectors and A is an
m by n matrix.
Parameters
==========
TRANS - CHARACTER*1.
On entry, TRANS specifies the operation to be performed as
follows:
TRANS = 'N' or 'n' y := alpha*A*x + beta*y.
TRANS = 'T' or 't' y := alpha*A'*x + beta*y.
TRANS = 'C' or 'c' y := alpha*A'*x + beta*y.
Unchanged on exit.
M - INTEGER.
On entry, M specifies the number of rows of the matrix A.
M must be at least zero.
Unchanged on exit.
N - INTEGER.
On entry, N specifies the number of columns of the matrix A.
N must be at least zero.
Unchanged on exit.
ALPHA - DOUBLE PRECISION.
On entry, ALPHA specifies the scalar alpha.
Unchanged on exit.
A - DOUBLE PRECISION array of DIMENSION ( LDA, n ).
Before entry, the leading m by n part of the array A must
contain the matrix of coefficients.
Unchanged on exit.
LDA - INTEGER.
On entry, LDA specifies the first dimension of A as declared
in the calling (sub) program. LDA must be at least
max( 1, m ).
Unchanged on exit.
X - DOUBLE PRECISION array of DIMENSION at least
( 1 + ( n - 1 )*abs( INCX ) ) when TRANS = 'N' or 'n'
and at least
( 1 + ( m - 1 )*abs( INCX ) ) otherwise.
Before entry, the incremented array X must contain the
vector x.
Unchanged on exit.
INCX - INTEGER.
On entry, INCX specifies the increment for the elements of
X. INCX must not be zero.
Unchanged on exit.
BETA - DOUBLE PRECISION.
On entry, BETA specifies the scalar beta. When BETA is
supplied as zero then Y need not be set on input.
Unchanged on exit.
Y - DOUBLE PRECISION array of DIMENSION at least
( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n'
and at least
( 1 + ( n - 1 )*abs( INCY ) ) otherwise.
Before entry with BETA non-zero, the incremented array Y
must contain the vector y. On exit, Y is overwritten by the
updated vector y.
INCY - INTEGER.
On entry, INCY specifies the increment for the elements of
Y. INCY must not be zero.
Unchanged on exit.
Level 2 Blas routine.
-- Written on 22-October-1986.
Jack Dongarra, Argonne National Lab.
Jeremy Du Croz, Nag Central Office.
Sven Hammarling, Nag Central Office.
Richard Hanson, Sandia National Labs.
Test the input parameters.
Parameter adjustments
Function Body */
#define X(I) x[(I)-1]
#define Y(I) y[(I)-1]
#define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)]
info = 0;
if (! NL_FORTRAN_WRAP(lsame)(trans, "N") && ! NL_FORTRAN_WRAP(lsame)(trans, "T") && !
NL_FORTRAN_WRAP(lsame)(trans, "C")) {
info = 1;
} else if (*m < 0) {
info = 2;
} else if (*n < 0) {
info = 3;
} else if (*lda < max(1,*m)) {
info = 6;
} else if (*incx == 0) {
info = 8;
} else if (*incy == 0) {
info = 11;
}
if (info != 0) {
NL_FORTRAN_WRAP(xerbla)("DGEMV ", &info);
return 0;
}
/* Quick return if possible. */
if (*m == 0 || *n == 0 || (*alpha == 0. && *beta == 1.)) {
return 0;
}
/* Set LENX and LENY, the lengths of the vectors x and y, and set
up the start points in X and Y. */
if (NL_FORTRAN_WRAP(lsame)(trans, "N")) {
lenx = *n;
leny = *m;
} else {
lenx = *m;
leny = *n;
}
if (*incx > 0) {
kx = 1;
} else {
kx = 1 - (lenx - 1) * *incx;
}
if (*incy > 0) {
ky = 1;
} else {
ky = 1 - (leny - 1) * *incy;
}
/* Start the operations. In this version the elements of A are
accessed sequentially with one pass through A.
First form y := beta*y. */
if (*beta != 1.) {
if (*incy == 1) {
if (*beta == 0.) {
i__1 = leny;
for (i = 1; i <= leny; ++i) {
Y(i) = 0.;
/* L10: */
}
} else {
i__1 = leny;
for (i = 1; i <= leny; ++i) {
Y(i) = *beta * Y(i);
/* L20: */
}
}
} else {
iy = ky;
if (*beta == 0.) {
i__1 = leny;
for (i = 1; i <= leny; ++i) {
Y(iy) = 0.;
iy += *incy;
/* L30: */
}
} else {
i__1 = leny;
for (i = 1; i <= leny; ++i) {
Y(iy) = *beta * Y(iy);
iy += *incy;
/* L40: */
}
}
}
}
if (*alpha == 0.) {
return 0;
}
if (NL_FORTRAN_WRAP(lsame)(trans, "N")) {
/* Form y := alpha*A*x + y. */
jx = kx;
if (*incy == 1) {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
if (X(jx) != 0.) {
temp = *alpha * X(jx);
i__2 = *m;
for (i = 1; i <= *m; ++i) {
Y(i) += temp * A(i,j);
/* L50: */
}
}
jx += *incx;
/* L60: */
}
} else {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
if (X(jx) != 0.) {
temp = *alpha * X(jx);
iy = ky;
i__2 = *m;
for (i = 1; i <= *m; ++i) {
Y(iy) += temp * A(i,j);
iy += *incy;
/* L70: */
}
}
jx += *incx;
/* L80: */
}
}
} else {
/* Form y := alpha*A'*x + y. */
jy = ky;
if (*incx == 1) {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
temp = 0.;
i__2 = *m;
for (i = 1; i <= *m; ++i) {
temp += A(i,j) * X(i);
/* L90: */
}
Y(jy) += *alpha * temp;
jy += *incy;
/* L100: */
}
} else {
i__1 = *n;
for (j = 1; j <= *n; ++j) {
temp = 0.;
ix = kx;
i__2 = *m;
for (i = 1; i <= *m; ++i) {
temp += A(i,j) * X(ix);
ix += *incx;
/* L110: */
}
Y(jy) += *alpha * temp;
jy += *incy;
/* L120: */
}
}
}
nl_arg_used(i__1);
nl_arg_used(i__2);
return 0;
/* End of DGEMV . */
} /* dgemv_ */
#undef X
#undef Y
#undef A
#else
extern void NL_FORTRAN_WRAP(daxpy)(
int *n, double *alpha, double *x,
int *incx, double *y, int *incy
) ;
extern double NL_FORTRAN_WRAP(dnrm2)( int *n, double *x, int *incx ) ;
extern int NL_FORTRAN_WRAP(dcopy)(int* n, double* dx, int* incx, double* dy, int* incy) ;
extern void NL_FORTRAN_WRAP(dscal)(int* n, double* alpha, double *x, int* incx) ;
#ifndef NEEDS_DTPSV
extern void NL_FORTRAN_WRAP(dtpsv)(
char *uplo, char *trans, char *diag,
int *n, double *AP, double *x, int *incx
) ;
#endif
extern void NL_FORTRAN_WRAP(dgemv)(
char *trans, int *m, int *n,
double *alpha, double *A, int *ldA,
double *x, int *incx,
double *beta, double *y, int *incy
) ;
#endif
#ifdef NEEDS_DTPSV
/* DECK DTPSV */
/* Subroutine */
static int NL_FORTRAN_WRAP(dtpsv)(
const char* uplo,
const char* trans,
const char* diag,
integer* n,
doublereal* ap,
doublereal* x,
integer* incx
) {
/* System generated locals */
integer i__1, i__2;
/* Local variables */
static integer info;
static doublereal temp;
static integer i__, j, k;
/* extern logical lsame_(); */
static integer kk, ix, jx, kx;
/* extern int xerbla_(); */
static logical nounit;
/* ***BEGIN PROLOGUE DTPSV */
/* ***PURPOSE Solve one of the systems of equations. */
/* ***LIBRARY SLATEC (BLAS) */
/* ***CATEGORY D1B4 */
/* ***TYPE DOUBLE PRECISION (STPSV-S, DTPSV-D, CTPSV-C) */
/* ***KEYWORDS LEVEL 2 BLAS, LINEAR ALGEBRA */
/* ***AUTHOR Dongarra, J. J., (ANL) */
/* Du Croz, J., (NAG) */
/* Hammarling, S., (NAG) */
/* Hanson, R. J., (SNLA) */
/* ***DESCRIPTION */
/* DTPSV solves one of the systems of equations */
/* A*x = b, or A'*x = b, */
/* where b and x are n element vectors and A is an n by n unit, or */
/* non-unit, upper or lower triangular matrix, supplied in packed form. */
/* No test for singularity or near-singularity is included in this */
/* routine. Such tests must be performed before calling this routine. */
/* Parameters */
/* ========== */
/* UPLO - CHARACTER*1. */
/* On entry, UPLO specifies whether the matrix is an upper or */
/* lower triangular matrix as follows: */
/* UPLO = 'U' or 'u' A is an upper triangular matrix. */
/* UPLO = 'L' or 'l' A is a lower triangular matrix. */
/* Unchanged on exit. */
/* TRANS - CHARACTER*1. */
/* On entry, TRANS specifies the equations to be solved as */
/* follows: */
/* TRANS = 'N' or 'n' A*x = b. */
/* TRANS = 'T' or 't' A'*x = b. */
/* TRANS = 'C' or 'c' A'*x = b. */
/* Unchanged on exit. */
/* DIAG - CHARACTER*1. */
/* On entry, DIAG specifies whether or not A is unit */
/* triangular as follows: */
/* DIAG = 'U' or 'u' A is assumed to be unit triangular. */
/* DIAG = 'N' or 'n' A is not assumed to be unit */
/* triangular. */
/* Unchanged on exit. */
/* N - INTEGER. */
/* On entry, N specifies the order of the matrix A. */
/* N must be at least zero. */
/* Unchanged on exit. */
/* AP - DOUBLE PRECISION array of DIMENSION at least */
/* ( ( n*( n + 1))/2). */
/* Before entry with UPLO = 'U' or 'u', the array AP must */
/* contain the upper triangular matrix packed sequentially, */
/* column by column, so that AP( 1 ) contains a( 1, 1 ), */
/* AP( 2 ) and AP( 3 ) contain a( 1, 2 ) and a( 2, 2 ) */
/* respectively, and so on. */
/* Before entry with UPLO = 'L' or 'l', the array AP must */
/* contain the lower triangular matrix packed sequentially, */
/* column by column, so that AP( 1 ) contains a( 1, 1 ), */
/* AP( 2 ) and AP( 3 ) contain a( 2, 1 ) and a( 3, 1 ) */
/* respectively, and so on. */
/* Note that when DIAG = 'U' or 'u', the diagonal elements of */
/* A are not referenced, but are assumed to be unity. */
/* Unchanged on exit. */
/* X - DOUBLE PRECISION array of dimension at least */
/* ( 1 + ( n - 1 )*abs( INCX ) ). */
/* Before entry, the incremented array X must contain the n */
/* element right-hand side vector b. On exit, X is overwritten */
/* with the solution vector x. */
/* INCX - INTEGER. */
/* On entry, INCX specifies the increment for the elements of */
/* X. INCX must not be zero. */
/* Unchanged on exit. */
/* ***REFERENCES Dongarra, J. J., Du Croz, J., Hammarling, S., and */
/* Hanson, R. J. An extended set of Fortran basic linear */
/* algebra subprograms. ACM TOMS, Vol. 14, No. 1, */
/* pp. 1-17, March 1988. */
/* ***ROUTINES CALLED LSAME, XERBLA */
/* ***REVISION HISTORY (YYMMDD) */
/* 861022 DATE WRITTEN */
/* 910605 Modified to meet SLATEC prologue standards. Only comment */
/* lines were modified. (BKS) */
/* ***END PROLOGUE DTPSV */
/* .. Scalar Arguments .. */
/* .. Array Arguments .. */
/* .. Parameters .. */
/* .. Local Scalars .. */
/* .. External Functions .. */
/* .. External Subroutines .. */
/* ***FIRST EXECUTABLE STATEMENT DTPSV */
/* Test the input parameters. */
/* Parameter adjustments */
--x;
--ap;
/* Function Body */
info = 0;
if (!NL_FORTRAN_WRAP(lsame)(uplo, "U") &&
!NL_FORTRAN_WRAP(lsame)(uplo, "L")
) {
info = 1;
} else if (
!NL_FORTRAN_WRAP(lsame)(trans, "N") &&
!NL_FORTRAN_WRAP(lsame)(trans, "T") &&
!NL_FORTRAN_WRAP(lsame)(trans, "C")
) {
info = 2;
} else if (
!NL_FORTRAN_WRAP(lsame)(diag, "U") &&
!NL_FORTRAN_WRAP(lsame)(diag, "N")
) {
info = 3;
} else if (*n < 0) {
info = 4;
} else if (*incx == 0) {
info = 7;
}
if (info != 0) {
NL_FORTRAN_WRAP(xerbla)("DTPSV ", &info);
return 0;
}
/* Quick return if possible. */
if (*n == 0) {
return 0;
}
nounit = (logical)(NL_FORTRAN_WRAP(lsame)(diag, "N"));
/* Set up the start point in X if the increment is not unity. This */
/* will be ( N - 1 )*INCX too small for descending loops. */
if (*incx <= 0) {
kx = 1 - (*n - 1) * *incx;
} else if (*incx != 1) {
kx = 1;
}
/* Start the operations. In this version the elements of AP are */
/* accessed sequentially with one pass through AP. */
if (NL_FORTRAN_WRAP(lsame)(trans, "N")) {
/* Form x := inv( A )*x. */
if (NL_FORTRAN_WRAP(lsame)(uplo, "U")) {
kk = *n * (*n + 1) / 2;
if (*incx == 1) {
for (j = *n; j >= 1; --j) {
if (x[j] != 0.) {
if (nounit) {
x[j] /= ap[kk];
}
temp = x[j];
k = kk - 1;
for (i__ = j - 1; i__ >= 1; --i__) {
x[i__] -= temp * ap[k];
--k;
/* L10: */
}
}
kk -= j;
/* L20: */
}
} else {
jx = kx + (*n - 1) * *incx;
for (j = *n; j >= 1; --j) {
if (x[jx] != 0.) {
if (nounit) {
x[jx] /= ap[kk];
}
temp = x[jx];
ix = jx;
i__1 = kk - j + 1;
for (k = kk - 1; k >= i__1; --k) {
ix -= *incx;
x[ix] -= temp * ap[k];
/* L30: */
}
}
jx -= *incx;
kk -= j;
/* L40: */
}
}
} else {
kk = 1;
if (*incx == 1) {
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
if (x[j] != 0.) {
if (nounit) {
x[j] /= ap[kk];
}
temp = x[j];
k = kk + 1;
i__2 = *n;
for (i__ = j + 1; i__ <= i__2; ++i__) {
x[i__] -= temp * ap[k];
++k;
/* L50: */
}
}
kk += *n - j + 1;
/* L60: */
}
} else {
jx = kx;
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
if (x[jx] != 0.) {
if (nounit) {
x[jx] /= ap[kk];
}
temp = x[jx];
ix = jx;
i__2 = kk + *n - j;
for (k = kk + 1; k <= i__2; ++k) {
ix += *incx;
x[ix] -= temp * ap[k];
/* L70: */
}
}
jx += *incx;
kk += *n - j + 1;
/* L80: */
}
}
}
} else {
/* Form x := inv( A' )*x. */
if (NL_FORTRAN_WRAP(lsame)(uplo, "U")) {
kk = 1;
if (*incx == 1) {
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
temp = x[j];
k = kk;
i__2 = j - 1;
for (i__ = 1; i__ <= i__2; ++i__) {
temp -= ap[k] * x[i__];
++k;
/* L90: */
}
if (nounit) {
temp /= ap[kk + j - 1];
}
x[j] = temp;
kk += j;
/* L100: */
}
} else {
jx = kx;
i__1 = *n;
for (j = 1; j <= i__1; ++j) {
temp = x[jx];
ix = kx;
i__2 = kk + j - 2;
for (k = kk; k <= i__2; ++k) {
temp -= ap[k] * x[ix];
ix += *incx;
/* L110: */
}
if (nounit) {
temp /= ap[kk + j - 1];
}
x[jx] = temp;
jx += *incx;
kk += j;
/* L120: */
}
}
} else {
kk = *n * (*n + 1) / 2;
if (*incx == 1) {
for (j = *n; j >= 1; --j) {
temp = x[j];
k = kk;
i__1 = j + 1;
for (i__ = *n; i__ >= i__1; --i__) {
temp -= ap[k] * x[i__];
--k;
/* L130: */
}
if (nounit) {
temp /= ap[kk - *n + j];
}
x[j] = temp;
kk -= *n - j + 1;
/* L140: */
}
} else {
kx += (*n - 1) * *incx;
jx = kx;
for (j = *n; j >= 1; --j) {
temp = x[jx];
ix = kx;
i__1 = kk - (*n - (j + 1));
for (k = kk; k >= i__1; --k) {
temp -= ap[k] * x[ix];
ix -= *incx;
/* L150: */
}
if (nounit) {
temp /= ap[kk - *n + j];
}
x[jx] = temp;
jx -= *incx;
kk -= *n - j + 1;
/* L160: */
}
}
}
}
return 0;
/* End of DTPSV . */
} /* dtpsv_ */
#endif
/* End of BLAS routines */
/* Abstract BLAS interface */
void nlBlasResetStats(NLBlas_t blas) {
blas->start_time = nlCurrentTime();
blas->flops = 0;
blas->used_ram[0] = 0;
blas->used_ram[1] = 0;
blas->max_used_ram[0] = 0;
blas->max_used_ram[1] = 0;
blas->sq_rnorm = 0.0;
blas->sq_bnorm = 0.0;
}
double nlBlasGFlops(NLBlas_t blas) {
double now = nlCurrentTime();
double elapsed_time = now - blas->start_time;
return (NLdouble)(blas->flops) / (elapsed_time * 1e9);
}
NLulong nlBlasUsedRam(NLBlas_t blas, NLmemoryType type) {
return blas->used_ram[type];
}
NLulong nlBlasMaxUsedRam(NLBlas_t blas, NLmemoryType type) {
return blas->max_used_ram[type];
}
NLboolean nlBlasHasUnifiedMemory(NLBlas_t blas) {
return blas->has_unified_memory;
}
static void* host_blas_malloc(
NLBlas_t blas, NLmemoryType type, size_t size
) {
nl_arg_used(type);
blas->used_ram[type] += (NLulong)size;
blas->max_used_ram[type] = MAX(
blas->max_used_ram[type],blas->used_ram[type]
);
return malloc(size);
}
static void host_blas_free(
NLBlas_t blas, NLmemoryType type, size_t size, void* ptr
) {
nl_arg_used(type);
blas->used_ram[type] -= (NLulong)size;
free(ptr);
}
static void host_blas_memcpy(
NLBlas_t blas,
void* to, NLmemoryType to_type,
void* from, NLmemoryType from_type,
size_t size
) {
nl_arg_used(blas);
nl_arg_used(to_type);
nl_arg_used(from_type);
memcpy(to,from,size);
}
static void host_blas_dcopy(
NLBlas_t blas, int n, const double *x, int incx, double *y, int incy
) {
nl_arg_used(blas);
NL_FORTRAN_WRAP(dcopy)(&n,(double*)x,&incx,y,&incy);
}
static double host_blas_ddot(
NLBlas_t blas, int n, const double *x, int incx, const double *y, int incy
) {
blas->flops += (NLulong)(2*n);
return NL_FORTRAN_WRAP(ddot)(&n,(double*)x,&incx,(double*)y,&incy);
}
static double host_blas_dnrm2(
NLBlas_t blas, int n, const double *x, int incx
) {
blas->flops += (NLulong)(2*n);
return NL_FORTRAN_WRAP(dnrm2)(&n,(double*)x,&incx);
}
static void host_blas_daxpy(
NLBlas_t blas, int n, double a, const double *x, int incx, double *y, int incy
) {
blas->flops += (NLulong)(2*n);
NL_FORTRAN_WRAP(daxpy)(&n,&a,(double*)x,&incx,y,&incy);
}
static void host_blas_dscal(
NLBlas_t blas, int n, double a, double *x, int incx
) {
blas->flops += (NLulong)n;
NL_FORTRAN_WRAP(dscal)(&n,&a,x,&incx);
}
static void host_blas_dgemv(
NLBlas_t blas, MatrixTranspose trans, int m, int n, double alpha,
const double *A, int ldA, const double *x, int incx,
double beta, double *y, int incy
) {
static const char *T[3] = { "N", "T", 0 };
nl_arg_used(blas);
NL_FORTRAN_WRAP(dgemv)(
T[(int)trans],&m,&n,&alpha,(double*)A,&ldA,
(double*)x,&incx,&beta,y,&incy
);
/* TODO: update flops */
}
static void host_blas_dtpsv(
NLBlas_t blas, MatrixTriangle uplo, MatrixTranspose trans,
MatrixUnitTriangular diag, int n, const double *AP,
double *x, int incx
) {
static const char *UL[2] = { "U", "L" };
static const char *T[3] = { "N", "T", 0 };
static const char *D[2] = { "U", "N" };
nl_arg_used(blas);
NL_FORTRAN_WRAP(dtpsv)(
UL[(int)uplo],T[(int)trans],D[(int)diag],&n,(double*)AP,x,&incx
);
/* TODO: update flops */
}
NLBlas_t nlHostBlas() {
static NLboolean initialized = NL_FALSE;
static struct NLBlas blas;
if(!initialized) {
memset(&blas, 0, sizeof(blas));
blas.has_unified_memory = NL_TRUE;
blas.Malloc = host_blas_malloc;
blas.Free = host_blas_free;
blas.Memcpy = host_blas_memcpy;
blas.Dcopy = host_blas_dcopy;
blas.Ddot = host_blas_ddot;
blas.Dnrm2 = host_blas_dnrm2;
blas.Daxpy = host_blas_daxpy;
blas.Dscal = host_blas_dscal;
blas.Dgemv = host_blas_dgemv;
blas.Dtpsv = host_blas_dtpsv;
nlBlasResetStats(&blas);
initialized = NL_TRUE;
}
return &blas;
}
/******* extracted from nl_iterative_solvers.c *******/
/* Solvers */
/*
* The implementation of the solvers is inspired by
* the lsolver library, by Christian Badura, available from:
* http://www.mathematik.uni-freiburg.de
* /IAM/Research/projectskr/lin_solver/
*
* About the Conjugate Gradient, details can be found in:
* Ashby, Manteuffel, Saylor
* A taxononmy for conjugate gradient methods
* SIAM J Numer Anal 27, 1542-1568 (1990)
*
* This version is completely abstract, the same code can be used for
* CPU/GPU, dense matrix / sparse matrix etc...
* Abstraction is realized through:
* - Abstract blas interface (NLBlas_t), that can implement BLAS
* operations on the CPU or on the GPU.
* - Abstract matrix interface (NLMatrix), that can implement different
* versions of matrix x vector product (CPU/GPU, sparse/dense ...)
*/
static NLuint nlSolveSystem_CG(
NLBlas_t blas,
NLMatrix M, NLdouble* b, NLdouble* x,
double eps, NLuint max_iter
) {
NLint N = (NLint)M->m;
NLdouble *g = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *r = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *p = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLuint its=0;
NLdouble t, tau, sig, rho, gam;
NLdouble b_square=blas->Ddot(blas,N,b,1,b,1);
NLdouble err=eps*eps*b_square;
NLdouble curr_err;
nlMultMatrixVector(M,x,g);
blas->Daxpy(blas,N,-1.,b,1,g,1);
blas->Dscal(blas,N,-1.,g,1);
blas->Dcopy(blas,N,g,1,r,1);
curr_err = blas->Ddot(blas,N,g,1,g,1);
while ( curr_err >err && its < max_iter) {
if(nlCurrentContext != NULL) {
if(nlCurrentContext->progress_func != NULL) {
nlCurrentContext->progress_func(its, max_iter, curr_err, err);
}
if(nlCurrentContext->verbose && !(its % 100)) {
nl_printf ( "%d : %.10e -- %.10e\n", its, curr_err, err );
}
}
nlMultMatrixVector(M,r,p);
rho=blas->Ddot(blas,N,p,1,p,1);
sig=blas->Ddot(blas,N,r,1,p,1);
tau=blas->Ddot(blas,N,g,1,r,1);
t=tau/sig;
blas->Daxpy(blas,N,t,r,1,x,1);
blas->Daxpy(blas,N,-t,p,1,g,1);
gam=(t*t*rho-tau)/tau;
blas->Dscal(blas,N,gam,r,1);
blas->Daxpy(blas,N,1.,g,1,r,1);
++its;
curr_err = blas->Ddot(blas,N,g,1,g,1);
}
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, g);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, r);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, p);
blas->sq_bnorm = b_square;
blas->sq_rnorm = curr_err;
return its;
}
static NLuint nlSolveSystem_PRE_CG(
NLBlas_t blas,
NLMatrix M, NLMatrix P, NLdouble* b, NLdouble* x,
double eps, NLuint max_iter
) {
NLint N = (NLint)M->n;
NLdouble* r = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble* d = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble* h = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *Ad = h;
NLuint its=0;
NLdouble rh, alpha, beta;
NLdouble b_square = blas->Ddot(blas,N,b,1,b,1);
NLdouble err=eps*eps*b_square;
NLdouble curr_err;
nlMultMatrixVector(M,x,r);
blas->Daxpy(blas,N,-1.,b,1,r,1);
nlMultMatrixVector(P,r,d);
blas->Dcopy(blas,N,d,1,h,1);
rh=blas->Ddot(blas,N,r,1,h,1);
curr_err = blas->Ddot(blas,N,r,1,r,1);
while ( curr_err >err && its < max_iter) {
if(nlCurrentContext != NULL) {
if(nlCurrentContext->progress_func != NULL) {
nlCurrentContext->progress_func(its, max_iter, curr_err, err);
}
if( nlCurrentContext->verbose && !(its % 100)) {
nl_printf ( "%d : %.10e -- %.10e\n", its, curr_err, err );
}
}
nlMultMatrixVector(M,d,Ad);
alpha=rh/blas->Ddot(blas,N,d,1,Ad,1);
blas->Daxpy(blas,N,-alpha,d,1,x,1);
blas->Daxpy(blas,N,-alpha,Ad,1,r,1);
nlMultMatrixVector(P,r,h);
beta=1./rh;
rh=blas->Ddot(blas,N,r,1,h,1);
beta*=rh;
blas->Dscal(blas,N,beta,d,1);
blas->Daxpy(blas,N,1.,h,1,d,1);
++its;
curr_err = blas->Ddot(blas,N,r,1,r,1);
}
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, r);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, d);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, h);
blas->sq_bnorm = b_square;
blas->sq_rnorm = curr_err;
return its;
}
static NLuint nlSolveSystem_BICGSTAB(
NLBlas_t blas,
NLMatrix M, NLdouble* b, NLdouble* x,
double eps, NLuint max_iter
) {
NLint N = (NLint)M->n;
NLdouble *rT = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *d = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *h = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *u = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *Ad = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *t = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *s = h;
NLdouble rTh, rTAd, rTr, alpha, beta, omega, st, tt;
NLuint its=0;
NLdouble b_square = blas->Ddot(blas,N,b,1,b,1);
NLdouble err=eps*eps*b_square;
NLdouble *r = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
nlMultMatrixVector(M,x,r);
blas->Daxpy(blas,N,-1.,b,1,r,1);
blas->Dcopy(blas,N,r,1,d,1);
blas->Dcopy(blas,N,d,1,h,1);
blas->Dcopy(blas,N,h,1,rT,1);
nl_assert( blas->Ddot(blas,N,rT,1,rT,1)>1e-40 );
rTh=blas->Ddot(blas,N,rT,1,h,1);
rTr=blas->Ddot(blas,N,r,1,r,1);
while ( rTr>err && its < max_iter) {
if(nlCurrentContext != NULL) {
if(nlCurrentContext->progress_func != NULL) {
nlCurrentContext->progress_func(its, max_iter, rTr, err);
}
if( (nlCurrentContext->verbose) && !(its % 100)) {
nl_printf ( "%d : %.10e -- %.10e\n", its, rTr, err );
}
}
nlMultMatrixVector(M,d,Ad);
rTAd=blas->Ddot(blas,N,rT,1,Ad,1);
nl_assert( fabs(rTAd)>1e-40 );
alpha=rTh/rTAd;
blas->Daxpy(blas,N,-alpha,Ad,1,r,1);
blas->Dcopy(blas,N,h,1,s,1);
blas->Daxpy(blas,N,-alpha,Ad,1,s,1);
nlMultMatrixVector(M,s,t);
blas->Daxpy(blas,N,1.,t,1,u,1);
blas->Dscal(blas,N,alpha,u,1);
st=blas->Ddot(blas,N,s,1,t,1);
tt=blas->Ddot(blas,N,t,1,t,1);
if ( fabs(st)<1e-40 || fabs(tt)<1e-40 ) {
omega = 0.;
} else {
omega = st/tt;
}
blas->Daxpy(blas,N,-omega,t,1,r,1);
blas->Daxpy(blas,N,-alpha,d,1,x,1);
blas->Daxpy(blas,N,-omega,s,1,x,1);
blas->Dcopy(blas,N,s,1,h,1);
blas->Daxpy(blas,N,-omega,t,1,h,1);
beta=(alpha/omega)/rTh;
rTh=blas->Ddot(blas,N,rT,1,h,1);
beta*=rTh;
blas->Dscal(blas,N,beta,d,1);
blas->Daxpy(blas,N,1.,h,1,d,1);
blas->Daxpy(blas,N,-beta*omega,Ad,1,d,1);
rTr=blas->Ddot(blas,N,r,1,r,1);
++its;
}
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, r);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, rT);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, d);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, h);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, u);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, Ad);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, t);
blas->sq_bnorm = b_square;
blas->sq_rnorm = rTr;
return its;
}
static NLuint nlSolveSystem_PRE_BICGSTAB(
NLBlas_t blas,
NLMatrix M, NLMatrix P, NLdouble* b, NLdouble* x,
double eps, NLuint max_iter
) {
NLint N = (NLint)M->n;
NLdouble *rT = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *d = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *h = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *u = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *Sd = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *t = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *aux = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
NLdouble *s = h;
NLdouble rTh, rTSd, rTr, alpha, beta, omega, st, tt;
NLuint its=0;
NLdouble b_square = blas->Ddot(blas,N,b,1,b,1);
NLdouble err = eps*eps*b_square;
NLdouble *r = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N);
nlMultMatrixVector(M,x,r);
blas->Daxpy(blas,N,-1.,b,1,r,1);
nlMultMatrixVector(P,r,d);
blas->Dcopy(blas,N,d,1,h,1);
blas->Dcopy(blas,N,h,1,rT,1);
nl_assert( blas->Ddot(blas,N,rT,1,rT,1)>1e-40 );
rTh=blas->Ddot(blas,N,rT,1,h,1);
rTr=blas->Ddot(blas,N,r,1,r,1);
while ( rTr>err && its < max_iter) {
if(nlCurrentContext != NULL) {
if(nlCurrentContext->progress_func != NULL) {
nlCurrentContext->progress_func(its, max_iter, rTr, err);
}
if( (nlCurrentContext->verbose) && !(its % 100)) {
nl_printf ( "%d : %.10e -- %.10e\n", its, rTr, err );
}
}
nlMultMatrixVector(M,d,aux);
nlMultMatrixVector(P,aux,Sd);
rTSd=blas->Ddot(blas,N,rT,1,Sd,1);
nl_assert( fabs(rTSd)>1e-40 );
alpha=rTh/rTSd;
blas->Daxpy(blas,N,-alpha,aux,1,r,1);
blas->Dcopy(blas,N,h,1,s,1);
blas->Daxpy(blas,N,-alpha,Sd,1,s,1);
nlMultMatrixVector(M,s,aux);
nlMultMatrixVector(P,aux,t);
blas->Daxpy(blas,N,1.,t,1,u,1);
blas->Dscal(blas,N,alpha,u,1);
st=blas->Ddot(blas,N,s,1,t,1);
tt=blas->Ddot(blas,N,t,1,t,1);
if ( fabs(st)<1e-40 || fabs(tt)<1e-40 ) {
omega = 0.;
} else {
omega = st/tt;
}
blas->Daxpy(blas,N,-omega,aux,1,r,1);
blas->Daxpy(blas,N,-alpha,d,1,x,1);
blas->Daxpy(blas,N,-omega,s,1,x,1);
blas->Dcopy(blas,N,s,1,h,1);
blas->Daxpy(blas,N,-omega,t,1,h,1);
beta=(alpha/omega)/rTh;
rTh=blas->Ddot(blas,N,rT,1,h,1);
beta*=rTh;
blas->Dscal(blas,N,beta,d,1);
blas->Daxpy(blas,N,1.,h,1,d,1);
blas->Daxpy(blas,N,-beta*omega,Sd,1,d,1);
rTr=blas->Ddot(blas,N,r,1,r,1);
++its;
}
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, r);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, rT);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, d);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, h);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, u);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, Sd);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, t);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, aux);
blas->sq_bnorm = b_square;
blas->sq_rnorm = rTr;
return its;
}
/*
* Note: this one cannot be executed on device (GPU)
* because it directly manipulates the vectors.
*/
static NLuint nlSolveSystem_GMRES(
NLBlas_t blas,
NLMatrix M, NLdouble* b, NLdouble* x,
double eps, NLuint max_iter, NLuint inner_iter
) {
NLint n = (NLint)M->n;
NLint m = (NLint)inner_iter;
typedef NLdouble *NLdoubleP;
NLdouble *V = NL_NEW_ARRAY(NLdouble, n*(m+1) );
NLdouble *U = NL_NEW_ARRAY(NLdouble, m*(m+1)/2 );
NLdouble *r = NL_NEW_ARRAY(NLdouble, n );
NLdouble *y = NL_NEW_ARRAY(NLdouble, m+1 );
NLdouble *c = NL_NEW_ARRAY(NLdouble, m );
NLdouble *s = NL_NEW_ARRAY(NLdouble, m );
NLdouble **v = NL_NEW_ARRAY(NLdoubleP, m+1 );
NLint i, j, io, uij, u0j;
NLint its = -1;
NLdouble beta, h, rd, dd, nrm2b;
/*
* The way it is written, this routine will not
* work on the GPU since it directly modifies the
* vectors.
*/
nl_assert(nlBlasHasUnifiedMemory(blas));
for ( i=0; i<=m; ++i ){
v[i]=V+i*n;
}
nrm2b=blas->Dnrm2(blas,n,b,1);
io=0;
do { /* outer loop */
++io;
nlMultMatrixVector(M,x,r);
blas->Daxpy(blas,n,-1.,b,1,r,1);
beta=blas->Dnrm2(blas,n,r,1);
blas->Dcopy(blas,n,r,1,v[0],1);
blas->Dscal(blas,n,1./beta,v[0],1);
y[0]=beta;
j=0;
uij=0;
do { /* inner loop: j=0,...,m-1 */
u0j=uij;
nlMultMatrixVector(M,v[j],v[j+1]);
blas->Dgemv(
blas,Transpose,n,j+1,1.,V,n,v[j+1],1,0.,U+u0j,1
);
blas->Dgemv(
blas,NoTranspose,n,j+1,-1.,V,n,U+u0j,1,1.,v[j+1],1
);
h=blas->Dnrm2(blas,n,v[j+1],1);
blas->Dscal(blas,n,1./h,v[j+1],1);
for (i=0; i<j; ++i ) { /* rotiere neue Spalte */
double tmp = c[i]*U[uij]-s[i]*U[uij+1];
U[uij+1] = s[i]*U[uij]+c[i]*U[uij+1];
U[uij] = tmp;
++uij;
}
{ /* berechne neue Rotation */
rd = U[uij];
dd = sqrt(rd*rd+h*h);
c[j] = rd/dd;
s[j] = -h/dd;
U[uij] = dd;
++uij;
}
{ /* rotiere rechte Seite y (vorher: y[j+1]=0) */
y[j+1] = s[j]*y[j];
y[j] = c[j]*y[j];
}
++j;
} while (
j<m && fabs(y[j])>=eps*nrm2b
);
{ /* minimiere bzgl Y */
blas->Dtpsv(
blas,
UpperTriangle,
NoTranspose,
NotUnitTriangular,
j,U,y,1
);
/* correct X */
blas->Dgemv(blas,NoTranspose,n,j,-1.,V,n,y,1,1.,x,1);
}
} while ( fabs(y[j])>=eps*nrm2b && (m*(io-1)+j) < (NLint)max_iter);
/* Count the inner iterations */
its = m*(io-1)+j;
blas->sq_bnorm = nrm2b*nrm2b;
blas->sq_rnorm = y[j]*y[j];
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, n, V);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, n, U);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, n, r);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, n, y);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, n, c);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, n, s);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, n, v);
return (NLuint)its;
}
/* Main driver routine */
NLuint nlSolveSystemIterative(
NLBlas_t blas,
NLMatrix M, NLMatrix P, NLdouble* b_in, NLdouble* x_in,
NLenum solver,
double eps, NLuint max_iter, NLuint inner_iter
) {
NLuint N = M->n;
NLuint result=0;
NLdouble rnorm=0.0;
NLdouble bnorm=0.0;
double* b = b_in;
double* x = x_in;
nl_assert(M->m == M->n);
if(!nlBlasHasUnifiedMemory(blas)) {
b = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, (int)M->n);
blas->Memcpy(
blas,
b, NL_DEVICE_MEMORY,
b_in, NL_HOST_MEMORY, (size_t)N*sizeof(double)
);
x = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, (int)M->n);
blas->Memcpy(
blas,
x, NL_DEVICE_MEMORY,
x_in, NL_HOST_MEMORY, (size_t)N*sizeof(double)
);
}
switch(solver) {
case NL_CG:
if(P == NULL) {
result = nlSolveSystem_CG(blas,M,b,x,eps,max_iter);
} else {
result = nlSolveSystem_PRE_CG(blas,M,P,b,x,eps,max_iter);
}
break;
case NL_BICGSTAB:
if(P == NULL) {
result = nlSolveSystem_BICGSTAB(blas,M,b,x,eps,max_iter);
} else {
result = nlSolveSystem_PRE_BICGSTAB(blas,M,P,b,x,eps,max_iter);
}
break;
case NL_GMRES:
result = nlSolveSystem_GMRES(blas,M,b,x,eps,max_iter,inner_iter);
break;
default:
nl_assert_not_reached;
}
/* Get residual norm and rhs norm from BLAS context */
if(nlCurrentContext != NULL) {
bnorm = sqrt(blas->sq_bnorm);
rnorm = sqrt(blas->sq_rnorm);
if(bnorm == 0.0) {
nlCurrentContext->error = rnorm;
if(nlCurrentContext->verbose) {
nl_printf("in OpenNL : ||Ax-b|| = %e\n",nlCurrentContext->error);
}
} else {
nlCurrentContext->error = rnorm/bnorm;
if(nlCurrentContext->verbose) {
nl_printf("in OpenNL : ||Ax-b||/||b|| = %e\n",
nlCurrentContext->error
);
}
}
}
nlCurrentContext->used_iterations = result;
if(!nlBlasHasUnifiedMemory(blas)) {
blas->Memcpy(
blas,
x_in, NL_HOST_MEMORY, x, NL_DEVICE_MEMORY, (size_t)N*sizeof(double)
);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, (int)M->n, x);
NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, (int)M->n, b);
}
return result;
}
/******* extracted from nl_preconditioners.c *******/
typedef struct {
NLuint m;
NLuint n;
NLenum type;
NLDestroyMatrixFunc destroy_func;
NLMultMatrixVectorFunc mult_func;
NLdouble* diag_inv;
} NLJacobiPreconditioner;
static void nlJacobiPreconditionerDestroy(NLJacobiPreconditioner* M) {
NL_DELETE_ARRAY(M->diag_inv);
}
static void nlJacobiPreconditionerMult(
NLJacobiPreconditioner* M, const double* x, double* y
) {
NLuint i;
for(i=0; i<M->n; ++i) {
y[i] = x[i] * M->diag_inv[i];
}
nlHostBlas()->flops += (NLulong)(M->n);
}
NLMatrix nlNewJacobiPreconditioner(NLMatrix M_in) {
NLSparseMatrix* M = NULL;
NLJacobiPreconditioner* result = NULL;
NLuint i;
nl_assert(M_in->type == NL_MATRIX_SPARSE_DYNAMIC);
nl_assert(M_in->m == M_in->n);
M = (NLSparseMatrix*)M_in;
result = NL_NEW(NLJacobiPreconditioner);
result->m = M->m;
result->n = M->n;
result->type = NL_MATRIX_OTHER;
result->destroy_func = (NLDestroyMatrixFunc)nlJacobiPreconditionerDestroy;
result->mult_func = (NLMultMatrixVectorFunc)nlJacobiPreconditionerMult;
result->diag_inv = NL_NEW_ARRAY(double, M->n);
for(i=0; i<M->n; ++i) {
result->diag_inv[i] = (M->diag[i] == 0.0) ? 1.0 : 1.0/M->diag[i];
}
return (NLMatrix)result;
}
typedef struct {
NLuint m;
NLuint n;
NLenum type;
NLDestroyMatrixFunc destroy_func;
NLMultMatrixVectorFunc mult_func;
NLSparseMatrix* M;
double omega;
NLdouble* work;
} NLSSORPreconditioner;
static void nlSSORPreconditionerDestroy(NLSSORPreconditioner* M) {
NL_DELETE_ARRAY(M->work);
}
static void nlSparseMatrixMultLowerInverse(
NLSparseMatrix* A, const NLdouble* x, NLdouble* y, double omega
) {
NLuint n = A->n;
NLdouble* diag = A->diag;
NLuint i;
NLuint ij;
NLCoeff* c = NULL;
NLdouble S;
nl_assert(A->storage & NL_MATRIX_STORE_SYMMETRIC);
nl_assert(A->storage & NL_MATRIX_STORE_ROWS);
for(i=0; i<n; i++) {
NLRowColumn* Ri = &(A->row[i]);
S = 0;
for(ij=0; ij < Ri->size; ij++) {
c = &(Ri->coeff[ij]);
nl_parano_assert(c->index <= i);
if(c->index != i) {
S += c->value * y[c->index];
}
}
nlHostBlas()->flops += (NLulong)(2*Ri->size);
y[i] = (x[i] - S) * omega / diag[i];
}
nlHostBlas()->flops += (NLulong)(n*3);
}
static void nlSparseMatrixMultUpperInverse(
NLSparseMatrix* A, const NLdouble* x, NLdouble* y, NLdouble omega
) {
NLuint n = A->n;
NLdouble* diag = A->diag;
NLint i;
NLuint ij;
NLCoeff* c = NULL;
NLdouble S;
nl_assert(A->storage & NL_MATRIX_STORE_SYMMETRIC);
nl_assert(A->storage & NL_MATRIX_STORE_COLUMNS);
for(i=(NLint)(n-1); i>=0; i--) {
NLRowColumn* Ci = &(A->column[i]);
S = 0;
for(ij=0; ij < Ci->size; ij++) {
c = &(Ci->coeff[ij]);
nl_parano_assert(c->index >= i);
if((NLint)(c->index) != i) {
S += c->value * y[c->index];
}
}
nlHostBlas()->flops += (NLulong)(2*Ci->size);
y[i] = (x[i] - S) * omega / diag[i];
}
nlHostBlas()->flops += (NLulong)(n*3);
}
static void nlSSORPreconditionerMult(
NLSSORPreconditioner* P, const double* x, double* y
) {
NLdouble* diag = P->M->diag;
NLuint i;
nlSparseMatrixMultLowerInverse(
P->M, x, P->work, P->omega
);
for(i=0; i<P->n; i++) {
P->work[i] *= (diag[i] / P->omega);
}
nlHostBlas()->flops += (NLulong)(P->n);
nlSparseMatrixMultUpperInverse(
P->M, P->work, y, P->omega
);
nlHostBlas()->Dscal(nlHostBlas(),(NLint)P->n, 2.0 - P->omega, y, 1);
}
NLMatrix nlNewSSORPreconditioner(NLMatrix M_in, double omega) {
NLSparseMatrix* M = NULL;
NLSSORPreconditioner* result = NULL;
nl_assert(M_in->type == NL_MATRIX_SPARSE_DYNAMIC);
nl_assert(M_in->m == M_in->n);
M = (NLSparseMatrix*)M_in;
result = NL_NEW(NLSSORPreconditioner);
result->m = M->m;
result->n = M->n;
result->type = NL_MATRIX_OTHER;
result->destroy_func = (NLDestroyMatrixFunc)nlSSORPreconditionerDestroy;
result->mult_func = (NLMultMatrixVectorFunc)nlSSORPreconditionerMult;
result->M = M;
result->work = NL_NEW_ARRAY(NLdouble, result->n);
result->omega = omega;
return (NLMatrix)result;
}
/******* extracted from nl_superlu.c *******/
#ifdef NL_OS_UNIX
# ifdef NL_OS_APPLE
# define SUPERLU_LIB_NAME "libsuperlu_5.dylib"
# else
# define SUPERLU_LIB_NAME "libsuperlu.so"
# endif
#else
# define SUPERLU_LIB_NAME "libsuperlu.xxx"
#endif
typedef enum {
SLU_NC, /* column-wise, no supernode */
SLU_NCP, /* column-wise, column-permuted, no supernode
(The consecutive columns of nonzeros, after permutation,
may not be stored contiguously.) */
SLU_NR, /* row-wize, no supernode */
SLU_SC, /* column-wise, supernode */
SLU_SCP, /* supernode, column-wise, permuted */
SLU_SR, /* row-wise, supernode */
SLU_DN, /* Fortran style column-wise storage for dense matrix */
SLU_NR_loc /* distributed compressed row format */
} Stype_t;
typedef enum {
SLU_S, /* single */
SLU_D, /* double */
SLU_C, /* single complex */
SLU_Z /* double complex */
} Dtype_t;
typedef enum {
SLU_GE, /* general */
SLU_TRLU, /* lower triangular, unit diagonal */
SLU_TRUU, /* upper triangular, unit diagonal */
SLU_TRL, /* lower triangular */
SLU_TRU, /* upper triangular */
SLU_SYL, /* symmetric, store lower half */
SLU_SYU, /* symmetric, store upper half */
SLU_HEL, /* Hermitian, store lower half */
SLU_HEU /* Hermitian, store upper half */
} Mtype_t;
typedef int int_t;
typedef struct {
int_t nnz; /* number of nonzeros in the matrix */
void *nzval; /* pointer to array of nonzero values, packed by raw */
int_t *colind; /* pointer to array of columns indices of the nonzeros */
int_t *rowptr; /* pointer to array of beginning of rows in nzval[]
and colind[] */
/* Note:
Zero-based indexing is used;
rowptr[] has nrow+1 entries, the last one pointing
beyond the last row, so that rowptr[nrow] = nnz. */
} NRformat;
typedef struct {
Stype_t Stype; /* Storage type: interprets the storage structure
pointed to by *Store. */
Dtype_t Dtype; /* Data type. */
Mtype_t Mtype; /* Matrix type: describes the mathematical property of
the matrix. */
int_t nrow; /* number of rows */
int_t ncol; /* number of columns */
void *Store; /* pointer to the actual storage of the matrix */
} SuperMatrix;
/* Stype == SLU_DN */
typedef struct {
int_t lda; /* leading dimension */
void *nzval; /* array of size lda*ncol to represent a dense matrix */
} DNformat;
typedef enum {NO, YES} yes_no_t;
typedef enum {DOFACT, SamePattern, SamePattern_SameRowPerm, FACTORED} fact_t;
typedef enum {NOROWPERM, LargeDiag, MY_PERMR} rowperm_t;
typedef enum {NATURAL, MMD_ATA, MMD_AT_PLUS_A, COLAMD,
METIS_AT_PLUS_A, PARMETIS, ZOLTAN, MY_PERMC} colperm_t;
typedef enum {NOTRANS, TRANS, CONJ} trans_t;
typedef enum {NOEQUIL, ROW, COL, BOTH} DiagScale_t;
typedef enum {NOREFINE, SLU_SINGLE=1, SLU_DOUBLE, SLU_EXTRA} IterRefine_t;
typedef enum {LUSUP, UCOL, LSUB, USUB, LLVL, ULVL} MemType;
typedef enum {HEAD, TAIL} stack_end_t;
typedef enum {SYSTEM, USER} LU_space_t;
typedef enum {ONE_NORM, TWO_NORM, INF_NORM} norm_t;
typedef enum {SILU, SMILU_1, SMILU_2, SMILU_3} milu_t;
typedef struct {
fact_t Fact;
yes_no_t Equil;
colperm_t ColPerm;
trans_t Trans;
IterRefine_t IterRefine;
double DiagPivotThresh;
yes_no_t SymmetricMode;
yes_no_t PivotGrowth;
yes_no_t ConditionNumber;
rowperm_t RowPerm;
int ILU_DropRule;
double ILU_DropTol; /* threshold for dropping */
double ILU_FillFactor; /* gamma in the secondary dropping */
norm_t ILU_Norm; /* infinity-norm, 1-norm, or 2-norm */
double ILU_FillTol; /* threshold for zero pivot perturbation */
milu_t ILU_MILU;
double ILU_MILU_Dim; /* Dimension of PDE (if available) */
yes_no_t ParSymbFact;
yes_no_t ReplaceTinyPivot; /* used in SuperLU_DIST */
yes_no_t SolveInitialized;
yes_no_t RefineInitialized;
yes_no_t PrintStat;
int nnzL, nnzU; /* used to store nnzs for now */
int num_lookaheads; /* num of levels in look-ahead */
yes_no_t lookahead_etree; /* use etree computed from the
serial symbolic factorization */
yes_no_t SymPattern; /* symmetric factorization */
} superlu_options_t;
typedef void* superlu_options_ptr;
typedef float flops_t;
typedef unsigned char Logical;
typedef struct {
int *panel_histo; /* histogram of panel size distribution */
double *utime; /* running time at various phases */
flops_t *ops; /* operation count at various phases */
int TinyPivots; /* number of tiny pivots */
int RefineSteps; /* number of iterative refinement steps */
int expansions; /* number of memory expansions (SuperLU4) */
} SuperLUStat_t;
/*! \brief Headers for 4 types of dynamatically managed memory */
typedef struct e_node {
int size; /* length of the memory that has been used */
void *mem; /* pointer to the new malloc'd store */
} ExpHeader;
typedef struct {
int size;
int used;
int top1; /* grow upward, relative to &array[0] */
int top2; /* grow downward */
void *array;
} LU_stack_t;
typedef struct {
int *xsup; /* supernode and column mapping */
int *supno;
int *lsub; /* compressed L subscripts */
int *xlsub;
void *lusup; /* L supernodes */
int *xlusup;
void *ucol; /* U columns */
int *usub;
int *xusub;
int nzlmax; /* current max size of lsub */
int nzumax; /* " " " ucol */
int nzlumax; /* " " " lusup */
int n; /* number of columns in the matrix */
LU_space_t MemModel; /* 0 - system malloc'd; 1 - user provided */
int num_expansions;
ExpHeader *expanders; /* Array of pointers to 4 types of memory */
LU_stack_t stack; /* use user supplied memory */
} GlobalLU_t;
typedef void (*FUNPTR_set_default_options)(superlu_options_ptr options);
typedef void (*FUNPTR_ilu_set_default_options)(superlu_options_ptr options);
typedef void (*FUNPTR_StatInit)(SuperLUStat_t *);
typedef void (*FUNPTR_StatFree)(SuperLUStat_t *);
typedef void (*FUNPTR_dCreate_CompCol_Matrix)(
SuperMatrix *, int, int, int, const double *,
const int *, const int *, Stype_t, Dtype_t, Mtype_t);
typedef void (*FUNPTR_dCreate_Dense_Matrix)(
SuperMatrix *, int, int, const double *, int,
Stype_t, Dtype_t, Mtype_t);
typedef void (*FUNPTR_Destroy_SuperNode_Matrix)(SuperMatrix *);
typedef void (*FUNPTR_Destroy_CompCol_Matrix)(SuperMatrix *);
typedef void (*FUNPTR_Destroy_CompCol_Permuted)(SuperMatrix *);
typedef void (*FUNPTR_Destroy_SuperMatrix_Store)(SuperMatrix *);
typedef void (*FUNPTR_dgssv)(
superlu_options_ptr, SuperMatrix *, int *, int *, SuperMatrix *,
SuperMatrix *, SuperMatrix *, SuperLUStat_t *, int *
);
typedef void (*FUNPTR_dgstrs)(
trans_t, SuperMatrix *, SuperMatrix *, int *, int *,
SuperMatrix *, SuperLUStat_t*, int *
);
typedef void (*FUNPTR_get_perm_c)(int, SuperMatrix *, int *);
typedef void (*FUNPTR_sp_preorder)(
superlu_options_t *, SuperMatrix*, int*, int*, SuperMatrix*
);
typedef int (*FUNPTR_sp_ienv)(int);
typedef int (*FUNPTR_input_error)(const char *, int *);
typedef void (*FUNPTR_dgstrf) (superlu_options_t *options, SuperMatrix *A,
int relax, int panel_size, int *etree, void *work, int lwork,
int *perm_c, int *perm_r, SuperMatrix *L, SuperMatrix *U,
GlobalLU_t *Glu, /* persistent to facilitate multiple factorizations */
SuperLUStat_t *stat, int *info
);
typedef struct {
FUNPTR_set_default_options set_default_options;
FUNPTR_ilu_set_default_options ilu_set_default_options;
FUNPTR_StatInit StatInit;
FUNPTR_StatFree StatFree;
FUNPTR_dCreate_CompCol_Matrix dCreate_CompCol_Matrix;
FUNPTR_dCreate_Dense_Matrix dCreate_Dense_Matrix;
FUNPTR_Destroy_SuperNode_Matrix Destroy_SuperNode_Matrix;
FUNPTR_Destroy_CompCol_Matrix Destroy_CompCol_Matrix;
FUNPTR_Destroy_CompCol_Permuted Destroy_CompCol_Permuted;
FUNPTR_Destroy_SuperMatrix_Store Destroy_SuperMatrix_Store;
FUNPTR_dgssv dgssv;
FUNPTR_dgstrs dgstrs;
FUNPTR_get_perm_c get_perm_c;
FUNPTR_sp_preorder sp_preorder;
FUNPTR_sp_ienv sp_ienv;
FUNPTR_dgstrf dgstrf;
FUNPTR_input_error input_error;
NLdll DLL_handle;
} SuperLUContext;
static SuperLUContext* SuperLU() {
static SuperLUContext context;
static NLboolean init = NL_FALSE;
if(!init) {
init = NL_TRUE;
memset(&context, 0, sizeof(context));
}
return &context;
}
NLboolean nlExtensionIsInitialized_SUPERLU() {
return
SuperLU()->DLL_handle != NULL &&
SuperLU()->set_default_options != NULL &&
SuperLU()->ilu_set_default_options != NULL &&
SuperLU()->StatInit != NULL &&
SuperLU()->StatFree != NULL &&
SuperLU()->dCreate_CompCol_Matrix != NULL &&
SuperLU()->dCreate_Dense_Matrix != NULL &&
SuperLU()->Destroy_SuperNode_Matrix != NULL &&
SuperLU()->Destroy_CompCol_Matrix != NULL &&
SuperLU()->Destroy_CompCol_Permuted != NULL &&
SuperLU()->Destroy_SuperMatrix_Store != NULL &&
SuperLU()->dgssv != NULL &&
SuperLU()->dgstrs != NULL &&
SuperLU()->get_perm_c != NULL &&
SuperLU()->sp_preorder != NULL &&
SuperLU()->sp_ienv != NULL &&
SuperLU()->dgstrf != NULL &&
SuperLU()->input_error != NULL;
}
static void nlTerminateExtension_SUPERLU(void) {
if(SuperLU()->DLL_handle != NULL) {
nlCloseDLL(SuperLU()->DLL_handle);
SuperLU()->DLL_handle = NULL;
}
}
#define find_superlu_func(name) \
if( \
( \
SuperLU()->name = \
(FUNPTR_##name)nlFindFunction(SuperLU()->DLL_handle,#name) \
) == NULL \
) { \
nlError("nlInitExtension_SUPERLU","function not found"); \
nlError("nlInitExtension_SUPERLU",#name); \
return NL_FALSE; \
}
NLboolean nlInitExtension_SUPERLU(void) {
NLenum flags = NL_LINK_NOW | NL_LINK_USE_FALLBACK;
if(nlCurrentContext == NULL || !nlCurrentContext->verbose) {
flags |= NL_LINK_QUIET;
}
if(SuperLU()->DLL_handle != NULL) {
return nlExtensionIsInitialized_SUPERLU();
}
SuperLU()->DLL_handle = nlOpenDLL(SUPERLU_LIB_NAME, flags);
if(SuperLU()->DLL_handle == NULL) {
return NL_FALSE;
}
find_superlu_func(set_default_options);
find_superlu_func(ilu_set_default_options);
find_superlu_func(StatInit);
find_superlu_func(StatFree);
find_superlu_func(dCreate_CompCol_Matrix);
find_superlu_func(dCreate_Dense_Matrix);
find_superlu_func(Destroy_SuperNode_Matrix);
find_superlu_func(Destroy_CompCol_Matrix);
find_superlu_func(Destroy_CompCol_Permuted);
find_superlu_func(Destroy_SuperMatrix_Store);
find_superlu_func(dgssv);
find_superlu_func(dgstrs);
find_superlu_func(get_perm_c);
find_superlu_func(sp_preorder);
find_superlu_func(sp_ienv);
find_superlu_func(dgstrf);
find_superlu_func(input_error);
atexit(nlTerminateExtension_SUPERLU);
return NL_TRUE;
}
typedef struct {
NLuint m;
NLuint n;
NLenum type;
NLDestroyMatrixFunc destroy_func;
NLMultMatrixVectorFunc mult_func;
SuperMatrix L;
SuperMatrix U;
int* perm_r;
int* perm_c;
trans_t trans;
} NLSuperLUFactorizedMatrix;
static void nlSuperLUFactorizedMatrixDestroy(NLSuperLUFactorizedMatrix* M) {
SuperLU()->Destroy_SuperNode_Matrix(&M->L);
SuperLU()->Destroy_CompCol_Matrix(&M->U);
NL_DELETE_ARRAY(M->perm_r);
NL_DELETE_ARRAY(M->perm_c);
}
static void nlSuperLUFactorizedMatrixMult(
NLSuperLUFactorizedMatrix* M, const double* x, double* y
) {
SuperMatrix B;
SuperLUStat_t stat;
int info = 0;
NLuint i;
/* Create vector */
SuperLU()->dCreate_Dense_Matrix(
&B, (int)(M->n), 1, y, (int)(M->n),
SLU_DN, /* Fortran-type column-wise storage */
SLU_D, /* doubles */
SLU_GE /* general */
);
/* copy rhs onto y (superLU matrix-vector product expects it here */
for(i = 0; i < M->n; i++){
y[i] = x[i];
}
/* Call SuperLU triangular solve */
SuperLU()->StatInit(&stat) ;
SuperLU()->dgstrs(
M->trans, &M->L, &M->U, M->perm_c, M->perm_r, &B, &stat, &info
);
SuperLU()->StatFree(&stat) ;
/* Only the "store" structure needs to be
* deallocated (the array has been allocated
* by client code).
*/
SuperLU()->Destroy_SuperMatrix_Store(&B) ;
}
/*
* Copied from SUPERLU/dgssv.c, removed call to linear solve.
*/
static void dgssv_factorize_only(
superlu_options_t *options, SuperMatrix *A, int *perm_c, int *perm_r,
SuperMatrix *L, SuperMatrix *U,
SuperLUStat_t *stat, int *info, trans_t *trans
) {
SuperMatrix *AA = NULL;
/* A in SLU_NC format used by the factorization routine.*/
SuperMatrix AC; /* Matrix postmultiplied by Pc */
int lwork = 0, *etree, i;
GlobalLU_t Glu; /* Not needed on return. */
/* Set default values for some parameters */
int panel_size; /* panel size */
int relax; /* no of columns in a relaxed snodes */
int permc_spec;
nl_assert(A->Stype == SLU_NR || A->Stype == SLU_NC);
*trans = NOTRANS;
if ( options->Fact != DOFACT ) *info = -1;
else if ( A->nrow != A->ncol || A->nrow < 0 ||
(A->Stype != SLU_NC && A->Stype != SLU_NR) ||
A->Dtype != SLU_D || A->Mtype != SLU_GE )
*info = -2;
if ( *info != 0 ) {
i = -(*info);
SuperLU()->input_error("SUPERLU/OpenNL dgssv_factorize_only", &i);
return;
}
/* Convert A to SLU_NC format when necessary. */
if ( A->Stype == SLU_NR ) {
NRformat *Astore = (NRformat*)A->Store;
AA = NL_NEW(SuperMatrix);
SuperLU()->dCreate_CompCol_Matrix(
AA, A->ncol, A->nrow, Astore->nnz,
(double*)Astore->nzval, Astore->colind, Astore->rowptr,
SLU_NC, A->Dtype, A->Mtype
);
*trans = TRANS;
} else {
if ( A->Stype == SLU_NC ) AA = A;
}
nl_assert(AA != NULL);
/*
* Get column permutation vector perm_c[], according to permc_spec:
* permc_spec = NATURAL: natural ordering
* permc_spec = MMD_AT_PLUS_A: minimum degree on structure of A'+A
* permc_spec = MMD_ATA: minimum degree on structure of A'*A
* permc_spec = COLAMD: approximate minimum degree column ordering
* permc_spec = MY_PERMC: the ordering already supplied in perm_c[]
*/
permc_spec = options->ColPerm;
if ( permc_spec != MY_PERMC && options->Fact == DOFACT )
SuperLU()->get_perm_c(permc_spec, AA, perm_c);
etree = NL_NEW_ARRAY(int,A->ncol);
SuperLU()->sp_preorder(options, AA, perm_c, etree, &AC);
panel_size = SuperLU()->sp_ienv(1);
relax = SuperLU()->sp_ienv(2);
SuperLU()->dgstrf(options, &AC, relax, panel_size, etree,
NULL, lwork, perm_c, perm_r, L, U, &Glu, stat, info);
NL_DELETE_ARRAY(etree);
SuperLU()->Destroy_CompCol_Permuted(&AC);
if ( A->Stype == SLU_NR ) {
SuperLU()->Destroy_SuperMatrix_Store(AA);
NL_DELETE(AA);
}
}
NLMatrix nlMatrixFactorize_SUPERLU(
NLMatrix M, NLenum solver
) {
NLSuperLUFactorizedMatrix* LU = NULL;
NLCRSMatrix* CRS = NULL;
SuperMatrix superM;
NLuint n = M->n;
superlu_options_t options;
SuperLUStat_t stat;
NLint info = 0; /* status code */
nl_assert(M->m == M->n);
if(M->type == NL_MATRIX_CRS) {
CRS = (NLCRSMatrix*)M;
} else if(M->type == NL_MATRIX_SPARSE_DYNAMIC) {
CRS = (NLCRSMatrix*)nlCRSMatrixNewFromSparseMatrix((NLSparseMatrix*)M);
}
nl_assert(!(CRS->symmetric_storage));
LU = NL_NEW(NLSuperLUFactorizedMatrix);
LU->m = M->m;
LU->n = M->n;
LU->type = NL_MATRIX_OTHER;
LU->destroy_func = (NLDestroyMatrixFunc)(nlSuperLUFactorizedMatrixDestroy);
LU->mult_func = (NLMultMatrixVectorFunc)(nlSuperLUFactorizedMatrixMult);
LU->perm_c = NL_NEW_ARRAY(int, n);
LU->perm_r = NL_NEW_ARRAY(int, n);
SuperLU()->dCreate_CompCol_Matrix(
&superM, (int)n, (int)n, (int)nlCRSMatrixNNZ(CRS),
CRS->val, (int*)CRS->colind, (int*)CRS->rowptr,
SLU_NR, /* Row_wise, no supernode */
SLU_D, /* doubles */
CRS->symmetric_storage ? SLU_SYL : SLU_GE
);
SuperLU()->set_default_options(&options);
switch(solver) {
case NL_SUPERLU_EXT: {
options.ColPerm = NATURAL;
} break;
case NL_PERM_SUPERLU_EXT: {
options.ColPerm = COLAMD;
} break;
case NL_SYMMETRIC_SUPERLU_EXT: {
options.ColPerm = MMD_AT_PLUS_A;
options.SymmetricMode = YES;
} break;
default:
nl_assert_not_reached;
}
SuperLU()->StatInit(&stat);
dgssv_factorize_only(
&options, &superM, LU->perm_c, LU->perm_r,
&LU->L, &LU->U, &stat, &info, &LU->trans
);
SuperLU()->StatFree(&stat);
/*
* Only the "store" structure needs to be deallocated
* (the arrays have been allocated by us, they are in CRS).
*/
SuperLU()->Destroy_SuperMatrix_Store(&superM);
if((NLMatrix)CRS != M) {
nlDeleteMatrix((NLMatrix)CRS);
}
if(info != 0) {
NL_DELETE(LU);
LU = NULL;
}
return (NLMatrix)LU;
}
/******* extracted from nl_cholmod.c *******/
#ifdef NL_OS_UNIX
# ifdef NL_OS_APPLE
# define CHOLMOD_LIB_NAME "libcholmod.dylib"
# else
# define CHOLMOD_LIB_NAME "libcholmod.so"
# endif
#else
# define CHOLMOD_LIB_NAME "libcholmod.xxx"
#endif
/* Excerpt from cholmod_core.h */
/* A dense matrix in column-oriented form. It has no itype since it contains
* no integers. Entry in row i and column j is located in x [i+j*d].
*/
typedef struct cholmod_dense_struct {
size_t nrow ; /* the matrix is nrow-by-ncol */
size_t ncol ;
size_t nzmax ; /* maximum number of entries in the matrix */
size_t d ; /* leading dimension (d >= nrow must hold) */
void *x ; /* size nzmax or 2*nzmax, if present */
void *z ; /* size nzmax, if present */
int xtype ; /* pattern, real, complex, or zomplex */
int dtype ; /* x and z double or float */
} cholmod_dense ;
/* A sparse matrix stored in compressed-column form. */
typedef struct cholmod_sparse_struct
{
size_t nrow ; /* the matrix is nrow-by-ncol */
size_t ncol ;
size_t nzmax ; /* maximum number of entries in the matrix */
/* pointers to int or SuiteSparse_long: */
void *p ; /* p [0..ncol], the column pointers */
void *i ; /* i [0..nzmax-1], the row indices */
/* for unpacked matrices only: */
void *nz ; /* nz [0..ncol-1], the # of nonzeros in each col. In
* packed form, the nonzero pattern of column j is in
* A->i [A->p [j] ... A->p [j+1]-1]. In unpacked form, column j is in
* A->i [A->p [j] ... A->p [j]+A->nz[j]-1] instead. In both cases, the
* numerical values (if present) are in the corresponding locations in
* the array x (or z if A->xtype is CHOLMOD_ZOMPLEX). */
/* pointers to double or float: */
void *x ; /* size nzmax or 2*nzmax, if present */
void *z ; /* size nzmax, if present */
int stype ; /* Describes what parts of the matrix are considered:
*
* 0: matrix is "unsymmetric": use both upper and lower triangular parts
* (the matrix may actually be symmetric in pattern and value, but
* both parts are explicitly stored and used). May be square or
* rectangular.
* >0: matrix is square and symmetric, use upper triangular part.
* Entries in the lower triangular part are ignored.
* <0: matrix is square and symmetric, use lower triangular part.
* Entries in the upper triangular part are ignored.
*
* Note that stype>0 and stype<0 are different for cholmod_sparse and
* cholmod_triplet. See the cholmod_triplet data structure for more
* details.
*/
int itype ; /* CHOLMOD_INT: p, i, and nz are int.
* CHOLMOD_INTLONG: p is SuiteSparse_long,
* i and nz are int.
* CHOLMOD_LONG: p, i, and nz are SuiteSparse_long */
int xtype ; /* pattern, real, complex, or zomplex */
int dtype ; /* x and z are double or float */
int sorted ; /* TRUE if columns are sorted, FALSE otherwise */
int packed ; /* TRUE if packed (nz ignored), FALSE if unpacked
* (nz is required) */
} cholmod_sparse ;
typedef void* cholmod_common_ptr;
typedef cholmod_dense* cholmod_dense_ptr;
typedef cholmod_sparse* cholmod_sparse_ptr;
typedef void* cholmod_factor_ptr;
typedef enum cholmod_xtype_enum {
CHOLMOD_PATTERN =0,
CHOLMOD_REAL =1,
CHOLMOD_COMPLEX =2,
CHOLMOD_ZOMPLEX =3
} cholmod_xtype;
typedef enum cholmod_solve_type_enum {
CHOLMOD_A =0,
CHOLMOD_LDLt =1,
CHOLMOD_LD =2,
CHOLMOD_DLt =3,
CHOLMOD_L =4,
CHOLMOD_Lt =5,
CHOLMOD_D =6,
CHOLMOD_P =7,
CHOLMOD_Pt =8
} cholmod_solve_type;
typedef int cholmod_stype;
typedef void (*FUNPTR_cholmod_start)(cholmod_common_ptr);
typedef cholmod_sparse_ptr (*FUNPTR_cholmod_allocate_sparse)(
size_t m, size_t n, size_t nnz, int sorted,
int packed, int stype, int xtype, cholmod_common_ptr
);
typedef cholmod_dense_ptr (*FUNPTR_cholmod_allocate_dense)(
size_t m, size_t n, size_t d, int xtype, cholmod_common_ptr
);
typedef cholmod_factor_ptr (*FUNPTR_cholmod_analyze)(
cholmod_sparse_ptr A, cholmod_common_ptr
);
typedef int (*FUNPTR_cholmod_factorize)(
cholmod_sparse_ptr A, cholmod_factor_ptr L, cholmod_common_ptr
);
typedef cholmod_dense_ptr (*FUNPTR_cholmod_solve)(
int solve_type, cholmod_factor_ptr, cholmod_dense_ptr, cholmod_common_ptr
);
typedef void (*FUNPTR_cholmod_free_factor)(
cholmod_factor_ptr*, cholmod_common_ptr
);
typedef void (*FUNPTR_cholmod_free_dense)(
cholmod_dense_ptr*, cholmod_common_ptr
);
typedef void (*FUNPTR_cholmod_free_sparse)(
cholmod_sparse_ptr*, cholmod_common_ptr
);
typedef void (*FUNPTR_cholmod_finish)(cholmod_common_ptr);
typedef struct {
char cholmod_common[16384];
FUNPTR_cholmod_start cholmod_start;
FUNPTR_cholmod_allocate_sparse cholmod_allocate_sparse;
FUNPTR_cholmod_allocate_dense cholmod_allocate_dense;
FUNPTR_cholmod_analyze cholmod_analyze;
FUNPTR_cholmod_factorize cholmod_factorize;
FUNPTR_cholmod_solve cholmod_solve;
FUNPTR_cholmod_free_factor cholmod_free_factor;
FUNPTR_cholmod_free_sparse cholmod_free_sparse;
FUNPTR_cholmod_free_dense cholmod_free_dense;
FUNPTR_cholmod_finish cholmod_finish;
NLdll DLL_handle;
} CHOLMODContext;
static CHOLMODContext* CHOLMOD() {
static CHOLMODContext context;
static NLboolean init = NL_FALSE;
if(!init) {
init = NL_TRUE;
memset(&context, 0, sizeof(context));
}
return &context;
}
NLboolean nlExtensionIsInitialized_CHOLMOD() {
return
CHOLMOD()->DLL_handle != NULL &&
CHOLMOD()->cholmod_start != NULL &&
CHOLMOD()->cholmod_allocate_sparse != NULL &&
CHOLMOD()->cholmod_allocate_dense != NULL &&
CHOLMOD()->cholmod_analyze != NULL &&
CHOLMOD()->cholmod_factorize != NULL &&
CHOLMOD()->cholmod_solve != NULL &&
CHOLMOD()->cholmod_free_factor != NULL &&
CHOLMOD()->cholmod_free_sparse != NULL &&
CHOLMOD()->cholmod_free_dense != NULL &&
CHOLMOD()->cholmod_finish != NULL ;
}
#define find_cholmod_func(name) \
if( \
( \
CHOLMOD()->name = \
(FUNPTR_##name)nlFindFunction(CHOLMOD()->DLL_handle,#name) \
) == NULL \
) { \
nlError("nlInitExtension_CHOLMOD","function not found"); \
return NL_FALSE; \
}
static void nlTerminateExtension_CHOLMOD(void) {
if(CHOLMOD()->DLL_handle != NULL) {
CHOLMOD()->cholmod_finish(&CHOLMOD()->cholmod_common);
nlCloseDLL(CHOLMOD()->DLL_handle);
CHOLMOD()->DLL_handle = NULL;
}
}
NLboolean nlInitExtension_CHOLMOD(void) {
NLenum flags = NL_LINK_NOW | NL_LINK_USE_FALLBACK;
if(nlCurrentContext == NULL || !nlCurrentContext->verbose) {
flags |= NL_LINK_QUIET;
}
if(CHOLMOD()->DLL_handle != NULL) {
return nlExtensionIsInitialized_CHOLMOD();
}
/*
* MKL has a built-in CHOLMOD that conflicts with
* the CHOLMOD used by OpenNL (to be fixed). For now
* we simply output a warning message and deactivate the
* CHOLMOD extension if the MKL extension was initialized
* before.
*/
if(NLMultMatrixVector_MKL != NULL) {
nl_fprintf(
stderr,
"CHOLMOD extension incompatible with MKL (deactivating)"
);
return NL_FALSE;
}
CHOLMOD()->DLL_handle = nlOpenDLL(CHOLMOD_LIB_NAME,flags);
if(CHOLMOD()->DLL_handle == NULL) {
return NL_FALSE;
}
find_cholmod_func(cholmod_start);
find_cholmod_func(cholmod_allocate_sparse);
find_cholmod_func(cholmod_allocate_dense);
find_cholmod_func(cholmod_analyze);
find_cholmod_func(cholmod_factorize);
find_cholmod_func(cholmod_solve);
find_cholmod_func(cholmod_free_factor);
find_cholmod_func(cholmod_free_sparse);
find_cholmod_func(cholmod_free_dense);
find_cholmod_func(cholmod_finish);
CHOLMOD()->cholmod_start(&CHOLMOD()->cholmod_common);
atexit(nlTerminateExtension_CHOLMOD);
return NL_TRUE;
}
typedef struct {
NLuint m;
NLuint n;
NLenum type;
NLDestroyMatrixFunc destroy_func;
NLMultMatrixVectorFunc mult_func;
cholmod_factor_ptr L;
} NLCholmodFactorizedMatrix;
static void nlCholmodFactorizedMatrixDestroy(NLCholmodFactorizedMatrix* M) {
CHOLMOD()->cholmod_free_factor(&M->L, &CHOLMOD()->cholmod_common);
}
static void nlCholmodFactorizedMatrixMult(
NLCholmodFactorizedMatrix* M, const double* x, double* y
) {
/*
* TODO: see whether CHOLDMOD can use user-allocated vectors
* (and avoid copy)
*/
cholmod_dense_ptr X=CHOLMOD()->cholmod_allocate_dense(
M->n, 1, M->n, CHOLMOD_REAL, &CHOLMOD()->cholmod_common
);
cholmod_dense_ptr Y=NULL;
memcpy(X->x, x, M->n*sizeof(double));
Y = CHOLMOD()->cholmod_solve(
CHOLMOD_A, M->L, X, &CHOLMOD()->cholmod_common
);
memcpy(y, Y->x, M->n*sizeof(double));
CHOLMOD()->cholmod_free_dense(&X, &CHOLMOD()->cholmod_common);
CHOLMOD()->cholmod_free_dense(&Y, &CHOLMOD()->cholmod_common);
}
NLMatrix nlMatrixFactorize_CHOLMOD(
NLMatrix M, NLenum solver
) {
NLCholmodFactorizedMatrix* LLt = NULL;
NLCRSMatrix* CRS = NULL;
cholmod_sparse_ptr cM= NULL;
NLuint nnz, cur, i, j, jj;
int* rowptr = NULL;
int* colind = NULL;
double* val = NULL;
NLuint n = M->n;
nl_assert(solver == NL_CHOLMOD_EXT);
nl_assert(M->m == M->n);
if(M->type == NL_MATRIX_CRS) {
CRS = (NLCRSMatrix*)M;
} else if(M->type == NL_MATRIX_SPARSE_DYNAMIC) {
/*
* Note: since we convert once again into symmetric storage,
* we could also directly read the NLSparseMatrix there instead
* of copying once more...
*/
CRS = (NLCRSMatrix*)nlCRSMatrixNewFromSparseMatrix((NLSparseMatrix*)M);
}
LLt = NL_NEW(NLCholmodFactorizedMatrix);
LLt->m = M->m;
LLt->n = M->n;
LLt->type = NL_MATRIX_OTHER;
LLt->destroy_func = (NLDestroyMatrixFunc)(nlCholmodFactorizedMatrixDestroy);
LLt->mult_func = (NLMultMatrixVectorFunc)(nlCholmodFactorizedMatrixMult);
/*
* Compute required nnz, if matrix is not already with symmetric storage,
* ignore entries in the upper triangular part.
*/
nnz=0;
for(i=0; i<n; ++i) {
for(jj=CRS->rowptr[i]; jj<CRS->rowptr[i+1]; ++jj) {
j=CRS->colind[jj];
if(j <= i) {
++nnz;
}
}
}
/*
* Copy CRS matrix into CHOLDMOD matrix (and ignore upper trianglar part)
*/
cM = CHOLMOD()->cholmod_allocate_sparse(
n, n, nnz, /* Dimensions and number of non-zeros */
NL_FALSE, /* Sorted = false */
NL_TRUE, /* Packed = true */
1, /* stype (-1 = lower triangular, 1 = upper triangular) */
CHOLMOD_REAL, /* Entries are real numbers */
&CHOLMOD()->cholmod_common
);
rowptr = (int*)cM->p;
colind = (int*)cM->i;
val = (double*)cM->x;
cur = 0;
for(i=0; i<n; ++i) {
rowptr[i] = (int)cur;
for(jj=CRS->rowptr[i]; jj<CRS->rowptr[i+1]; ++jj) {
j = CRS->colind[jj];
if(j <= i) {
val[cur] = CRS->val[jj];
colind[cur] = (int)j;
++cur;
}
}
}
rowptr[n] = (int)cur;
nl_assert(cur==nnz);
LLt->L = CHOLMOD()->cholmod_analyze(cM, &CHOLMOD()->cholmod_common);
if(!CHOLMOD()->cholmod_factorize(cM, LLt->L, &CHOLMOD()->cholmod_common)) {
CHOLMOD()->cholmod_free_factor(&LLt->L, &CHOLMOD()->cholmod_common);
NL_DELETE(LLt);
}
CHOLMOD()->cholmod_free_sparse(&cM, &CHOLMOD()->cholmod_common);
if((NLMatrix)CRS != M) {
nlDeleteMatrix((NLMatrix)CRS);
}
return (NLMatrix)(LLt);
}
/******* extracted from nl_arpack.c *******/
#ifdef NL_OS_UNIX
# ifdef NL_OS_APPLE
# define ARPACK_LIB_NAME "libarpack.dylib"
# else
# define ARPACK_LIB_NAME "libarpack.so"
# endif
#else
# define ARPACK_LIB_NAME "libarpack.dll"
#endif
typedef int ARint;
typedef int ARlogical;
/* double precision symmetric routines */
typedef void (*FUNPTR_dsaupd)(
ARint *ido, char *bmat, ARint *n, char *which,
ARint *nev, double *tol, double *resid,
ARint *ncv, double *V, ARint *ldv,
ARint *iparam, ARint *ipntr, double *workd,
double *workl, ARint *lworkl, ARint *info
);
typedef void (*FUNPTR_dseupd)(
ARlogical *rvec, char *HowMny, ARlogical *select,
double *d, double *Z, ARint *ldz,
double *sigma, char *bmat, ARint *n,
char *which, ARint *nev, double *tol,
double *resid, ARint *ncv, double *V,
ARint *ldv, ARint *iparam, ARint *ipntr,
double *workd, double *workl,
ARint *lworkl, ARint *info
);
/* double precision nonsymmetric routines */
typedef void (*FUNPTR_dnaupd)(
ARint *ido, char *bmat, ARint *n, char *which,
ARint *nev, double *tol, double *resid,
ARint *ncv, double *V, ARint *ldv,
ARint *iparam, ARint *ipntr, double *workd,
double *workl, ARint *lworkl, ARint *info
);
typedef void (*FUNPTR_dneupd)(
ARlogical *rvec, char *HowMny, ARlogical *select,
double *dr, double *di, double *Z,
ARint *ldz, double *sigmar,
double *sigmai, double *workev,
char *bmat, ARint *n, char *which,
ARint *nev, double *tol, double *resid,
ARint *ncv, double *V, ARint *ldv,
ARint *iparam, ARint *ipntr,
double *workd, double *workl,
ARint *lworkl, ARint *info
);
typedef struct {
FUNPTR_dsaupd dsaupd;
FUNPTR_dseupd dseupd;
FUNPTR_dnaupd dnaupd;
FUNPTR_dneupd dneupd;
NLdll DLL_handle;
} ARPACKContext;
static ARPACKContext* ARPACK() {
static ARPACKContext context;
static NLboolean init = NL_FALSE;
if(!init) {
init = NL_TRUE;
memset(&context, 0, sizeof(context));
}
return &context;
}
NLboolean nlExtensionIsInitialized_ARPACK() {
return
ARPACK()->DLL_handle != NULL &&
ARPACK()->dsaupd != NULL &&
ARPACK()->dseupd != NULL &&
ARPACK()->dnaupd != NULL &&
ARPACK()->dneupd != NULL;
}
static void nlTerminateExtension_ARPACK(void) {
if(ARPACK()->DLL_handle != NULL) {
nlCloseDLL(ARPACK()->DLL_handle);
ARPACK()->DLL_handle = NULL;
}
}
static char* u(const char* str) {
static char buff[1000];
sprintf(buff, "%s_", str);
return buff;
}
#define find_arpack_func(name) \
if( \
( \
ARPACK()->name = \
(FUNPTR_##name)nlFindFunction(ARPACK()->DLL_handle,u(#name)) \
) == NULL \
) { \
nlError("nlInitExtension_ARPACK","function not found"); \
nlError("nlInitExtension_ARPACK",u(#name)); \
return NL_FALSE; \
}
NLboolean nlInitExtension_ARPACK(void) {
NLenum flags = NL_LINK_NOW | NL_LINK_USE_FALLBACK;
if(nlCurrentContext == NULL || !nlCurrentContext->verbose) {
flags |= NL_LINK_QUIET;
}
if(ARPACK()->DLL_handle != NULL) {
return nlExtensionIsInitialized_ARPACK();
}
ARPACK()->DLL_handle = nlOpenDLL(ARPACK_LIB_NAME, flags);
if(ARPACK()->DLL_handle == NULL) {
return NL_FALSE;
}
find_arpack_func(dsaupd);
find_arpack_func(dseupd);
find_arpack_func(dnaupd);
find_arpack_func(dneupd);
atexit(nlTerminateExtension_ARPACK);
return NL_TRUE;
}
static NLMatrix create_OP(NLboolean symmetric) {
NLuint n = nlCurrentContext->M->n;
NLuint i;
NLMatrix result = NULL;
if(nlCurrentContext->eigen_shift != 0.0) {
/*
* A = M
*/
NLSparseMatrix* A = NL_NEW(NLSparseMatrix);
nlSparseMatrixConstruct(A, n, n, NL_MATRIX_STORE_ROWS);
nlSparseMatrixAddMatrix(A, 1.0, nlCurrentContext->M);
if(nlCurrentContext->B == NULL) {
/*
* A = A - shift * Id
*/
for(i=0; i<n; ++i) {
nlSparseMatrixAdd(A, i, i, -nlCurrentContext->eigen_shift);
}
} else {
/*
* A = A - shift * B
*/
nlSparseMatrixAddMatrix(
A, -nlCurrentContext->eigen_shift, nlCurrentContext->B
);
}
/*
* OP = A^{-1}
*/
if(nlCurrentContext->verbose) {
nl_printf("Factorizing matrix...\n");
}
result = nlMatrixFactorize(
(NLMatrix)A,
symmetric ? NL_SYMMETRIC_SUPERLU_EXT : NL_PERM_SUPERLU_EXT
);
if(nlCurrentContext->verbose) {
if(result == NULL) {
nl_printf("Could not factorize matrix\n");
} else {
nl_printf("Matrix factorized\n");
}
}
nlDeleteMatrix((NLMatrix)A);
} else {
/*
* OP = M^{-1}
*/
if(nlCurrentContext->verbose) {
nl_printf("Factorizing matrix...\n");
}
result = nlMatrixFactorize(
nlCurrentContext->M,
symmetric ? NL_SYMMETRIC_SUPERLU_EXT : NL_PERM_SUPERLU_EXT
);
if(nlCurrentContext->verbose) {
if(result == NULL) {
nl_printf("Could not factorize matrix\n");
} else {
nl_printf("Matrix factorized\n");
}
}
}
if(result == NULL) {
return NULL;
}
if(nlCurrentContext->B != NULL) {
/*
* OP = OP * B
*/
result = nlMatrixNewFromProduct(
result, NL_TRUE, /* mem. ownership transferred */
nlCurrentContext->B, NL_FALSE /* mem. ownership kept by context */
);
}
return result;
}
static int eigencompare(const void* pi, const void* pj) {
NLuint i = *(const NLuint*)pi;
NLuint j = *(const NLuint*)pj;
double vali = fabs(nlCurrentContext->temp_eigen_value[i]);
double valj = fabs(nlCurrentContext->temp_eigen_value[j]);
if(vali == valj) {
return 0;
}
return vali < valj ? -1 : 1;
}
void nlEigenSolve_ARPACK(void) {
NLboolean symmetric =
nlCurrentContext->symmetric && (nlCurrentContext->B == NULL);
int n = (int)nlCurrentContext->M->n; /* Dimension of the matrix */
int nev = /* Number of eigenvectors requested */
(int)nlCurrentContext->nb_systems;
NLMatrix OP = create_OP(symmetric);
int ncv = (int)(nev * 2.5); /* Length of Arnoldi factorization */
/* Rule of thumb in ARPACK documentation: ncv > 2 * nev */
int* iparam = NULL;
int* ipntr = NULL;
NLdouble* resid = NULL;
NLdouble* workev = NULL;
NLdouble* workd = NULL;
NLdouble* workl = NULL;
NLdouble* v = NULL;
NLdouble* d = NULL;
ARlogical* select = NULL;
ARlogical rvec = 1;
double sigmar = 0.0;
double sigmai = 0.0;
int ierr;
int i,k,kk;
int ldv = (int)n;
char* bmat = (char*)"I"; /*Standard problem */
char* which = (char*)"LM"; /*Largest eigenvalues, but we invert->smallest */
char* howmny = (char*)"A"; /*which eigens should be computed: all */
double tol = nlCurrentContext->threshold;
int ido = 0; /* reverse communication variable (which operation ?) */
int info = 1; /* start with initial value of resid */
int lworkl; /* size of work array */
NLboolean converged = NL_FALSE;
NLdouble value;
int index;
int* sorted; /* indirection array for sorting eigenpairs */
if(OP == NULL) {
nlError("nlEigenSolve_ARPACK","Could not factorize matrix");
return;
}
if(ncv > n) {
ncv = n;
}
if(nev > n) {
nev = n;
}
if(nev + 2 > ncv) {
nev = ncv - 2;
}
if(symmetric) {
lworkl = ncv * (ncv + 8) ;
} else {
lworkl = 3*ncv*ncv + 6*ncv ;
}
iparam = NL_NEW_ARRAY(int, 11);
ipntr = NL_NEW_ARRAY(int, 14);
iparam[1-1] = 1; /* ARPACK chooses the shifts */
iparam[3-1] = (int)nlCurrentContext->max_iterations;
iparam[7-1] = 1; /* Normal mode (we do not use
shift-invert (3) since we do our own shift-invert */
workev = NL_NEW_ARRAY(NLdouble, 3*ncv);
workd = NL_NEW_ARRAY(NLdouble, 3*n);
resid = NL_NEW_ARRAY(NLdouble, n);
for(i=0; i<n; ++i) {
resid[i] = 1.0; /* (double)i / (double)n; */
}
v = NL_NEW_ARRAY(NLdouble, ldv*ncv);
if(symmetric) {
d = NL_NEW_ARRAY(NLdouble, 2*ncv);
} else {
d = NL_NEW_ARRAY(NLdouble, 3*ncv);
}
workl = NL_NEW_ARRAY(NLdouble, lworkl);
if(nlCurrentContext->verbose) {
if(symmetric) {
nl_printf("calling dsaupd()\n");
} else {
nl_printf("calling dnaupd()\n");
}
}
while(!converged) {
/*
if(nlCurrentContext->verbose) {
fprintf(stderr, ".");
fflush(stderr);
}
*/
if(symmetric) {
ARPACK()->dsaupd(
&ido, bmat, &n, which, &nev, &tol, resid, &ncv,
v, &ldv, iparam, ipntr, workd, workl, &lworkl, &info
);
} else {
ARPACK()->dnaupd(
&ido, bmat, &n, which, &nev, &tol, resid, &ncv,
v, &ldv, iparam, ipntr, workd, workl, &lworkl, &info
);
}
if(ido == 1) {
nlMultMatrixVector(
OP,
workd+ipntr[1-1]-1, /*The "-1"'s are for FORTRAN-to-C conversion */
workd+ipntr[2-1]-1 /*to keep the same indices as in ARPACK doc */
);
} else {
converged = NL_TRUE;
}
}
if(info < 0) {
if(symmetric) {
nl_fprintf(stderr, "\nError with dsaupd(): %d\n", info);
} else {
nl_fprintf(stderr, "\nError with dnaupd(): %d\n", info);
}
} else {
if(nlCurrentContext->verbose) {
fprintf(stderr, "\nconverged\n");
}
select = NL_NEW_ARRAY(ARlogical, ncv);
for(i=0; i<ncv; ++i) {
select[i] = 1;
}
if(nlCurrentContext->verbose) {
if(symmetric) {
nl_printf("calling dseupd()\n");
} else {
nl_printf("calling dneupd()\n");
}
}
if(symmetric) {
ARPACK()->dseupd(
&rvec, howmny, select, d, v,
&ldv, &sigmar, bmat, &n, which, &nev,
&tol, resid, &ncv, v, &ldv,
iparam, ipntr, workd,
workl, &lworkl, &ierr
);
} else {
ARPACK()->dneupd(
&rvec, howmny, select, d, d+ncv,
v, &ldv,
&sigmar, &sigmai, workev, bmat, &n,
which, &nev, &tol,
resid, &ncv, v, &ldv, iparam,
ipntr, workd, workl, &lworkl, &ierr
) ;
}
if(nlCurrentContext->verbose) {
if(ierr != 0) {
if(symmetric) {
nl_fprintf(stderr, "Error with dseupd(): %d\n", ierr);
} else {
nl_fprintf(stderr, "Error with dneupd(): %d\n", ierr);
}
} else {
if(symmetric) {
nl_printf("dseupd() OK, nconv= %d\n", iparam[3-1]);
} else {
nl_printf("dneupd() OK, nconv= %d\n", iparam[3-1]);
}
}
}
NL_DELETE_ARRAY(select);
}
for(i=0; i<nev; ++i) {
d[i] = (fabs(d[i]) < 1e-30) ? 1e30 : 1.0 / d[i] ;
d[i] += nlCurrentContext->eigen_shift ;
}
/* Make it visible to the eigen_compare function */
nlCurrentContext->temp_eigen_value = d;
sorted = NL_NEW_ARRAY(int, nev);
for(i=0; i<nev; ++i) {
sorted[i] = i;
}
qsort(sorted, (size_t)nev, sizeof(NLuint), eigencompare);
nlCurrentContext->temp_eigen_value = NULL;
for(k=0; k<nev; ++k) {
kk = sorted[k];
nlCurrentContext->eigen_value[k] = d[kk];
for(i=0; i<(int)nlCurrentContext->nb_variables; ++i) {
if(!nlCurrentContext->variable_is_locked[i]) {
index = (int)nlCurrentContext->variable_index[i];
nl_assert(index < n);
value = v[kk*n+index];
NL_BUFFER_ITEM(
nlCurrentContext->variable_buffer[k],(NLuint)i
) = value;
}
}
}
NL_DELETE_ARRAY(sorted);
NL_DELETE_ARRAY(workl);
NL_DELETE_ARRAY(d);
NL_DELETE_ARRAY(v);
NL_DELETE_ARRAY(resid);
NL_DELETE_ARRAY(workd);
NL_DELETE_ARRAY(workev);
nlDeleteMatrix(OP);
NL_DELETE_ARRAY(iparam);
NL_DELETE_ARRAY(ipntr);
}
/******* extracted from nl_mkl.c *******/
typedef unsigned int MKL_INT;
typedef void (*FUNPTR_mkl_cspblas_dcsrgemv)(
const char *transa, const MKL_INT *m, const double *a,
const MKL_INT *ia, const MKL_INT *ja, const double *x, double *y
);
typedef void (*FUNPTR_mkl_cspblas_dcsrsymv)(
const char *transa, const MKL_INT *m, const double *a,
const MKL_INT *ia, const MKL_INT *ja, const double *x, double *y
);
typedef struct {
NLdll DLL_mkl_intel_lp64;
NLdll DLL_mkl_intel_thread;
NLdll DLL_mkl_core;
NLdll DLL_iomp5;
FUNPTR_mkl_cspblas_dcsrgemv mkl_cspblas_dcsrgemv;
FUNPTR_mkl_cspblas_dcsrsymv mkl_cspblas_dcsrsymv;
} MKLContext;
static MKLContext* MKL() {
static MKLContext context;
static NLboolean init = NL_FALSE;
if(!init) {
init = NL_TRUE;
memset(&context, 0, sizeof(context));
}
return &context;
}
NLboolean nlExtensionIsInitialized_MKL() {
if(
MKL()->DLL_iomp5 == NULL ||
MKL()->DLL_mkl_core == NULL ||
MKL()->DLL_mkl_intel_thread == NULL ||
MKL()->DLL_mkl_intel_lp64 == NULL ||
MKL()->mkl_cspblas_dcsrgemv == NULL ||
MKL()->mkl_cspblas_dcsrsymv == NULL
) {
return NL_FALSE;
}
return NL_TRUE;
}
#define find_mkl_func(name) \
if( \
( \
MKL()->name = \
(FUNPTR_##name)nlFindFunction( \
MKL()->DLL_mkl_intel_lp64,#name \
) \
) == NULL \
) { \
nlError("nlInitExtension_MKL","function not found"); \
return NL_FALSE; \
}
static void nlTerminateExtension_MKL(void) {
if(!nlExtensionIsInitialized_MKL()) {
return;
}
nlCloseDLL(MKL()->DLL_mkl_intel_lp64);
nlCloseDLL(MKL()->DLL_mkl_intel_thread);
nlCloseDLL(MKL()->DLL_mkl_core);
nlCloseDLL(MKL()->DLL_iomp5);
}
NLMultMatrixVectorFunc NLMultMatrixVector_MKL = NULL;
static void NLMultMatrixVector_MKL_impl(NLMatrix M_in, const double* x, double* y) {
NLCRSMatrix* M = (NLCRSMatrix*)(M_in);
nl_debug_assert(M_in->type == NL_MATRIX_CRS);
if(M->symmetric_storage) {
MKL()->mkl_cspblas_dcsrsymv(
"N", /* No transpose */
&M->m,
M->val,
M->rowptr,
M->colind,
x,
y
);
} else {
MKL()->mkl_cspblas_dcsrgemv(
"N", /* No transpose */
&M->m,
M->val,
M->rowptr,
M->colind,
x,
y
);
}
}
#define INTEL_PREFIX "/opt/intel/"
#define LIB_DIR "lib/intel64/"
#define MKL_PREFIX INTEL_PREFIX "mkl/" LIB_DIR
NLboolean nlInitExtension_MKL(void) {
NLenum flags = NL_LINK_LAZY | NL_LINK_GLOBAL;
if(nlCurrentContext == NULL || !nlCurrentContext->verbose) {
flags |= NL_LINK_QUIET;
}
if(MKL()->DLL_mkl_intel_lp64 != NULL) {
return nlExtensionIsInitialized_MKL();
}
MKL()->DLL_iomp5 = nlOpenDLL(
INTEL_PREFIX LIB_DIR "libiomp5.so",
flags
);
MKL()->DLL_mkl_core = nlOpenDLL(
MKL_PREFIX "libmkl_core.so",
flags
);
MKL()->DLL_mkl_intel_thread = nlOpenDLL(
MKL_PREFIX "libmkl_intel_thread.so",
flags
);
MKL()->DLL_mkl_intel_lp64 = nlOpenDLL(
MKL_PREFIX "libmkl_intel_lp64.so",
flags
);
if(
MKL()->DLL_iomp5 == NULL ||
MKL()->DLL_mkl_core == NULL ||
MKL()->DLL_mkl_intel_thread == NULL ||
MKL()->DLL_mkl_intel_lp64 == NULL
) {
return NL_FALSE;
}
find_mkl_func(mkl_cspblas_dcsrgemv);
find_mkl_func(mkl_cspblas_dcsrsymv);
if(nlExtensionIsInitialized_MKL()) {
NLMultMatrixVector_MKL = NLMultMatrixVector_MKL_impl;
}
atexit(nlTerminateExtension_MKL);
return NL_TRUE;
}
/******* extracted from nl_cuda.c *******/
/* CUDA structures and functions */
/* Repeated here so that one can compile OpenNL without */
/* requiring CUDA to be installed in the system. */
struct cudaDeviceProp {
char name[256];
size_t totalGlobalMem;
size_t sharedMemPerBlock;
int regsPerBlock;
int warpSize;
size_t memPitch;
int maxThreadsPerBlock;
int maxThreadsDim[3];
int maxGridSize[3];
int clockRate;
size_t totalConstMem;
int major;
int minor;
size_t textureAlignment;
size_t texturePitchAlignment;
int deviceOverlap;
int multiProcessorCount;
int kernelExecTimeoutEnabled;
int integrated;
int canMapHostMemory;
int computeMode;
int maxTexture1D;
int maxTexture1DMipmap;
int maxTexture1DLinear;
int maxTexture2D[2];
int maxTexture2DMipmap[2];
int maxTexture2DLinear[3];
int maxTexture2DGather[2];
int maxTexture3D[3];
int maxTexture3DAlt[3];
int maxTextureCubemap;
int maxTexture1DLayered[2];
int maxTexture2DLayered[3];
int maxTextureCubemapLayered[2];
int maxSurface1D;
int maxSurface2D[2];
int maxSurface3D[3];
int maxSurface1DLayered[2];
int maxSurface2DLayered[3];
int maxSurfaceCubemap;
int maxSurfaceCubemapLayered[2];
size_t surfaceAlignment;
int concurrentKernels;
int ECCEnabled;
int pciBusID;
int pciDeviceID;
int pciDomainID;
int tccDriver;
int asyncEngineCount;
int unifiedAddressing;
int memoryClockRate;
int memoryBusWidth;
int l2CacheSize;
int maxThreadsPerMultiProcessor;
int streamPrioritiesSupported;
int globalL1CacheSupported;
int localL1CacheSupported;
size_t sharedMemPerMultiprocessor;
int regsPerMultiprocessor;
int managedMemSupported;
int isMultiGpuBoard;
int multiGpuBoardGroupID;
int singleToDoublePrecisionPerfRatio;
int pageableMemoryAccess;
int concurrentManagedAccess;
char padding[1024]; /* More room for future evolutions */
};
enum cudaComputeMode {
cudaComputeModeDefault = 0,
cudaComputeModeExclusive = 1,
cudaComputeModeProhibited = 2,
cudaComputeModeExclusiveProcess = 3
};
enum cudaMemcpyKind {
cudaMemcpyHostToHost = 0,
cudaMemcpyHostToDevice = 1,
cudaMemcpyDeviceToHost = 2,
cudaMemcpyDeviceToDevice = 3,
cudaMemcpyDefault = 4
};
typedef int cudaError_t;
typedef cudaError_t (*FUNPTR_cudaGetDeviceCount)(int* device_count);
typedef cudaError_t (*FUNPTR_cudaGetDeviceProperties)(
struct cudaDeviceProp *props, int device
);
typedef cudaError_t (*FUNPTR_cudaDeviceReset)(void);
typedef cudaError_t (*FUNPTR_cudaMalloc)(void **devPtr, size_t size);
typedef cudaError_t (*FUNPTR_cudaFree)(void* devPtr);
typedef cudaError_t (*FUNPTR_cudaMemcpy)(
void *dst, const void *src, size_t count, enum cudaMemcpyKind kind
);
#define find_cuda_func(name) \
if( \
( \
CUDA()->name = \
(FUNPTR_##name)nlFindFunction( \
CUDA()->DLL_cudart,#name \
) \
) == NULL \
) { \
nlError("nlInitExtension_CUDA: function not found", #name); \
return NL_FALSE; \
}
/* CUBLAS structures and functions */
struct cublasContext;
typedef struct cublasContext *cublasHandle_t;
typedef int cublasStatus_t;
typedef enum {
CUBLAS_SIDE_LEFT =0,
CUBLAS_SIDE_RIGHT=1
} cublasSideMode_t;
typedef enum {
CUBLAS_FILL_MODE_LOWER=0,
CUBLAS_FILL_MODE_UPPER=1
} cublasFillMode_t;
typedef enum {
CUBLAS_OP_N=0,
CUBLAS_OP_T=1,
CUBLAS_OP_C=2
} cublasOperation_t;
typedef enum {
CUBLAS_DIAG_NON_UNIT=0,
CUBLAS_DIAG_UNIT=1
} cublasDiagType_t;
typedef cublasStatus_t (*FUNPTR_cublasCreate)(cublasHandle_t* handle);
typedef cublasStatus_t (*FUNPTR_cublasDestroy)(cublasHandle_t handle);
typedef cublasStatus_t (*FUNPTR_cublasGetVersion)(
cublasHandle_t handle, int* version
);
typedef cublasStatus_t (*FUNPTR_cublasDdot)(
cublasHandle_t handle, int n,
const double *x, int incx,
const double *y, int incy,
double *result
);
typedef cublasStatus_t (*FUNPTR_cublasDcopy)(
cublasHandle_t handle, int n,
const double *x, int incx,
const double *y, int incy
);
typedef cublasStatus_t (*FUNPTR_cublasDaxpy)(
cublasHandle_t handle, int n,
const double* alpha,
const double *x, int incx,
const double *y, int incy
);
typedef cublasStatus_t (*FUNPTR_cublasDscal)(
cublasHandle_t handle, int n,
const double* alpha,
const double *x, int incx
);
typedef cublasStatus_t (*FUNPTR_cublasDnrm2)(
cublasHandle_t handle, int n,
const double *x, int incx,
double* result
);
typedef cublasStatus_t (*FUNPTR_cublasDdgmm)(
cublasHandle_t handle, cublasSideMode_t mode,
int m, int n,
const double* A, int lda,
const double* x, int incx,
double* C, int ldc
);
typedef cublasStatus_t (*FUNPTR_cublasDgemv)(
cublasHandle_t handle,
cublasOperation_t trans,
int m,
int n,
const double *alpha,
const double *A,
int lda,
const double *x,
int incx,
const double *beta,
double *y,
int incy
);
typedef cublasStatus_t (*FUNPTR_cublasDtpsv)(
cublasHandle_t handle, cublasFillMode_t uplo,
cublasOperation_t trans, cublasDiagType_t diag,
int n, const double *AP,
double* x, int incx
);
#define find_cublas_func(name) \
if( \
( \
CUDA()->name = \
(FUNPTR_##name)nlFindFunction( \
CUDA()->DLL_cublas,#name "_v2" \
) \
) == NULL \
) { \
nlError("nlInitExtension_CUDA: function not found", #name); \
return NL_FALSE; \
}
#define find_cublas_func_v1(name) \
if( \
( \
CUDA()->name = \
(FUNPTR_##name)nlFindFunction( \
CUDA()->DLL_cublas,#name \
) \
) == NULL \
) { \
nlError("nlInitExtension_CUDA: function not found", #name); \
return NL_FALSE; \
}
/* CUSPARSE structures and functions */
struct cusparseContext;
typedef struct cusparseContext *cusparseHandle_t;
typedef int cusparseStatus_t;
struct cusparseMatDescr;
typedef struct cusparseMatDescr *cusparseMatDescr_t;
typedef enum {
CUSPARSE_MATRIX_TYPE_GENERAL = 0,
CUSPARSE_MATRIX_TYPE_SYMMETRIC = 1,
CUSPARSE_MATRIX_TYPE_HERMITIAN = 2,
CUSPARSE_MATRIX_TYPE_TRIANGULAR = 3
} cusparseMatrixType_t;
typedef enum {
CUSPARSE_INDEX_BASE_ZERO = 0,
CUSPARSE_INDEX_BASE_ONE = 1
} cusparseIndexBase_t;
typedef enum {
CUSPARSE_OPERATION_NON_TRANSPOSE = 0,
CUSPARSE_OPERATION_TRANSPOSE = 1,
CUSPARSE_OPERATION_CONJUGATE_TRANSPOSE = 2
} cusparseOperation_t;
struct cusparseHybMat;
typedef struct cusparseHybMat *cusparseHybMat_t;
typedef enum {
CUSPARSE_HYB_PARTITION_AUTO = 0,
CUSPARSE_HYB_PARTITION_USER = 1,
CUSPARSE_HYB_PARTITION_MAX = 2
} cusparseHybPartition_t;
typedef cusparseStatus_t (*FUNPTR_cusparseCreate)(cusparseHandle_t* handle);
typedef cusparseStatus_t (*FUNPTR_cusparseDestroy)(cusparseHandle_t handle);
typedef cusparseStatus_t (*FUNPTR_cusparseGetVersion)(
cusparseHandle_t handle, int* version
);
typedef cusparseStatus_t (*FUNPTR_cusparseCreateMatDescr)(
cusparseMatDescr_t* descr
);
typedef cusparseStatus_t (*FUNPTR_cusparseDestroyMatDescr)(
cusparseMatDescr_t descr
);
typedef cusparseStatus_t (*FUNPTR_cusparseSetMatType)(
cusparseMatDescr_t descr, cusparseMatrixType_t mtype
);
typedef cusparseStatus_t (*FUNPTR_cusparseSetMatIndexBase)(
cusparseMatDescr_t descr, cusparseIndexBase_t ibase
);
typedef cusparseStatus_t (*FUNPTR_cusparseDcsrmv)(
cusparseHandle_t handle, cusparseOperation_t transA,
int m, int n, int nnz,
const double *alpha, const cusparseMatDescr_t descrA,
const double *csrSortedValA, const int *csrSortedRowPtrA,
const int *csrSortedColIndA, const double *x,
const double *beta, double *y
);
typedef cusparseStatus_t (*FUNPTR_cusparseCreateHybMat)(
cusparseHybMat_t *hybA
);
typedef cusparseStatus_t (*FUNPTR_cusparseDestroyHybMat)(
cusparseHybMat_t hybA
);
typedef cusparseStatus_t (*FUNPTR_cusparseDcsr2hyb)(
cusparseHandle_t handle,
int m,
int n,
const cusparseMatDescr_t descrA,
const double *csrSortedValA,
const int *csrSortedRowPtrA,
const int *csrSortedColIndA,
cusparseHybMat_t hybA,
int userEllWidth,
cusparseHybPartition_t partitionType
);
typedef cusparseStatus_t (*FUNPTR_cusparseDhybmv)(
cusparseHandle_t handle,
cusparseOperation_t transA,
const double *alpha,
const cusparseMatDescr_t descrA,
const cusparseHybMat_t hybA,
const double *x,
const double *beta,
double *y
);
#define find_cusparse_func(name) \
if( \
( \
CUDA()->name = \
(FUNPTR_##name)nlFindFunction( \
CUDA()->DLL_cusparse,#name \
) \
) == NULL \
) { \
nlError("nlInitExtension_CUDA : function not found", #name); \
return NL_FALSE; \
}
typedef struct {
NLdll DLL_cudart;
FUNPTR_cudaGetDeviceCount cudaGetDeviceCount;
FUNPTR_cudaGetDeviceProperties cudaGetDeviceProperties;
FUNPTR_cudaDeviceReset cudaDeviceReset;
FUNPTR_cudaMalloc cudaMalloc;
FUNPTR_cudaFree cudaFree;
FUNPTR_cudaMemcpy cudaMemcpy;
NLdll DLL_cublas;
cublasHandle_t HNDL_cublas;
FUNPTR_cublasCreate cublasCreate;
FUNPTR_cublasDestroy cublasDestroy;
FUNPTR_cublasGetVersion cublasGetVersion;
FUNPTR_cublasDdot cublasDdot;
FUNPTR_cublasDcopy cublasDcopy;
FUNPTR_cublasDaxpy cublasDaxpy;
FUNPTR_cublasDscal cublasDscal;
FUNPTR_cublasDnrm2 cublasDnrm2;
FUNPTR_cublasDdgmm cublasDdgmm;
FUNPTR_cublasDgemv cublasDgemv;
FUNPTR_cublasDtpsv cublasDtpsv;
NLdll DLL_cusparse;
cusparseHandle_t HNDL_cusparse;
FUNPTR_cusparseCreate cusparseCreate;
FUNPTR_cusparseDestroy cusparseDestroy;
FUNPTR_cusparseGetVersion cusparseGetVersion;
FUNPTR_cusparseCreateMatDescr cusparseCreateMatDescr;
FUNPTR_cusparseDestroyMatDescr cusparseDestroyMatDescr;
FUNPTR_cusparseSetMatType cusparseSetMatType;
FUNPTR_cusparseSetMatIndexBase cusparseSetMatIndexBase;
FUNPTR_cusparseDcsrmv cusparseDcsrmv;
FUNPTR_cusparseCreateHybMat cusparseCreateHybMat;
FUNPTR_cusparseDestroyHybMat cusparseDestroyHybMat;
FUNPTR_cusparseDcsr2hyb cusparseDcsr2hyb;
FUNPTR_cusparseDhybmv cusparseDhybmv;
int devID;
} CUDAContext;
static CUDAContext* CUDA() {
static CUDAContext context;
static NLboolean init = NL_FALSE;
if(!init) {
init = NL_TRUE;
memset(&context, 0, sizeof(context));
}
return &context;
}
NLboolean nlExtensionIsInitialized_CUDA() {
if(
CUDA()->DLL_cudart == NULL ||
CUDA()->cudaGetDeviceCount == NULL ||
CUDA()->cudaGetDeviceProperties == NULL ||
CUDA()->cudaDeviceReset == NULL ||
CUDA()->cudaMalloc == NULL ||
CUDA()->cudaFree == NULL ||
CUDA()->cudaMemcpy == NULL ||
CUDA()->DLL_cublas == NULL ||
CUDA()->HNDL_cublas == NULL ||
CUDA()->cublasCreate == NULL ||
CUDA()->cublasDestroy == NULL ||
CUDA()->cublasGetVersion == NULL ||
CUDA()->cublasDdot == NULL ||
CUDA()->cublasDcopy == NULL ||
CUDA()->cublasDaxpy == NULL ||
CUDA()->cublasDscal == NULL ||
CUDA()->cublasDnrm2 == NULL ||
CUDA()->cublasDdgmm == NULL ||
CUDA()->DLL_cusparse == NULL ||
CUDA()->HNDL_cusparse == NULL ||
CUDA()->cusparseCreate == NULL ||
CUDA()->cusparseDestroy == NULL ||
CUDA()->cusparseGetVersion == NULL ||
CUDA()->cusparseCreateMatDescr == NULL ||
CUDA()->cusparseDestroyMatDescr == NULL ||
CUDA()->cusparseSetMatType == NULL ||
CUDA()->cusparseSetMatIndexBase == NULL ||
CUDA()->cusparseDcsrmv == NULL ||
CUDA()->cusparseCreateHybMat == NULL ||
CUDA()->cusparseDestroyHybMat == NULL ||
CUDA()->cusparseDcsr2hyb == NULL ||
CUDA()->cusparseDhybmv == NULL
) {
return NL_FALSE;
}
return NL_TRUE;
}
static void nlTerminateExtension_CUDA(void) {
if(!nlExtensionIsInitialized_CUDA()) {
return;
}
CUDA()->cusparseDestroy(CUDA()->HNDL_cusparse);
nlCloseDLL(CUDA()->DLL_cusparse);
CUDA()->cublasDestroy(CUDA()->HNDL_cublas);
nlCloseDLL(CUDA()->DLL_cublas);
CUDA()->cudaDeviceReset();
nlCloseDLL(CUDA()->DLL_cudart);
}
static int ConvertSMVer2Cores(int major, int minor) {
/* Defines for GPU Architecture types (using the SM version
to determine the # of cores per SM */
typedef struct {
int SM; /* 0xMm (hexadecimal notation),
M = SM Major version,
and m = SM minor version */
int Cores;
} sSMtoCores;
sSMtoCores nGpuArchCoresPerSM[] = {
{ 0x10, 8 }, /* Tesla Generation (SM 1.0) G80 class */
{ 0x11, 8 }, /* Tesla Generation (SM 1.1) G8x class */
{ 0x12, 8 }, /* Tesla Generation (SM 1.2) G9x class */
{ 0x13, 8 }, /* Tesla Generation (SM 1.3) GT200 class */
{ 0x20, 32 }, /* Fermi Generation (SM 2.0) GF100 class */
{ 0x21, 48 }, /* Fermi Generation (SM 2.1) GF10x class */
{ 0x30, 192}, /* Kepler Generation (SM 3.0) GK10x class */
{ 0x35, 192}, /* Kepler Generation (SM 3.5) GK11x class */
{ 0x50, 128}, /* Maxwell Generation (SM 5.0) GM10x class
(yes, #cores smaller than with 3.x) */
{ 0x52, 128}, /* Maxwell Generation (SM 5.2) GM20x class */
{ 0x60, 64 }, /* Pascal Generation (SM 6.0) GP100,GP102
(yes, 64, but GP100 has superfast double precision) */
{ 0x61, 128}, /* Pascal Generation (SM 6.1) GP104 class
(but FP64 runs as 1/32 FP32 speed) */
{ -1, -1 }
};
int index = 0;
while (nGpuArchCoresPerSM[index].SM != -1) {
if (nGpuArchCoresPerSM[index].SM == ((major << 4) + minor)) {
return nGpuArchCoresPerSM[index].Cores;
}
index++;
}
/* If we don't find the values, we default use the
previous one to run properly */
nl_printf(
"MapSMtoCores for SM %d.%d is undefined. Default to use %d Cores/SM\n",
major, minor, nGpuArchCoresPerSM[8].Cores
);
return nGpuArchCoresPerSM[8].Cores;
}
static int getBestDeviceID() {
int current_device = 0, sm_per_multiproc = 0;
int max_compute_perf = 0, max_perf_device = 0;
int device_count = 0, best_SM_arch = 0;
int compute_perf = 0;
struct cudaDeviceProp deviceProp;
CUDA()->cudaGetDeviceCount(&device_count);
/* Find the best major SM Architecture GPU device */
while (current_device < device_count) {
CUDA()->cudaGetDeviceProperties(&deviceProp, current_device);
/* If this GPU is not running on Compute Mode prohibited,
then we can add it to the list */
if (deviceProp.computeMode != cudaComputeModeProhibited) {
if (deviceProp.major > 0 && deviceProp.major < 9999) {
best_SM_arch = MAX(best_SM_arch, deviceProp.major);
}
}
current_device++;
}
/* Find the best CUDA capable GPU device */
current_device = 0;
while (current_device < device_count) {
CUDA()->cudaGetDeviceProperties(&deviceProp, current_device);
/* If this GPU is not running on Compute Mode prohibited,
then we can add it to the list */
if (deviceProp.computeMode != cudaComputeModeProhibited) {
if (deviceProp.major == 9999 && deviceProp.minor == 9999) {
sm_per_multiproc = 1;
} else {
sm_per_multiproc = ConvertSMVer2Cores(
deviceProp.major, deviceProp.minor
);
}
compute_perf =
deviceProp.multiProcessorCount *
sm_per_multiproc * deviceProp.clockRate;
if (compute_perf > max_compute_perf) {
/* If we find GPU with SM major > 2, search only these */
if (best_SM_arch > 2) {
/* If our device==dest_SM_arch, choose this, or else pass */
if (deviceProp.major == best_SM_arch) {
max_compute_perf = compute_perf;
max_perf_device = current_device;
}
} else {
max_compute_perf = compute_perf;
max_perf_device = current_device;
}
}
}
++current_device;
}
return max_perf_device;
}
#ifdef NL_OS_UNIX
# define LIBPREFIX "lib"
# ifdef NL_OS_APPLE
# define LIBEXTENSION ".dylib"
# else
# define LIBEXTENSION ".so"
# endif
#else
# define LIBPREFIX
# define LIBEXTENSION ".dll"
#endif
NLboolean nlInitExtension_CUDA(void) {
struct cudaDeviceProp deviceProp;
int cublas_version;
int cusparse_version;
NLenum flags = NL_LINK_LAZY | NL_LINK_GLOBAL;
if(nlCurrentContext == NULL || !nlCurrentContext->verbose) {
flags |= NL_LINK_QUIET;
}
if(nlExtensionIsInitialized_CUDA()) {
return NL_TRUE;
}
CUDA()->DLL_cudart = nlOpenDLL(
LIBPREFIX "cudart" LIBEXTENSION, flags
);
find_cuda_func(cudaGetDeviceCount);
find_cuda_func(cudaGetDeviceProperties);
find_cuda_func(cudaDeviceReset);
find_cuda_func(cudaMalloc);
find_cuda_func(cudaFree);
find_cuda_func(cudaMemcpy);
CUDA()->devID = getBestDeviceID();
if(CUDA()->cudaGetDeviceProperties(&deviceProp, CUDA()->devID)) {
nl_fprintf(stderr,"OpenNL CUDA: could not find a CUDA device\n");
return NL_FALSE;
}
nl_printf("OpenNL CUDA: Device ID = %d\n", CUDA()->devID);
nl_printf("OpenNL CUDA: Device name=%s\n", deviceProp.name);
nl_printf(
"OpenNL CUDA: Device has %d Multi-Processors, "
"%d cores per Multi-Processor, SM %d.%d compute capabilities\n",
deviceProp.multiProcessorCount,
ConvertSMVer2Cores(deviceProp.major, deviceProp.minor),
deviceProp.major, deviceProp.minor
);
nl_printf(
"OpenNL CUDA: %d kB shared mem. per block, %d per MP\n",
(int)(deviceProp.sharedMemPerBlock / 1024),
(int)(deviceProp.sharedMemPerMultiprocessor / 1024)
);
nl_printf(
"OpenNL CUDA: %d regs. per block, %d per MP\n",
deviceProp.regsPerBlock,
deviceProp.regsPerMultiprocessor
);
nl_printf(
"OpenNL CUDA: warpsize=%d\n",
deviceProp.warpSize
);
if ((deviceProp.major * 0x10 + deviceProp.minor) < 0x11) {
nl_fprintf(stderr, "OpenNL CUDA requires a minimum CUDA compute 1.1 capability\n");
CUDA()->cudaDeviceReset();
return NL_FALSE;
}
CUDA()->DLL_cublas = nlOpenDLL(
LIBPREFIX "cublas" LIBEXTENSION, flags
);
find_cublas_func(cublasCreate);
find_cublas_func(cublasDestroy);
find_cublas_func(cublasGetVersion);
find_cublas_func(cublasDdot);
find_cublas_func(cublasDaxpy);
find_cublas_func(cublasDcopy);
find_cublas_func(cublasDscal);
find_cublas_func(cublasDnrm2);
find_cublas_func(cublasDgemv);
find_cublas_func(cublasDtpsv);
find_cublas_func_v1(cublasDdgmm);
if(CUDA()->cublasCreate(&CUDA()->HNDL_cublas)) {
return NL_FALSE;
}
if(CUDA()->cublasGetVersion(CUDA()->HNDL_cublas, &cublas_version)) {
return NL_FALSE;
}
nl_printf("OpenNL CUDA: cublas version = %d\n", cublas_version);
CUDA()->DLL_cusparse = nlOpenDLL(
LIBPREFIX "cusparse" LIBEXTENSION, flags
);
find_cusparse_func(cusparseCreate);
find_cusparse_func(cusparseDestroy);
find_cusparse_func(cusparseGetVersion);
find_cusparse_func(cusparseCreateMatDescr);
find_cusparse_func(cusparseDestroyMatDescr);
find_cusparse_func(cusparseSetMatType);
find_cusparse_func(cusparseSetMatIndexBase);
find_cusparse_func(cusparseDcsrmv);
find_cusparse_func(cusparseCreateHybMat);
find_cusparse_func(cusparseDestroyHybMat);
find_cusparse_func(cusparseDcsr2hyb);
find_cusparse_func(cusparseDhybmv);
if(CUDA()->cusparseCreate(&CUDA()->HNDL_cusparse)) {
return NL_FALSE;
}
if(CUDA()->cusparseGetVersion(CUDA()->HNDL_cusparse, &cusparse_version)) {
return NL_FALSE;
}
nl_printf("OpenNL CUDA: cusparse version = %d\n", cusparse_version);
if(!nlExtensionIsInitialized_CUDA()) {
return NL_FALSE;
}
atexit(nlTerminateExtension_CUDA);
return NL_TRUE;
}
static void nlCUDACheckImpl(int status, int line) {
if(status != 0) {
nl_fprintf(stderr,"nl_cuda.c:%d fatal error %d\n",line, status);
CUDA()->cudaDeviceReset();
exit(-1);
}
}
#define nlCUDACheck(status) nlCUDACheckImpl(status, __LINE__)
typedef struct {
NLuint m;
NLuint n;
NLenum type;
NLDestroyMatrixFunc destroy_func;
NLMultMatrixVectorFunc mult_func;
cusparseMatDescr_t descr;
NLuint nnz;
int* colind;
int* rowptr;
double* val;
cusparseHybMat_t hyb;
} NLCUDASparseMatrix;
static void nlCRSMatrixCUDADestroyCRS(NLCUDASparseMatrix* Mcuda) {
if(Mcuda->colind != NULL) {
nlCUDACheck(CUDA()->cudaFree(Mcuda->colind));
Mcuda->colind = NULL;
}
if(Mcuda->rowptr != NULL) {
nlCUDACheck(CUDA()->cudaFree(Mcuda->rowptr));
Mcuda->rowptr = NULL;
}
if(Mcuda->val != NULL) {
nlCUDACheck(CUDA()->cudaFree(Mcuda->val));
Mcuda->val = NULL;
}
}
static void nlCRSMatrixCUDADestroy(NLCUDASparseMatrix* Mcuda) {
if(Mcuda->hyb != NULL) {
nlCUDACheck(CUDA()->cusparseDestroyHybMat(Mcuda->hyb));
}
nlCRSMatrixCUDADestroyCRS(Mcuda);
nlCUDACheck(CUDA()->cusparseDestroyMatDescr(Mcuda->descr));
memset(Mcuda, 0, sizeof(*Mcuda));
}
static void nlCRSMatrixCUDAMult(
NLCUDASparseMatrix* Mcuda, const double* x, double* y
) {
const double one = 1;
const double zero = 0;
if(Mcuda->hyb != NULL) {
nlCUDACheck(
CUDA()->cusparseDhybmv(
CUDA()->HNDL_cusparse,
CUSPARSE_OPERATION_NON_TRANSPOSE,
&one,
Mcuda->descr,
Mcuda->hyb,
x,
&zero,
y
)
);
} else {
nlCUDACheck(
CUDA()->cusparseDcsrmv(
CUDA()->HNDL_cusparse,
CUSPARSE_OPERATION_NON_TRANSPOSE,
(int)Mcuda->m,
(int)Mcuda->n,
(int)Mcuda->nnz,
&one,
Mcuda->descr,
Mcuda->val,
Mcuda->rowptr,
Mcuda->colind,
x,
&zero,
y
)
);
}
nlCUDABlas()->flops += (NLulong)(2*Mcuda->nnz);
}
NLMatrix nlCUDAMatrixNewFromCRSMatrix(NLMatrix M_in) {
NLCUDASparseMatrix* Mcuda = NL_NEW(NLCUDASparseMatrix);
NLCRSMatrix* M = (NLCRSMatrix*)(M_in);
size_t colind_sz, rowptr_sz, val_sz;
nl_assert(M_in->type == NL_MATRIX_CRS);
nlCUDACheck(CUDA()->cusparseCreateMatDescr(&Mcuda->descr));
if(M->symmetric_storage) {
nlCUDACheck(CUDA()->cusparseSetMatType(
Mcuda->descr, CUSPARSE_MATRIX_TYPE_SYMMETRIC)
);
} else {
nlCUDACheck(CUDA()->cusparseSetMatType(
Mcuda->descr, CUSPARSE_MATRIX_TYPE_GENERAL)
);
}
nlCUDACheck(CUDA()->cusparseSetMatIndexBase(
Mcuda->descr, CUSPARSE_INDEX_BASE_ZERO)
);
Mcuda->m = M->m;
Mcuda->n = M->n;
Mcuda->nnz = nlCRSMatrixNNZ(M);
colind_sz = (size_t)Mcuda->nnz*sizeof(int);
rowptr_sz = (size_t)(Mcuda->m+1)*sizeof(int);
val_sz = (size_t)Mcuda->nnz*sizeof(double);
nlCUDACheck(CUDA()->cudaMalloc((void**)&Mcuda->colind,colind_sz));
nlCUDACheck(CUDA()->cudaMalloc((void**)&Mcuda->rowptr,rowptr_sz));
nlCUDACheck(CUDA()->cudaMalloc((void**)&Mcuda->val,val_sz));
nlCUDACheck(CUDA()->cudaMemcpy(
Mcuda->colind, M->colind, colind_sz, cudaMemcpyHostToDevice)
);
nlCUDACheck(CUDA()->cudaMemcpy(
Mcuda->rowptr, M->rowptr, rowptr_sz, cudaMemcpyHostToDevice)
);
nlCUDACheck(CUDA()->cudaMemcpy(
Mcuda->val, M->val, val_sz, cudaMemcpyHostToDevice)
);
Mcuda->hyb=NULL;
if(!M->symmetric_storage) {
nlCUDACheck(CUDA()->cusparseCreateHybMat(&Mcuda->hyb));
nlCUDACheck(CUDA()->cusparseDcsr2hyb(
CUDA()->HNDL_cusparse,
(int)M->m,
(int)M->n,
Mcuda->descr,
Mcuda->val,
Mcuda->rowptr,
Mcuda->colind,
Mcuda->hyb,
0,
CUSPARSE_HYB_PARTITION_AUTO
));
/* We no longer need the CRS part */
nlCRSMatrixCUDADestroyCRS(Mcuda);
}
Mcuda->type=NL_MATRIX_OTHER;
Mcuda->destroy_func=(NLDestroyMatrixFunc)nlCRSMatrixCUDADestroy;
Mcuda->mult_func=(NLMultMatrixVectorFunc)nlCRSMatrixCUDAMult;
return (NLMatrix)Mcuda;
}
typedef struct {
NLuint m;
NLuint n;
NLenum type;
NLDestroyMatrixFunc destroy_func;
NLMultMatrixVectorFunc mult_func;
double* val;
} NLDiagonalMatrixCUDA;
static void nlDiagonalMatrixCUDADestroy(NLDiagonalMatrixCUDA* Mcuda) {
nlCUDACheck(CUDA()->cudaFree(Mcuda->val));
memset(Mcuda, 0, sizeof(*Mcuda));
}
static void nlDiagonalMatrixCUDAMult(
NLDiagonalMatrixCUDA* Mcuda, const double* x, double* y
) {
int N = (int)Mcuda->n;
/*
* vector x vector component-wise product implemented
* using diagonal matrix x matrix function.
*/
nlCUDACheck(CUDA()->cublasDdgmm(
CUDA()->HNDL_cublas, CUBLAS_SIDE_LEFT,
N, 1,
x, N,
Mcuda->val, 1,
y, N
));
nlCUDABlas()->flops += (NLulong)N;
}
static NLMatrix nlDiagonalMatrixCUDANew(const double* diag, NLuint n) {
NLDiagonalMatrixCUDA* Mcuda = NL_NEW(NLDiagonalMatrixCUDA);
Mcuda->m = n;
Mcuda->n = n;
Mcuda->type = NL_MATRIX_OTHER;
nlCUDACheck(CUDA()->cudaMalloc(
(void**)&Mcuda->val, n*sizeof(double))
);
nlCUDACheck(CUDA()->cudaMemcpy(
Mcuda->val, diag, n*sizeof(double), cudaMemcpyHostToDevice)
);
Mcuda->destroy_func=(NLDestroyMatrixFunc)nlDiagonalMatrixCUDADestroy;
Mcuda->mult_func=(NLMultMatrixVectorFunc)nlDiagonalMatrixCUDAMult;
return (NLMatrix)Mcuda;
}
NLMatrix nlCUDAJacobiPreconditionerNewFromCRSMatrix(NLMatrix M_in) {
NLuint N = M_in->n;
NLuint i,jj;
double* diag = NULL;
NLMatrix result = NULL;
NLCRSMatrix* M = (NLCRSMatrix*)(M_in);
nl_assert(M_in->type == NL_MATRIX_CRS);
diag = NL_NEW_ARRAY(double,N);
for(i=0; i<N; ++i) {
for(jj=M->rowptr[i]; jj<M->rowptr[i+1]; ++jj) {
if(M->colind[jj] == i) {
diag[i] = M->val[jj];
}
}
}
for(i=0; i<N; ++i) {
diag[i] = ((diag[i] == 0.0) ? 1.0 : 1.0 / diag[i]);
}
result = nlDiagonalMatrixCUDANew(diag, N);
NL_DELETE_ARRAY(diag);
return result;
}
static void* cuda_blas_malloc(
NLBlas_t blas, NLmemoryType type, size_t size
) {
void* result = NULL;
blas->used_ram[type] += (NLulong)size;
blas->max_used_ram[type] = MAX(
blas->max_used_ram[type],blas->used_ram[type]
);
if(type == NL_HOST_MEMORY) {
result = malloc(size);
} else {
nlCUDACheck(CUDA()->cudaMalloc(&result,size));
}
return result;
}
static void cuda_blas_free(
NLBlas_t blas, NLmemoryType type, size_t size, void* ptr
) {
blas->used_ram[type] -= (NLulong)size;
if(type == NL_HOST_MEMORY) {
free(ptr);
} else {
nlCUDACheck(CUDA()->cudaFree(ptr));
}
}
static void cuda_blas_memcpy(
NLBlas_t blas,
void* to, NLmemoryType to_type,
void* from, NLmemoryType from_type,
size_t size
) {
enum cudaMemcpyKind kind = cudaMemcpyDefault;
nl_arg_used(blas);
if(from_type == NL_HOST_MEMORY) {
if(to_type == NL_HOST_MEMORY) {
kind = cudaMemcpyHostToHost;
} else {
kind = cudaMemcpyHostToDevice;
}
} else {
if(to_type == NL_HOST_MEMORY) {
kind = cudaMemcpyDeviceToHost;
} else {
kind = cudaMemcpyDeviceToDevice;
}
}
nlCUDACheck(CUDA()->cudaMemcpy(to, from, size, kind));
}
static void cuda_blas_dcopy(
NLBlas_t blas, int n, const double *x, int incx, double *y, int incy
) {
nl_arg_used(blas);
CUDA()->cublasDcopy(CUDA()->HNDL_cublas,n,x,incx,y,incy);
}
static double cuda_blas_ddot(
NLBlas_t blas, int n, const double *x, int incx, const double *y, int incy
) {
double result = 0.0;
blas->flops += (NLulong)(2*n);
CUDA()->cublasDdot(CUDA()->HNDL_cublas,n,x,incx,y,incy,&result);
return result;
}
static double cuda_blas_dnrm2(
NLBlas_t blas, int n, const double *x, int incx
) {
double result = 0.0;
blas->flops += (NLulong)(2*n);
CUDA()->cublasDnrm2(CUDA()->HNDL_cublas,n,x,incx,&result);
return result;
}
static void cuda_blas_daxpy(
NLBlas_t blas, int n,
double a, const double *x, int incx, double *y, int incy
) {
blas->flops += (NLulong)(2*n);
CUDA()->cublasDaxpy(CUDA()->HNDL_cublas,n,&a,x,incx,y,incy);
}
static void cuda_blas_dscal(
NLBlas_t blas, int n, double a, double *x, int incx
) {
blas->flops += (NLulong)n;
CUDA()->cublasDscal(CUDA()->HNDL_cublas,n,&a,x,incx);
}
static void cuda_blas_dgemv(
NLBlas_t blas, MatrixTranspose trans, int m, int n, double alpha,
const double *A, int ldA, const double *x, int incx,
double beta, double *y, int incy
) {
nl_arg_used(blas);
/* TODO: update FLOPS */
CUDA()->cublasDgemv(
CUDA()->HNDL_cublas, (cublasOperation_t)trans,
m, n, &alpha, A, ldA, x, incx, &beta, y, incy
);
}
static void cuda_blas_dtpsv(
NLBlas_t blas, MatrixTriangle uplo, MatrixTranspose trans,
MatrixUnitTriangular diag, int n, const double *AP,
double *x, int incx
) {
nl_arg_used(blas);
/* TODO: update FLOPS */
CUDA()->cublasDtpsv(
CUDA()->HNDL_cublas,
(cublasFillMode_t)uplo,
(cublasOperation_t)trans,
(cublasDiagType_t)diag, n,
AP, x, incx
);
}
NLBlas_t nlCUDABlas() {
static NLboolean initialized = NL_FALSE;
static struct NLBlas blas;
if(!initialized) {
memset(&blas, 0, sizeof(blas));
blas.has_unified_memory = NL_FALSE;
blas.Malloc = cuda_blas_malloc;
blas.Free = cuda_blas_free;
blas.Memcpy = cuda_blas_memcpy;
blas.Dcopy = cuda_blas_dcopy;
blas.Ddot = cuda_blas_ddot;
blas.Dnrm2 = cuda_blas_dnrm2;
blas.Daxpy = cuda_blas_daxpy;
blas.Dscal = cuda_blas_dscal;
blas.Dgemv = cuda_blas_dgemv;
blas.Dtpsv = cuda_blas_dtpsv;
nlBlasResetStats(&blas);
initialized = NL_TRUE;
}
return &blas;
}
/******* extracted from nl_api.c *******/
static NLSparseMatrix* nlGetCurrentSparseMatrix() {
NLSparseMatrix* result = NULL;
switch(nlCurrentContext->matrix_mode) {
case NL_STIFFNESS_MATRIX: {
nl_assert(nlCurrentContext->M != NULL);
nl_assert(nlCurrentContext->M->type == NL_MATRIX_SPARSE_DYNAMIC);
result = (NLSparseMatrix*)(nlCurrentContext->M);
} break;
case NL_MASS_MATRIX: {
nl_assert(nlCurrentContext->B != NULL);
nl_assert(nlCurrentContext->B->type == NL_MATRIX_SPARSE_DYNAMIC);
result = (NLSparseMatrix*)(nlCurrentContext->B);
} break;
default:
nl_assert_not_reached;
}
return result;
}
NLboolean nlInitExtension(const char* extension) {
if(!strcmp(extension, "SUPERLU")) {
return nlInitExtension_SUPERLU();
} else if(!strcmp(extension, "CHOLMOD")) {
return nlInitExtension_CHOLMOD();
} else if(!strcmp(extension, "ARPACK")) {
/*
* SUPERLU is needed by OpenNL's ARPACK driver
* (factorizes the matrix for the shift-invert spectral
* transform).
*/
return nlInitExtension_SUPERLU() && nlInitExtension_ARPACK();
} else if(!strcmp(extension, "MKL")) {
return nlInitExtension_MKL();
} else if(!strcmp(extension, "CUDA")) {
return nlInitExtension_CUDA();
}
return NL_FALSE;
}
NLboolean nlExtensionIsInitialized(const char* extension) {
if(!strcmp(extension, "SUPERLU")) {
return nlExtensionIsInitialized_SUPERLU();
} else if(!strcmp(extension, "CHOLMOD")) {
return nlExtensionIsInitialized_CHOLMOD();
} else if(!strcmp(extension, "ARPACK")) {
/*
* SUPERLU is needed by OpenNL's ARPACK driver
* (factorizes the matrix for the shift-invert spectral
* transform).
*/
return nlExtensionIsInitialized_SUPERLU() && nlExtensionIsInitialized_ARPACK();
} else if(!strcmp(extension, "MKL")) {
return nlExtensionIsInitialized_MKL();
} else if(!strcmp(extension, "CUDA")) {
return nlExtensionIsInitialized_CUDA();
}
return NL_FALSE;
}
void nlInitialize(int argc, char** argv) {
int i=0;
char* ptr=NULL;
char extension[255];
/* Find all the arguments with the form:
* nl:<extension>=true|false
* and try to activate the corresponding extensions.
*/
for(i=1; i<argc; ++i) {
ptr = strstr(argv[i],"=true");
if(!strncmp(argv[i], "nl:", 3) &&
(strlen(argv[i]) > 3) &&
(ptr != NULL)) {
strncpy(extension, argv[i]+3, (size_t)(ptr-argv[i]-3));
extension[(size_t)(ptr-argv[i]-3)] = '\0';
if(nlInitExtension(extension)) {
nl_fprintf(stdout,"OpenNL %s: initialized\n", extension);
} else {
nl_fprintf(stderr,"OpenNL %s: could not initialize\n", extension);
}
}
}
}
/* Get/Set parameters */
void nlSolverParameterd(NLenum pname, NLdouble param) {
nlCheckState(NL_STATE_INITIAL);
switch(pname) {
case NL_THRESHOLD: {
nl_assert(param >= 0);
nlCurrentContext->threshold = (NLdouble)param;
nlCurrentContext->threshold_defined = NL_TRUE;
} break;
case NL_OMEGA: {
nl_range_assert(param,1.0,2.0);
nlCurrentContext->omega = (NLdouble)param;
} break;
default: {
nlError("nlSolverParameterd","Invalid parameter");
nl_assert_not_reached;
}
}
}
void nlSolverParameteri(NLenum pname, NLint param) {
nlCheckState(NL_STATE_INITIAL);
switch(pname) {
case NL_SOLVER: {
nlCurrentContext->solver = (NLenum)param;
} break;
case NL_NB_VARIABLES: {
nl_assert(param > 0);
nlCurrentContext->nb_variables = (NLuint)param;
} break;
case NL_NB_SYSTEMS: {
nl_assert(param > 0);
nlCurrentContext->nb_systems = (NLuint)param;
} break;
case NL_LEAST_SQUARES: {
nlCurrentContext->least_squares = (NLboolean)param;
} break;
case NL_MAX_ITERATIONS: {
nl_assert(param > 0);
nlCurrentContext->max_iterations = (NLuint)param;
nlCurrentContext->max_iterations_defined = NL_TRUE;
} break;
case NL_SYMMETRIC: {
nlCurrentContext->symmetric = (NLboolean)param;
} break;
case NL_INNER_ITERATIONS: {
nl_assert(param > 0);
nlCurrentContext->inner_iterations = (NLuint)param;
} break;
case NL_PRECONDITIONER: {
nlCurrentContext->preconditioner = (NLuint)param;
nlCurrentContext->preconditioner_defined = NL_TRUE;
} break;
default: {
nlError("nlSolverParameteri","Invalid parameter");
nl_assert_not_reached;
}
}
}
void nlGetBooleanv(NLenum pname, NLboolean* params) {
switch(pname) {
case NL_LEAST_SQUARES: {
*params = nlCurrentContext->least_squares;
} break;
case NL_SYMMETRIC: {
*params = nlCurrentContext->symmetric;
} break;
default: {
nlError("nlGetBooleanv","Invalid parameter");
nl_assert_not_reached;
}
}
}
void nlGetDoublev(NLenum pname, NLdouble* params) {
switch(pname) {
case NL_THRESHOLD: {
*params = nlCurrentContext->threshold;
} break;
case NL_OMEGA: {
*params = nlCurrentContext->omega;
} break;
case NL_ERROR: {
*params = nlCurrentContext->error;
} break;
case NL_ELAPSED_TIME: {
*params = nlCurrentContext->elapsed_time;
} break;
case NL_GFLOPS: {
if(nlCurrentContext->elapsed_time == 0) {
*params = 0.0;
} else {
*params = (NLdouble)(nlCurrentContext->flops) /
(nlCurrentContext->elapsed_time * 1e9);
}
} break;
default: {
nlError("nlGetDoublev","Invalid parameter");
nl_assert_not_reached;
}
}
}
void nlGetIntegerv(NLenum pname, NLint* params) {
switch(pname) {
case NL_SOLVER: {
*params = (NLint)(nlCurrentContext->solver);
} break;
case NL_NB_VARIABLES: {
*params = (NLint)(nlCurrentContext->nb_variables);
} break;
case NL_NB_SYSTEMS: {
*params = (NLint)(nlCurrentContext->nb_systems);
} break;
case NL_LEAST_SQUARES: {
*params = (NLint)(nlCurrentContext->least_squares);
} break;
case NL_MAX_ITERATIONS: {
*params = (NLint)(nlCurrentContext->max_iterations);
} break;
case NL_SYMMETRIC: {
*params = (NLint)(nlCurrentContext->symmetric);
} break;
case NL_USED_ITERATIONS: {
*params = (NLint)(nlCurrentContext->used_iterations);
} break;
case NL_PRECONDITIONER: {
*params = (NLint)(nlCurrentContext->preconditioner);
} break;
case NL_NNZ: {
*params = (NLint)(nlMatrixNNZ(nlCurrentContext->M));
} break;
default: {
nlError("nlGetIntegerv","Invalid parameter");
nl_assert_not_reached;
}
}
}
/* Enable / Disable */
void nlEnable(NLenum pname) {
switch(pname) {
case NL_NORMALIZE_ROWS: {
nl_assert(nlCurrentContext->state != NL_STATE_ROW);
nlCurrentContext->normalize_rows = NL_TRUE;
} break;
case NL_VERBOSE: {
nlCurrentContext->verbose = NL_TRUE;
} break;
case NL_VARIABLES_BUFFER: {
nlCurrentContext->user_variable_buffers = NL_TRUE;
} break;
default: {
nlError("nlEnable","Invalid parameter");
nl_assert_not_reached;
}
}
}
void nlDisable(NLenum pname) {
switch(pname) {
case NL_NORMALIZE_ROWS: {
nl_assert(nlCurrentContext->state != NL_STATE_ROW);
nlCurrentContext->normalize_rows = NL_FALSE;
} break;
case NL_VERBOSE: {
nlCurrentContext->verbose = NL_FALSE;
} break;
case NL_VARIABLES_BUFFER: {
nlCurrentContext->user_variable_buffers = NL_FALSE;
} break;
default: {
nlError("nlDisable","Invalid parameter");
nl_assert_not_reached;
}
}
}
NLboolean nlIsEnabled(NLenum pname) {
NLboolean result = NL_FALSE;
switch(pname) {
case NL_NORMALIZE_ROWS: {
result = nlCurrentContext->normalize_rows;
} break;
case NL_VERBOSE: {
result = nlCurrentContext->verbose;
} break;
case NL_VARIABLES_BUFFER: {
result = nlCurrentContext->user_variable_buffers;
} break;
default: {
nlError("nlIsEnables","Invalid parameter");
nl_assert_not_reached;
}
}
return result;
}
/* NL functions */
void nlSetFunction(NLenum pname, NLfunc param) {
switch(pname) {
case NL_FUNC_SOLVER:
nlCurrentContext->solver_func = (NLSolverFunc)(param);
nlCurrentContext->solver = NL_SOLVER_USER;
break;
case NL_FUNC_MATRIX:
nlDeleteMatrix(nlCurrentContext->M);
nlCurrentContext->M = nlMatrixNewFromFunction(
nlCurrentContext->n, nlCurrentContext->n,
(NLMatrixFunc)param
);
break;
case NL_FUNC_PRECONDITIONER:
nlDeleteMatrix(nlCurrentContext->P);
nlCurrentContext->P = nlMatrixNewFromFunction(
nlCurrentContext->n, nlCurrentContext->n,
(NLMatrixFunc)param
);
nlCurrentContext->preconditioner = NL_PRECOND_USER;
break;
case NL_FUNC_PROGRESS:
nlCurrentContext->progress_func = (NLProgressFunc)(param);
break;
default:
nlError("nlSetFunction","Invalid parameter");
nl_assert_not_reached;
}
}
void nlGetFunction(NLenum pname, NLfunc* param) {
switch(pname) {
case NL_FUNC_SOLVER:
*param = (NLfunc)(nlCurrentContext->solver_func);
break;
case NL_FUNC_MATRIX:
*param = (NLfunc)(nlMatrixGetFunction(nlCurrentContext->M));
break;
case NL_FUNC_PRECONDITIONER:
*param = (NLfunc)(nlMatrixGetFunction(nlCurrentContext->P));
break;
default:
nlError("nlGetFunction","Invalid parameter");
nl_assert_not_reached;
}
}
/* Get/Set Lock/Unlock variables */
void nlSetVariable(NLuint index, NLdouble value) {
nlCheckState(NL_STATE_SYSTEM);
nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables - 1);
NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[0],index) = value;
}
void nlMultiSetVariable(NLuint index, NLuint system, NLdouble value) {
nlCheckState(NL_STATE_SYSTEM);
nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables-1);
nl_debug_range_assert(system, 0, nlCurrentContext->nb_systems-1);
NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[system],index) = value;
}
NLdouble nlGetVariable(NLuint index) {
nl_assert(nlCurrentContext->state != NL_STATE_INITIAL);
nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables - 1);
return NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[0],index);
}
NLdouble nlMultiGetVariable(NLuint index, NLuint system) {
nl_assert(nlCurrentContext->state != NL_STATE_INITIAL);
nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables-1);
nl_debug_range_assert(system, 0, nlCurrentContext->nb_systems-1);
return NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[system],index);
}
void nlLockVariable(NLuint index) {
nlCheckState(NL_STATE_SYSTEM);
nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables - 1);
nlCurrentContext->variable_is_locked[index] = NL_TRUE;
}
void nlUnlockVariable(NLuint index) {
nlCheckState(NL_STATE_SYSTEM);
nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables - 1);
nlCurrentContext->variable_is_locked[index] = NL_FALSE;
}
NLboolean nlVariableIsLocked(NLuint index) {
nl_assert(nlCurrentContext->state != NL_STATE_INITIAL);
nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables - 1);
return nlCurrentContext->variable_is_locked[index];
}
/* System construction */
static void nlVariablesToVector() {
NLuint n=nlCurrentContext->n;
NLuint k,i,index;
NLdouble value;
nl_assert(nlCurrentContext->x != NULL);
for(k=0; k<nlCurrentContext->nb_systems; ++k) {
for(i=0; i<nlCurrentContext->nb_variables; ++i) {
if(!nlCurrentContext->variable_is_locked[i]) {
index = nlCurrentContext->variable_index[i];
nl_assert(index < nlCurrentContext->n);
value = NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[k],i);
nlCurrentContext->x[index+k*n] = value;
}
}
}
}
static void nlVectorToVariables() {
NLuint n=nlCurrentContext->n;
NLuint k,i,index;
NLdouble value;
nl_assert(nlCurrentContext->x != NULL);
for(k=0; k<nlCurrentContext->nb_systems; ++k) {
for(i=0; i<nlCurrentContext->nb_variables; ++i) {
if(!nlCurrentContext->variable_is_locked[i]) {
index = nlCurrentContext->variable_index[i];
nl_assert(index < nlCurrentContext->n);
value = nlCurrentContext->x[index+k*n];
NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[k],i) = value;
}
}
}
}
static void nlBeginSystem() {
NLuint k;
nlTransition(NL_STATE_INITIAL, NL_STATE_SYSTEM);
nl_assert(nlCurrentContext->nb_variables > 0);
nlCurrentContext->variable_buffer = NL_NEW_ARRAY(
NLBufferBinding, nlCurrentContext->nb_systems
);
if(nlCurrentContext->user_variable_buffers) {
nlCurrentContext->variable_value = NULL;
} else {
nlCurrentContext->variable_value = NL_NEW_ARRAY(
NLdouble,
nlCurrentContext->nb_variables * nlCurrentContext->nb_systems
);
for(k=0; k<nlCurrentContext->nb_systems; ++k) {
nlCurrentContext->variable_buffer[k].base_address =
nlCurrentContext->variable_value +
k * nlCurrentContext->nb_variables;
nlCurrentContext->variable_buffer[k].stride = sizeof(NLdouble);
}
}
nlCurrentContext->variable_is_locked = NL_NEW_ARRAY(
NLboolean, nlCurrentContext->nb_variables
);
nlCurrentContext->variable_index = NL_NEW_ARRAY(
NLuint, nlCurrentContext->nb_variables
);
}
static void nlEndSystem() {
nlTransition(NL_STATE_MATRIX_CONSTRUCTED, NL_STATE_SYSTEM_CONSTRUCTED);
}
static void nlInitializeM() {
NLuint i;
NLuint n = 0;
NLenum storage = NL_MATRIX_STORE_ROWS;
for(i=0; i<nlCurrentContext->nb_variables; i++) {
if(!nlCurrentContext->variable_is_locked[i]) {
nlCurrentContext->variable_index[i] = n;
n++;
} else {
nlCurrentContext->variable_index[i] = (NLuint)~0;
}
}
nlCurrentContext->n = n;
/*
* If the user trusts OpenNL and has left solver as NL_SOLVER_DEFAULT,
* then we setup reasonable parameters for him.
*/
if(nlCurrentContext->solver == NL_SOLVER_DEFAULT) {
if(nlCurrentContext->least_squares || nlCurrentContext->symmetric) {
nlCurrentContext->solver = NL_CG;
if(!nlCurrentContext->preconditioner_defined) {
nlCurrentContext->preconditioner = NL_PRECOND_JACOBI;
}
} else {
nlCurrentContext->solver = NL_BICGSTAB;
}
if(!nlCurrentContext->max_iterations_defined) {
nlCurrentContext->max_iterations = n*5;
}
if(!nlCurrentContext->threshold_defined) {
nlCurrentContext->threshold = 1e-6;
}
}
/* SSOR preconditioner requires rows and columns */
if(nlCurrentContext->preconditioner == NL_PRECOND_SSOR) {
storage = (storage | NL_MATRIX_STORE_COLUMNS);
}
/* a least squares problem results in a symmetric matrix */
if(nlCurrentContext->least_squares) {
nlCurrentContext->symmetric = NL_TRUE;
}
if(
nlCurrentContext->symmetric &&
nlCurrentContext->preconditioner == NL_PRECOND_SSOR
) {
/*
* For now, only used with SSOR preconditioner, because
* for other modes it is either unsupported (SUPERLU) or
* causes performance loss (non-parallel sparse SpMV)
*/
storage = (storage | NL_MATRIX_STORE_SYMMETRIC);
}
nlCurrentContext->M = (NLMatrix)(NL_NEW(NLSparseMatrix));
nlSparseMatrixConstruct(
(NLSparseMatrix*)(nlCurrentContext->M), n, n, storage
);
nlCurrentContext->x = NL_NEW_ARRAY(
NLdouble, n*nlCurrentContext->nb_systems
);
nlCurrentContext->b = NL_NEW_ARRAY(
NLdouble, n*nlCurrentContext->nb_systems
);
nlVariablesToVector();
nlRowColumnConstruct(&nlCurrentContext->af);
nlRowColumnConstruct(&nlCurrentContext->al);
nlCurrentContext->right_hand_side = NL_NEW_ARRAY(
double, nlCurrentContext->nb_systems
);
nlCurrentContext->current_row = 0;
}
static void nlEndMatrix() {
nlTransition(NL_STATE_MATRIX, NL_STATE_MATRIX_CONSTRUCTED);
nlRowColumnClear(&nlCurrentContext->af);
nlRowColumnClear(&nlCurrentContext->al);
if(!nlCurrentContext->least_squares) {
nl_assert(
nlCurrentContext->ij_coefficient_called || (
nlCurrentContext->current_row ==
nlCurrentContext->n
)
);
}
}
static void nlBeginRow() {
nlTransition(NL_STATE_MATRIX, NL_STATE_ROW);
nlRowColumnZero(&nlCurrentContext->af);
nlRowColumnZero(&nlCurrentContext->al);
}
static void nlScaleRow(NLdouble s) {
NLRowColumn* af = &nlCurrentContext->af;
NLRowColumn* al = &nlCurrentContext->al;
NLuint nf = af->size;
NLuint nl = al->size;
NLuint i,k;
for(i=0; i<nf; i++) {
af->coeff[i].value *= s;
}
for(i=0; i<nl; i++) {
al->coeff[i].value *= s;
}
for(k=0; k<nlCurrentContext->nb_systems; ++k) {
nlCurrentContext->right_hand_side[k] *= s;
}
}
static void nlNormalizeRow(NLdouble weight) {
NLRowColumn* af = &nlCurrentContext->af;
NLRowColumn* al = &nlCurrentContext->al;
NLuint nf = af->size;
NLuint nl = al->size;
NLuint i;
NLdouble norm = 0.0;
for(i=0; i<nf; i++) {
norm += af->coeff[i].value * af->coeff[i].value;
}
for(i=0; i<nl; i++) {
norm += al->coeff[i].value * al->coeff[i].value;
}
norm = sqrt(norm);
nlScaleRow(weight / norm);
}
static void nlEndRow() {
NLRowColumn* af = &nlCurrentContext->af;
NLRowColumn* al = &nlCurrentContext->al;
NLSparseMatrix* M = nlGetCurrentSparseMatrix();
NLdouble* b = nlCurrentContext->b;
NLuint nf = af->size;
NLuint nl = al->size;
NLuint n = nlCurrentContext->n;
NLuint current_row = nlCurrentContext->current_row;
NLuint i,j,jj;
NLdouble S;
NLuint k;
nlTransition(NL_STATE_ROW, NL_STATE_MATRIX);
if(nlCurrentContext->normalize_rows) {
nlNormalizeRow(nlCurrentContext->row_scaling);
} else if(nlCurrentContext->row_scaling != 1.0) {
nlScaleRow(nlCurrentContext->row_scaling);
}
/*
* if least_squares : we want to solve
* A'A x = A'b
*/
if(nlCurrentContext->least_squares) {
for(i=0; i<nf; i++) {
for(j=0; j<nf; j++) {
nlSparseMatrixAdd(
M, af->coeff[i].index, af->coeff[j].index,
af->coeff[i].value * af->coeff[j].value
);
}
}
for(k=0; k<nlCurrentContext->nb_systems; ++k) {
S = -nlCurrentContext->right_hand_side[k];
for(jj=0; jj<nl; ++jj) {
j = al->coeff[jj].index;
S += al->coeff[jj].value *
NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[k],j);
}
for(jj=0; jj<nf; jj++) {
b[ k*n+af->coeff[jj].index ] -= af->coeff[jj].value * S;
}
}
} else {
for(jj=0; jj<nf; ++jj) {
nlSparseMatrixAdd(
M, current_row, af->coeff[jj].index, af->coeff[jj].value
);
}
for(k=0; k<nlCurrentContext->nb_systems; ++k) {
b[k*n+current_row] = nlCurrentContext->right_hand_side[k];
for(jj=0; jj<nl; ++jj) {
j = al->coeff[jj].index;
b[k*n+current_row] -= al->coeff[jj].value *
NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[k],j);
}
}
}
nlCurrentContext->current_row++;
for(k=0; k<nlCurrentContext->nb_systems; ++k) {
nlCurrentContext->right_hand_side[k] = 0.0;
}
nlCurrentContext->row_scaling = 1.0;
}
void nlCoefficient(NLuint index, NLdouble value) {
nlCheckState(NL_STATE_ROW);
nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables - 1);
if(nlCurrentContext->variable_is_locked[index]) {
/*
* Note: in al, indices are NLvariable indices,
* within [0..nb_variables-1]
*/
nlRowColumnAppend(&(nlCurrentContext->al), index, value);
} else {
/*
* Note: in af, indices are system indices,
* within [0..n-1]
*/
nlRowColumnAppend(
&(nlCurrentContext->af),
nlCurrentContext->variable_index[index], value
);
}
}
void nlAddIJCoefficient(NLuint i, NLuint j, NLdouble value) {
NLSparseMatrix* M = nlGetCurrentSparseMatrix();
nlCheckState(NL_STATE_MATRIX);
nl_debug_range_assert(i, 0, nlCurrentContext->nb_variables - 1);
nl_debug_range_assert(j, 0, nlCurrentContext->nb_variables - 1);
#ifdef NL_DEBUG
for(NLuint i=0; i<nlCurrentContext->nb_variables; ++i) {
nl_debug_assert(!nlCurrentContext->variable_is_locked[i]);
}
#endif
nlSparseMatrixAdd(M, i, j, value);
nlCurrentContext->ij_coefficient_called = NL_TRUE;
}
void nlAddIRightHandSide(NLuint i, NLdouble value) {
nlCheckState(NL_STATE_MATRIX);
nl_debug_range_assert(i, 0, nlCurrentContext->nb_variables - 1);
#ifdef NL_DEBUG
for(NLuint i=0; i<nlCurrentContext->nb_variables; ++i) {
nl_debug_assert(!nlCurrentContext->variable_is_locked[i]);
}
#endif
nlCurrentContext->b[i] += value;
nlCurrentContext->ij_coefficient_called = NL_TRUE;
}
void nlMultiAddIRightHandSide(NLuint i, NLuint k, NLdouble value) {
NLuint n = nlCurrentContext->n;
nlCheckState(NL_STATE_MATRIX);
nl_debug_range_assert(i, 0, nlCurrentContext->nb_variables - 1);
nl_debug_range_assert(k, 0, nlCurrentContext->nb_systems - 1);
#ifdef NL_DEBUG
for(NLuint i=0; i<nlCurrentContext->nb_variables; ++i) {
nl_debug_assert(!nlCurrentContext->variable_is_locked[i]);
}
#endif
nlCurrentContext->b[i + k*n] += value;
nlCurrentContext->ij_coefficient_called = NL_TRUE;
}
void nlRightHandSide(NLdouble value) {
nlCurrentContext->right_hand_side[0] = value;
}
void nlMultiRightHandSide(NLuint k, NLdouble value) {
nl_debug_range_assert(k, 0, nlCurrentContext->nb_systems - 1);
nlCurrentContext->right_hand_side[k] = value;
}
void nlRowScaling(NLdouble value) {
nlCheckState(NL_STATE_MATRIX);
nlCurrentContext->row_scaling = value;
}
void nlBegin(NLenum prim) {
switch(prim) {
case NL_SYSTEM: {
nlBeginSystem();
} break;
case NL_MATRIX: {
nlTransition(NL_STATE_SYSTEM, NL_STATE_MATRIX);
if(
nlCurrentContext->matrix_mode == NL_STIFFNESS_MATRIX &&
nlCurrentContext->M == NULL
) {
nlInitializeM();
}
} break;
case NL_ROW: {
nlBeginRow();
} break;
default: {
nl_assert_not_reached;
}
}
}
void nlEnd(NLenum prim) {
switch(prim) {
case NL_SYSTEM: {
nlEndSystem();
} break;
case NL_MATRIX: {
nlEndMatrix();
} break;
case NL_ROW: {
nlEndRow();
} break;
default: {
nl_assert_not_reached;
}
}
}
/* nlSolve() driver routine */
NLboolean nlSolve() {
NLboolean result;
nlCheckState(NL_STATE_SYSTEM_CONSTRUCTED);
nlCurrentContext->start_time = nlCurrentTime();
nlCurrentContext->elapsed_time = 0.0;
nlCurrentContext->flops = 0;
result = nlCurrentContext->solver_func();
nlVectorToVariables();
nlCurrentContext->elapsed_time = nlCurrentTime() - nlCurrentContext->start_time;
nlTransition(NL_STATE_SYSTEM_CONSTRUCTED, NL_STATE_SOLVED);
return result;
}
void nlUpdateRightHandSide(NLdouble* values) {
/*
* If we are in the solved state, get back to the
* constructed state.
*/
nl_assert(nlCurrentContext->nb_systems == 1);
if(nlCurrentContext->state == NL_STATE_SOLVED) {
nlTransition(NL_STATE_SOLVED, NL_STATE_SYSTEM_CONSTRUCTED);
}
nlCheckState(NL_STATE_SYSTEM_CONSTRUCTED);
memcpy(nlCurrentContext->x, values, nlCurrentContext->n * sizeof(double));
}
/* Buffers management */
void nlBindBuffer(
NLenum buffer, NLuint k, void* addr, NLuint stride
) {
nlCheckState(NL_STATE_SYSTEM);
nl_assert(nlIsEnabled(buffer));
nl_assert(buffer == NL_VARIABLES_BUFFER);
nl_assert(k<nlCurrentContext->nb_systems);
if(stride == 0) {
stride = sizeof(NLdouble);
}
nlCurrentContext->variable_buffer[k].base_address = addr;
nlCurrentContext->variable_buffer[k].stride = stride;
}
/* Eigen solver */
void nlMatrixMode(NLenum matrix) {
NLuint n = 0;
NLuint i;
nl_assert(
nlCurrentContext->state == NL_STATE_SYSTEM ||
nlCurrentContext->state == NL_STATE_MATRIX_CONSTRUCTED
);
nlCurrentContext->state = NL_STATE_SYSTEM;
nlCurrentContext->matrix_mode = matrix;
nlCurrentContext->current_row = 0;
nlCurrentContext->ij_coefficient_called = NL_FALSE;
switch(matrix) {
case NL_STIFFNESS_MATRIX: {
/* Stiffness matrix is already constructed. */
} break ;
case NL_MASS_MATRIX: {
if(nlCurrentContext->B == NULL) {
for(i=0; i<nlCurrentContext->nb_variables; ++i) {
if(!nlCurrentContext->variable_is_locked[i]) {
++n;
}
}
nlCurrentContext->B = (NLMatrix)(NL_NEW(NLSparseMatrix));
nlSparseMatrixConstruct(
(NLSparseMatrix*)(nlCurrentContext->B),
n, n, NL_MATRIX_STORE_ROWS
);
}
} break ;
default:
nl_assert_not_reached;
}
}
void nlEigenSolverParameterd(
NLenum pname, NLdouble val
) {
switch(pname) {
case NL_EIGEN_SHIFT: {
nlCurrentContext->eigen_shift = val;
} break;
case NL_EIGEN_THRESHOLD: {
nlSolverParameterd(pname, val);
} break;
default:
nl_assert_not_reached;
}
}
void nlEigenSolverParameteri(
NLenum pname, NLint val
) {
switch(pname) {
case NL_EIGEN_SOLVER: {
nlCurrentContext->eigen_solver = (NLenum)val;
} break;
case NL_SYMMETRIC:
case NL_NB_VARIABLES:
case NL_NB_EIGENS:
case NL_EIGEN_MAX_ITERATIONS: {
nlSolverParameteri(pname, val);
} break;
default:
nl_assert_not_reached;
}
}
void nlEigenSolve() {
if(nlCurrentContext->eigen_value == NULL) {
nlCurrentContext->eigen_value = NL_NEW_ARRAY(
NLdouble,nlCurrentContext->nb_systems
);
}
nlMatrixCompress(&nlCurrentContext->M);
if(nlCurrentContext->B != NULL) {
nlMatrixCompress(&nlCurrentContext->B);
}
switch(nlCurrentContext->eigen_solver) {
case NL_ARPACK_EXT:
nlEigenSolve_ARPACK();
break;
default:
nl_assert_not_reached;
}
}
double nlGetEigenValue(NLuint i) {
nl_debug_assert(i < nlCurrentContext->nb_variables);
return nlCurrentContext->eigen_value[i];
}
| [
"[email protected]"
] | |
c45b8dbc95c4e28bbdf63bb529c3db62bc253028 | 8ad39dce5b7a4d9b0fa6bfc3d1745ae02064f506 | /Book & Movie rental shop management/SpellChecker.cpp | 510555a127341559f3b22496b5369196e3742e56 | [] | no_license | aywhr75/Object-oriented-programming | 73cf6c7d87fd834390b7c1d60281a63b1e067689 | c9506420f9f36e931e13f091525e54fd91ca51d2 | refs/heads/master | 2021-03-11T22:45:23.157920 | 2020-03-11T12:46:39 | 2020-03-11T12:46:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,561 | cpp | // Name: YoungA Lee
// Seneca Student ID: 048417083
// Seneca email: [email protected]
// Date of completion: Fab 17 2020
//
// I confirm that the content of this file is created by me,
// with the exception of the parts provided to me by my professor.
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<string>
#include<fstream>
#include "SpellChecker.h"
using namespace std;
namespace sdds {
SpellChecker::SpellChecker(const char* filename) {
auto pos = 0u; // unsigned int
string len;
ifstream textfile(filename); // ready to read a file
if (!textfile.good())
throw "Bad file name!"; // exceptional check
else {
for (size_t i = 0; i < WORD_SIZE; i++) {
getline(textfile, len);
pos = len.find(' '); // find location number of white space
m_badWords[i] = len.substr(0, pos);
m_badWords[i].erase(remove(m_badWords[i].begin(), m_badWords[i].end(), ' '), m_badWords[i].end());// removed white space
m_goodWords[i] = len.substr(pos, len.length() - 1);
m_goodWords[i].erase(remove(m_goodWords[i].begin(), m_goodWords[i].end(), ' '), m_goodWords[i].end()); // remove white space
}
}
}
void SpellChecker::operator()(std::string& text) const {
auto pos = 0u;
for (size_t i = 0; i < WORD_SIZE; i++) {
while (text.find(m_badWords[i]) != string::npos){ // if text.find is same with m_badWords return npos otherwise keep checking
pos = text.find(m_badWords[i]);
text.replace(pos, m_badWords[i].length(), m_goodWords[i]); // replace badwords to goodwords
}
}
}
} | [
"[email protected]"
] | |
ae654a7c9b7902b516c3caae1e1dd4d9f5c95dd6 | aefc133fdb19e4c7f20048fe9babf68cada7a109 | /MD5/MD5.hpp | a5bd09889b23ab0121b584cf0d141219c98a569b | [] | no_license | abodelot/cpp-utils | d3998add2efe6fbfa5c77388dff65d4e8be690a8 | 480e172349c84725ae978e495a875d50770282af | refs/heads/master | 2020-05-27T03:16:42.077984 | 2019-10-23T22:39:49 | 2019-10-23T22:56:33 | 20,619,186 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 464 | hpp | #ifndef MD5_HPP
#define MD5_HPP
#include <string>
#include <cstdint>
class MD5 {
public:
MD5();
MD5(const char* data, size_t len);
void update(const char* data, size_t len);
/**
* Get digest as a 32 hexadecimal characters string
*/
std::string hexdigest() const;
private:
void transform();
void finalize();
uint32_t buffer_[4];
uint32_t bits_[2];
unsigned char in_[64];
unsigned char digest_[16];
};
#endif
| [
"[email protected]"
] | |
539bab2aaac7668978b291bdd3a39411c199b005 | 766996d84cc71493deaf100f2493ee42ed0d4243 | /src/ifc/ifc4/IfcRelAssociatesLibrary.h | 27a11dedd5c93ee66e42a44ff22de28026bab3a4 | [] | no_license | andreasniggl/ifclite | 6040cd72460d401a364c4c7554f2fe3f44ee6df8 | aacc8a9f0add7036c4c04eeaed7938e731726ead | refs/heads/master | 2020-03-09T05:13:57.641923 | 2018-08-06T21:42:27 | 2018-08-06T21:42:27 | 128,607,886 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,389 | h | // Automatically generated by ifclite express parser from ifc4 express file - do not modify
#pragma once
#include "IfcTypeDefinitions.h"
#include "IfcRelAssociates.h"
#include "IfcLibrarySelect.h"
namespace ifc4
{
class IfcRelAssociatesLibrary : public IfcRelAssociates
{
public:
virtual ~IfcRelAssociatesLibrary(){}
explicit IfcRelAssociatesLibrary() = default;
explicit IfcRelAssociatesLibrary(const IfcGloballyUniqueId& _GlobalId, const std::vector< boost::optional<IfcDefinitionSelect> >& _RelatedObjects, const IfcLibrarySelect& _RelatingLibrary)
: IfcRelAssociates(_GlobalId, _RelatedObjects), RelatingLibrary(_RelatingLibrary) {}
virtual std::string className() const { return "IfcRelAssociatesLibrary"; }
boost::optional<IfcLibrarySelect> RelatingLibrary; // required parameter
protected:
virtual void serialize(ifc::StepWriter& w) const
{
w.beginEntity(this);
w.writeAttributeValue(GlobalId);
w.writeAttributeInstance(OwnerHistory);
w.writeAttributeValue(Name);
w.writeAttributeValue(Description);
w.writeAttributeSelect<IfcDefinitionSelectWriterVisitor>(RelatedObjects);
w.writeAttributeSelect<IfcLibrarySelectWriterVisitor>(RelatingLibrary);
w.endEntity();
}
};
} // namespace ifc4
| [
"[email protected]"
] | |
3bfb5442b4377d84bcf56e5ae6238b76ae268581 | c32a95e4444812f204bed4de2c59e5ee9e5134ad | /AlgorithmChallenges/ActorJobs.cpp | 7c7ca025ff00ff3cf50c95381d5644d31f8deb3d | [] | no_license | AlwinJoshy/Algorithm_Challenges | 7f6fb060df458e7012195d7b87c194761d8c629d | dd2ef610148d7f5bdca12d90ecd5fa4461089a3e | refs/heads/master | 2020-08-10T16:28:16.686273 | 2019-10-11T13:58:03 | 2019-10-11T13:58:03 | 214,371,542 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,311 | cpp | #include <iostream>
enum Months
{
jan,
feb,
mar,
apr,
may,
jun,
jul,
aug,
sep,
oct,
nov,
dec
};
class Job
{
public:
int startMonth;
int endMonth;
Job(Months start, Months end)
{
startMonth = start;
endMonth = end;
}
};
bool Overlaping(Job jobOne, Job jobTwo)
{
if (jobOne.startMonth < jobTwo.endMonth && jobOne.endMonth > jobTwo.startMonth) return true;
else return false;
}
int main()
{
Job allJobs[11] =
{
Job(jan, oct),
Job(may, jun),
Job(jan, apr),
Job(oct, dec),
Job(aug, oct),
Job(apr, aug),
Job(feb, jul),
Job(sep, nov),
Job(may, jul),
Job(jan, feb),
Job(feb, mar)
};
int jobMemo[10] = { 0,0,0,0,0,0,0,0,0,0 };
int memoSize = 0;
for (int i = 0; i < 11; i++)
{
memoSize = 1;
jobMemo[memoSize - 1] = i;
for (int n = 0; n < 11; n++)
{
bool addJob = true;
for (int k = 0; k < memoSize; k++)
{
if (jobMemo[k] != n)
{
if (Overlaping(allJobs[jobMemo[k]], allJobs[n]))
{
addJob = false;
break;
}
}
else addJob = false;
}
if (addJob)
{
memoSize++;
jobMemo[memoSize - 1] = n;
}
}
std::cout << "job count is : " << memoSize << " the job list no : ";
for (int i = 0; i < memoSize; i++)
{
std::cout << jobMemo[i] << " | ";
}
std::cout << "\n";
}
}
| [
"[email protected]"
] | |
498754cac19b2e0d4ec3906d3522676a14d85ee3 | 4c2062307f83cbd57e0cd83d57ed23272676ab88 | /src/ast.cpp | 7d028f2ecd37b5193c65269301015a5b03d7a0b4 | [] | no_license | yunjuanhuakai/regex_syntax | 14020700cf8dcc32bb0089b150fc61f66930d396 | 08a8ba7dda2158f8ac66f6c4c092d6008bc991c2 | refs/heads/master | 2021-01-20T21:06:38.170364 | 2017-03-10T13:59:51 | 2017-03-10T13:59:51 | 66,179,985 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,100 | cpp | //
// Created by makai on 16-6-19.
//
#include <iostream>
#include <algorithm>
#include <iomanip>
#include "ast.h"
namespace regex {
using std::cout;
using std::copy;
using std::make_move_iterator;
using std::ostream_iterator;
ast::ast() noexcept
: is_null_(true), t_(mTAG::CONCAT) {}
ast::ast(token const &t) noexcept
: is_null_(false), t_(t) {}
ast::ast(ast &&a) noexcept
: is_null_(a.is_null_), t_(a.t_), children_(std::move(a.children_)) { a.clear(); }
void ast::clear() noexcept {
is_null_ = true;
children_.clear();
}
ast &ast::operator[](size_t i) noexcept {
return children_[i];
}
ast const &ast::operator[](size_t i) const noexcept {
return children_[i];
}
token const &ast::get_token()
const noexcept {
return t_;
}
token &ast::get_token() noexcept {
return t_;
}
bool ast::null()
const noexcept {
return is_null_;
}
bool ast::empty()
const noexcept {
return children_.empty();
}
size_t ast::size() const noexcept {
return children_.size();
}
void ast::emplace_child(token const &t) {
this->is_null_ = false;
children_.emplace_back(t);
}
void ast::push_child(ast &&a) {
this->is_null_ = false;
ast item;
if (/*(*/a.t_.is(mTAG::CONCAT) /*|| a.t_.is(mTAG::Or))*/ && a.children_.size() == 1) {
item.swap(a.children_[0]);
a.clear();
} else {
item.swap(a);
}
children_.push_back(std::move(item));
// children_.push_back(make_unique<ast>(std::move(a)));
}
ast &ast::last() noexcept {
return children_.back();
}
ast const &ast::last()
const noexcept {
return children_.back();
}
void ast::swap(ast &a) {
std::swap(a.t_, t_);
std::swap(a.is_null_, is_null_);
children_.swap(a.children_);
}
ast_iterator ast::begin() noexcept {
return ast_iterator(children_.begin());
}
ast_const_iterator ast::begin() const noexcept {
return ast_const_iterator(children_.cbegin());
}
ast_iterator ast::end() noexcept {
return ast_iterator(children_.end());
}
ast_const_iterator ast::end() const noexcept {
return ast_const_iterator(children_.cend());
}
string ast::to_string()
const noexcept {
return is_null_ ? "null" : token_to_string(t_);
}
string ast::to_string_tree() const {
return _to_string_tree(0);
}
struct Set_E { int N_; };
Set_E set_e(int i) { return {i}; }
ostream &operator<<(ostream &os, Set_E const &e) {
std::fill_n(ostream_iterator<char>(os), e.N_, ' ');
return os;
}
string ast::_to_string_tree(int i) const {
ostringstream buf;
if (children_.empty()) {
buf << set_e(i) << to_string();
return buf.str();
}
if (!null()) {
buf << set_e(i) << '(' << t_ << '\n';
}
auto beg = children_.begin();
while (beg != children_.end() - 1) {
buf << (beg++)->_to_string_tree(i + 1) << '\n';
}
buf << beg->_to_string_tree(i + 1);
if (!null()) buf << ')';
return buf.str();
}
}
/*
namespace regex {
ast_iterator::ast_iterator(AstPtrs::iterator iter)
: iter_(iter) {}
ast &ast_iterator::operator*() const noexcept {
return *(*iter_);
}
ast *ast_iterator::operator->() const noexcept {
return iter_->get();
}
ast_iterator& ast_iterator::operator++() noexcept {
++iter_;
return *this;
}
ast_iterator ast_iterator::operator++(int) noexcept {
return _Self(iter_++);
}
bool ast_iterator::operator==(_Self const &rhs) const noexcept {
return rhs.iter_ == iter_;
}
bool ast_iterator::operator!=(_Self const &rhs) const noexcept {
return !(this->operator==(rhs));
}
ast_const_iterator::ast_const_iterator(AstPtrs::const_iterator iter)
: iter_(iter) {}
ast const& ast_const_iterator::operator*() const noexcept {
return *(*iter_);
}
ast const *ast_const_iterator::operator->() const noexcept {
return iter_->get();
}
ast_const_iterator &ast_const_iterator::operator++() noexcept {
++iter_;
return *this;
}
ast_const_iterator ast_const_iterator::operator++(int) noexcept {
return _Self(iter_++);
}
bool ast_const_iterator::operator==(_Self const &rhs) const noexcept {
return rhs.iter_ == iter_;
}
bool ast_const_iterator::operator!=(_Self const &rhs) const noexcept {
return !(this->operator==(rhs));
}
}
*/ | [
"[email protected]"
] | |
a90dd159ef105427d1cf4330c73ea7433dadd24e | d625eb0f2e675d6e40b0849d1e5f20b1aef4c406 | /codeforce/Codeforce_Rating_Round/Round_395/B_test.cpp | 4102b655ca9600da0c79b0b504a7bf2111f74d02 | [] | no_license | aseem01/Competitive_Programming | b5a57c7b10b731ea2b03288c500dd85c8f5fda2c | ad7354c56cada964b2c5331f15424d580febe2b6 | refs/heads/master | 2021-01-25T11:28:57.402352 | 2018-11-09T06:59:46 | 2018-11-09T06:59:46 | 93,930,174 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 847 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n,l;
cin>>n>>l;
int i,j,m;
int k[100],s[100],kk[100];
for(i=0; i<n; i++)
{
cin>>k[i];
}
kk[0]=l-k[n-1]+k[0];
for(i=1; i<n; i++)
{
kk[i]=k[i]-k[i-1];
}
for(i=0; i<n; i++)
{
cin>>s[i];
}
int ss[1000];
ss[0]=l-s[n-1]+s[0];
for(i=1; i<n; i++)
{
ss[i]=s[i]-s[i-1];
}
j=0;
for(i=n; i<2*n; i++)
{
ss[i]=ss[j];
j++;
}
int flg;
for(i=0; i<n; i++)
{
flg=0;
for(j=0; j<n; j++)
{
if(ss[i+j]!=kk[j])
{
flg=1;
break;
}
}
if(flg==0)
{
cout<<"YES"<<endl;
return 0;
}
}
cout<<"NO"<<endl;
}
| [
"[email protected]"
] | |
a6a34e5454cde0e7ab848175c76f1e4d99b0e29a | 104a2ae28ff3a649c92ffa9cc0f397e452330f24 | /aws-cpp-sdk-kinesisanalyticsv2/include/aws/kinesisanalyticsv2/model/MonitoringConfiguration.h | e6c73aa321c4ee170a10cbd8dbbbb83251a0c3c6 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | quatmax/aws-sdk-cpp | 6ca111b3da69af5e802a3feac70a8da4de006d5d | 578070580b614460a8bd76cf86e305a2e69d0adb | refs/heads/master | 2021-01-18T00:30:48.206056 | 2020-10-05T14:10:05 | 2020-10-05T14:10:05 | 301,419,784 | 0 | 0 | Apache-2.0 | 2020-10-05T13:34:23 | 2020-10-05T13:34:22 | null | UTF-8 | C++ | false | false | 6,441 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/kinesisanalyticsv2/KinesisAnalyticsV2_EXPORTS.h>
#include <aws/kinesisanalyticsv2/model/ConfigurationType.h>
#include <aws/kinesisanalyticsv2/model/MetricsLevel.h>
#include <aws/kinesisanalyticsv2/model/LogLevel.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace KinesisAnalyticsV2
{
namespace Model
{
/**
* <p>Describes configuration parameters for Amazon CloudWatch logging for a
* Java-based Kinesis Data Analytics application. For more information about
* CloudWatch logging, see <a
* href="https://docs.aws.amazon.com/kinesisanalytics/latest/java/monitoring-overview.html">Monitoring</a>.</p><p><h3>See
* Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/kinesisanalyticsv2-2018-05-23/MonitoringConfiguration">AWS
* API Reference</a></p>
*/
class AWS_KINESISANALYTICSV2_API MonitoringConfiguration
{
public:
MonitoringConfiguration();
MonitoringConfiguration(Aws::Utils::Json::JsonView jsonValue);
MonitoringConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>Describes whether to use the default CloudWatch logging configuration for an
* application. You must set this property to <code>CUSTOM</code> in order to set
* the <code>LogLevel</code> or <code>MetricsLevel</code> parameters.</p>
*/
inline const ConfigurationType& GetConfigurationType() const{ return m_configurationType; }
/**
* <p>Describes whether to use the default CloudWatch logging configuration for an
* application. You must set this property to <code>CUSTOM</code> in order to set
* the <code>LogLevel</code> or <code>MetricsLevel</code> parameters.</p>
*/
inline bool ConfigurationTypeHasBeenSet() const { return m_configurationTypeHasBeenSet; }
/**
* <p>Describes whether to use the default CloudWatch logging configuration for an
* application. You must set this property to <code>CUSTOM</code> in order to set
* the <code>LogLevel</code> or <code>MetricsLevel</code> parameters.</p>
*/
inline void SetConfigurationType(const ConfigurationType& value) { m_configurationTypeHasBeenSet = true; m_configurationType = value; }
/**
* <p>Describes whether to use the default CloudWatch logging configuration for an
* application. You must set this property to <code>CUSTOM</code> in order to set
* the <code>LogLevel</code> or <code>MetricsLevel</code> parameters.</p>
*/
inline void SetConfigurationType(ConfigurationType&& value) { m_configurationTypeHasBeenSet = true; m_configurationType = std::move(value); }
/**
* <p>Describes whether to use the default CloudWatch logging configuration for an
* application. You must set this property to <code>CUSTOM</code> in order to set
* the <code>LogLevel</code> or <code>MetricsLevel</code> parameters.</p>
*/
inline MonitoringConfiguration& WithConfigurationType(const ConfigurationType& value) { SetConfigurationType(value); return *this;}
/**
* <p>Describes whether to use the default CloudWatch logging configuration for an
* application. You must set this property to <code>CUSTOM</code> in order to set
* the <code>LogLevel</code> or <code>MetricsLevel</code> parameters.</p>
*/
inline MonitoringConfiguration& WithConfigurationType(ConfigurationType&& value) { SetConfigurationType(std::move(value)); return *this;}
/**
* <p>Describes the granularity of the CloudWatch Logs for an application.</p>
*/
inline const MetricsLevel& GetMetricsLevel() const{ return m_metricsLevel; }
/**
* <p>Describes the granularity of the CloudWatch Logs for an application.</p>
*/
inline bool MetricsLevelHasBeenSet() const { return m_metricsLevelHasBeenSet; }
/**
* <p>Describes the granularity of the CloudWatch Logs for an application.</p>
*/
inline void SetMetricsLevel(const MetricsLevel& value) { m_metricsLevelHasBeenSet = true; m_metricsLevel = value; }
/**
* <p>Describes the granularity of the CloudWatch Logs for an application.</p>
*/
inline void SetMetricsLevel(MetricsLevel&& value) { m_metricsLevelHasBeenSet = true; m_metricsLevel = std::move(value); }
/**
* <p>Describes the granularity of the CloudWatch Logs for an application.</p>
*/
inline MonitoringConfiguration& WithMetricsLevel(const MetricsLevel& value) { SetMetricsLevel(value); return *this;}
/**
* <p>Describes the granularity of the CloudWatch Logs for an application.</p>
*/
inline MonitoringConfiguration& WithMetricsLevel(MetricsLevel&& value) { SetMetricsLevel(std::move(value)); return *this;}
/**
* <p>Describes the verbosity of the CloudWatch Logs for an application.</p>
*/
inline const LogLevel& GetLogLevel() const{ return m_logLevel; }
/**
* <p>Describes the verbosity of the CloudWatch Logs for an application.</p>
*/
inline bool LogLevelHasBeenSet() const { return m_logLevelHasBeenSet; }
/**
* <p>Describes the verbosity of the CloudWatch Logs for an application.</p>
*/
inline void SetLogLevel(const LogLevel& value) { m_logLevelHasBeenSet = true; m_logLevel = value; }
/**
* <p>Describes the verbosity of the CloudWatch Logs for an application.</p>
*/
inline void SetLogLevel(LogLevel&& value) { m_logLevelHasBeenSet = true; m_logLevel = std::move(value); }
/**
* <p>Describes the verbosity of the CloudWatch Logs for an application.</p>
*/
inline MonitoringConfiguration& WithLogLevel(const LogLevel& value) { SetLogLevel(value); return *this;}
/**
* <p>Describes the verbosity of the CloudWatch Logs for an application.</p>
*/
inline MonitoringConfiguration& WithLogLevel(LogLevel&& value) { SetLogLevel(std::move(value)); return *this;}
private:
ConfigurationType m_configurationType;
bool m_configurationTypeHasBeenSet;
MetricsLevel m_metricsLevel;
bool m_metricsLevelHasBeenSet;
LogLevel m_logLevel;
bool m_logLevelHasBeenSet;
};
} // namespace Model
} // namespace KinesisAnalyticsV2
} // namespace Aws
| [
"[email protected]"
] | |
3561654a4a0bf7177c63030b327a9fcee7649a30 | 696e35ccdf167c3f6b1a7f5458406d3bb81987c9 | /net/base/ip_address.cc | 6d39175a05bee3e2c0c73ac5b9251a4b8ce10b34 | [
"BSD-3-Clause"
] | permissive | mgh3326/iridium-browser | 064e91a5e37f4e8501ea971483bd1c76297261c3 | e7de6a434d2659f02e94917be364a904a442d2d0 | refs/heads/master | 2023-03-30T16:18:27.391772 | 2019-04-24T02:14:32 | 2019-04-24T02:14:32 | 183,128,065 | 0 | 0 | BSD-3-Clause | 2019-11-30T06:06:02 | 2019-04-24T02:04:51 | null | UTF-8 | C++ | false | false | 15,410 | cc | // Copyright (c) 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/ip_address.h"
#include <algorithm>
#include <climits>
#include "base/containers/stack_container.h"
#include "base/stl_util.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/stringprintf.h"
#include "net/base/parse_number.h"
#include "url/gurl.h"
#include "url/url_canon_ip.h"
namespace net {
namespace {
// The prefix for IPv6 mapped IPv4 addresses.
// https://tools.ietf.org/html/rfc4291#section-2.5.5.2
constexpr uint8_t kIPv4MappedPrefix[] = {0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0xFF, 0xFF};
// Note that this function assumes:
// * |ip_address| is at least |prefix_length_in_bits| (bits) long;
// * |ip_prefix| is at least |prefix_length_in_bits| (bits) long.
bool IPAddressPrefixCheck(const IPAddressBytes& ip_address,
const uint8_t* ip_prefix,
size_t prefix_length_in_bits) {
// Compare all the bytes that fall entirely within the prefix.
size_t num_entire_bytes_in_prefix = prefix_length_in_bits / 8;
for (size_t i = 0; i < num_entire_bytes_in_prefix; ++i) {
if (ip_address[i] != ip_prefix[i])
return false;
}
// In case the prefix was not a multiple of 8, there will be 1 byte
// which is only partially masked.
size_t remaining_bits = prefix_length_in_bits % 8;
if (remaining_bits != 0) {
uint8_t mask = 0xFF << (8 - remaining_bits);
size_t i = num_entire_bytes_in_prefix;
if ((ip_address[i] & mask) != (ip_prefix[i] & mask))
return false;
}
return true;
}
// Returns false if |ip_address| matches any of the reserved IPv4 ranges. This
// method operates on a blacklist of reserved IPv4 ranges. Some ranges are
// consolidated.
// Sources for info:
// www.iana.org/assignments/ipv4-address-space/ipv4-address-space.xhtml
// www.iana.org/assignments/iana-ipv4-special-registry/
// iana-ipv4-special-registry.xhtml
bool IsPubliclyRoutableIPv4(const IPAddressBytes& ip_address) {
// Different IP versions have different range reservations.
DCHECK_EQ(IPAddress::kIPv4AddressSize, ip_address.size());
struct {
const uint8_t address[4];
size_t prefix_length_in_bits;
} static const kReservedIPv4Ranges[] = {
{{0, 0, 0, 0}, 8}, {{10, 0, 0, 0}, 8}, {{100, 64, 0, 0}, 10},
{{127, 0, 0, 0}, 8}, {{169, 254, 0, 0}, 16}, {{172, 16, 0, 0}, 12},
{{192, 0, 2, 0}, 24}, {{192, 88, 99, 0}, 24}, {{192, 168, 0, 0}, 16},
{{198, 18, 0, 0}, 15}, {{198, 51, 100, 0}, 24}, {{203, 0, 113, 0}, 24},
{{224, 0, 0, 0}, 3}};
for (const auto& range : kReservedIPv4Ranges) {
if (IPAddressPrefixCheck(ip_address, range.address,
range.prefix_length_in_bits)) {
return false;
}
}
return true;
}
// Returns false if |ip_address| matches any of the IPv6 ranges IANA reserved
// for local networks. This method operates on a whitelist of non-reserved
// IPv6 ranges, plus the blacklist of reserved IPv4 ranges mapped to IPv6.
// Sources for info:
// www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml
bool IsPubliclyRoutableIPv6(const IPAddressBytes& ip_address) {
DCHECK_EQ(IPAddress::kIPv6AddressSize, ip_address.size());
struct {
const uint8_t address_prefix[2];
size_t prefix_length_in_bits;
} static const kPublicIPv6Ranges[] = {// 2000::/3 -- Global Unicast
{{0x20, 0}, 3},
// ff00::/8 -- Multicast
{{0xff, 0}, 8}};
for (const auto& range : kPublicIPv6Ranges) {
if (IPAddressPrefixCheck(ip_address, range.address_prefix,
range.prefix_length_in_bits)) {
return true;
}
}
IPAddress addr(ip_address);
if (addr.IsIPv4MappedIPv6()) {
IPAddress ipv4 = ConvertIPv4MappedIPv6ToIPv4(addr);
return IsPubliclyRoutableIPv4(ipv4.bytes());
}
return false;
}
bool ParseIPLiteralToBytes(const base::StringPiece& ip_literal,
IPAddressBytes* bytes) {
// |ip_literal| could be either an IPv4 or an IPv6 literal. If it contains
// a colon however, it must be an IPv6 address.
if (ip_literal.find(':') != base::StringPiece::npos) {
// GURL expects IPv6 hostnames to be surrounded with brackets.
std::string host_brackets = "[";
ip_literal.AppendToString(&host_brackets);
host_brackets.push_back(']');
url::Component host_comp(0, host_brackets.size());
// Try parsing the hostname as an IPv6 literal.
bytes->Resize(16); // 128 bits.
return url::IPv6AddressToNumber(host_brackets.data(), host_comp,
bytes->data());
}
// Otherwise the string is an IPv4 address.
bytes->Resize(4); // 32 bits.
url::Component host_comp(0, ip_literal.size());
int num_components;
url::CanonHostInfo::Family family = url::IPv4AddressToNumber(
ip_literal.data(), host_comp, bytes->data(), &num_components);
return family == url::CanonHostInfo::IPV4;
}
} // namespace
IPAddressBytes::IPAddressBytes() : size_(0) {}
IPAddressBytes::IPAddressBytes(const uint8_t* data, size_t data_len) {
Assign(data, data_len);
}
IPAddressBytes::~IPAddressBytes() = default;
IPAddressBytes::IPAddressBytes(IPAddressBytes const& other) = default;
void IPAddressBytes::Assign(const uint8_t* data, size_t data_len) {
size_ = data_len;
CHECK_GE(16u, data_len);
std::copy_n(data, data_len, bytes_.data());
}
bool IPAddressBytes::operator<(const IPAddressBytes& other) const {
if (size_ == other.size_)
return std::lexicographical_compare(begin(), end(), other.begin(),
other.end());
return size_ < other.size_;
}
bool IPAddressBytes::operator==(const IPAddressBytes& other) const {
return size_ == other.size_ && std::equal(begin(), end(), other.begin());
}
bool IPAddressBytes::operator!=(const IPAddressBytes& other) const {
return !(*this == other);
}
IPAddress::IPAddress() = default;
IPAddress::IPAddress(const IPAddress& other) = default;
IPAddress::IPAddress(const IPAddressBytes& address) : ip_address_(address) {}
IPAddress::IPAddress(const uint8_t* address, size_t address_len)
: ip_address_(address, address_len) {}
IPAddress::IPAddress(uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3) {
ip_address_.push_back(b0);
ip_address_.push_back(b1);
ip_address_.push_back(b2);
ip_address_.push_back(b3);
}
IPAddress::IPAddress(uint8_t b0,
uint8_t b1,
uint8_t b2,
uint8_t b3,
uint8_t b4,
uint8_t b5,
uint8_t b6,
uint8_t b7,
uint8_t b8,
uint8_t b9,
uint8_t b10,
uint8_t b11,
uint8_t b12,
uint8_t b13,
uint8_t b14,
uint8_t b15) {
ip_address_.push_back(b0);
ip_address_.push_back(b1);
ip_address_.push_back(b2);
ip_address_.push_back(b3);
ip_address_.push_back(b4);
ip_address_.push_back(b5);
ip_address_.push_back(b6);
ip_address_.push_back(b7);
ip_address_.push_back(b8);
ip_address_.push_back(b9);
ip_address_.push_back(b10);
ip_address_.push_back(b11);
ip_address_.push_back(b12);
ip_address_.push_back(b13);
ip_address_.push_back(b14);
ip_address_.push_back(b15);
}
IPAddress::~IPAddress() = default;
bool IPAddress::IsIPv4() const {
return ip_address_.size() == kIPv4AddressSize;
}
bool IPAddress::IsIPv6() const {
return ip_address_.size() == kIPv6AddressSize;
}
bool IPAddress::IsValid() const {
return IsIPv4() || IsIPv6();
}
bool IPAddress::IsPubliclyRoutable() const {
if (IsIPv4()) {
return IsPubliclyRoutableIPv4(ip_address_);
} else if (IsIPv6()) {
return IsPubliclyRoutableIPv6(ip_address_);
}
return true;
}
bool IPAddress::IsZero() const {
for (auto x : ip_address_) {
if (x != 0)
return false;
}
return !empty();
}
bool IPAddress::IsIPv4MappedIPv6() const {
return IsIPv6() && IPAddressStartsWith(*this, kIPv4MappedPrefix);
}
bool IPAddress::IsLoopback() const {
// 127.0.0.1/8
if (IsIPv4())
return ip_address_[0] == 127;
// ::1
if (IsIPv6()) {
for (size_t i = 0; i + 1 < ip_address_.size(); ++i) {
if (ip_address_[i] != 0)
return false;
}
return ip_address_.back() == 1;
}
return false;
}
bool IPAddress::IsLinkLocal() const {
// 169.254.0.0/16
if (IsIPv4())
return (ip_address_[0] == 169) && (ip_address_[1] == 254);
// [fe80::]/10
if (IsIPv6())
return (ip_address_[0] == 0xFE) && ((ip_address_[1] & 0xC0) == 0x80);
return false;
}
bool IPAddress::AssignFromIPLiteral(const base::StringPiece& ip_literal) {
bool success = ParseIPLiteralToBytes(ip_literal, &ip_address_);
if (!success)
ip_address_.Resize(0);
return success;
}
std::vector<uint8_t> IPAddress::CopyBytesToVector() const {
return std::vector<uint8_t>(ip_address_.begin(), ip_address_.end());
}
// static
IPAddress IPAddress::IPv4Localhost() {
static const uint8_t kLocalhostIPv4[] = {127, 0, 0, 1};
return IPAddress(kLocalhostIPv4);
}
// static
IPAddress IPAddress::IPv6Localhost() {
static const uint8_t kLocalhostIPv6[] = {0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1};
return IPAddress(kLocalhostIPv6);
}
// static
IPAddress IPAddress::AllZeros(size_t num_zero_bytes) {
CHECK_LE(num_zero_bytes, 16u);
IPAddress result;
for (size_t i = 0; i < num_zero_bytes; ++i)
result.ip_address_.push_back(0u);
return result;
}
// static
IPAddress IPAddress::IPv4AllZeros() {
return AllZeros(kIPv4AddressSize);
}
// static
IPAddress IPAddress::IPv6AllZeros() {
return AllZeros(kIPv6AddressSize);
}
bool IPAddress::operator==(const IPAddress& that) const {
return ip_address_ == that.ip_address_;
}
bool IPAddress::operator!=(const IPAddress& that) const {
return ip_address_ != that.ip_address_;
}
bool IPAddress::operator<(const IPAddress& that) const {
// Sort IPv4 before IPv6.
if (ip_address_.size() != that.ip_address_.size()) {
return ip_address_.size() < that.ip_address_.size();
}
return ip_address_ < that.ip_address_;
}
std::string IPAddress::ToString() const {
std::string str;
url::StdStringCanonOutput output(&str);
if (IsIPv4()) {
url::AppendIPv4Address(ip_address_.data(), &output);
} else if (IsIPv6()) {
url::AppendIPv6Address(ip_address_.data(), &output);
}
output.Complete();
return str;
}
std::string IPAddressToStringWithPort(const IPAddress& address, uint16_t port) {
std::string address_str = address.ToString();
if (address_str.empty())
return address_str;
if (address.IsIPv6()) {
// Need to bracket IPv6 addresses since they contain colons.
return base::StringPrintf("[%s]:%d", address_str.c_str(), port);
}
return base::StringPrintf("%s:%d", address_str.c_str(), port);
}
std::string IPAddressToPackedString(const IPAddress& address) {
return std::string(reinterpret_cast<const char*>(address.bytes().data()),
address.size());
}
IPAddress ConvertIPv4ToIPv4MappedIPv6(const IPAddress& address) {
DCHECK(address.IsIPv4());
// IPv4-mapped addresses are formed by:
// <80 bits of zeros> + <16 bits of ones> + <32-bit IPv4 address>.
base::StackVector<uint8_t, 16> bytes;
bytes->insert(bytes->end(), std::begin(kIPv4MappedPrefix),
std::end(kIPv4MappedPrefix));
bytes->insert(bytes->end(), address.bytes().begin(), address.bytes().end());
return IPAddress(bytes->data(), bytes->size());
}
IPAddress ConvertIPv4MappedIPv6ToIPv4(const IPAddress& address) {
DCHECK(address.IsIPv4MappedIPv6());
base::StackVector<uint8_t, 16> bytes;
bytes->insert(bytes->end(),
address.bytes().begin() + base::size(kIPv4MappedPrefix),
address.bytes().end());
return IPAddress(bytes->data(), bytes->size());
}
bool IPAddressMatchesPrefix(const IPAddress& ip_address,
const IPAddress& ip_prefix,
size_t prefix_length_in_bits) {
// Both the input IP address and the prefix IP address should be either IPv4
// or IPv6.
DCHECK(ip_address.IsValid());
DCHECK(ip_prefix.IsValid());
DCHECK_LE(prefix_length_in_bits, ip_prefix.size() * 8);
// In case we have an IPv6 / IPv4 mismatch, convert the IPv4 addresses to
// IPv6 addresses in order to do the comparison.
if (ip_address.size() != ip_prefix.size()) {
if (ip_address.IsIPv4()) {
return IPAddressMatchesPrefix(ConvertIPv4ToIPv4MappedIPv6(ip_address),
ip_prefix, prefix_length_in_bits);
}
return IPAddressMatchesPrefix(ip_address,
ConvertIPv4ToIPv4MappedIPv6(ip_prefix),
96 + prefix_length_in_bits);
}
return IPAddressPrefixCheck(ip_address.bytes(), ip_prefix.bytes().data(),
prefix_length_in_bits);
}
bool ParseCIDRBlock(const std::string& cidr_literal,
IPAddress* ip_address,
size_t* prefix_length_in_bits) {
// We expect CIDR notation to match one of these two templates:
// <IPv4-literal> "/" <number of bits>
// <IPv6-literal> "/" <number of bits>
std::vector<base::StringPiece> parts = base::SplitStringPiece(
cidr_literal, "/", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
if (parts.size() != 2)
return false;
// Parse the IP address.
if (!ip_address->AssignFromIPLiteral(parts[0]))
return false;
// Parse the prefix length.
uint32_t number_of_bits;
if (!ParseUint32(parts[1], &number_of_bits))
return false;
// Make sure the prefix length is in a valid range.
if (number_of_bits > ip_address->size() * 8)
return false;
*prefix_length_in_bits = number_of_bits;
return true;
}
bool ParseURLHostnameToAddress(const base::StringPiece& hostname,
IPAddress* ip_address) {
if (hostname.size() >= 2 && hostname.front() == '[' &&
hostname.back() == ']') {
// Strip the square brackets that surround IPv6 literals.
auto ip_literal =
base::StringPiece(hostname).substr(1, hostname.size() - 2);
return ip_address->AssignFromIPLiteral(ip_literal) && ip_address->IsIPv6();
}
return ip_address->AssignFromIPLiteral(hostname) && ip_address->IsIPv4();
}
unsigned CommonPrefixLength(const IPAddress& a1, const IPAddress& a2) {
DCHECK_EQ(a1.size(), a2.size());
for (size_t i = 0; i < a1.size(); ++i) {
unsigned diff = a1.bytes()[i] ^ a2.bytes()[i];
if (!diff)
continue;
for (unsigned j = 0; j < CHAR_BIT; ++j) {
if (diff & (1 << (CHAR_BIT - 1)))
return i * CHAR_BIT + j;
diff <<= 1;
}
NOTREACHED();
}
return a1.size() * CHAR_BIT;
}
unsigned MaskPrefixLength(const IPAddress& mask) {
base::StackVector<uint8_t, 16> all_ones;
all_ones->resize(mask.size(), 0xFF);
return CommonPrefixLength(mask,
IPAddress(all_ones->data(), all_ones->size()));
}
} // namespace net
| [
"[email protected]"
] | |
3fd1506b83aa157b78f07bff76b195861270aced | ebfd5f8e22c68d85511a771e6c65a9d496016a90 | /dense.cpp | ce7597bdc96e415674159fccd05acbc4175b18cc | [] | no_license | zhoujian89/Leetcode | 4d3926fd2e7a5b52569f60750a7cc1e073b90247 | 68e91ae797557c7d23b0532b0e7b3c4d654e8f82 | refs/heads/master | 2021-01-01T05:49:57.720815 | 2015-07-21T14:45:15 | 2015-07-21T14:45:15 | 35,457,770 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 10,330 | cpp | #include "DenseTrackStab.h"
#include "Initialize.h"
#include "Descriptors.h"
#include "OpticalFlow.h"
#include <time.h>
using namespace cv;
int show_track = 0; // set show_track = 1, if you want to visualize the trajectories
int main(int argc, char** argv)
{
//加载视频
VideoCapture capture;
char* video = argv[1];
int flag = arg_parse(argc, argv);
capture.open(video);
if(!capture.isOpened()) {
fprintf(stderr, "Could not initialize capturing..\n");
return -1;
}
//帧数
int frame_num = 0;
TrackInfo trackInfo;
DescInfo hogInfo, hofInfo, mbhInfo;
//四种特征
/*
1.trajectory
2.HOG nxy_cell*nxy_cell*nt_cell 8个方向 path_size 32个像素
3.HOF nxy_cell*nxy_cell*nt_cell 9个方向
4.MBH nxy_cell*nxy_cell*nt_cell 8个方向
*/
InitTrackInfo(&trackInfo, track_length, init_gap);
InitDescInfo(&hogInfo, 8, false, patch_size, nxy_cell, nt_cell);
InitDescInfo(&hofInfo, 9, true, patch_size, nxy_cell, nt_cell);
InitDescInfo(&mbhInfo, 8, false, patch_size, nxy_cell, nt_cell);
SeqInfo seqInfo;
InitSeqInfo(&seqInfo, video);
std::vector<Frame> bb_list;
if(bb_file) {
LoadBoundBox(bb_file, bb_list);//加载人检测的boundbox
assert(bb_list.size() == seqInfo.length);
}
if(flag)
seqInfo.length = end_frame - start_frame + 1;
// fprintf(stderr, "video size, length: %d, width: %d, height: %d\n", seqInfo.length, seqInfo.width, seqInfo.height);
if(show_track == 1)
namedWindow("DenseTrackStab", 0);
SurfFeatureDetector detector_surf(200);
SurfDescriptorExtractor extractor_surf(true, true);
std::vector<Point2f> prev_pts_flow, pts_flow;
std::vector<Point2f> prev_pts_surf, pts_surf;
std::vector<Point2f> prev_pts_all, pts_all;
std::vector<KeyPoint> prev_kpts_surf, kpts_surf;
Mat prev_desc_surf, desc_surf;
Mat flow, human_mask;
Mat image, prev_grey, grey;
std::vector<float> fscales(0);
std::vector<Size> sizes(0);
std::vector<Mat> prev_grey_pyr(0), grey_pyr(0), flow_pyr(0), flow_warp_pyr(0);
std::vector<Mat> prev_poly_pyr(0), poly_pyr(0), poly_warp_pyr(0);
std::vector<std::list<Track> > xyScaleTracks;
int init_counter = 0; // indicate when to detect new feature points
while(true) {
Mat frame;
int i, j, c;
// get a new frame 输入一帧
capture >> frame;
if(frame.empty())
break;
if(frame_num < start_frame || frame_num > end_frame) {
frame_num++; //在start和end里面
continue;
}
if(frame_num == start_frame) {
image.create(frame.size(), CV_8UC3);
grey.create(frame.size(), CV_8UC1);
prev_grey.create(frame.size(), CV_8UC1);
InitPry(frame, fscales, sizes);
BuildPry(sizes, CV_8UC1, prev_grey_pyr);
BuildPry(sizes, CV_8UC1, grey_pyr);
BuildPry(sizes, CV_32FC2, flow_pyr);
BuildPry(sizes, CV_32FC2, flow_warp_pyr);
BuildPry(sizes, CV_32FC(5), prev_poly_pyr);
BuildPry(sizes, CV_32FC(5), poly_pyr);
BuildPry(sizes, CV_32FC(5), poly_warp_pyr);
xyScaleTracks.resize(scale_num);//尺度
frame.copyTo(image);
cvtColor(image, prev_grey, CV_BGR2GRAY);//转为灰度
for(int iScale = 0; iScale < scale_num; iScale++) {
if(iScale == 0)
prev_grey.copyTo(prev_grey_pyr[0]);
else//不同的尺度进行resize
resize(prev_grey_pyr[iScale-1], prev_grey_pyr[iScale], prev_grey_pyr[iScale].size(), 0, 0, INTER_LINEAR);
// dense sampling feature points min_distance=5 足够dense
std::vector<Point2f> points(0);
DenseSample(prev_grey_pyr[iScale], points, quality, min_distance);//每一个尺度,在每一帧,dense采点
// save the feature points //对每个尺度保存特征点
std::list<Track>& tracks = xyScaleTracks[iScale];
for(i = 0; i < points.size(); i++)
tracks.push_back(Track(points[i], trackInfo, hogInfo, hofInfo, mbhInfo));
}
// compute polynomial expansion
my::FarnebackPolyExpPyr(prev_grey, prev_poly_pyr, fscales, 7, 1.5);
human_mask = Mat::ones(frame.size(), CV_8UC1);
if(bb_file)
InitMaskWithBox(human_mask, bb_list[frame_num].BBs);
detector_surf.detect(prev_grey, prev_kpts_surf, human_mask);
extractor_surf.compute(prev_grey, prev_kpts_surf, prev_desc_surf);
frame_num++;
continue;
}
init_counter++;
frame.copyTo(image);
cvtColor(image, grey, CV_BGR2GRAY);
// match surf features
if(bb_file)
InitMaskWithBox(human_mask, bb_list[frame_num].BBs);
detector_surf.detect(grey, kpts_surf, human_mask);
extractor_surf.compute(grey, kpts_surf, desc_surf);
ComputeMatch(prev_kpts_surf, kpts_surf, prev_desc_surf, desc_surf, prev_pts_surf, pts_surf);
// compute optical flow for all scales once
my::FarnebackPolyExpPyr(grey, poly_pyr, fscales, 7, 1.5);
my::calcOpticalFlowFarneback(prev_poly_pyr, poly_pyr, flow_pyr, 10, 2);
MatchFromFlow(prev_grey, flow_pyr[0], prev_pts_flow, pts_flow, human_mask);
MergeMatch(prev_pts_flow, pts_flow, prev_pts_surf, pts_surf, prev_pts_all, pts_all);
Mat H = Mat::eye(3, 3, CV_64FC1);
if(pts_all.size() > 50) {
std::vector<unsigned char> match_mask;
Mat temp = findHomography(prev_pts_all, pts_all, RANSAC, 1, match_mask);
if(countNonZero(Mat(match_mask)) > 25)
H = temp;
}
Mat H_inv = H.inv();
Mat grey_warp = Mat::zeros(grey.size(), CV_8UC1);
MyWarpPerspective(prev_grey, grey, grey_warp, H_inv); // warp the second frame
// compute optical flow for all scales once
my::FarnebackPolyExpPyr(grey_warp, poly_warp_pyr, fscales, 7, 1.5);
my::calcOpticalFlowFarneback(prev_poly_pyr, poly_warp_pyr, flow_warp_pyr, 10, 2);
for(int iScale = 0; iScale < scale_num; iScale++) {
if(iScale == 0)
grey.copyTo(grey_pyr[0]);
else
resize(grey_pyr[iScale-1], grey_pyr[iScale], grey_pyr[iScale].size(), 0, 0, INTER_LINEAR);
int width = grey_pyr[iScale].cols;
int height = grey_pyr[iScale].rows;
// compute the integral histograms
DescMat* hogMat = InitDescMat(height+1, width+1, hogInfo.nBins);
HogComp(prev_grey_pyr[iScale], hogMat->desc, hogInfo);
DescMat* hofMat = InitDescMat(height+1, width+1, hofInfo.nBins);
HofComp(flow_warp_pyr[iScale], hofMat->desc, hofInfo);
DescMat* mbhMatX = InitDescMat(height+1, width+1, mbhInfo.nBins);
DescMat* mbhMatY = InitDescMat(height+1, width+1, mbhInfo.nBins);
MbhComp(flow_warp_pyr[iScale], mbhMatX->desc, mbhMatY->desc, mbhInfo);
// track feature points in each scale separately 在每一个尺度分开跟踪特征点
std::list<Track>& tracks = xyScaleTracks[iScale];
for (std::list<Track>::iterator iTrack = tracks.begin(); iTrack != tracks.end();) {
int index = iTrack->index;
Point2f prev_point = iTrack->point[index];
int x = std::min<int>(std::max<int>(cvRound(prev_point.x), 0), width-1);
int y = std::min<int>(std::max<int>(cvRound(prev_point.y), 0), height-1);
Point2f point;
point.x = prev_point.x + flow_pyr[iScale].ptr<float>(y)[2*x];
point.y = prev_point.y + flow_pyr[iScale].ptr<float>(y)[2*x+1];
if(point.x <= 0 || point.x >= width || point.y <= 0 || point.y >= height) {
iTrack = tracks.erase(iTrack);
continue;
}
iTrack->disp[index].x = flow_warp_pyr[iScale].ptr<float>(y)[2*x];
iTrack->disp[index].y = flow_warp_pyr[iScale].ptr<float>(y)[2*x+1];
// get the descriptors for the feature point
RectInfo rect;
GetRect(prev_point, rect, width, height, hogInfo);
GetDesc(hogMat, rect, hogInfo, iTrack->hog, index);
GetDesc(hofMat, rect, hofInfo, iTrack->hof, index);
GetDesc(mbhMatX, rect, mbhInfo, iTrack->mbhX, index);
GetDesc(mbhMatY, rect, mbhInfo, iTrack->mbhY, index);
iTrack->addPoint(point);
// draw the trajectories at the first scale
if(show_track == 1 && iScale == 0)
DrawTrack(iTrack->point, iTrack->index, fscales[iScale], image);
// if the trajectory achieves the maximal length
if(iTrack->index >= trackInfo.length) {
std::vector<Point2f> trajectory(trackInfo.length+1);
for(int i = 0; i <= trackInfo.length; ++i)
trajectory[i] = iTrack->point[i]*fscales[iScale];
std::vector<Point2f> displacement(trackInfo.length);
for (int i = 0; i < trackInfo.length; ++i)
displacement[i] = iTrack->disp[i]*fscales[iScale];
float mean_x(0), mean_y(0), var_x(0), var_y(0), length(0);
if(IsValid(trajectory, mean_x, mean_y, var_x, var_y, length) && IsCameraMotion(displacement)) {
// output the trajectory
printf("%d\t%f\t%f\t%f\t%f\t%f\t%f\t", frame_num, mean_x, mean_y, var_x, var_y, length, fscales[iScale]);
// for spatio-temporal pyramid
printf("%f\t", std::min<float>(std::max<float>(mean_x/float(seqInfo.width), 0), 0.999));
printf("%f\t", std::min<float>(std::max<float>(mean_y/float(seqInfo.height), 0), 0.999));
printf("%f\t", std::min<float>(std::max<float>((frame_num - trackInfo.length/2.0 - start_frame)/float(seqInfo.length), 0), 0.999));
// output the trajectory
for (int i = 0; i < trackInfo.length; ++i)
printf("%f\t%f\t", displacement[i].x, displacement[i].y);
PrintDesc(iTrack->hog, hogInfo, trackInfo);
PrintDesc(iTrack->hof, hofInfo, trackInfo);
PrintDesc(iTrack->mbhX, mbhInfo, trackInfo);
PrintDesc(iTrack->mbhY, mbhInfo, trackInfo);
printf("\n");
}
iTrack = tracks.erase(iTrack);
continue;
}
++iTrack;
}
ReleDescMat(hogMat);
ReleDescMat(hofMat);
ReleDescMat(mbhMatX);
ReleDescMat(mbhMatY);
if(init_counter != trackInfo.gap)
continue;
// detect new feature points every gap frames
std::vector<Point2f> points(0);
for(std::list<Track>::iterator iTrack = tracks.begin(); iTrack != tracks.end(); iTrack++)
points.push_back(iTrack->point[iTrack->index]);
DenseSample(grey_pyr[iScale], points, quality, min_distance);
// save the new feature points
for(i = 0; i < points.size(); i++)
tracks.push_back(Track(points[i], trackInfo, hogInfo, hofInfo, mbhInfo));
}
init_counter = 0;
grey.copyTo(prev_grey);
for(i = 0; i < scale_num; i++) {
grey_pyr[i].copyTo(prev_grey_pyr[i]);
poly_pyr[i].copyTo(prev_poly_pyr[i]);
}
prev_kpts_surf = kpts_surf;
desc_surf.copyTo(prev_desc_surf);
frame_num++;
if( show_track == 1 ) {
imshow( "DenseTrackStab", image);
c = cvWaitKey(3);
if((char)c == 27) break;
}
}
if( show_track == 1 )
destroyWindow("DenseTrackStab");
return 0;
}
| [
"[email protected]"
] | |
f1d77dd7c8099155ca159879fa476468809c5d57 | 5f130ab9cceca7da249b768d787c80a1fe118476 | /include/httprequest.h | c13daea55e87b9a444af55724af1d265a842772a | [] | no_license | taryura/Requests | 64d97be389a1809ca9ea990f563de86ca5f0ce2b | 02af79db8eb5d09e70bda7db66266dd4a6d02016 | refs/heads/master | 2021-04-15T05:04:58.046431 | 2019-02-13T17:36:02 | 2019-02-13T17:36:02 | 126,525,000 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 294 | h | #ifndef HTTPREQUEST_H
#define HTTPREQUEST_H
#include "a_requests.h"
class httprequest
{
public:
void rqst_set (std::string addr, std::string prt, const std::string &req_text);
std::string replyreceived;
protected:
private:
};
#endif // HTTPREQUEST_H
| [
"[email protected]"
] | |
46a00a240b0509bc0d7427eef72dc2cb0f02d6d6 | 47a485fe6b512aee8ba7ccd03a97f744936801a9 | /HR/maximal_square.cpp | 1703b6bb8048ba80c44453cd67a7bd827f0e0425 | [] | no_license | yuyashiraki/CTCI | 9e641557cf5a9d9629d2edc665b9d089e648881f | ddc2384314894d3a1536fa2b179f14ebfd2a4df3 | refs/heads/master | 2021-04-27T11:33:30.568159 | 2018-10-01T01:02:55 | 2018-10-01T01:02:55 | 122,563,481 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,873 | cpp | class Solution {
public:
// DP[x] = min(DP[x], DP[x-1], prev) + 1
// Time O(nm) Space O(m)
int maximalSquare(vector<vector<char>>& matrix) {
int n = matrix.size();
if (!n) return 0;
int m = matrix[0].size(), prev = 0, tmp;
vector<int> dp(m, 0); // bottom right down corner of rectangle, the length of the side of rectangle
int ans = 0;
for (int y = 0; y < n; y++) {
for (int x = 0; x < m; x++) {
if ('0' == matrix[y][x]) {
prev = dp[x];
dp[x] = 0;
} else {
if (x == 0) {
prev = dp[x];
dp[x] = 1;
} else {
tmp = min(min(dp[x], dp[x - 1]), prev) + 1;
prev = dp[x];
dp[x] = tmp;
}
ans = max(ans, dp[x]);
}
}
}
return ans*ans;
}
// Brute Force
// Time O(nm^2) Space O(m)
int maximalSquare(vector<vector<char>>& matrix) {
int n = matrix.size();
if (!n) return 0;
int m = matrix[0].size();
vector<int> height(m, 0);
int ans = 0;
for (int y = 0; y < n; y++) {
for (int x = 0; x < m; x++) {
if ('0' == matrix[y][x]) height[x] = 0;
else {
height[x]++;
int min_height = height[x];
for (int p = x; p >= 0; p--) {
min_height = min(min_height, height[p]);
int hor = x - p + 1;
if (min_height >= hor) ans = max(ans, hor*hor);
else break;
}
}
}
}
return ans;
}
};
| [
"[email protected]"
] | |
614092c26bd523eed51b31f45bdb1a6200de12ce | 17a3219394eae342439be25d11c543944d6c7351 | /common/trace_dump.hpp | 4ffe65ac09b460f3fcdbb5da8e67b277f2913de9 | [
"MIT"
] | permissive | rawoul/apitrace | 1526bb0414d5499f2992d59a3e32aa3b9203230a | e9fcdcf14a99f5cb4729abb7bbf7817d7aa59d18 | refs/heads/master | 2020-04-08T02:53:03.770028 | 2011-12-14T23:18:49 | 2011-12-14T23:20:00 | 3,009,443 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,015 | hpp | /**************************************************************************
*
* Copyright 2010 VMware, 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.
*
**************************************************************************/
/*
* Human-readible dumping.
*/
#ifndef _TRACE_DUMP_HPP_
#define _TRACE_DUMP_HPP_
#include <iostream>
#include "trace_model.hpp"
namespace trace {
typedef unsigned DumpFlags;
enum {
DUMP_FLAG_NO_COLOR = (1 << 0),
DUMP_FLAG_NO_ARG_NAMES = (1 << 1),
};
void dump(Value *value, std::ostream &os, DumpFlags flags = 0);
inline std::ostream & operator <<(std::ostream &os, Value *value) {
if (value) {
dump(value, os);
}
return os;
}
void dump(Call &call, std::ostream &os, DumpFlags flags = 0);
inline std::ostream & operator <<(std::ostream &os, Call &call) {
dump(call, os);
return os;
}
} /* namespace trace */
#endif /* _TRACE_DUMP_HPP_ */
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.