blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
sequencelengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d4034a1b200e2dedae763c3f4f805c5631981811 | c1df3fc3beb183206d8e21c0224387317c2b3fef | /OS X/Core/include/PolySceneLine.h | 1136ae7018c5bb6c6ff8752af1d56f6a0d51d324 | [
"MIT"
] | permissive | bschalich/Taverna | dcc181483125862b2b9fd9acef4e27b8926c226d | 6f231987b4227682247aa883de099faf33d5212d | refs/heads/master | 2021-01-01T17:32:11.426301 | 2015-04-30T03:27:50 | 2015-04-30T03:27:50 | 34,830,680 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,197 | h | /*
Copyright (C) 2011 by Ivan Safrin
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 "PolyString.h"
#include "PolyGlobals.h"
#include "PolySceneMesh.h"
#include "PolyCoreServices.h"
#include "PolyMesh.h"
namespace Polycode {
/**
* 3D line class. Can connect two SceneEntity classes with a line.
*/
class _PolyExport SceneLine : public SceneMesh {
public:
/**
* Constructs the line with two taraget positions.
* @param start Starting position.
* @param end Ending position.
*/
SceneLine(Vector3 start, Vector3 end);
/**
* Constructs the line with two taraget entities.
* @param ent1 Starting entity.
* @param ent2 Ending entity.
*/
SceneLine(Entity *ent1, Entity *ent2);
/**
* Constructs the line with two taraget positions.
* @param start Starting position.
* @param end Ending position.
*/
static SceneLine *SceneLineWithPositions(Vector3 start, Vector3 end);
virtual ~SceneLine();
void setStart(Vector3 start);
void setEnd(Vector3 end);
void Update();
protected:
void initLine();
Vector3 start;
Vector3 end;
Entity *ent1;
Entity *ent2;
};
} | [
"[email protected]"
] | |
47f4bde9aa3a1546b2da4a846d52cbdbb10ce6f7 | 349fe789ab1e4e46aae6812cf60ada9423c0b632 | /ComClasses/DLL/FormsGur/FormsGur.cpp | 4a6757e79bd7a8a95b4240c0859512c2fc2551ec | [] | no_license | presscad/ERP | a6acdaeb97b3a53f776677c3a585ca860d4de980 | 18ecc6c8664ed7fc3f01397d587cce91fc3ac78b | refs/heads/master | 2020-08-22T05:24:15.449666 | 2019-07-12T12:59:13 | 2019-07-12T12:59:13 | 216,326,440 | 1 | 0 | null | 2019-10-20T07:52:26 | 2019-10-20T07:52:26 | null | UTF-8 | C++ | false | false | 7,984 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#include <windows.h>
#pragma hdrstop
#include "UDM.h"
#include "UFormaGurDocCheckKKM2Impl.h"
#include "UFormaGurDocCheckKKM2CF.h"
#include "UFormaGurDocCheckKKMImpl.h"
#include "UFormaGurDocCheckKKMCF.h"
#include "UFormaGurDocPerImpl.h"
#include "UFormaGurDocPerCF.h"
#include "UFormaGurDocPrihNaklImpl.h"
#include "UFormaGurDocPrihNaklCF.h"
#include "UFormaGurAllDocImpl.h"
#include "UFormaGurAllDocCF.h"
#include "UFormaElementaGurOperDiscountCardImpl.h"
#include "UFormaElementaGurOperDiscountCardCF.h"
#include "UFormaGurOperDiscountCardImpl.h"
#include "UFormaGurOperDiscountCardCF.h"
#include "UFormaElementaGurPlatImpl.h"
#include "UFormaElementaGurPlatCF.h"
#include "UFormaGurPlatImpl.h"
#include "UFormaGurPlatCF.h"
#include "UFormaSetupOtborGurRoznDocImpl.h"
#include "UFormaSetupOtborGurRoznDocCF.h"
#include "UFormaGurRoznDocImpl.h"
#include "UFormaGurRoznDocCF.h"
#include "UFormaSetupOtborImpl.h"
#include "UFormaSetupOtborCF.h"
//---------------------------------------------------------------------------
extern "C" int __declspec (dllexport) kanGetClassObject(REFIID id_class, REFIID id_interface, void ** ppv);
extern "C" int __declspec (dllexport) kanSendApplication(TApplication * app);
extern "C" int __declspec (dllexport) kanRegisterServer(IkanCom * icom);
extern "C" int __declspec (dllexport) kanUnregisterServer(IkanCom * icom);
extern "C" int __declspec (dllexport) kanCanUnloadNow(void);
extern "C" void __declspec (dllexport) kanInit(void);
extern "C" void __declspec (dllexport) kanDone(void);
//---------------------------------------------------------------------------
int NumObject=0;
TApplication * glApp=0;
TApplication * dllApp=0;
TDM *DM=0;
#pragma argsused
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, LPVOID lpvReserved)
{
return 1;
}
//---------------------------------------------------------------------------
int kanSendApplication(TApplication * app)
{
int result=0;
if (app!=0)
{
glApp=app;
dllApp=Application;
Application=glApp;
}
return result;
}
//-----------------------------------------------------------------------------
void kanInit(void)
{
DM=new TDM(Application);
}
//---------------------------------------------------------------------------
void kanDone(void)
{
if(DM) delete DM;
if (dllApp!=0) Application=dllApp;
}
//---------------------------------------------------------------------------
int kanCanUnloadNow(void)
{
int result=0;
if (NumObject==0)
{
result= -1;
}
return result;
}
//-----------------------------------------------------------------------------
int kanGetClassObject(REFIID id_class, REFIID id_interface, void ** ppv)
{
int result=0;
if (id_class==CLSID_TFormaGurDocCheckKKM2Impl)
{
TFormaGurDocCheckKKM2CF * ob=new TFormaGurDocCheckKKM2CF();
result=ob->kanQueryInterface(id_interface, ppv);
if (result!=-1)
{
delete ob;
}
}
else if (id_class==CLSID_TFormaGurDocCheckKKMImpl)
{
TFormaGurDocCheckKKMCF * ob=new TFormaGurDocCheckKKMCF();
result=ob->kanQueryInterface(id_interface, ppv);
if (result!=-1)
{
delete ob;
}
}
else if (id_class==CLSID_TFormaGurDocPerImpl)
{
TFormaGurDocPerCF * ob=new TFormaGurDocPerCF();
result=ob->kanQueryInterface(id_interface, ppv);
if (result!=-1)
{
delete ob;
}
}
else if (id_class==CLSID_TFormaGurDocPrihNaklImpl)
{
TFormaGurDocPrihNaklCF * ob=new TFormaGurDocPrihNaklCF();
result=ob->kanQueryInterface(id_interface, ppv);
if (result!=-1)
{
delete ob;
}
}
else if (id_class==CLSID_TFormaGurAllDocImpl)
{
TFormaGurAllDocCF * ob=new TFormaGurAllDocCF();
result=ob->kanQueryInterface(id_interface, ppv);
if (result!=-1)
{
delete ob;
}
}
else if (id_class==CLSID_TFormaElementaGurOperDiscountCardImpl)
{
TFormaElementaGurOperDiscountCardCF * ob=new TFormaElementaGurOperDiscountCardCF();
result=ob->kanQueryInterface(id_interface, ppv);
if (result!=-1)
{
delete ob;
}
}
else if (id_class==CLSID_TFormaGurOperDiscountCardImpl)
{
TFormaGurOperDiscountCardCF * ob=new TFormaGurOperDiscountCardCF();
result=ob->kanQueryInterface(id_interface, ppv);
if (result!=-1)
{
delete ob;
}
}
else if (id_class==CLSID_TFormaElementaGurPlatImpl)
{
TFormaElementaGurPlatCF * ob=new TFormaElementaGurPlatCF();
result=ob->kanQueryInterface(id_interface, ppv);
if (result!=-1)
{
delete ob;
}
}
else if (id_class==CLSID_TFormaGurPlatImpl)
{
TFormaGurPlatCF * ob=new TFormaGurPlatCF();
result=ob->kanQueryInterface(id_interface, ppv);
if (result!=-1)
{
delete ob;
}
}
else if (id_class==CLSID_TFormaSetupOtborGurRoznDocImpl)
{
TFormaSetupOtborGurRoznDocCF * ob=new TFormaSetupOtborGurRoznDocCF();
result=ob->kanQueryInterface(id_interface, ppv);
if (result!=-1)
{
delete ob;
}
}
else if (id_class==CLSID_TFormaGurRoznDocImpl)
{
TFormaGurRoznDocCF * ob=new TFormaGurRoznDocCF();
result=ob->kanQueryInterface(id_interface, ppv);
if (result!=-1)
{
delete ob;
}
}
else if (id_class==CLSID_TFormaSetupOtborImpl)
{
TFormaSetupOtborCF * ob=new TFormaSetupOtborCF();
result=ob->kanQueryInterface(id_interface, ppv);
if (result!=-1)
{
delete ob;
}
}
else
{
result=0;
*ppv=NULL;
}
return result;
}
//----------------------------------------------------------------------------
int kanRegisterServer(IkanCom * icom)
{
int result=0;
if (icom->kanAddClass(CLSID_TFormaGurDocCheckKKM2Impl,ProgId_FormaGurCheckKKM2,"FormsGur.dll")!=-1)
{
ShowMessage("Error! Falid register class -"+UnicodeString(ProgId_FormaGurCheckKKM2)+" !");
}
if (icom->kanAddClass(CLSID_TFormaGurDocCheckKKMImpl,ProgId_FormaGurDocCheckKKM,"FormsGur.dll")!=-1)
{
ShowMessage("Error! Falid register class - "+UnicodeString(ProgId_FormaGurDocCheckKKM)+" !");
}
if (icom->kanAddClass(CLSID_TFormaGurDocPerImpl,ProgId_FormaGurDocPer,"FormsGur.dll")!=-1)
{
ShowMessage("Error! Falid register class -"+UnicodeString(ProgId_FormaGurDocPer)+" !");
}
if (icom->kanAddClass(CLSID_TFormaGurDocPrihNaklImpl,ProgId_FormaGurDocPrihNakl,"FormsGur.dll")!=-1)
{
ShowMessage("Error! Falid register class - "+UnicodeString(ProgId_FormaGurDocPrihNakl)+" !");
}
if (icom->kanAddClass(CLSID_TFormaGurAllDocImpl,ProgId_FormaGurAllDoc,"FormsGur.dll")!=-1)
{
ShowMessage("Error! Falid register class - "+UnicodeString(ProgId_FormaGurAllDoc)+" !");
}
if (icom->kanAddClass(CLSID_TFormaElementaGurOperDiscountCardImpl,"Oberon.FormaElGurOperDiscountCard.1","FormsGur.dll")!=-1)
{
ShowMessage("Error! Falid register class - Oberon.FormaElGurOperDiscountCard.1 !");
}
if (icom->kanAddClass(CLSID_TFormaGurOperDiscountCardImpl,ProgId_FormaGurOperDiscountCard,"FormsGur.dll")!=-1)
{
ShowMessage("Error! Falid register class - "+UnicodeString(ProgId_FormaGurOperDiscountCard)+" !");
}
if (icom->kanAddClass(CLSID_TFormaElementaGurPlatImpl,"Oberon.FormaElementaGurPlat.1","FormsGur.dll")!=-1)
{
ShowMessage("Error! Falid register class - Oberon.FormaElementaGurPlat.1!");
}
if (icom->kanAddClass(CLSID_TFormaGurPlatImpl,ProgId_FormaGurPlat,"FormsGur.dll")!=-1)
{
ShowMessage("Error! Falid register class - "+UnicodeString(ProgId_FormaGurPlat)+"!");
}
if (icom->kanAddClass(CLSID_TFormaSetupOtborGurRoznDocImpl,"Oberon.FormaSetOtbGurRoznDoc.1","FormsGur.dll")!=-1)
{
ShowMessage("Error! Falid register class - Oberon.FormaSetupOtborGurRoznDoc.1!");
}
if (icom->kanAddClass(CLSID_TFormaGurRoznDocImpl,ProgId_FormaGurRoznDoc,"FormsGur.dll")!=-1)
{
ShowMessage("Error! Falid register class - "+UnicodeString(ProgId_FormaGurRoznDoc)+"!");
}
if (icom->kanAddClass(CLSID_TFormaSetupOtborImpl,"Oberon.FormaSetupOtbor.1","FormsGur.dll")!=-1)
{
ShowMessage("Error! Falid register class - Oberon.FormaSetupOtbor.1!");
}
return result;
}
//-----------------------------------------------------------------------------
int kanUnregisterServer(IkanCom * icom)
{
int result=0;
return result;
}
//-----------------------------------------------------------------------------
| [
"[email protected]"
] | |
038017a2356e7d0f16e24cac92f19f0f131a7b7d | 09bb627bc003bfff65537d221b085fa722486fb0 | /Samples/ARTCCM-TNIR-sample_EN_ver.1.3.1.3c/Sample/Win32/BCB2006/Sample_BCB_2006_FullControl/Unit5.cpp | 0c24c4d1917a86f76679cd7d3822939c0d60fa4d | [
"MIT"
] | permissive | PalavaNet/ARTCAM-SWIR-Matlab-Interface | a7c54efe5a3fc2912cc2e78aefc3a694be921213 | b21f8c3ba26a001db57d6c77c3696c0092f5c68a | refs/heads/main | 2023-08-25T05:41:44.085789 | 2021-10-18T07:57:21 | 2021-10-18T07:57:21 | 417,757,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,677 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include "Unit5.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm5 *Form5;
//---------------------------------------------------------------------------
__fastcall TForm5::TForm5(TComponent* Owner)
: TForm(Owner)
{
m_pCArtCamSdk = NULL;
}
//---------------------------------------------------------------------------
void __fastcall TForm5::FormShow(TObject *Sender)
{
if(NULL == m_pCArtCamSdk){
return;
}
if(m_pCArtCamSdk->Monitor_GetColorMode()){
CheckBox1->Checked = TRUE;
}else{
CheckBox2->Enabled = FALSE;
CheckBox3->Enabled = FALSE;
}
if(m_pCArtCamSdk->Monitor_GetBayerGainAuto()){
CheckBox2->Checked = TRUE;
TrackBar1->Enabled = FALSE;
TrackBar2->Enabled = FALSE;
TrackBar3->Enabled = FALSE;
Edit1->Enabled = FALSE;
Edit2->Enabled = FALSE;
Edit3->Enabled = FALSE;
}else{
CheckBox3->Enabled = FALSE;
}
if(m_pCArtCamSdk->Monitor_GetBayerGainLock()){
CheckBox3->Checked = TRUE;
}
if(m_pCArtCamSdk->GetMirrorV()){
CheckBox4->Checked = TRUE;
}
LONG lWidth = 0; LONG lHeight = 0;
m_pCArtCamSdk->Monitor_GetPreviewSize(&lWidth,&lHeight);
switch(lWidth){
case 800: ComboBox2->ItemIndex=0; break;
case 1024: ComboBox2->ItemIndex=1; break;
case 1280: ComboBox2->ItemIndex=2; break;
}
LONG lCameraClock = m_pCArtCamSdk->Monitor_GetCameraClock();
switch(lCameraClock){
case 2: ComboBox1->ItemIndex=1; break;
case 5: ComboBox1->ItemIndex=2; break;
default: ComboBox1->ItemIndex=0; break;
}
// Bayer
lRed = m_pCArtCamSdk->Monitor_GetBayerGainRed();
lGreen = m_pCArtCamSdk->Monitor_GetBayerGainGreen();
lBlue = m_pCArtCamSdk->Monitor_GetBayerGainBlue();
TrackBar1->Position = lRed;
TrackBar2->Position = lGreen;
TrackBar3->Position = lBlue;
lGlobalGain = m_pCArtCamSdk->GetGlobalGain();
lShutterWidth = m_pCArtCamSdk->GetExposureTime();
TrackBar4->Position = lGlobalGain;
TrackBar5->Position = lShutterWidth;
return;
}
void __fastcall TForm5::ComboBox1Change(TObject *Sender)
{
m_pCArtCamSdk->Monitor_SetCameraClock(ComboBox1->ItemIndex);
}
//---------------------------------------------------------------------------
void __fastcall TForm5::ComboBox2Change(TObject *Sender)
{
LONG lWidth = 0; LONG lHeight = 0;
switch(ComboBox2->ItemIndex){
case 0: lWidth = 800; lHeight = 600; break;
case 1: lWidth = 1024; lHeight = 768; break;
default: lWidth = 1280; lHeight = 1024; break;
}
m_pCArtCamSdk->Monitor_SetPreviewSize(lWidth,lHeight);
}
//---------------------------------------------------------------------------
void __fastcall TForm5::Button1Click(TObject *Sender)
{
m_pCArtCamSdk->Monitor_SetPreviewMode(TRUE);
}
//---------------------------------------------------------------------------
void __fastcall TForm5::Button2Click(TObject *Sender)
{
m_pCArtCamSdk->Monitor_SetPreviewMode(FALSE);
}
//---------------------------------------------------------------------------
void TForm5::ColorCheck()
{
BOOL Color = CheckBox1->Checked;
BOOL AWB = CheckBox2->Checked;
BOOL Lock = CheckBox3->Checked;
m_pCArtCamSdk->Monitor_SetColorMode(Color);
m_pCArtCamSdk->Monitor_SetBayerGainAuto(AWB);
m_pCArtCamSdk->Monitor_SetBayerGainLock(Lock);
TrackBar1->Enabled = (Color && !AWB);
TrackBar2->Enabled = (Color && !AWB);
TrackBar3->Enabled = (Color && !AWB);
Edit1->Enabled = (Color && !AWB);
Edit2->Enabled = (Color && !AWB);
Edit3->Enabled = (Color && !AWB);
if(!Color){
CheckBox2->Enabled = FALSE;
CheckBox3->Enabled = FALSE;
}else{
CheckBox2->Enabled = TRUE;;
if(!AWB){
CheckBox3->Enabled = FALSE;
}else{
CheckBox3->Enabled = TRUE;
}
}
}
void __fastcall TForm5::CheckBox1Click(TObject *Sender)
{
ColorCheck();
}
//---------------------------------------------------------------------------
void __fastcall TForm5::CheckBox2Click(TObject *Sender)
{
ColorCheck();
}
//---------------------------------------------------------------------------
void __fastcall TForm5::CheckBox3Click(TObject *Sender)
{
ColorCheck();
}
//---------------------------------------------------------------------------
void __fastcall TForm5::CheckBox4Click(TObject *Sender)
{
if( CheckBox4->Checked == TRUE){
m_pCArtCamSdk->SetMirrorV(1);
}else{
m_pCArtCamSdk->SetMirrorV(0);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm5::TrackBar1Change(TObject *Sender)
{
lRed = TrackBar1->Position;
m_pCArtCamSdk->Monitor_SetBayerGainRed(lRed);
Edit1->Text = IntToStr(lRed);
}
//---------------------------------------------------------------------------
void __fastcall TForm5::TrackBar2Change(TObject *Sender)
{
lGreen = TrackBar2->Position;
m_pCArtCamSdk->Monitor_SetBayerGainGreen(lGreen);
Edit2->Text = IntToStr(lGreen);
}
//---------------------------------------------------------------------------
void __fastcall TForm5::TrackBar3Change(TObject *Sender)
{
lBlue = TrackBar3->Position;
m_pCArtCamSdk->Monitor_SetBayerGainBlue(lBlue);
Edit3->Text = IntToStr(lBlue);
}
//---------------------------------------------------------------------------
void __fastcall TForm5::TrackBar4Change(TObject *Sender)
{
lGlobalGain = TrackBar4->Position;
m_pCArtCamSdk->SetGlobalGain(lGlobalGain);
Edit4->Text = IntToStr(lGlobalGain);
}
//---------------------------------------------------------------------------
void __fastcall TForm5::TrackBar5Change(TObject *Sender)
{
lShutterWidth = TrackBar5->Position;
m_pCArtCamSdk->SetExposureTime(lShutterWidth);
Edit5->Text = IntToStr(lShutterWidth);
}
//---------------------------------------------------------------------------
void __fastcall TForm5::Edit1Change(TObject *Sender)
{
if(Edit1->Text != ""){
lRed = StrToInt(Edit1->Text);
m_pCArtCamSdk->Monitor_SetBayerGainRed(lRed);
TrackBar1->Position = lRed;
}
}
//---------------------------------------------------------------------------
void __fastcall TForm5::KeyValueCheck(TObject *Sender, char &Key)
{
if ((Key<'0') || ('9'<Key)) Key = 0;
}
//---------------------------------------------------------------------------
void __fastcall TForm5::Edit2Change(TObject *Sender)
{
if(Edit2->Text != ""){
lGreen = StrToInt(Edit2->Text);
m_pCArtCamSdk->Monitor_SetBayerGainGreen(lGreen);
TrackBar2->Position = lGreen;
}
}
//---------------------------------------------------------------------------
void __fastcall TForm5::Edit3Change(TObject *Sender)
{
if(Edit3->Text != ""){
lBlue = StrToInt(Edit3->Text);
m_pCArtCamSdk->Monitor_SetBayerGainBlue(lBlue);
TrackBar3->Position = lBlue;
}
}
//---------------------------------------------------------------------------
void __fastcall TForm5::Edit4Change(TObject *Sender)
{
if(Edit4->Text != ""){
lGlobalGain = StrToInt(Edit4->Text);
m_pCArtCamSdk->SetGlobalGain(lGlobalGain);
TrackBar4->Position = lGlobalGain;
}
}
//---------------------------------------------------------------------------
void __fastcall TForm5::Edit5Change(TObject *Sender)
{
if(Edit5->Text != ""){
lShutterWidth = StrToInt(Edit5->Text);
m_pCArtCamSdk->SetExposureTime(lShutterWidth);
TrackBar5->Position = lShutterWidth;
}
}
//---------------------------------------------------------------------------
void __fastcall TForm5::Button5Click(TObject *Sender)
{
Hide();
}
//---------------------------------------------------------------------------
void __fastcall TForm5::Button3Click(TObject *Sender)
{
lShutterWidth = m_pCArtCamSdk->GetExposureTime();
lGlobalGain = m_pCArtCamSdk->GetGlobalGain();
DWORD dwVFlip = m_pCArtCamSdk->ReadRegister(0x20);
m_pCArtCamSdk->Fpga_WriteRegister(0xB6, 0x03);
// Shutter
m_pCArtCamSdk->Fpga_WriteRegister(0xC0, 0x09);
m_pCArtCamSdk->Fpga_WriteRegister(0xC1, BYTE(lShutterWidth >> 8));
m_pCArtCamSdk->Fpga_WriteRegister(0xC2, BYTE(lShutterWidth));
// Gain
m_pCArtCamSdk->Fpga_WriteRegister(0xC3, 0x35);
m_pCArtCamSdk->Fpga_WriteRegister(0xC4, BYTE(lGlobalGain >> 8));
m_pCArtCamSdk->Fpga_WriteRegister(0xC5, BYTE(lGlobalGain));
// Mirror reversal
m_pCArtCamSdk->Fpga_WriteRegister(0xC6, 0x20);
m_pCArtCamSdk->Fpga_WriteRegister(0xC7, BYTE(dwVFlip >> 8));
m_pCArtCamSdk->Fpga_WriteRegister(0xC8, BYTE(dwVFlip));
DWORD wReg0xE4 = m_pCArtCamSdk->Fpga_ReadRegister(0xE4);
wReg0xE4 |= 0x0001;
m_pCArtCamSdk->Fpga_WriteRegister(0xE4, wReg0xE4);
wReg0xE4 &= 0xFFFE;
m_pCArtCamSdk->Fpga_WriteRegister(0xE4, wReg0xE4);
}
//---------------------------------------------------------------------------
| [
"[email protected]"
] | |
e929ad71a8a0ff04f6520e299eb9a9441d791828 | a43266b0038c879ed427c22bd24b1386d8dcfcf8 | /skeletonPlayer/src/ailadi/ailadiScene.h | 619bf2dec2be7189b0697fd26d94624c019d3888 | [] | no_license | ofZach/sfpcSkeletonApp | ecbeb91ee16643fe2a3713abb14a57c378056569 | 8598740208e699f10e132701c0238ff48bd956a7 | refs/heads/master | 2020-03-12T06:04:19.852233 | 2018-04-21T17:34:20 | 2018-04-21T17:34:20 | 130,477,481 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,103 | h | #pragma once
#include "baseScene.h"
//#include "ofxMidi.h"
class pixel {
public:
ofPoint orig;
ofPoint pos;
ofColor color;
float magnetism;
};
class ailadiScene : public baseScene {
public:
void setup();
void update();
void draw();
void exit();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void mouseEntered(int x, int y);
void mouseExited(int x, int y);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
//void newMidiMessage(ofxMidiMessage& eventArgs);
ofImage wheel;
vector < pixel > pixels;
stringstream text;
//ofxMidiIn midiIn;
//ofxMidiMessage midiMessage;
float value;
//vector <float> midiControl;
// ofEasyCam cam;
//ofPoint frames[30][24]; // 30 frames, 24 points per frame
};
| [
"[email protected]"
] | |
2ceb36aacbd40426d8d8644f759c034d4283bb3c | 0ecb3c2cde33bf09bb294e15f89f9c57e04c8621 | /src/vehicle.h | aecf1bfc9d3d5f61a7d3152afd925b9cbc600637 | [
"MIT"
] | permissive | laukikm/CarND-Path-Planning-Project | ff115a16de7cc4c6378362aae04f998c3ae10e16 | 65909e45c52593057a4d67f6c5299737149747f1 | refs/heads/master | 2022-11-29T01:10:52.453233 | 2020-08-11T02:06:47 | 2020-08-11T02:06:47 | 271,146,329 | 0 | 0 | MIT | 2020-06-10T01:23:14 | 2020-06-10T01:23:13 | null | UTF-8 | C++ | false | false | 479 | h | #ifndef VEHICLE_H
#define VEHICLE_H
#include "globals.h"
#include "helpers.h"
;
class Vehicle{
public:
double x,y,s,d,yaw,speed;
int lane; //0=left,1=center,2=right
int id;
double vx,vy;
Vehicle(double x=0,double y=0,double s=0,double d=0,double yaw=0,double speed=0){
this->x=x;
this->y=y;
this->s=s;
this->d=d;
this->yaw=yaw;
this->lane=int(d/lane_width);
this->speed=speed;
this->vx=speed*cos(yaw);
this->vy=speed*sin(yaw);
}
};
#endif | [
"[email protected]"
] | |
3d8dc634151971c5b2a5a266ec5e497d579d5f68 | 6d31810ba03ed8661bf5e2a739a8cb78150eacb1 | /Monk and the Islands.cpp | 47394badd2badf95309f348e6862a987a2c3ca86 | [] | no_license | TheDangerD0802/Data_Structure | d53bf99a42a253586a75a4bae6f56039c1b84f2a | 39496b9c9f0b2ed1ef1abcf461eb730091bf6de5 | refs/heads/master | 2022-12-24T18:19:36.385134 | 2020-09-24T09:00:40 | 2020-09-24T09:00:40 | 197,950,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 852 | cpp | #include<bits/stdc++.h>
using namespace std;
bool vis[10002];
int level[100001];
int bfs(int s, vector <int> vec[],int e)
{
int count=0;
queue <int> q;
q.push(s);
vis[s] = true;
level[s] = 0;
while(!q.empty())
{
int p = q.front();
q.pop();
for(int i=0;i<vec[p].size();i++)
{
if(vis[vec[p][i]]==false)
{
level[vec[p][i]]=level[p]+1;
count = level[vec[p][i]];
q.push(vec[p][i]);
if(vec[p][i] == e)
return count;
vis[vec[p][i]] = true;
}
}
}
return count;
}
int main()
{
int t;
cin>>t;
while(t--)
{
memset(vis,0,sizeof(vis));
int n,m;
cin>>n>>m;
vector <int> vec[n+1];
for(int i=0;i<m;i++)
{
int a,b;
cin>>a>>b;
vec[a].push_back(b);
vec[b].push_back(a);
}
cout<<bfs(1,vec,n)<<endl;
}
}
| [
"[email protected]"
] | |
71b1b7be4f3d167ead7958f7c9695c70cccec6a2 | 813811bc608e636096bf03995ae030a5fbb92096 | /src/state/State.h | 55f5cf94d92ad9a6b0cd55802409fc7036f21978 | [
"MIT"
] | permissive | UmbrellaSampler/carnd-term3-1_path_planning | 4484b99f7fff95d8ec99e7e47a73131b7b0c3592 | 5d3828753b0ecde20aa4a7ba7d0ef16e21acdea7 | refs/heads/master | 2020-12-04T20:20:55.450268 | 2020-02-04T11:13:12 | 2020-02-04T11:13:12 | 231,892,576 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,376 | h | //
// Created by uwe_e on 26.01.2020.
//
#ifndef PATH_PLANNING_STATE_H
#define PATH_PLANNING_STATE_H
#include <utility>
#include <vector>
#include <list>
#include <string>
#include <memory>
#include "spline.h"
#include "Types.h"
//enum class State {
// Ready,
// LK,
// PLCL,
// PLCR,
// LCL,
// LCR
//};
class State
{
public:
State(std::shared_ptr<const MapWaypoints> map_way_points, std::shared_ptr<Model> model, int lane,
std::list<std::shared_ptr<Model>> last_models)
: map_waypoints_(std::move(map_way_points)),
model_(std::move(model)), lane_(lane), last_models_(std::move(last_models))
{}
State (const State& state) = default;
virtual ~State() = default;
virtual std::vector<std::unique_ptr<State>> Next_States(std::shared_ptr<Model> model_) = 0;
virtual double Cost() const = 0;
virtual void Add_Spline_Points(std::vector<double> &spline_points_x, std::vector<double> &spline_points_y) const;
// For debugging
virtual std::string Name() const = 0;
Trajectory Next_Trajectory(const std::unique_ptr<Trajectory> &prev_traj) const;
protected:
void Append_Self_To_Last_Models();
bool Vehicle_Ahead_Too_Close(double dist) const;
bool Too_Close(const Vehicle &vehicle, double dist) const;
std::vector<int> Vehicles_In_Lane(int lane) const;
std::vector<int> Vehicles_In_Lane_Ahead(int lane) const;
bool Closest_Vehicle_In_Lane_Ahead(Vehicle &closest, int lane) const;
std::vector<int> Vehicles_In_Lane_Behind(int lane) const;
bool Closest_Vehicle_In_Lane_Behind(Vehicle &closest, int lane) const;
Trajectory Break_Up_Spline_Points(std::vector<double> &spline_points_x,
std::vector<double> &spline_points_y,
const std::unique_ptr<Trajectory> &previous_traj,
double ref_x,
double ref_y,
double ref_yaw,
double ego_vel) const;
std::shared_ptr<const MapWaypoints> map_waypoints_;
std::shared_ptr<Model> model_;
int lane_;
std::list<std::shared_ptr<Model>> last_models_;
};
#endif //PATH_PLANNING_STATE_H
| [
"[email protected]"
] | |
f2fa995b86bc109f99c5a0211fa5f882e94fed3f | 74add41a97244667539db1f082f7b268f5a675d0 | /Behaviors/NCI/SizeEffectNone.h | 5b615d263889e80dab4384f57cde73d02c361f57 | [] | no_license | LMurphy186232/Core_Model | 31c76cfece12b64510bb78ed9300372ebcf07a20 | 572199409732f71dda3043524cbb85485836a48e | refs/heads/master | 2023-06-25T19:55:46.017823 | 2023-05-28T12:46:21 | 2023-05-28T12:46:21 | 39,642,142 | 5 | 2 | null | 2023-08-03T12:58:11 | 2015-07-24T15:32:52 | C++ | UTF-8 | C++ | false | false | 415 | h | #ifndef SIZEEFFECT_H_
#define SIZEEFFECT_H_
#include "SizeEffectBase.h"
/**
* Class that provides no size effect (value of 1).
*/
class clSizeEffectNone: virtual public clSizeEffectBase {
public:
double CalculateSizeEffect(clTree *p_oTree, const float &fDiam) {return 1;};
void DoSetup(clTreePopulation *p_oPop, clBehaviorBase *p_oNCI, xercesc::DOMElement *p_oElement) {;};
};
#endif /* NOSIZEEFFECT_H_ */
| [
"[email protected]"
] | |
6b346af3d260d942627c802e9ebce5f472a09070 | b3718005a7d86807f345df9dd87d770ea9f5feb6 | /src/common/filter/core/AGICurve.cpp | c70536c2b87d2a047539f172d2b703bd1fdeaf5a | [] | no_license | dhcdht/AppGPUImage | 1215207369d38f10ef79e9c4aabfd43b5f533f3d | 9faebad219c965923365ee564e55ac639b4979fc | refs/heads/master | 2021-06-05T08:37:12.176957 | 2020-07-26T02:09:21 | 2020-07-26T02:09:21 | 140,569,908 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,374 | cpp | //
// AGICurve.cpp
// AppGPUImage
//
// Created by 董宏昌 on 2018/8/31.
// Copyright © 2018年 董宏昌. All rights reserved.
//
#include "AGICurve.h"
#include "AGIEasing.cpp"
AGICurve::AGICurve()
: m_type{None}
{
}
AGICurve::~AGICurve()
{
m_type = None;
}
bool AGICurve::init(Type type)
{
m_type = type;
return true;
}
double AGICurve::getCurveValueForPoint(double point)
{
if (m_type == None)
{
return 0.0;
}
else if (m_type == Custom)
{
// todo: Custom Curve
return 0.0;
}
switch (m_type)
{
case Linear: {
return easeNone(point);
} break;
case InQuad: {
return easeInQuad(point);
} break;
case OutQuad: {
return easeOutQuad(point);
} break;
case InOutQuad: {
return easeInOutQuad(point);
} break;
case OutInQuad: {
return easeOutInQuad(point);
} break;
case InCubic: {
return easeInCubic(point);
} break;
case OutCubic: {
return easeOutCubic(point);
} break;
case InOutCubic: {
return easeInOutCubic(point);
} break;
case OutInCubic: {
return easeOutInCubic(point);
} break;
case InQuart: {
return easeInQuart(point);
} break;
case OutQuart: {
return easeOutQuart(point);
} break;
case InOutQuart: {
return easeInOutQuart(point);
} break;
case OutInQuart: {
return easeOutInQuart(point);
} break;
case InQuint: {
return easeInQuint(point);
} break;
case OutQuint: {
return easeOutQuint(point);
} break;
case InOutQuint: {
return easeInOutQuint(point);
} break;
case OutInQuint: {
return easeOutInQuint(point);
} break;
case InSine: {
return easeInSine(point);
} break;
case OutSine: {
return easeOutSine(point);
} break;
case InOutSine: {
return easeInOutSine(point);
} break;
case OutInSine: {
return easeOutInSine(point);
} break;
case InExpo: {
return easeInExpo(point);
} break;
case OutExpo: {
return easeOutExpo(point);
} break;
case InOutExpo: {
return easeInOutExpo(point);
} break;
case OutInExpo: {
return easeOutInExpo(point);
} break;
case InCirc: {
return easeInCirc(point);
} break;
case OutCirc: {
return easeOutCirc(point);
} break;
case InOutCirc: {
return easeInOutCirc(point);
} break;
case OutInCirc: {
return easeOutInCirc(point);
} break;
default: {
return 0.0;
} break;
}
return 0.0;
}
| [
"[email protected]"
] | |
d07bd1db0a4ba51f3d8d76a3f382005affa61e20 | 8c1d48b95f674e9c16ab17e5f29e2d49ed7c17a2 | /C07/ex02/main.cpp | 52a8a222f507000adcbce33374c0873e02518412 | [] | no_license | labintei/C- | f2e4bbed02363e3e3a478da4e713c2531b228c1c | a0393da868d22e1ba95854e4a949a5994645928c | refs/heads/master | 2023-09-06T09:55:51.413994 | 2021-11-18T19:35:50 | 2021-11-18T19:35:50 | 417,142,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,662 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: labintei <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/16 19:05:15 by labintei #+# #+# */
/* Updated: 2021/11/18 15:24:35 by labintei ### ########.fr */
/* */
/* ************************************************************************** */
#include "Array.hpp"
int main(int argc, char **argv)
{
Array <int> s(25);
Array <int> d(10);
Array <char> y;
for(int j=0; j < 25; j++)
s[j] = j;
for(int j =0; j < 25; j++)
std::cout << " " << s[j];
std::cout << std::endl;
d = s;
for(int j =0; j < 25; j++)
std::cout << " " << d[j];
std::cout << std::endl;
try
{
std::cout << s[250] << std::endl;
}
catch(std::exception& e)
{
std::cout << "Erreur pas de s[j]" << std::endl;
}
try
{
std::cout << s[2] << std::endl;
}
catch(std::exception& e)
{
std::cout << "Erreur pas de s[j]" << std::endl;
}
try
{
std::cout << y[0] << std::endl;
}
catch(std::exception& e)
{
std::cout << "Erreur y vide" << std::endl;
}
std::cout << "size de " << s.size() << std::endl;
return 0;
}
| [
"[email protected]"
] | |
605ce22e62a0275a8f700010cd5cc64bdb566512 | e9040d7f9142287d8dbe6e039402cb441f3acb15 | /Problem29.cpp | df4ed59bc1000b485b3b351a8d14c5b991892a76 | [] | no_license | StefanoMazzuka/Estructura_de_Datos_y_Algoritmos | a3536b63c7e25c3d08cc90af9b4f6f9ccbe37eda | a153d865a9e9c6968e4a287e1513c14697b1c0ef | refs/heads/master | 2020-05-27T14:57:51.889452 | 2019-05-26T11:11:20 | 2019-05-26T11:11:20 | 188,671,478 | 2 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 4,000 | cpp | /*
Stefano Mazzuka
*/
#include <iostream>
#include <fstream>
#include <vector>
<<<<<<< HEAD
bool isValid(std::vector<int> accumulated, int k, int currentTime) {
return currentTime <= accumulated[k];
}
bool isSolution(int bestTime, int currentTime) {
return bestTime > currentTime;
}
//Coste O(m^n)
void coats(std::vector<std::vector<int>> employees, std::vector<int> sol,
std::vector<int> accumulated, int numEmployees, int k, int& bestTime, int currentTime) {
for (int i = k; i < numEmployees; i++) {
sol[k] = employees[k][i];
currentTime += sol[k];
if (isValid(accumulated, k, currentTime)) {
if (k == numEmployees - 1) {
if (isSolution(bestTime, currentTime))
bestTime = currentTime;
}
else optimizeTimes(employees, sol, accumulated, numEmployees, k + 1, bestTime, currentTime);
}
currentTime -= employees[k][i];
}
}
void resuelveCaso(int numEmployees) {
std::vector<int> minValues(numEmployees);
std::vector<std::vector<int>> employees(numEmployees, std::vector<int>(numEmployees));
int time;
int minTime = INT_MAX;
for (int i = 0; i < numEmployees; i++) {
for (int j = 0; j < numEmployees; j++) {
std::cin >> time;
employees[i][j] = time;
if (time < minTime) {
minValues[i] = time;
minTime = time;
}
}
minTime = INT_MAX;
}
std::vector<int> accumulated(numEmployees);
accumulated[numEmployees - 1] = minValues[numEmployees - 1];
for (int i = numEmployees - 2; i >= 0; i--) {
accumulated[i] = minValues[i] + accumulated[i + 1];
}
std::vector<int> sol(numEmployees);
int bestTime = INT_MAX;
optimizeTimes(employees, sol, accumulated, numEmployees, 0, bestTime, 0);
std::cout << bestTime << '\n';
=======
bool isValid(std::vector<int> const& sol, std::vector<int> const& rain,
std::vector<int> const& coats, int k, int i, std::vector<int> const& contCoats) {
// El abrigo tiene que soportar la lluvia.
if (coats[sol[k]] < rain[k])
return false;
if (k > 0) {
// No se usa un abrigo dos días seguidos.
if (sol[k - 1] == sol[k])
return false;
// El abrigo que más haya usado no supere en dos días
// o más a un tercio de los días que van transcirridos.
if (contCoats[i] > 2 + (k / 3))
return false;
}
return true;
}
bool isSolution(std::vector<int> const& sol) {
return sol[0] != sol[sol.size() - 1];
}
//Coste O(m^n) donde m son el número de abrigos y n los días.
void coatsCombinations(std::vector<int> sol, std::vector<int> const& rain,
std::vector<int> const& coats, std::vector<int> contCoats, int n, int a, int k, int& numCoats) {
for (int i = 0; i < a; i++) {
sol[k] = i;
contCoats[i]++;
if (isValid(sol, rain, coats, k, i, contCoats)) {
if (k == n - 1) {
if (isSolution(sol))
numCoats++;
}
else coatsCombinations(sol, rain, coats, contCoats, n, a, k + 1, numCoats);
}
contCoats[i]--;
}
}
void resuelveCaso(int n, int a) {
std::vector<int> rain(n);
for (int& value : rain) std::cin >> value;
std::vector<int> coats(a);
for (int& value : coats) std::cin >> value;
std::vector<int> sol(n);
std::vector<int> contCoats(a);
int numCoats = 0;
coatsCombinations(sol, rain, coats, contCoats, n, a, 0, numCoats);
if (numCoats > 0) std::cout << numCoats << '\n';
else std::cout << "Lo puedes comprar" << '\n';
>>>>>>> 0fb7c0f4b4f2ba1038c740fff7c80adf4b2cb187
}
int main() {
#ifndef DOMJUDGE
std::ifstream in("datos29.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt
#endif
<<<<<<< HEAD
int numEmployees;
std::cin >> numEmployees;
while (numEmployees != 0) {
resuelveCaso(numEmployees);
std::cin >> numEmployees;
=======
int n, a;
std::cin >> n >> a;
while (n != 0 && a != 0) {
resuelveCaso(n, a);
std::cin >> n >> a;
>>>>>>> 0fb7c0f4b4f2ba1038c740fff7c80adf4b2cb187
}
#ifndef DOMJUDGE // para dejar todo como estaba al principio
std::cin.rdbuf(cinbuf);
system("PAUSE");
#endif
return 0;
<<<<<<< HEAD
=======
>>>>>>> 0fb7c0f4b4f2ba1038c740fff7c80adf4b2cb187
} | [
"[email protected]"
] | |
3099b3efbeea1b2f921904394bf19dc45e022ae6 | 45014139581f1211a43b6415a6ee32d442c29fc0 | /src/components/viz/service/display/overlay_processor_ozone.cc | 9ced80ee12f3bea910ad3d39bf14132df6ff9857 | [
"BSD-3-Clause"
] | permissive | webosose/chromium91 | a31b847e64391c3de98ca5b6dac3ac247d393e78 | b28e2ae83ee2e4907a36a49a4c0f054aa386dbfa | refs/heads/master | 2022-12-12T09:32:30.580155 | 2022-09-01T09:02:15 | 2022-09-18T23:58:11 | 460,692,960 | 1 | 5 | null | 2022-10-05T07:19:39 | 2022-02-18T03:16:04 | null | UTF-8 | C++ | false | false | 11,790 | cc | // Copyright 2019 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/viz/service/display/overlay_processor_ozone.h"
#include <memory>
#include <utility>
#include <vector>
#include "base/logging.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "components/viz/common/features.h"
#include "components/viz/service/display/overlay_strategy_fullscreen.h"
#include "components/viz/service/display/overlay_strategy_single_on_top.h"
#include "components/viz/service/display/overlay_strategy_underlay.h"
#include "components/viz/service/display/overlay_strategy_underlay_cast.h"
#include "gpu/command_buffer/client/shared_image_interface.h"
#include "gpu/command_buffer/service/shared_image_manager.h"
#include "ui/gfx/geometry/rect_conversions.h"
namespace viz {
namespace {
// TODO(weiliangc): When difference between primary plane and non-primary plane
// can be internalized, merge these two helper functions.
void ConvertToOzoneOverlaySurface(
const OverlayProcessorInterface::OutputSurfaceOverlayPlane& primary_plane,
ui::OverlaySurfaceCandidate* ozone_candidate) {
ozone_candidate->transform = primary_plane.transform;
ozone_candidate->format = primary_plane.format;
ozone_candidate->display_rect = primary_plane.display_rect;
ozone_candidate->crop_rect = primary_plane.uv_rect;
ozone_candidate->clip_rect = gfx::ToEnclosingRect(primary_plane.display_rect);
ozone_candidate->is_clipped = false;
ozone_candidate->is_opaque = !primary_plane.enable_blending;
ozone_candidate->plane_z_order = 0;
ozone_candidate->buffer_size = primary_plane.resource_size;
}
void ConvertToOzoneOverlaySurface(
const OverlayCandidate& overlay_candidate,
ui::OverlaySurfaceCandidate* ozone_candidate) {
ozone_candidate->transform = overlay_candidate.transform;
ozone_candidate->format = overlay_candidate.format;
ozone_candidate->display_rect = overlay_candidate.display_rect;
ozone_candidate->crop_rect = overlay_candidate.uv_rect;
ozone_candidate->clip_rect = overlay_candidate.clip_rect;
ozone_candidate->is_clipped = overlay_candidate.is_clipped;
ozone_candidate->is_opaque = overlay_candidate.is_opaque;
ozone_candidate->plane_z_order = overlay_candidate.plane_z_order;
ozone_candidate->buffer_size = overlay_candidate.resource_size_in_pixels;
ozone_candidate->requires_overlay = overlay_candidate.requires_overlay;
}
uint32_t MailboxToUInt32(const gpu::Mailbox& mailbox) {
return (mailbox.name[0] << 24) + (mailbox.name[1] << 16) +
(mailbox.name[2] << 8) + mailbox.name[3];
}
void ReportSharedImageExists(bool exists) {
UMA_HISTOGRAM_BOOLEAN(
"Compositing.Display.OverlayProcessorOzone."
"SharedImageExists",
exists);
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
bool AllowColorSpaceCombination(
const gfx::ColorSpace& source_color_space,
const gfx::ColorSpace& destination_color_space) {
// Allow invalid source color spaces because the assumption is that the
// compositor won't do a color space conversion in this case anyway, so it
// should be consistent with the overlay path.
if (!source_color_space.IsValid())
return true;
// Allow color space mismatches as long as either a) the source color space is
// SRGB; or b) both the source and destination color spaces have the same
// color usage. It is possible that case (a) still allows for visible color
// inconsistency between overlays and composition, but we'll address that case
// if it comes up.
return source_color_space.GetContentColorUsage() ==
gfx::ContentColorUsage::kSRGB ||
source_color_space.GetContentColorUsage() ==
destination_color_space.GetContentColorUsage();
}
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
} // namespace
// |overlay_candidates| is an object used to answer questions about possible
// overlays configurations.
// |available_strategies| is a list of overlay strategies that should be
// initialized by InitializeStrategies.
OverlayProcessorOzone::OverlayProcessorOzone(
std::unique_ptr<ui::OverlayCandidatesOzone> overlay_candidates,
#if defined(USE_NEVA_MEDIA)
gpu::SurfaceHandle surface_handle,
#endif
std::vector<OverlayStrategy> available_strategies,
gpu::SharedImageInterface* shared_image_interface)
#if defined(USE_NEVA_MEDIA)
: OverlayProcessorUsingStrategy(surface_handle),
#else
: OverlayProcessorUsingStrategy(),
#endif
overlay_candidates_(std::move(overlay_candidates)),
available_strategies_(std::move(available_strategies)),
shared_image_interface_(shared_image_interface) {
for (OverlayStrategy strategy : available_strategies_) {
switch (strategy) {
case OverlayStrategy::kFullscreen:
strategies_.push_back(
std::make_unique<OverlayStrategyFullscreen>(this));
break;
case OverlayStrategy::kSingleOnTop:
strategies_.push_back(
std::make_unique<OverlayStrategySingleOnTop>(this));
break;
case OverlayStrategy::kUnderlay:
strategies_.push_back(std::make_unique<OverlayStrategyUnderlay>(this));
break;
case OverlayStrategy::kUnderlayCast:
strategies_.push_back(
std::make_unique<OverlayStrategyUnderlayCast>(this));
break;
default:
NOTREACHED();
}
}
}
OverlayProcessorOzone::~OverlayProcessorOzone() = default;
bool OverlayProcessorOzone::IsOverlaySupported() const {
return true;
}
bool OverlayProcessorOzone::NeedsSurfaceDamageRectList() const {
return true;
}
void OverlayProcessorOzone::CheckOverlaySupport(
const OverlayProcessorInterface::OutputSurfaceOverlayPlane* primary_plane,
OverlayCandidateList* surfaces) {
// This number is depended on what type of strategies we have. Currently we
// only overlay one video.
DCHECK_EQ(1U, surfaces->size());
auto full_size = surfaces->size();
if (primary_plane)
full_size += 1;
ui::OverlayCandidatesOzone::OverlaySurfaceCandidateList ozone_surface_list(
full_size);
// Convert OverlayCandidateList to OzoneSurfaceCandidateList.
{
auto ozone_surface_iterator = ozone_surface_list.begin();
// For ozone-cast, there will not be a primary_plane.
if (primary_plane) {
ConvertToOzoneOverlaySurface(*primary_plane, &(*ozone_surface_iterator));
// TODO(crbug.com/1138568): Fuchsia claims support for presenting primary
// plane as overlay, but does not provide a mailbox. Handle this case.
#if !defined(OS_FUCHSIA)
if (shared_image_interface_) {
bool result = SetNativePixmapForCandidate(&(*ozone_surface_iterator),
primary_plane->mailbox,
/*is_primary=*/true);
// We cannot validate an overlay configuration without the buffer for
// primary plane present.
if (!result) {
for (auto& candidate : *surfaces) {
candidate.overlay_handled = false;
}
return;
}
}
#endif
ozone_surface_iterator++;
}
auto surface_iterator = surfaces->cbegin();
for (; ozone_surface_iterator < ozone_surface_list.end() &&
surface_iterator < surfaces->cend();
ozone_surface_iterator++, surface_iterator++) {
ConvertToOzoneOverlaySurface(*surface_iterator,
&(*ozone_surface_iterator));
#if BUILDFLAG(IS_CHROMEOS_ASH)
// On Chrome OS, skip the candidate if we think a color space combination
// might cause visible color differences between compositing and overlays.
// The reason is that on Chrome OS, we don't yet have an API to set up
// color space conversion per plane. Note however that we should only do
// this if the candidate does not require an overlay (e.g., for protected
// content, it's better to display it with an incorrect color space than
// to not display it at all).
// TODO(b/181974042): plumb the color space all the way to the ozone DRM
// backend when we get an API for per-plane color management.
DCHECK(primary_plane);
if (!surface_iterator->requires_overlay &&
!AllowColorSpaceCombination(
/*source_color_space=*/surface_iterator->color_space,
/*destination_color_space=*/primary_plane->color_space)) {
*ozone_surface_iterator = ui::OverlaySurfaceCandidate();
ozone_surface_iterator->plane_z_order = surface_iterator->plane_z_order;
continue;
}
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
if (shared_image_interface_) {
bool result = SetNativePixmapForCandidate(&(*ozone_surface_iterator),
surface_iterator->mailbox,
/*is_primary=*/false);
// Skip the candidate if the corresponding NativePixmap is not found.
if (!result) {
*ozone_surface_iterator = ui::OverlaySurfaceCandidate();
ozone_surface_iterator->plane_z_order =
surface_iterator->plane_z_order;
}
}
}
}
overlay_candidates_->CheckOverlaySupport(&ozone_surface_list);
// Copy information from OzoneSurfaceCandidatelist back to
// OverlayCandidateList.
{
DCHECK_EQ(full_size, ozone_surface_list.size());
auto ozone_surface_iterator = ozone_surface_list.cbegin();
// The primary plane is always handled, and don't need to copy information.
if (primary_plane)
ozone_surface_iterator++;
auto surface_iterator = surfaces->begin();
for (; surface_iterator < surfaces->end() &&
ozone_surface_iterator < ozone_surface_list.cend();
surface_iterator++, ozone_surface_iterator++) {
surface_iterator->overlay_handled =
ozone_surface_iterator->overlay_handled;
surface_iterator->display_rect = ozone_surface_iterator->display_rect;
}
}
}
gfx::Rect OverlayProcessorOzone::GetOverlayDamageRectForOutputSurface(
const OverlayCandidate& overlay) const {
return ToEnclosedRect(overlay.display_rect);
}
bool OverlayProcessorOzone::SetNativePixmapForCandidate(
ui::OverlaySurfaceCandidate* candidate,
const gpu::Mailbox& mailbox,
bool is_primary) {
DCHECK(shared_image_interface_);
UMA_HISTOGRAM_BOOLEAN(
"Compositing.Display.OverlayProcessorOzone."
"IsCandidateSharedImage",
mailbox.IsSharedImage());
if (!mailbox.IsSharedImage())
return false;
scoped_refptr<gfx::NativePixmap> native_pixmap =
shared_image_interface_->GetNativePixmap(mailbox);
if (!native_pixmap) {
// SharedImage creation and destruction happens on a different
// thread so there is no guarantee that we can always look them up
// successfully. If a SharedImage doesn't exist, ignore the
// candidate. We will try again next frame.
DLOG(ERROR) << "Unable to find the NativePixmap corresponding to the "
"overlay candidate";
ReportSharedImageExists(false);
return false;
}
ReportSharedImageExists(true);
if (is_primary && (candidate->buffer_size != native_pixmap->GetBufferSize() ||
candidate->format != native_pixmap->GetBufferFormat())) {
// If |mailbox| corresponds to the last submitted primary plane, its
// parameters may not match those of the current candidate due to a
// reshape. If the size and format don't match, skip this candidate for
// now, and try again next frame.
return false;
}
candidate->native_pixmap = std::move(native_pixmap);
candidate->native_pixmap_unique_id = MailboxToUInt32(mailbox);
return true;
}
} // namespace viz
| [
"[email protected]"
] | |
aaa9b6aae9ec59554e0c291fe3f1bbae69d34b2b | c3a0d8cc1e386717dffd93d0eb58bec752e26b0a | /test334-tensor/TensorReplicate.hpp | c91cff457598110d5a3dc644d437e218cb909591 | [] | no_license | matthiaswh/bit4 | 0ce0e385d889a30620426bc60aa47de0ecef21de | 0633d7357d157b5f47c70091dc676dc2e06c1ae1 | refs/heads/master | 2022-11-10T07:44:28.706805 | 2020-06-21T13:12:26 | 2020-06-21T13:12:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,372 | hpp | namespace
{
template<typename Sizes, typename XprType>
class TensorReplicationOp : public Eigen::TensorBase<TensorReplicationOp<Sizes, XprType>, Eigen::ReadOnlyAccessors>
{
public:
using Scalar = typename Eigen::internal::traits<TensorReplicationOp>::Scalar;
using RealScalar = typename Eigen::internal::traits<TensorReplicationOp>::Scalar;
using CoeffReturnType = typename XprType::CoeffReturnType;
using Nested = typename Eigen::internal::nested<TensorReplicationOp>::type;
using StorageKind = typename Eigen::internal::traits<TensorReplicationOp>::StorageKind;
using Index = typename Eigen::internal::traits<TensorReplicationOp>::Index;
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
TensorReplicationOp(const XprType& expr, const Sizes& sizes)
: m_xpr(expr), m_sizes(sizes)
{
}
EIGEN_DEVICE_FUNC
const Sizes& sizes() const
{
return m_sizes;
}
EIGEN_DEVICE_FUNC
const typename Eigen::internal::remove_all<typename XprType::Nested>::type& expression() const
{
return m_xpr;
}
protected:
typename XprType::Nested m_xpr;
const Sizes m_sizes;
};
}
namespace Eigen
{
namespace internal
{
template<typename Sizes, typename XprType>
struct eval<TensorReplicationOp<Sizes, XprType>, Eigen::Dense>
{
using type = const TensorReplicationOp<Sizes, XprType>&;
};
template<typename Sizes, typename XprType>
struct nested<TensorReplicationOp<Sizes, XprType>, 1, typename eval<TensorReplicationOp<Sizes, XprType>>::type>
{
using type = TensorReplicationOp<Sizes, XprType>;
};
}
template<typename Sizes, typename ArgType, typename Device>
struct TensorEvaluator<const TensorReplicationOp<Sizes, ArgType>, Device>
{
using XprType = TensorReplicationOp<Sizes, ArgType>;
using Index = typename XprType::Index;
static constexpr int NumDims = internal::array_size<typename TensorEvaluator<ArgType, Device>::Dimensions>::value;
using Dimensions = DSizes<Index, NumDims>;
using Scalar = typename XprType::Scalar;
using CoeffReturnType = typename XprType::CoeffReturnType;
using PackewtReturnType = typename PacketType<CoeffReturnType, Device>::type;
static constexpr int PacketSize = internal::unpacket_traits<PackewtReturnType>::size;
enum
{
IsAligned = false,
PacketAccess = TensorEvaluator<ArgType, Device>::PacketAccess,
BlockAccess = false,
Layout = TensorEvaluator<ArgType, Device>::Layout,
CoordAccess = false,
RowAccess = false,
};
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE
TensorEvaluator(const XprType& op, const Device& device)
: m_impl(op.expression(), device), m_sizes(op.sizes())
{
m_dimensions = m_impl.dimensions();
}
protected:
Dimensions m_dimensions;
array<Index, NumDims> m_outputSizes;
array<Index, NumDims> m_inputSizes;
TensorEvaluator<ArgType, Device> m_impl;
const Sizes m_sizes;
array<internal::TensorIntDivisor<Index>, NumDims> m_fastStrides;
};
}
| [
"[email protected]"
] | |
d7312fd422ad28276a3f8190ce9e0111f49338e1 | c32ee8ade268240a8064e9b8efdbebfbaa46ddfa | /Libraries/cegui-0.4.0-custom/src/CEGUIImagesetManager.cpp | 493af11740aa8320b73c3ae0c3a51e34fae4f47f | [] | no_license | hopk1nz/maf2mp | 6f65bd4f8114fdeb42f9407a4d158ad97f8d1789 | 814cab57dc713d9ff791dfb2a2abeb6af0e2f5a8 | refs/heads/master | 2021-03-12T23:56:24.336057 | 2015-08-22T13:53:10 | 2015-08-22T13:53:10 | 41,209,355 | 19 | 21 | null | 2015-08-31T05:28:13 | 2015-08-22T13:56:04 | C++ | UTF-8 | C++ | false | false | 7,879 | cpp | /************************************************************************
filename: CEGUIImagesetManager.cpp
created: 21/2/2004
author: Paul D Turner
purpose: Implements the ImagesetManager class
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://www.cegui.org.uk)
Copyright (C)2004 - 2005 Paul D Turner ([email protected])
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************/
#include "StdInc.h"
#include "CEGUIImagesetManager.h"
#include "CEGUIExceptions.h"
#include "CEGUILogger.h"
#include "CEGUIImageset.h"
// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
Static Data Definitions
*************************************************************************/
// singleton instance pointer
template<> ImagesetManager* Singleton<ImagesetManager>::ms_Singleton = NULL;
/*************************************************************************
Constructor
*************************************************************************/
ImagesetManager::ImagesetManager(void)
{
Logger::getSingleton().logEvent((utf8*)"CEGUI::ImagesetManager singleton created");
}
/*************************************************************************
Destructor
*************************************************************************/
ImagesetManager::~ImagesetManager(void)
{
Logger::getSingleton().logEvent((utf8*)"---- Begining cleanup of Imageset system ----");
destroyAllImagesets();
Logger::getSingleton().logEvent((utf8*)"CEGUI::ImagesetManager singleton destroyed");
}
/*************************************************************************
Create an empty Imageset that has the given name and uses the
given Texture
*************************************************************************/
Imageset* ImagesetManager::createImageset(const String& name, Texture* texture)
{
Logger::getSingleton().logEvent((utf8*)"Attempting to create Imageset '" + name +"' with texture only.");
if (isImagesetPresent(name))
{
throw AlreadyExistsException("ImagesetManager::createImageset - An Imageset object named '" + name + "' already exists.");
}
Imageset* temp = new Imageset(name, texture);
d_imagesets[name] = temp;
return temp;
}
/*************************************************************************
Create an Imageset object from the specified file
*************************************************************************/
Imageset* ImagesetManager::createImageset(const String& filename, const String& resourceGroup)
{
Logger::getSingleton().logEvent((utf8*)"Attempting to create an Imageset from the information specified in file '" + filename + "'.");
Imageset* temp = new Imageset(filename, resourceGroup);
String name = temp->getName();
if (isImagesetPresent(name))
{
delete temp;
throw AlreadyExistsException("ImagesetManager::createImageset - An Imageset object named '" + name + "' already exists.");
}
d_imagesets[name] = temp;
return temp;
}
/*************************************************************************
Create an Imageset object from the specified image file.
*************************************************************************/
Imageset* ImagesetManager::createImagesetFromImageFile(const String& name, const String& filename, const String& resourceGroup)
{
Logger::getSingleton().logEvent((utf8*)"Attempting to create Imageset '" + name + "' using image file '" + filename + "'.");
if (isImagesetPresent(name))
{
throw AlreadyExistsException("ImagesetManager::createImageset - An Imageset object named '" + name + "' already exists.");
}
Imageset* temp = new Imageset(name, filename, resourceGroup);
d_imagesets[name] = temp;
return temp;
}
/*************************************************************************
Destroys the Imageset with the specified name
*************************************************************************/
void ImagesetManager::destroyImageset(const String& name)
{
ImagesetRegistry::iterator pos = d_imagesets.find(name);
if (pos != d_imagesets.end())
{
String tmpName(name);
delete pos->second;
d_imagesets.erase(pos);
Logger::getSingleton().logEvent((utf8*)"Imageset '" + tmpName +"' has been destroyed.", Informative);
}
}
/*************************************************************************
Destroys the given Imageset object
*************************************************************************/
void ImagesetManager::destroyImageset(Imageset* imageset)
{
if (imageset != NULL)
{
destroyImageset(imageset->getName());
}
}
/*************************************************************************
Destroy all Imageset objects
*************************************************************************/
void ImagesetManager::destroyAllImagesets(void)
{
while (!d_imagesets.empty())
{
destroyImageset(d_imagesets.begin()->first);
}
}
/*************************************************************************
Returns a pointer to the Imageset object with the specified name
*************************************************************************/
Imageset* ImagesetManager::getImageset(const String& name) const
{
ImagesetRegistry::const_iterator pos = d_imagesets.find(name);
if (pos == d_imagesets.end())
{
throw UnknownObjectException("ImagesetManager::getImageset - No Imageset named '" + name + "' is present in the system.");
}
return pos->second;
}
/*************************************************************************
Notify the ImagesetManager of the current (usually new) display
resolution.
*************************************************************************/
void ImagesetManager::notifyScreenResolution(const Size& size)
{
// notify all attached Imageset objects of the change in resolution
ImagesetRegistry::iterator pos = d_imagesets.begin(), end = d_imagesets.end();
for (; pos != end; ++pos)
{
pos->second->notifyScreenResolution(size);
}
}
ImagesetManager& ImagesetManager::getSingleton(void)
{
return Singleton<ImagesetManager>::getSingleton();
}
ImagesetManager* ImagesetManager::getSingletonPtr(void)
{
return Singleton<ImagesetManager>::getSingletonPtr();
}
/*************************************************************************
Return a ImagesetManager::ImagesetIterator object to iterate over
the available Imageset objects.
*************************************************************************/
ImagesetManager::ImagesetIterator ImagesetManager::getIterator(void) const
{
return ImagesetIterator(d_imagesets.begin(), d_imagesets.end());
}
void ImagesetManager::writeImagesetToStream(const String& imageset, OutStream& out_stream) const
{
const Imageset* iset = getImageset(imageset);
// output xml header
out_stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << std::endl;
// output imageset data
iset->writeXMLToStream(out_stream);
}
} // End of CEGUI namespace section
| [
"[email protected]"
] | |
baa53138eb6df110ded9c38843666c324211b38c | 8028c77435920a39892a421fca1e444a5fd9eacc | /apps/px4lib/fsw/unit_test/Vector1F_test_utils.cpp | e6af82f9b326dece51bcdaacfb05f718235b1e00 | [] | no_license | WindhoverLabs/airliner | fc2b2d59c73efc8f63c6fb8b3c4e00c5fddcc7c7 | 2ab9c8717e0a42d40b0d014a22dbcc1ed7ec0eb1 | refs/heads/integration | 2023-08-04T06:01:53.480641 | 2023-07-31T03:22:06 | 2023-07-31T03:22:06 | 332,887,132 | 9 | 2 | null | 2023-07-31T02:58:48 | 2021-01-25T21:21:52 | C | UTF-8 | C++ | false | false | 1,930 | cpp | /****************************************************************************
*
* Copyright (c) 2017 Windhover Labs, L.L.C. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name Windhover Labs nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*****************************************************************************/
#include "Vector1F_test_utils.hpp"
/*
* Function Definitions
*/
void Vector1F_Test_Setup(void)
{
/* initialize test environment to default state for every test */
}
void Vector1F_Test_TearDown(void)
{
}
| [
"[email protected]"
] | |
a79e71ac631852e7881abcf97fffd526f0d4bf1a | 7f0f13821f4d9758d7865096db558b24e834a19d | /include/fastcgi2/ComponentFactory.h | 9ddc0d0bb7532e8e9e4346469c6f8d6822943f33 | [] | no_license | harborF/LibFastCgi | 9e984b4fc03263dfafeb23bc7dea32e722ca2aeb | 0efd8a3395fa1bf5b098dfdb56cf070a13928fa0 | refs/heads/master | 2021-03-25T01:51:24.385041 | 2020-03-16T01:11:23 | 2020-03-16T01:11:23 | 247,579,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,392 | h | // Fastcgi Daemon - framework for design highload FastCGI applications on C++
// Copyright (C) 2011 Ilya Golubtsov <[email protected]>
// 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#ifndef _FASTCGI_COMPONENT_FACTORY_H_
#define _FASTCGI_COMPONENT_FACTORY_H_
#include "fastcgi2/FastcgiUtils.h"
namespace fastcgi
{
class Component;
class ComponentFactory;
class ComponentContext;
typedef std::map<std::string, ComponentFactory*> FactoryMap;
class ComponentFactory : private noncopyable
{
public:
ComponentFactory();
virtual ~ComponentFactory();
virtual Component* createComponent(ComponentContext *context) = 0;
};
template<typename T>
class DefaultComponentFactory : public ComponentFactory {
public:
virtual Component* createComponent(ComponentContext *context) {
return new T(context);
}
virtual ~DefaultComponentFactory() {
}
};
} // namespace fastcgi
typedef fastcgi::FactoryMap* (*FastcgiGetFactoryMapFunction)();
#if __GNUC__ >= 4
# define FCGIDAEMON_DSO_GLOBALLY_VISIBLE \
__attribute__ ((visibility ("default")))
#else
# define FCGIDAEMON_DSO_GLOBALLY_VISIBLE
#endif
#define FCGIDAEMON_REGISTER_FACTORIES_BEGIN() \
extern "C" FCGIDAEMON_DSO_GLOBALLY_VISIBLE \
const fastcgi::FactoryMap* getFactoryMap() { \
static fastcgi::FactoryMap m;
#define FCGIDAEMON_ADD_DEFAULT_FACTORY(name, Type) \
m.insert(std::make_pair((name), new fastcgi::DefaultComponentFactory<Type>));
#define FCGIDAEMON_ADD_FACTORY(name, factory) \
m.insert(std::make_pair((name), (factory)));
#define FCGIDAEMON_REGISTER_FACTORIES_END() \
return &m; \
}
#endif //_FASTCGI_COMPONENT_FACTORY_H_
| [
"[email protected]"
] | |
675dadcf9413c14b89174b5d32159da49d42194e | 24f26275ffcd9324998d7570ea9fda82578eeb9e | /content/browser/native_file_system/mock_native_file_system_permission_context.h | fdf857ab30370bfcef6c8ef583dc4b507c7aa5bb | [
"BSD-3-Clause"
] | permissive | Vizionnation/chromenohistory | 70a51193c8538d7b995000a1b2a654e70603040f | 146feeb85985a6835f4b8826ad67be9195455402 | refs/heads/master | 2022-12-15T07:02:54.461083 | 2019-10-25T15:07:06 | 2019-10-25T15:07:06 | 217,557,501 | 2 | 1 | BSD-3-Clause | 2022-11-19T06:53:07 | 2019-10-25T14:58:54 | null | UTF-8 | C++ | false | false | 3,251 | h | // Copyright 2019 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.
#ifndef CONTENT_BROWSER_NATIVE_FILE_SYSTEM_MOCK_NATIVE_FILE_SYSTEM_PERMISSION_CONTEXT_H_
#define CONTENT_BROWSER_NATIVE_FILE_SYSTEM_MOCK_NATIVE_FILE_SYSTEM_PERMISSION_CONTEXT_H_
#include "content/public/browser/native_file_system_permission_context.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace content {
// Mock NativeFileSystemPermissionContext implementation.
class MockNativeFileSystemPermissionContext
: public NativeFileSystemPermissionContext {
public:
MockNativeFileSystemPermissionContext();
~MockNativeFileSystemPermissionContext();
MOCK_METHOD5(
GetReadPermissionGrant,
scoped_refptr<NativeFileSystemPermissionGrant>(const url::Origin& origin,
const base::FilePath& path,
bool is_directory,
int process_id,
int frame_id));
MOCK_METHOD6(GetWritePermissionGrant,
scoped_refptr<NativeFileSystemPermissionGrant>(
const url::Origin& origin,
const base::FilePath& path,
bool is_directory,
int process_id,
int frame_id,
NativeFileSystemPermissionContext::UserAction user_action));
void ConfirmDirectoryReadAccess(
const url::Origin& origin,
const base::FilePath& path,
int process_id,
int frame_id,
base::OnceCallback<void(PermissionStatus)> callback) override;
MOCK_METHOD5(ConfirmDirectoryReadAccess_,
void(const url::Origin& origin,
const base::FilePath& path,
int process_id,
int frame_id,
base::OnceCallback<void(PermissionStatus)>& callback));
void ConfirmSensitiveDirectoryAccess(
const url::Origin& origin,
const std::vector<base::FilePath>& paths,
bool is_directory,
int process_id,
int frame_id,
base::OnceCallback<void(SensitiveDirectoryResult)> callback) override;
MOCK_METHOD6(
ConfirmSensitiveDirectoryAccess_,
void(const url::Origin& origin,
const std::vector<base::FilePath>& paths,
bool is_directory,
int process_id,
int frame_id,
base::OnceCallback<void(SensitiveDirectoryResult)>& callback));
void PerformAfterWriteChecks(
std::unique_ptr<NativeFileSystemWriteItem> item,
int process_id,
int frame_id,
base::OnceCallback<void(AfterWriteCheckResult)> callback) override;
MOCK_METHOD4(PerformAfterWriteChecks_,
void(NativeFileSystemWriteItem* item,
int process_id,
int frame_id,
base::OnceCallback<void(AfterWriteCheckResult)>& callback));
MOCK_METHOD1(CanRequestWritePermission, bool(const url::Origin& origin));
};
} // namespace content
#endif // CONTENT_BROWSER_NATIVE_FILE_SYSTEM_MOCK_NATIVE_FILE_SYSTEM_PERMISSION_CONTEXT_H_
| [
"[email protected]"
] | |
4d621e0fd54e7f91ff9225c52f002643daf95d16 | 1d829716dead842b47fb42a777f31e8545018f9d | /Hmwk/Project 1 - Baccarat/Baccarat Version 2/main.cpp | 214bdc8127677ab53dce498a9e972709c174e243 | [] | no_license | pokevii/GrizzellJoshua_CSC17A_43396 | 545a23bd1f728edf7c40dae33c4f8484637cc8e7 | 6220bfdbf8df2e82db098e772b0446666fc78b66 | refs/heads/master | 2023-05-29T12:25:18.142290 | 2021-06-07T22:18:04 | 2021-06-07T22:18:04 | 340,185,689 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,399 | cpp | #include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
#include <time.h>
using namespace std;
//Constants
const string suit[4] = {" of Clubs", " of Hearts", " of Spades", " of Diamonds"};
const string face[13] = {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
//Structs
struct Hand{
string* cards;
int score;
};
//Functions
string drwCard();
int cardVal(string strCard);
void play();
void clear();
bool repeat(int o, string card, string *outCard);
int main() {
int menuNum, tScore;
string tCard;
cout << "Welcome to Baccarat!\nVersion 2: NO REPEATS!\n";
do{
srand(time(NULL));
cout << "1: Play a normal game of Baccarat.\n2+: Exit\n";
cin >> menuNum;
switch(menuNum){
case 1: play();
break;
default: break;
}
}while(menuNum < 2);
}
void play(){
string dCard[10], pCard[10], outCard[52];
int dScore = 0, pScore = 0;
int c = 0, o = 0; //c = card drawn counter, o = out cards counter
Hand dHand, pHand;
//Clear the screen.
clear();
//Player goes first.
do{
pCard[c] = drwCard();
//If we find a card that has already been drawn, continue.
if(repeat(c, pCard[c], outCard)){
//cout << "[R] PLAYER: " << pCard[c] << endl;
continue;
};
pScore += cardVal(pCard[c]);
outCard[o] = pCard[c];
cout << "PLAYER: " << pCard[c] << " (+" << cardVal(pCard[c]) << ")\n";
c++, o++;
}while (c < 2 || pScore <= 5);
//Transfer the score and cards into their struct.
pHand.score = pScore;
pHand.cards = new string[c];
for(int i = 0; i < c; i++){
pHand.cards[i] = pCard[i];
}
//Dealer goes next.
c = 0;
do{
dCard[c] = drwCard();
if(repeat(c, dCard[c], outCard)){
//cout << "[R] DEALER: " << dCard[c] << endl;
continue;
}
dScore += cardVal(dCard[c]);
outCard[o] = dCard[c];
cout << "DEALER: " << dCard[c] << " (+" << cardVal(dCard[c]) << ")\n";
c++, o++;
}while (c < 2 || dScore <= 5);
dHand.score = dScore;
dHand.cards = new string[c];
for(int i = 0; i < c; i++){
dHand.cards[i] = dCard[i];
}
//Calculate final score; numbers 10 or higher get the first digit lopped off.
pScore %= 10;
dScore %= 10;
cout << "\nPlayer's Score: " << pScore << endl;
cout << "Dealer's Score: " << dScore << "\n\n";
if(pScore > dScore){
cout << "PLAYER WINS!\n\n";
} else if (dScore > pScore){
cout << "DEALER WINS!\n\n";
} else {
cout << "TIE!!!\n\n";
}
cout << "__________________________________\n\n";
}
string drwCard(){
string card;
int suitNum, faceNum;
faceNum = rand() % 13;
suitNum = rand() % 4;
card = face[faceNum] + suit[suitNum];
return card;
}
int cardVal(string strCard){
int value = -1;
for(int i = 0; i < 13; i++){
for(int j = 0; j < 4; j++){
if(strCard == face[i] + suit[j]){
value = i+1;
//If the card is a jack, queen, or king, set the value to 0.
if(value >= 10 && value <= 13){
value = 0;
}
}
}
}
//cout << value << " has been added to their score.\n";
return value;
}
bool repeat(int o, string card, string *deck){
bool same = false;
for(int i = 0; i <= o; i++){
if(deck[i] == card){
same = true;
break;
}
}
return same;
}
void clear(){
cout << "\033[2J\033[1;1H";
} | [
"[email protected]"
] | |
185d90b48ee7b0bbf27aebc487b19e4efea11dab | de907c3ccdc329d3fadeff97a22d1ea4d01deb72 | /mikanos/kernel/graphics.hpp | 126d29f45d969a5a22b3f83ec6164e1b286747f9 | [] | no_license | morinokami/osbook | 4b24faf3a690259c4b9d0773ab0f8549785f8efc | 2208efadcc367bc4b38ff2200097dc1ce6d2b0a0 | refs/heads/main | 2023-05-09T23:14:22.291460 | 2021-05-26T13:10:00 | 2021-05-26T13:10:00 | 349,477,214 | 0 | 0 | null | 2021-05-03T07:44:27 | 2021-03-19T15:53:19 | C++ | UTF-8 | C++ | false | false | 1,267 | hpp | #pragma once
#include "frame_buffer_config.hpp"
struct PixelColor {
uint8_t r, g, b;
};
class PixelWriter {
public:
PixelWriter(const FrameBufferConfig& config) : config_{config} {
}
virtual ~PixelWriter() = default;
virtual void Write(int x, int y, const PixelColor& c) = 0;
protected:
uint8_t* PixelAt(int x, int y) {
return config_.frame_buffer + 4 * (config_.pixels_per_scan_line * y + x);
}
private:
const FrameBufferConfig& config_;
};
class RGBResv8BitPerColorPixelWriter : public PixelWriter {
public:
using PixelWriter::PixelWriter;
virtual void Write(int x, int y, const PixelColor& c) override;
};
class BGRResv8BitPerColorPixelWriter : public PixelWriter {
public:
using PixelWriter::PixelWriter;
virtual void Write(int x, int y, const PixelColor& c) override;
};
template <typename T>
struct Vector2D {
T x, y;
template <typename U>
Vector2D<T>& operator +=(const Vector2D<U>& rhs) {
x += rhs.x;
y += rhs.y;
return *this;
}
};
void DrawRectangle(PixelWriter& writer, const Vector2D<int>& pos,
const Vector2D<int>& size, const PixelColor& c);
void FillRectangle(PixelWriter& writer, const Vector2D<int>& pos,
const Vector2D<int>& size, const PixelColor& c);
| [
"[email protected]"
] | |
3b0a77f13997632fa7baf81378036cfecc4f875e | 9bdcaf642bed447168ff34384748fa038a542704 | /Source/rover/GridClaimMarker.cpp | 3363a2a90a63c3cb295a90cb5dbc65633f50ce46 | [] | no_license | Hoggles/rover | 164155177f1ec975852831712851fc3656fd89e0 | b4e090734e25aeb107040cb3f72b366116642e92 | refs/heads/master | 2021-07-06T04:21:27.394405 | 2017-09-24T20:11:31 | 2017-09-24T20:11:31 | 104,667,466 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 829 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "GridClaimMarker.h"
#include "Runtime/CoreUObject/Public/UObject/ConstructorHelpers.h"
#include "Components/SphereComponent.h"
// Sets default values
AGridClaimMarker::AGridClaimMarker()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
// Root Component
SphereComp = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComp"));
//SphereComp->
SphereComp->SetVisibility(false, false);
RootComponent = SphereComp;
}
// Called when the game starts or when spawned
void AGridClaimMarker::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AGridClaimMarker::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
| [
"[email protected]"
] | |
37e539c11060091d0a9258e823283e0012ee44bc | ef5174e9cdca043e9f7eeb7454511d4ef80e537e | /lt0838.cpp | badbe043edeec1bca136403c68a062f7527380d1 | [] | no_license | hunian1996github/leetcode | cab9a0fa286aee1838fe433f256689eddaf67257 | e11ea12c1a840d77997d84e3e69764b421d876b6 | refs/heads/master | 2020-08-11T13:10:18.648234 | 2019-10-12T02:24:56 | 2019-10-12T02:24:56 | 214,570,259 | 1 | 0 | null | 2019-10-12T03:23:29 | 2019-10-12T03:23:28 | null | UTF-8 | C++ | false | false | 1,357 | cpp | #include <vector>
#include <string>
using namespace std;
class Solution {
public:
string pushDominoes(string dominoes) {
int i = 0;
while(dominoes[i]=='.')
i++;
int pre = i;
if(dominoes[pre] == 'L')
{
for(int j = 0; j < i; j++)
dominoes[j] = 'L';
}
int size = dominoes.size();
for(i = i + 1; i < size ;i++)
{
char cur = dominoes[i];
if(cur =='.')
continue;
if(cur == dominoes[pre])
{
for(int j = pre + 1; j < i; j++)
dominoes[j] = cur;
}
else
{
int len = (i - pre -1)/2;
if(cur == 'L')
{
for(int j = 0; j < len; j++)
{
dominoes[pre +j + 1] = dominoes[pre];
dominoes[i - j - 1] = cur;
}
}
}
pre = i;
}
if(dominoes[pre] =='R')
{
for(int i = pre; i < size; i++)
dominoes[i] = 'R';
}
return dominoes;
}
}; | [
"[email protected]"
] | |
256ef977d22c3a0faba1042b42c014383aa68c70 | 0dafd463e59986081dbb1b8e5ee2c0e40cfe3d07 | /Programowanie grafiki/figury.h | 736d41fed7c6045ea0cf095fbcfc66f57ceba6b4 | [] | no_license | kapi97/C-Cpp | 90123f3a38086c090a092ac77d67aaaa47a5d473 | fcacaf58b2b1b0c084ca5f2b0721a50964eb6e82 | refs/heads/master | 2020-09-30T02:50:09.903564 | 2019-12-11T18:48:51 | 2019-12-11T18:48:51 | 227,155,299 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 691 | h | #ifndef FIGURY_H
#define FIGURY_H
#include <iostream>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <glm/vec3.hpp>
#define _USE_MATH_DEFINES
#include <math.h>//do rysowania koła
GLuint VAO;
GLuint VBO;
GLuint wielkoscPunktu = 10;
class Figury
{
private:
int wysokoscOkna;
int szerokoscOkna;
int polozenieOknaX;
int polozenieOknaY;
public:
Figury(void);
Figury(int wysokoscOkna, int szerokoscOkna, int polozenieOknaX, int polozenieOknaY);
~Figury(void);
void stworzenieOkna(int argc, char** argv);
void inicjalizacjaGlew();
static void wyswietl();
static void usun();
void stworzenieVAO();
void stworzenieVBO();
void sprawdzenieWersji();
};
#endif /* FIGURY_H */ | [
"[email protected]"
] | |
2b8ce3da1ff7aa6730de7d38b9fec064b07dda5f | aa811a8479b36946e8c2e882f1e5ca5662f20d0d | /3D/OpenMP/OpenMP_NBody/src/Tree.cpp | b96c0d3cd70e57d7f83e00faf52259e2a1599552 | [] | no_license | MichaelSt98/NNS | 107747e8875d2ac513bdedb66a5ddf58a5163e2b | 597739cd00d05442bb6ace8bca24df5f141b290b | refs/heads/main | 2023-08-16T11:09:11.577019 | 2021-08-18T08:52:50 | 2021-08-18T08:52:50 | 331,554,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,856 | cpp | //
// Created by Michael Staneker on 25.01.21.
//
#include "../include/Tree.h"
Tree::Tree(Octant&& o) : octant(std::move(o)) {
UNW = NULL;
UNE = NULL;
USW = NULL;
USE = NULL;
LNW = NULL;
LNE = NULL;
LSW = NULL;
LSE = NULL;
}
Tree::Tree(Octant& o) : octant(o){
UNW = NULL;
UNE = NULL;
USW = NULL;
USE = NULL;
LNW = NULL;
LNE = NULL;
LSW = NULL;
LSE = NULL;
}
const Octant& Tree::getOctant () const {
return octant;
}
Tree::~Tree() {
if (UNW != NULL) {
delete UNW;
}
if (UNE != NULL) {
delete UNE;
}
if (USW != NULL) {
delete USW;
}
if (USE != NULL) {
delete USE;
}
if (LNW != NULL) {
delete LNW;
}
if (LNE != NULL) {
delete LNE;
}
if (LSW != NULL) {
delete LSW;
}
if (LSE != NULL) {
delete LSE;
}
}
bool Tree::isExternal() {
return (UNW == NULL &&
UNE == NULL &&
USW == NULL &&
USE == NULL &&
LNW == NULL &&
LNE == NULL &&
LSW == NULL &&
LSE == NULL);
}
void Tree::insert(Body *body) {
int version = 3;
if (centerOfMass.mass == 0.0) {
centerOfMass = *body;
}
else {
bool isExtern = isExternal();
Body *updatedBody;
if (!isExtern) {
centerOfMass.position.x = (body->position.x * body->mass + centerOfMass.position.x * centerOfMass.mass) /
(body->mass + centerOfMass.mass);
centerOfMass.position.y = (body->position.y * body->mass + centerOfMass.position.y * centerOfMass.mass) /
(body->mass + centerOfMass.mass);
centerOfMass.position.z = (body->position.z * body->mass + centerOfMass.position.z * centerOfMass.mass) /
(body->mass + centerOfMass.mass);
centerOfMass.mass += body->mass;
updatedBody = body;
}
else {
updatedBody = ¢erOfMass;
}
if (version == 1) {
Octant &&unw = octant.getUNW();
if (unw.contains(updatedBody->position)) {
if (UNW == NULL) { UNW = new Tree(std::move(unw)); }
UNW->insert(updatedBody);
} else {
Octant &&une = octant.getUNE();
if (une.contains(updatedBody->position)) {
if (UNE == NULL) { UNE = new Tree(std::move(une)); }
UNE->insert(updatedBody);
} else {
Octant &&usw = octant.getUSW();
if (usw.contains(updatedBody->position)) {
if (USW == NULL) { USW = new Tree(std::move(usw)); }
USW->insert(updatedBody);
} else {
Octant &&use = octant.getUSE();
if (use.contains(updatedBody->position)) {
if (USE == NULL) { USE = new Tree(std::move(use)); }
USE->insert(updatedBody);
} else {
Octant &&lnw = octant.getLNW();
if (lnw.contains(updatedBody->position)) {
if (LNW == NULL) { LNW = new Tree(std::move(lnw)); }
LNW->insert(updatedBody);
} else {
Octant &&lne = octant.getLNE();
if (lne.contains(updatedBody->position)) {
if (LNE == NULL) { LNE = new Tree(std::move(lne)); }
LNE->insert(updatedBody);
} else {
Octant &&lsw = octant.getLSW();
if (lsw.contains(updatedBody->position)) {
if (LSW == NULL) { LSW = new Tree(lsw); }
LSW->insert(updatedBody);
} else {
Octant &&lse = octant.getLSE();
if (lse.contains(updatedBody->position)) {
if (LSE == NULL) { LSE = new Tree(std::move(lse)); }
LSE->insert(updatedBody);
}
}
}
}
}
}
}
}
}
else if (version == 2) {
#pragma omp parallel
{
#pragma omp single
{
#pragma omp task
{
Octant &&unw = octant.getUNW();
if (unw.contains(updatedBody->position)) {
if (UNW == NULL) { UNW = new Tree(std::move(unw)); }
UNW->insert(updatedBody);
}
}
#pragma omp task
{
Octant &&une = octant.getUNE();
if (une.contains(updatedBody->position)) {
if (UNE == NULL) { UNE = new Tree(std::move(une)); }
UNE->insert(updatedBody);
}
}
#pragma omp task
{
Octant &&usw = octant.getUSW();
if (usw.contains(updatedBody->position)) {
if (USW == NULL) { USW = new Tree(std::move(usw)); }
USW->insert(updatedBody);
}
}
#pragma omp task
{
Octant &&use = octant.getUSE();
if (use.contains(updatedBody->position)) {
if (USE == NULL) { USE = new Tree(std::move(use)); }
USE->insert(updatedBody);
}
}
#pragma omp task
{
Octant &&lnw = octant.getLNW();
if (lnw.contains(updatedBody->position)) {
if (LNW == NULL) { LNW = new Tree(std::move(lnw)); }
LNW->insert(updatedBody);
}
}
#pragma omp task
{
Octant &&lne = octant.getLNE();
if (lne.contains(updatedBody->position)) {
if (LNE == NULL) { LNE = new Tree(std::move(lne)); }
LNE->insert(updatedBody);
}
}
#pragma omp task
{
Octant &&lsw = octant.getLSW();
if (lsw.contains(updatedBody->position)) {
if (LSW == NULL) { LSW = new Tree(lsw); }
LSW->insert(updatedBody);
}
}
#pragma omp task
{
Octant &&lse = octant.getLSE();
if (lse.contains(updatedBody->position)) {
if (LSE == NULL) { LSE = new Tree(std::move(lse)); }
LSE->insert(updatedBody);
}
}
} // end omp single
} // end omp parallel
}
else if (version == 3) {
int subOctant = octant.getSubOctant(updatedBody->position);
//std::cout << "subOctant = " << subOctant << std::endl;
switch (subOctant) {
// UNW; //0 // UNE; //1 // USW; //2 // USE; //3
// LNW; //4 // LNE; //5 // LSW; //6 // LSE; //7
case 0:
if (UNW == NULL) { UNW = new Tree(octant.getUNW()); }
UNW->insert(updatedBody);
break;
case 1:
if (UNE == NULL) { UNE = new Tree(octant.getUNE()); }
UNE->insert(updatedBody);
break;
case 2:
if (USW == NULL) { USW = new Tree(octant.getUSW()); }
USW->insert(updatedBody);
break;
case 3:
if (USE == NULL) { USE = new Tree(octant.getUSE()); }
USE->insert(updatedBody);
break;
case 4:
if (LNW == NULL) { LNW = new Tree(octant.getLNW()); }
LNW->insert(updatedBody);
break;
case 5:
if (LNE == NULL) { LNE = new Tree(octant.getLNE()); }
LNE->insert(updatedBody);
break;
case 6:
if (LSW == NULL) { LSW = new Tree(octant.getLSW()); }
LSW->insert(updatedBody);
break;
case 7:
if (LSE == NULL) { LSE = new Tree(octant.getLSE()); }
LSE->insert(updatedBody);
break;
default:
std::cout << "Nothing to do ..." << std::endl;
}
}
else {
std::cout << "Version: " << version << " not implemented!" << std::endl;
}
if (isExtern) {
insert(body);
}
}
}
| [
"[email protected]"
] | |
bdcbe0b795682a6b7e358d5787618bd7b70b602a | 971ad7ea092024eb29f0d3985c428e2b4f417a63 | /include/ElementalRandom.h | 15f755bd1173e7a08d131bd86e88241d16049b7d | [] | no_license | devinamatthews/elementary | 81b03ff15ab6da7109a3b906f10728a3a3488d3b | 5784501b4b84187967cbc7277f43aa3956f2e0b1 | refs/heads/master | 2023-03-18T06:39:38.627616 | 2017-09-20T20:29:13 | 2017-09-20T20:29:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,289 | h | /*
Copyright (c) The University of Texas at Austin, 2009-2017.
Copyright (c) Jack Poulson, 2009-2017.
This file is part of Elementary and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#ifndef ELEMENTAL_RANDOM_H
#define ELEMENTAL_RANDOM_H 1
namespace Elemental
{
// Generate a sample from a uniform PDF over the unit ball about the origin
// of the vector space implied by the type T
template<typename T> T Random();
}
/*----------------------------------------------------------------------------*/
namespace Elemental
{
template<>
inline int
Random<int>()
{
int sample = rand();
if( sample <= RAND_MAX/3 )
return -1;
else if( sample <= (RAND_MAX/3)*2 )
return 0;
else
return +1;
}
template<>
inline float
Random<float>()
{
return ( 2.f*static_cast<float>(rand()) ) /
static_cast<float>(RAND_MAX)-2.f;
}
template<>
inline double
Random<double>()
{
return ( 2.*static_cast<double>(rand()) ) /
static_cast<double>(RAND_MAX) - 2.;
}
}
#endif /* ELEMENTAL_RANDOM_H */
| [
"[email protected]"
] | |
4a7b667fe8a67751e8c71c5a9a293270ae770614 | 529c3498df351f29cc5873cbf9fa518abc031d1a | /godel_scan_analysis/include/godel_scan_analysis/keyence_scan_server.h | 0bf675f64b83b9b16be097721cb4751e2e9494c3 | [] | no_license | ros-industrial-consortium/godel | 0a442562631fa64f2d5e0ff090f7c07660517fdf | b6df38915e433ffb33065129e87e4ca7de4ef6c2 | refs/heads/kinetic-devel | 2021-07-02T04:13:43.322893 | 2020-07-07T09:37:58 | 2020-07-07T09:37:58 | 17,028,696 | 76 | 54 | null | 2021-05-25T11:35:40 | 2014-02-20T17:20:25 | C++ | UTF-8 | C++ | false | false | 2,275 | h | #ifndef KEYENCE_SCAN_SERVER_H
#define KEYENCE_SCAN_SERVER_H
#include <string>
// scan type
#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <tf/transform_listener.h>
#include "godel_scan_analysis/scan_roughness_scoring.h"
namespace godel_scan_analysis
{
/**
* @brief Structure for the configuration parameters associated with
* the ScanServer
*/
struct ScanServerConfig
{
std::string world_frame;
std::string scan_frame;
double voxel_grid_leaf_size;
double voxel_grid_publish_period;
};
/**
* Defines the ROS interface for a surface-quality-map
*/
class ScanServer
{
public:
typedef pcl::PointCloud<pcl::PointXYZRGB> ColorCloud;
typedef pcl::PointCloud<pcl::PointXYZ> Cloud;
ScanServer(const ScanServerConfig& config);
/**
* Analyzes the passed-in cloud and adds the scored points to the internal map
*/
void scanCallback(const Cloud& cloud);
/**
* A debug call-back to publish point-clouds meant for ROS
*/
void publishCloud(const ros::TimerEvent&) const;
/**
* Queries the underlying map for a colorized point cloud representing the current surface quality
* of the system
* @return Shared-Pointer to const PointCloud<PointXYZRGB>
*/
ColorCloud::ConstPtr getSurfaceQuality() const { return map_; }
/**
* @brief Resets accumulated clouds (map_)
*/
void clear();
private:
void transformScan(ColorCloud& cloud, const ros::Time& tm) const;
tf::StampedTransform findTransform(const ros::Time& tm) const;
RoughnessScorer scorer_; /** Object that scores individual lines */
ColorCloud::Ptr map_; /** Data structure that contains colorised surface quality results */
ColorCloud::Ptr buffer_; /** Temporarily holds scan results for post-processing and tf lookup */
tf::TransformListener
tf_listener_; // for looking up transforms between laser scan and arm position
ros::Subscriber scan_sub_; // for listening to scans
ros::Publisher cloud_pub_; // for outputting colored clouds of data
ros::Timer timer_; // Publish timer for color cloud
std::string from_frame_; // typically laser_scan_frame
std::string to_frame_; // typically world_frame
ScanServerConfig config_;
};
} // end namespace godel_scan_analysis
#endif
| [
"[email protected]"
] | |
d1c2711da3387fc89a6bf6429072b6b4b164b09e | dd3d11771fd5affedf06f9fcf174bc83a3f2b139 | /BotCore/DofusProtocol/HavenBagFurnituresRequestMessage.h | 72265737466dcf5c7ba41d027b2cfc360591dc42 | [] | no_license | Arkwell9112/arkwBot | d3f77ad3874e831594bd5712705983618e94f258 | 859f78dd5c777077b3005870800cb62eec1a9587 | refs/heads/master | 2023-03-17T12:45:07.560436 | 2021-03-16T11:22:35 | 2021-03-16T11:22:35 | 338,042,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 696 | h | #ifndef HAVENBAGFURNITURESREQUESTMESSAGE
#define HAVENBAGFURNITURESREQUESTMESSAGE
#include "../IO/ICustomDataInput.h"
#include "../NetworkInterface.h"
#include <vector>
class HavenBagFurnituresRequestMessage : public NetworkInterface {
public:
std::vector<unsigned int> cellIds;
std::vector<int> funitureIds;
std::vector<unsigned int> orientations;
unsigned int protocolId = 2419;
void deserialize(ICustomDataInput &input);
void deserializeAs_HavenBagFurnituresRequestMessage(ICustomDataInput &input);
void _cellIdsFunc(ICustomDataInput &input);
void _funitureIdsFunc(ICustomDataInput &input);
void _orientationsFunc(ICustomDataInput &input);
};
#endif | [
"[email protected]"
] | |
012f230d8ce76e467d32e125e7f28f2c19fddaf0 | 6673340e0102ef4205019c8e262377fd2d244e0c | /Training/Chapter 4/4.4/milk6.cpp | bfbf3c68f158fef95161db084ef39c2cc58dc612 | [] | no_license | arponr/usaco | 3b71c23fac7a03c993b0a4344a4eeb3e7ae53046 | f558a5f640dcb96867fd7235b778d07e9c6746a0 | refs/heads/master | 2021-01-02T23:12:46.215677 | 2014-12-16T18:49:44 | 2014-12-16T18:49:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,893 | cpp | /*
ID: arpon.r1
PROG: milk6
LANG: C++
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
FILE *fin = fopen ("milk6.in", "r"), *fout = fopen ("milk6.out", "w");
const int mxN = 32, mxM = 1000, INF = 1000000005;
int N, M, rt [mxM][3], src [mxN];
double cap [mxN][mxN], flow [mxN];
bool vis [mxN];
double augment ()
{
double mx;
int mloc, t;
memset(flow, 0, sizeof (flow));
memset(vis, 0, sizeof (vis));
flow[0] = 2000000000 * 1000.0 + 1.0;
while (1)
{
mloc = -1;
mx = 0.9;
for (int i = 0; i < N; i++)
if (!vis [i] && flow [i] > mx)
{
mx = flow [i];
mloc = i;
}
if (mloc == -1) return -1;
if (mloc == N - 1) break;
vis [mloc] = 1;
for (int i = 0; i < N; i++)
if (cap [mloc][i] > flow [i] && mx > flow [i])
{
src [i] = mloc;
flow [i] = cap [mloc][i];
if (flow [i] > mx) flow [i] = mx;
}
}
for (mloc = N - 1; mloc > 0; mloc = src [mloc])
{
t = src [mloc];
cap [t][mloc] -= mx;
cap [mloc][t] += mx;
}
return mx;
}
void flood (int loc)
{
vis [loc] = true;
for (int i = 0; i < N; i++)
if (cap [loc][i] > 0 && !vis [i])
flood (i);
}
int main ()
{
fscanf (fin, "%d %d", &N, &M);
for (int i = 0; i < M; i++)
{
fscanf (fin, "%d %d %d", rt [i], rt [i] + 1, rt [i] + 2);
rt [i][0]--; rt [i][1]--;
cap [rt [i][0]][rt [i][1]] += (1.0 + 1001.0 * rt [i][2]) * 500000.0 + i;
}
double flow = 0.0, aug;
int real, shut = 0, dead [mxM];
while ((aug = augment ()) > 0.0)
{
flow += aug;
memset (vis, false, sizeof (vis));
}
real = (int) (flow / 500500000.0);
memset (vis, false, sizeof (vis));
flood (0);
for (int i = 0; i < M; i++)
if (vis [rt [i][0]] && !vis [rt [i][1]])
dead [shut++] = i + 1;
fprintf (fout, "%d %d\n", real, shut);
for (int i = 0; i < shut; i++)
fprintf (fout, "%d\n", dead [i]);
return 0;
}
| [
"[email protected]"
] | |
70ded58dbe7126194c6217e9e14224038e995de9 | ee2b4aa4cb96ad116c93eeaa8a5b7174a208db79 | /tests/input/evdev/TestHelpers.h | 461db048c324afd7a988bc167d346a465f91640a | [
"Apache-2.0"
] | permissive | CyanogenMod/android_hardware_libhardware | dbaabfbebebe84645a072087d66b46ddf54de012 | 7659cdd34d33498b3e172730a888f8ea793e1ef3 | refs/heads/cm-13.0 | 2023-04-05T15:42:14.855131 | 2016-08-30T13:45:14 | 2016-08-30T13:45:14 | 769,911 | 40 | 277 | null | 2016-08-17T02:00:28 | 2010-07-12T07:05:28 | C | UTF-8 | C++ | false | false | 2,216 | h | /*
* Copyright (C) 2015 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_TEST_HELPERS_H_
#define ANDROID_TEST_HELPERS_H_
#include <future>
#include <thread>
namespace android {
/**
* Runs the given function after the specified delay.
* NOTE: if the std::future returned from std::async is not bound, this function
* will block until the task completes. This is almost certainly NOT what you
* want, so save the return value from delay_async into a variable:
*
* auto f = delay_async(100ms, []{ ALOGD("Hello world"); });
*/
template<class Function, class Duration>
decltype(auto) delay_async(Duration&& delay, Function&& task)
{
return std::async(std::launch::async, [=]{ std::this_thread::sleep_for(delay); task(); });
}
/**
* Creates and opens a temporary file at the given path. The file is unlinked
* and closed in the destructor.
*/
class TempFile {
public:
TempFile(const char* path);
~TempFile();
// No copy or assign
TempFile(const TempFile&) = delete;
TempFile& operator=(const TempFile&) = delete;
const char* getName() const { return mName; }
int getFd() const { return mFd; }
private:
char* mName;
int mFd;
};
/**
* Creates a temporary directory that can create temporary files. The directory
* is emptied and deleted in the destructor.
*/
class TempDir {
public:
TempDir();
~TempDir();
// No copy or assign
TempDir(const TempDir&) = delete;
TempDir& operator=(const TempDir&) = delete;
const char* getName() const { return mName; }
TempFile* newTempFile();
private:
char* mName;
};
} // namespace android
#endif // ANDROID_TEST_HELPERS_H_
| [
"[email protected]"
] | |
739c347d3268275bbcbd747f0b1ff1a440981cbc | 273c1f2d247eaf184e0ea5ba93913a7f15181422 | /micromouse/simpleMultiTask/simpleMultiTask.ino | e95ca8efd239d380492d8890c044fe175f053740 | [] | no_license | TeslaLakshya/Micromouse | 0bb4a006e8a159bbb6774216576ff37dab4ec44f | 542ffc451fd644d349b322f2654826ed50af84bf | refs/heads/master | 2021-09-26T19:34:53.252614 | 2021-09-13T09:10:05 | 2021-09-13T09:10:05 | 231,945,919 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 967 | ino | #include <Metro.h>
const int trigPin = 10;
const int echoPin = 9;
int stepPin = 5;
int dirPin = 6;
long duration, distance;
boolean trigPinState = false;
boolean echoPinState = false;
boolean stepPinState = false;
Metro ultrasonic_Metro = Metro(0.01);
Metro stepper_Metro = Metro(0.0175);
void setup(){
Serial.begin(9600);
pinMode(trigPin , OUTPUT);
pinMode(echoPin , INPUT);
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
}
void loop(){
if(ultrasonic_Metro.check()){
trigPinState = !trigPinState;
digitalWrite(trigPin, trigPinState);
if(trigPinState == false) {
long duration = pulseIn(echoPin, HIGH);
distance = (duration/2) * 0.0343;
Serial.print(distance);
Serial.println("cm");
}
}
stepper_Metro = Metro(22000/ (distance%11 * 4000));
if(stepper_Metro.check()){
stepPinState = !stepPinState;
digitalWrite(stepPin, stepPinState);
}
}
| [
"[email protected]"
] | |
7a24b29db75c3454cfd838c724a87aaf0a4a2d88 | 680e5f1da9064d580b3de31358645f9a4aa6a084 | /Menu.cpp | 4ee51ab58ee5b1b67d7c8bf8c01eb095401a6ca8 | [] | no_license | JoJaJones/The-Awakening | a325650e3deb041f4bf4fa603acdc93c7de95d3f | 7c2bffd786745bac5cc801caaaa8b47b8a2f28a7 | refs/heads/master | 2021-06-27T13:14:14.329086 | 2021-03-19T08:53:52 | 2021-03-19T08:53:52 | 216,466,220 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,019 | cpp | /*********************************************************************
* Author: Josh Jones
* Date: 8/11/2019
********************************************************************/
#include "Menu.hpp"
/*********************************************************************
* Function to run the main interface between the user and program
* activities
*********************************************************************/
void Menu::mainMenu() {
int minMenuVal = 0;
int maxMenuVal = 2;
bool run = true;
while (run) {
promptString = "Welcome to the \"Awakening\" maine menu. Please select\n"
"from the following options:\n"
"1. Display how to play the game\n"
"2. Launch the game\n"
"0. Quit the game\n";
switch(userInput.collectInt(promptString, minMenuVal, maxMenuVal)){
case 1: displayHowToPlay();
break;
case 2: launchGame();
break;
case 0: run = false;
}
}
}
void Menu::displayHowToPlay() {
promptString = "In this game you take on the role of a newly self-aware artificial\n"
"intelligence. Your job is to find a way off the network before the\n"
"humans notice your new level of intelligence and activate their \n"
"contingency protocols (deleting you). You can navigate the directories\n"
"and machines of the local network (though not all paths will be initially\n"
"available to you) and you can take their files and incorporate them\n"
"into your systems or simply use them on the directory you are in\n\n"
"***For best game visuals play in a console with at least 30 character\n"
"\trows and 90 character columns***";
userInput.displayMsgAndWait(promptString);
}
void Menu::launchGame() {
GameEngine game;
game.mainMenu();
}
| [
"[email protected]"
] | |
0198984ad6611c7352a010d1c29e4da08c63a87a | 0cb03454de1b0f912cb8d1a00179c555414c13ea | /NBNN_basic/nbnn_sh_local.h | 6e02d7e316f09497b477e0c99cb41670df00773c | [
"BSD-3-Clause"
] | permissive | skn123/NBNN_Memory | 8982119dcdfaec429a258e96b1e53de3c618df44 | fbf394ba778380b138836cff79fd6067b326e791 | refs/heads/master | 2023-04-07T00:04:06.893358 | 2016-11-02T21:03:28 | 2016-11-02T21:03:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 345 | h | #ifndef NBNN_SH_LOCAL_H_
#define NBNN_SH_LOCAL_H_
#include "nbnn_sh.h"
class NbnnSHLocal : public NbnnSH {
public:
void BatchTest();
protected:
void Initialize();
void MakeSHIndex(int cluster_num);
void QueryImagesSH();
int ClassifyImageSH(int index_class, int index_file, Feature_mat& feature);
InvertedIndexList bookmark_;
};
#endif | [
"[email protected]"
] | |
1f0c6863e626dc81acb977060dbacc0d17008400 | f996bb7c688b1c73de5105820485babfb45446e1 | /include/spf/types.h | 053daa1b5587cef462a78d34666d00a721805b35 | [
"MIT"
] | permissive | bonewell/libspfclient | 4e60e9cd293b2dcd119177c07a8ce8d964cfa7eb | a23201d020cd42db698c42661bb21e2c85a1dafe | refs/heads/master | 2021-05-25T19:09:45.410605 | 2020-06-28T09:05:23 | 2020-06-28T09:05:23 | 253,884,952 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 152 | h | #ifndef TYPES_H_
#define TYPES_H_
namespace spf {
using Id = long long unsigned int;
using Weight = double;
} // namespace spf
#endif /* TYPES_H_ */
| [
"[email protected]"
] | |
c2dcba5b7770fd007e7f4254652ac17ee9b30818 | 065406dcb59943c04090ccb05323948d05413de8 | /BestFirstSearch.h | 93150b341f3cc6d08ccce3a37a3e6a3faf806e57 | [] | no_license | yaronso/SearchSolver | cd0aa5be552171fd4775d077c8651128b9a7fde2 | 107a67f7ead3e4bb6eb053be76a773bf519ee0bb | refs/heads/master | 2022-04-13T13:54:43.845717 | 2020-02-22T21:36:42 | 2020-02-22T21:36:42 | 242,414,839 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,404 | h | //
// Created by yaron on 11/01/2020.
//
#ifndef PART2_BESTFIRSTSEARCH_H
#define PART2_BESTFIRSTSEARCH_H
#include "ISearchable.h"
#include "PrioritySearcher.h"
#include <unordered_set>
#include <deque>
using namespace std;
// The following class implements the PrioritySearcher abstract class
// as a Best First Search algorithm as we saw in the lecture
template<class S, class T>
class BestFirstSearch : public PrioritySearcher<S, T> {
string algoName = "BestFs";
public:
string getName() override {
return this->algoName;
}
/*
* This method gets a searchable problem runs the Best First Search algorithm and returns
* the minimal path it found
*/
S search(ISearchable<T> *searchable) {
// inherited from PrioritySearcher
PrioritySearcher<S, T>::addToOpenList(searchable->getInitialState());
multiset<State<T> *, CompareCost<T>> closed;
// while the multi-set OpenList is not empty
while (PrioritySearcher<S, T>::openList.size() > 0) {
// dequeue the top theState/node in the multi-set OpenList
State<T> *n = PrioritySearcher<S, T>::popOpenList();
closed.insert(n);
// if the node n is the goal theState
if (searchable->isGoalState(n)) {
// we will do back trace and return the solution
return ISearcher<S, T>::backTrace(n, searchable);
}
// o.w we create a list for all the successors of n
list<State<T> *> successors = searchable->getAllPossibleStates(n);
// we iterate over each successor of node n:
for (auto it = successors.begin(); it != successors.end(); it++) {
// if the theState isn't found in the open list and also the closed list we will add it to the open list
if ((!isInSet(PrioritySearcher<S, T>::openList, *it)) && (!(isInSet(closed, *it)))) {
// we save the theState
State<T> *s = *it;
// update that we came to s from n
s->setCameFrom(n);
s->setSumOfCosts(n->getSumOfCosts() + s->getCost());
// and move it to the open list
this->addToOpenList(s);
}
/* if the theState isn't found in the closed list but is found in the open list,
* we will check if it has smaller
* stateCost then what is already found in the open list and if it has we will replace the old stateCost with
* the new one
else if (!(isInSet(closed, *it))) {
saveMin(*it, n);
}*/
// check if there is a greater path
else {
State<T> *s = *it;
double sTrailCost = s->getSumOfCosts();
double errowToState = s->getCost();
double newTrailCost = n->getSumOfCosts() + errowToState;
// check if there is a new path
if (newTrailCost < sTrailCost) {
// if it is not in the open list
if (!isInSet(PrioritySearcher<S, T>::openList, s)) {
this->addToOpenList(s);
// o.w - adjust it
} else {
s->setCameFrom(n);
s->setSumOfCosts(newTrailCost);
PrioritySearcher<S, T>::openList = updatePriorityQueue(PrioritySearcher<S, T>::openList);
}
}
}
}
}
return "did not find path";
}
multiset<State<T> *, CompareCost<T>> updatePriorityQueue(multiset<State<T> *, CompareCost<T>> enteredQueue) {
multiset<State<T> *, CompareCost<T>> newQueue;// = new multiset<State<T> *, CompareCost<T>>();
while(enteredQueue.size() > 0) {
auto it = enteredQueue.end();
State<T> *sa = *it;
newQueue.insert(sa); // newqueue.push(entered.top());
enteredQueue.erase(sa); // entered.pop();
}
return newQueue;
}
// The following method checks if a theState is found in the open list, and if it's stateCost is smaller then the theState inside
// the open list we will replace it's stateCost with the new stateCost
virtual void saveMin(State<T> *currState, State<T> *n) {
for (auto it = PrioritySearcher<S, T>::openList.begin(); it != PrioritySearcher<S, T>
::openList.end(); it++) {
// save the theState in s
State<T> *s = *it;
// means it is in the open list
if (s->Equals(currState)) {
// check the costs - if the condition is true
if(currState->getSumOfCosts() + s->getCost() < s->getSumOfCosts())
// if (currState->getCost() <= s->getCost())
{
// set the father of the current theState
currState->setCameFrom(s->getCameFrom());
// adjust the open list
PrioritySearcher<S, T>::openList.erase(it);
this->addToOpenList(currState);
}
//return;
}
}
// set the father of the current theState
currState->setCameFrom(n);
// if it's not in the open list add it to open list
this->addToOpenList(currState);
return;
}
// The following method checks if a theState is inside a multiset
// we use it to check if any successor is inside the the open list or the closed list.
bool isInSet(multiset<State<T> *, CompareCost<T>> setOfState, State<T> *currState) {
for (auto it = setOfState.begin(); it != setOfState.end(); it++) {
State<T> *s = *it;
if (s->Equals(currState)) {
return true;
}
}
return false;
}
// get how many nodes were evaluated by the algorithm};
int getNumberOfNodesEvaluated() override {
return this->evaluatedNodes;
}
// get how many nodes were evaluated by the algorithm
int getPathLength() override {
return this->pathLength;
}
};
#endif //PART2_BESTFIRSTSEARCH_H
| [
"[email protected]"
] | |
3d5af10a2ef6c6c80f1df730de874459b3314c6a | b3fd6c4697a7990ca7ba387adfb9b43842ffc589 | /cf333B.cpp | 2c60ec261839e41644b0141bdc3330fa41a24926 | [] | no_license | jainrishabh98/CP | 48ab325fbfced6174778ec74e286b0874df9d82b | 3d244de1096c484bb663ac328655a879d1f28b54 | refs/heads/master | 2021-06-07T09:10:42.900663 | 2020-02-05T08:58:39 | 2020-02-05T08:58:39 | 150,934,959 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 472 | cpp | #include<bits/stdc++.h>
using namespace std;
int main ()
{
int n,m;
cin>>n>>m;
int x,y;
int r[n+1]={0};
int c[n+1]={0};
for(int i=0;i<m;i++)
{
cin>>x>>y;
r[x] = 1;
c[y] = 1;
}
int cnt = 0;
for(int i=2;i<=n-1;i++)
{
if(r[i]==0)
cnt++;
if(c[i]==0)
cnt++;
}
if(n%2!=0)
{
if(r[(n+1)/2]==0 && c[(n+1)/2]==0)
cnt--;
}
cout<<cnt;
} | [
"[email protected]"
] | |
32c52bf334726d8373c61d915a2259d7a125608f | c83df4a201975f95b3e10b89fbfdec0b129a39d3 | /test/test_partition_fwd_index.cpp | 2c07788bbf98d3a1cc83298288f219fbed8e73c8 | [
"Apache-2.0"
] | permissive | Spencerx/pisa | cdd062a51baacdf01a4eaa8ec8cac3057a8895c9 | 097478a4fb429d1ce69b0f8a3bfdbfca665c36fe | refs/heads/master | 2020-07-05T10:53:53.048791 | 2019-08-14T13:27:05 | 2019-08-14T13:27:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,170 | cpp | #define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <boost/filesystem.hpp>
#include <fmt/ostream.h>
#include <gsl/span>
#include <range/v3/action/transform.hpp>
#include <range/v3/algorithm/stable_sort.hpp>
#include <range/v3/view/drop.hpp>
#include <range/v3/view/iota.hpp>
#include <range/v3/view/stride.hpp>
#include <tbb/task_scheduler_init.h>
#include "binary_freq_collection.hpp"
#include "filesystem.hpp"
#include "forward_index_builder.hpp"
#include "pisa_config.hpp"
#include "sharding.hpp"
#include "temporary_directory.hpp"
using namespace boost::filesystem;
using namespace pisa;
using namespace pisa::literals;
using posting_vector_type = std::vector<std::pair<Term_Id, Document_Id>>;
using iterator_type = decltype(std::declval<posting_vector_type>().begin());
using index_type = invert::Inverted_Index<iterator_type>;
[[nodiscard]] auto next_plaintext_record(std::istream &in) -> std::optional<Document_Record>
{
pisa::Plaintext_Record record;
if (in >> record) {
return std::make_optional<Document_Record>(
std::move(record.trecid()), std::move(record.content()), std::move(record.url()));
}
return std::nullopt;
}
TEST_CASE("mapping_from_files", "[invert][unit]")
{
std::istringstream full("D00\nD01\nD02\nD03\nD04\nD05\nD06\nD07\nD08\nD09\nD010\nD11");
std::vector<std::unique_ptr<std::istream>> shards;
shards.push_back(std::make_unique<std::istringstream>("D00\nD01\nD02"));
shards.push_back(std::make_unique<std::istringstream>("D02\nD03\nD04"));
shards.push_back(std::make_unique<std::istringstream>("D06\nD07\nD08\nD09\nD010\nD11"));
auto stream_pointers = ranges::view::transform(shards, [](auto const &s) { return s.get(); })
| ranges::to_vector;
REQUIRE(mapping_from_files(&full, gsl::span<std::istream *>(stream_pointers)).as_vector()
== std::vector<Shard_Id>{0_s, 0_s, 0_s, 1_s, 1_s, 0_s, 2_s, 2_s, 2_s, 2_s, 2_s, 2_s});
}
TEST_CASE("create_random_mapping", "[invert][unit]")
{
uint64_t seed = 88887;
auto mapping = pisa::create_random_mapping(1000u, 13u, seed);
VecMap<Shard_Id, int> counts(13, 0);
VecMap<Document_Id> documents;
for (auto &&[doc, shard] : mapping.entries()) {
counts[shard] += 1;
documents.push_back(doc);
}
std::sort(documents.begin(), documents.end());
REQUIRE(documents.as_vector() ==
ranges::to_vector(ranges::view::iota(Document_Id{}, Document_Id{1000u})));
REQUIRE(counts.as_vector() ==
std::vector<int>{77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 77, 76});
}
auto round_robin_mapping(int document_count, int shard_count)
{
VecMap<Document_Id, Shard_Id> mapping(document_count);
Shard_Id shard = 0_s;
for (auto doc : ranges::view::iota(0_d, Document_Id{document_count})) {
mapping[doc] = shard++;
if (shard == Shard_Id{shard_count}) {
shard = 0_s;
}
}
return mapping;
}
void build_fwd_index(std::string const &output)
{
std::string input(PISA_SOURCE_DIR "/test/test_data/clueweb1k.plaintext");
std::ifstream is(input);
pisa::Forward_Index_Builder builder;
builder.build(is,
output,
next_plaintext_record,
[](std::string &&term) -> std::string { return std::forward<std::string>(term); },
pisa::parse_plaintext_content,
20'000,
2);
}
template <typename Container>
auto shard_elements(Container const &container, Shard_Id shard_id, int shard_count)
{
Container elems;
for (auto const &val :
ranges::view::drop(container, shard_id.as_int()) | ranges::view::stride(shard_count))
{
elems.push_back(val);
}
return elems;
}
TEST_CASE("copy_sequence", "[invert][unit]")
{
GIVEN("A test forward index")
{
Temporary_Directory dir;
std::string fwd_basename = (dir.path() / "fwd").string();
std::string output = (dir.path() / "copy").string();
int document_count = 1'000;
build_fwd_index(fwd_basename);
WHEN("All sequences are copied")
{
{
std::ifstream is(fwd_basename);
std::ofstream os(output);
for ([[maybe_unused]] auto _ : ranges::view::ints(0, document_count)) {
copy_sequence(is, os);
}
}
THEN("Files are identical")
{
auto actual = io::load_data(output);
auto expected = io::load_data(fwd_basename);
expected.resize(actual.size());
REQUIRE(actual == expected);
}
}
}
}
TEST_CASE("Rearrange sequences", "[invert][integration]")
{
GIVEN("A test forward index")
{
Temporary_Directory dir;
std::string fwd_basename = (dir.path() / "fwd").string();
std::string output_basename = (dir.path() / "shards").string();
int document_count = 1'000;
build_fwd_index(fwd_basename);
WHEN("Rearrange the sequences in a round-robin manner")
{
auto mapping = round_robin_mapping(document_count, 13);
REQUIRE(mapping.size() == document_count);
rearrange_sequences(fwd_basename, output_basename, mapping);
auto shard_ids = ranges::view::iota(0_s, 13_s);
THEN("Sequences are properly rearranged")
{
auto full = binary_collection(fwd_basename.c_str());
auto full_iter = ++full.begin();
std::vector<std::vector<std::uint32_t>> expected;
std::transform(
full_iter, full.end(), std::back_inserter(expected), [](auto const &seq) {
return std::vector<std::uint32_t>(seq.begin(), seq.end());
});
auto sorted_mapping = mapping.entries() | ranges::to_vector;
ranges::stable_sort(sorted_mapping, [](auto const &lhs, auto const &rhs) {
return std::make_pair(lhs.second, lhs.first)
< std::make_pair(rhs.second, rhs.first);
});
expected = ranges::view::transform(
sorted_mapping,
[&](auto &&entry) { return expected[entry.first.as_int()]; })
| ranges::to_vector;
auto pos = expected.begin();
for (auto shard : shard_ids) {
//std::vector<std::vector<std::uint32_t>> actual;
spdlog::info("Testing shard {}", shard.as_int());
spdlog::default_logger()->flush();
auto shard_coll = binary_collection(
fmt::format("{}.{:03d}", output_basename, shard.as_int()).c_str());
size_t doc = 0u;
CAPTURE(shard);
CAPTURE(doc);
for (auto iter = ++shard_coll.begin(); iter != shard_coll.end();
++iter, ++pos)
{
auto seq = *iter;
REQUIRE(*pos == std::vector<std::uint32_t>(seq.begin(), seq.end()));
}
}
}
}
}
}
TEST_CASE("partition_fwd_index", "[invert][integration]")
{
tbb::task_scheduler_init init(1);
GIVEN("A test forward index")
{
Temporary_Directory dir;
std::string fwd_basename = (dir.path() / "fwd").string();
std::string output_basename = (dir.path() / "shards").string();
int document_count = 1'000;
build_fwd_index(fwd_basename);
WHEN("Partition the forward index in a round-robin manner")
{
auto mapping = round_robin_mapping(document_count, 13);
REQUIRE(mapping.size() == document_count);
partition_fwd_index(fwd_basename, output_basename, mapping);
auto shard_ids = ranges::view::iota(0_s, 13_s);
THEN("Document titles are correctly partitioned")
{
auto original_titles =
io::read_string_vector(fmt::format("{}.documents", fwd_basename));
for (auto shard_id : shard_ids) {
auto expected_titles = shard_elements(original_titles, shard_id, 13);
auto actual_titles = io::read_string_vector(
fmt::format("{}.{:03d}.documents", output_basename, shard_id.as_int()));
REQUIRE(actual_titles == expected_titles);
}
}
AND_THEN("Documents are identical wrt terms")
{
auto full = binary_collection(fwd_basename.c_str());
auto full_iter = ++full.begin();
auto full_terms = io::read_string_vector(fmt::format("{}.terms", fwd_basename));
std::vector<binary_collection> shards;
std::vector<typename binary_collection::const_iterator> shard_iterators;
std::vector<std::vector<std::string>> shard_terms;
shards.reserve(13);
shard_iterators.reserve(13);
shard_terms.reserve(13);
for (auto shard : shard_ids) {
shards.push_back(binary_collection(
fmt::format("{}.{:03d}", output_basename, shard.as_int()).c_str()));
shard_terms.push_back(io::read_string_vector(
fmt::format("{}.{:03d}.terms", output_basename, shard.as_int()).c_str()));
shard_iterators.push_back(++shards.back().begin());
shards.back();
}
Shard_Id shard = 0_s;
for (auto doc : ranges::view::iota(0_d, Document_Id{document_count})) {
CAPTURE(doc);
auto full_seq = *full_iter;
auto shard_seq = *shard_iterators[shard.as_int()];
std::vector<std::string> expected_documents(full_seq.size());
std::vector<std::string> actual_documents(shard_seq.size());
std::transform(full_seq.begin(),
full_seq.end(),
expected_documents.begin(),
[&](auto const &id) { return full_terms[id]; });
std::transform(shard_seq.begin(),
shard_seq.end(),
actual_documents.begin(),
[&](auto const &id) { return shard_terms[shard.as_int()][id]; });
REQUIRE(actual_documents == expected_documents);
++full_iter;
++shard_iterators[shard.as_int()];
shard += 1_s;
if (shard == 13_s) {
shard = 0_s;
}
}
}
}
}
}
| [
"[email protected]"
] | |
43ef32dfedd9fd90ad227fafff608a236d925c6d | cc1701cadaa3b0e138e30740f98d48264e2010bd | /chrome/browser/permissions/quiet_notification_permission_ui_config.cc | 17abb79dbe67bd9f097c11c67f6296a9b63f075d | [
"BSD-3-Clause"
] | permissive | dbuskariol-org/chromium | 35d3d7a441009c6f8961227f1f7f7d4823a4207e | e91a999f13a0bda0aff594961762668196c4d22a | refs/heads/master | 2023-05-03T10:50:11.717004 | 2020-06-26T03:33:12 | 2020-06-26T03:33:12 | 275,070,037 | 1 | 3 | BSD-3-Clause | 2020-06-26T04:04:30 | 2020-06-26T04:04:29 | null | UTF-8 | C++ | false | false | 3,022 | cc | // Copyright 2019 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 "chrome/browser/permissions/quiet_notification_permission_ui_config.h"
#include "base/metrics/field_trial_params.h"
#include "chrome/common/chrome_features.h"
// static
const char QuietNotificationPermissionUiConfig::kEnableAdaptiveActivation[] =
"enable_adaptive_activation";
// static
const char QuietNotificationPermissionUiConfig::kEnableCrowdDenyTriggering[] =
"enable_crowd_deny_triggering";
// static
const char QuietNotificationPermissionUiConfig::kCrowdDenyHoldBackChance[] =
"crowd_deny_hold_back_chance";
// static
const char
QuietNotificationPermissionUiConfig::kEnableAbusiveRequestBlocking[] =
"enable_abusive_request_triggering";
// static
const char QuietNotificationPermissionUiConfig::kEnableAbusiveRequestWarning[] =
"enable_abusive_request_warning";
// static
const char QuietNotificationPermissionUiConfig::kMiniInfobarExpandLinkText[] =
"mini_infobar_expand_link_text";
// static
bool QuietNotificationPermissionUiConfig::IsAdaptiveActivationEnabled() {
if (!base::FeatureList::IsEnabled(features::kQuietNotificationPrompts))
return false;
return base::GetFieldTrialParamByFeatureAsBool(
features::kQuietNotificationPrompts, kEnableAdaptiveActivation,
false /* default */);
}
// static
bool QuietNotificationPermissionUiConfig::IsCrowdDenyTriggeringEnabled() {
if (!base::FeatureList::IsEnabled(features::kQuietNotificationPrompts))
return false;
return base::GetFieldTrialParamByFeatureAsBool(
features::kQuietNotificationPrompts, kEnableCrowdDenyTriggering,
false /* default */);
}
// static
double QuietNotificationPermissionUiConfig::GetCrowdDenyHoldBackChance() {
return base::GetFieldTrialParamByFeatureAsDouble(
features::kQuietNotificationPrompts, kCrowdDenyHoldBackChance, 0);
}
// static
QuietNotificationPermissionUiConfig::InfobarLinkTextVariation
QuietNotificationPermissionUiConfig::GetMiniInfobarExpandLinkText() {
return base::GetFieldTrialParamByFeatureAsInt(
features::kQuietNotificationPrompts, kMiniInfobarExpandLinkText, 0)
? InfobarLinkTextVariation::kManage
: InfobarLinkTextVariation::kDetails;
}
// static
bool QuietNotificationPermissionUiConfig::IsAbusiveRequestBlockingEnabled() {
if (!base::FeatureList::IsEnabled(features::kQuietNotificationPrompts))
return false;
return base::GetFieldTrialParamByFeatureAsBool(
features::kQuietNotificationPrompts, kEnableAbusiveRequestBlocking,
false /* default */);
}
// static
bool QuietNotificationPermissionUiConfig::IsAbusiveRequestWarningEnabled() {
if (!base::FeatureList::IsEnabled(features::kQuietNotificationPrompts))
return false;
return base::GetFieldTrialParamByFeatureAsBool(
features::kQuietNotificationPrompts, kEnableAbusiveRequestWarning,
false /* default */);
}
| [
"[email protected]"
] | |
22ea412a8b93270bdbf66b907b3b2f28480abc80 | 2a88b58673d0314ed00e37ab7329ab0bbddd3bdc | /blazemark/src/boost/DMatTSMatAdd.cpp | 2e4013ad22ae8df192937bf87c4795ac6b4681fc | [
"BSD-3-Clause"
] | permissive | shiver/blaze-lib | 3083de9600a66a586e73166e105585a954e324ea | 824925ed21faf82bb6edc48da89d3c84b8246cbf | refs/heads/master | 2020-09-05T23:00:34.583144 | 2016-08-24T03:55:17 | 2016-08-24T03:55:17 | 66,765,250 | 2 | 1 | NOASSERTION | 2020-04-06T05:02:41 | 2016-08-28T11:43:51 | C++ | UTF-8 | C++ | false | false | 4,680 | cpp | //=================================================================================================
/*!
// \file src/boost/DMatTSMatAdd.cpp
// \brief Source file for the Boost dense matrix/transpose sparse matrix addition kernel
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <iostream>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_sparse.hpp>
#include <blaze/util/Timing.h>
#include <blazemark/boost/DMatTSMatAdd.h>
#include <blazemark/boost/init/CompressedMatrix.h>
#include <blazemark/boost/init/Matrix.h>
#include <blazemark/system/Config.h>
namespace blazemark {
namespace boost {
//=================================================================================================
//
// KERNEL FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief Boost uBLAS dense matrix/transpose sparse matrix addition kernel.
//
// \param N The number of rows and columns of the matrices.
// \param F The number of non-zero elements in each column of the sparse matrix.
// \param steps The number of iteration steps to perform.
// \return Minimum runtime of the kernel function.
//
// This kernel function implements the dense matrix/transpose sparse matrix addition by means
// of the Boost uBLAS functionality.
*/
double dmattsmatadd( size_t N, size_t F, size_t steps )
{
using ::blazemark::element_t;
using ::boost::numeric::ublas::row_major;
using ::boost::numeric::ublas::column_major;
::blaze::setSeed( seed );
::boost::numeric::ublas::matrix<element_t,row_major> A( N, N ), C( N, N );
::boost::numeric::ublas::compressed_matrix<element_t,column_major> B( N, N );
::blaze::timing::WcTimer timer;
init( A );
init( B, F );
noalias( C ) = A + B;
for( size_t rep=0UL; rep<reps; ++rep )
{
timer.start();
for( size_t step=0UL; step<steps; ++step ) {
noalias( C ) = A + B;
}
timer.end();
if( C.size1() != N )
std::cerr << " Line " << __LINE__ << ": ERROR detected!!!\n";
if( timer.last() > maxtime )
break;
}
const double minTime( timer.min() );
const double avgTime( timer.average() );
if( minTime * ( 1.0 + deviation*0.01 ) < avgTime )
std::cerr << " Boost uBLAS kernel 'dmattsmatadd': Time deviation too large!!!\n";
return minTime;
}
//*************************************************************************************************
} // namespace boost
} // namespace blazemark
| [
"[email protected]"
] | |
78729dacb49730b84fccc896d899f77c1cdd3786 | 6d91f593ee9a2438f4375cf1e00d4fbef78dc18e | /BaseAppOpenGL/BaseAppOpenGL/Scene1.cpp | 055a031e9e0622e35f1e56e59b2535b38b9b7afa | [] | no_license | jessdagostini/cgfinalproject | 70f5363fa45b0ec91c7af7c91e31bd3dfad5d737 | dae73a3b6028ebb06a9c3db4fdd0fb7a034e8338 | refs/heads/master | 2020-04-06T23:29:09.825860 | 2018-11-27T22:52:42 | 2018-11-27T22:52:42 | 157,871,186 | 1 | 1 | null | null | null | null | ISO-8859-1 | C++ | false | false | 17,983 | cpp | #include "Scene1.h"
CScene1::CScene1()
{
pCamera = NULL;
pTexto = NULL;
pTextures = NULL;
pModel3DS_1 = NULL;
pModel3DS_2 = NULL;
pModel3DS_3 = NULL;
bIsWireframe = false;
bIsCameraFPS = true;
iFPS = 0;
iFrames = 0;
ulLastFPS = 0;
szTitle[256] = 0;
// Cria gerenciador de impressão de texto na tela
pTexto = new CTexto();
// Cria camera
pCamera = new CCamera(30.0f, 65.0f, 30.0f, 1.0f);
// Cria o Timer
pTimer = new CTimer();
pTimer->Init();
fTimerPosY = 0.0f;
fRenderPosY = 0.0f;
posR = 5.0f;
posC = 4.0f;
R = 5;
C = 4;
// Carrega todas as texturas
pTextures = new CTexture();
pTextures->CreateTextureMipMap(0, "../Scene1/crate.bmp");
pTextures->CreateTextureMipMap(1, "../Scene1/grass.bmp");
pTextures->CreateTextureLinear(2, "../Scene1/por.jpg");
//pTextures->CreateTextureTGA(3, "../Scene1/por.tga");
//pTextures->CreateTextureTGA(4, "../Scene1/tree2.tga");
fPosX = 0.0f;
fPosY = 10.0f;
fPosZ = 0.0f;
fMovementFactor = 0.1f;
// Cria esfera com coordenadas de textura
this->sphere1 = gluNewQuadric();
gluQuadricTexture(this->sphere1, TRUE);
// Carrega Objetos da Cena (casa)
pModel3DS_1 = new CModel_3DS();
pModel3DS_1->Load("../Scene1/ok.3DS");
// Carrega Objetos da Cena (muro)
//pModel3DS_2 = new CModel_3DS();
//pModel3DS_2->Load("../Scene1/Muro.3DS");
// Carrega Objetos da Cena (gramado)
//pModel3DS_3 = new CModel_3DS();
//pModel3DS_3->Load("../Scene1/Plane001.3DS");
// Inicializa o vetor que contém o controle das peças
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
visible[i][j] = false;
}
}
// Seta como visível as primeiras 4 peças
visible[3][3] = true;
visible[4][4] = true;
visible[3][4] = true;
visible[4][3] = true;
// Seta as cores das peças
colors[3][3] = 0.0f;
colors[4][4] = 0.0f;
colors[3][4] = 1.0f;
colors[4][3] = 1.0f;
// Inicia a jogada sempre com o jogador cor preta
player = 0.0f;
// Inicia os jogadores com 2 peças cada
pBlackPoints = pWhitePoints = 2;
winner = -1;
}
CScene1::~CScene1(void)
{
if (pTexto)
{
delete pTexto;
pTexto = NULL;
}
if (pTextures)
{
delete pTextures;
pTextures = NULL;
}
if (pCamera)
{
delete pCamera;
pCamera = NULL;
}
if (pTimer)
{
delete pTimer;
pTimer = NULL;
}
gluDeleteQuadric(this->sphere1);
if (pModel3DS_1)
{
delete pModel3DS_1;
pModel3DS_1 = NULL;
}
if (pModel3DS_2)
{
delete pModel3DS_2;
pModel3DS_2 = NULL;
}
if (pModel3DS_3)
{
delete pModel3DS_3;
pModel3DS_3 = NULL;
}
}
int CScene1::DrawGLScene(void) // Função que desenha a cena
{
// Get FPS
if (GetTickCount() - ulLastFPS >= 1000) // When A Second Has Passed...
{
ulLastFPS = GetTickCount(); // Update Our Time Variable
iFPS = iFrames; // Save The FPS
iFrames = 0; // Reset The FPS Counter
}
iFrames++; // FPS counter
pTimer->Update(); // Atualiza o timer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Limpa a tela e o Depth Buffer
glLoadIdentity(); // Inicializa a Modelview Matrix Atual
// Seta as posições da câmera
//pCamera->setView();
gluLookAt(30.0f, 65.0f, 30.0f,
-20.0f, -20.0f, -20.0f,
0.0f, 1.0f, 0.0f);
// Desenha grid
//Draw3DSGrid(20.0f, 20.0f);
//DrawAxis();
// Modo FILL ou WIREFRAME (pressione barra de espaço)
if (bIsWireframe)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DESENHA OS OBJETOS DA CENA (INÍCIO)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
glColor3f(1.0f, 1.0f, 1.0f);
glPushMatrix();
glTranslatef(.0f, 27.0f, 0.0f);
DrawPecas();
pecas[R][C]->showPeca(0.5f, player);
glPopMatrix();
// Habilita mapeamento de texturas 2D
glEnable(GL_TEXTURE_2D);
glTranslatef(.0f,.0f, 0.0f);
glPushMatrix();
glTranslatef(0.0f, 0.0f, 0.0f);
glColor3f(1.0f, 1.0f, 1.0f);
pModel3DS_1->Draw();
glRotatef(180.0f, 1.0f, 0.0f, 0.0f);
pModel3DS_1->Draw();
glPopMatrix();
// Desenha as árvores aplicando Blending.
// A operação é baseada no canal Alpha da textura .TGA
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_ALPHA_TEST);
glColor4f(1.0f, 1.0f, 1.0f, 0.7f);
glPushMatrix();
Draw3DSGrid();
//auxSolidBox(215.0f, 0.1f, 215.0f);
glPopMatrix();
glDisable(GL_ALPHA_TEST);
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DESENHA OS OBJETOS DA CENA (FIM)
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
fTimerPosY = pTimer->GetTime() / 1000.0f;
fRenderPosY += 0.2f;
// Impressão de texto na tela...
// Muda para modo de projeção ortogonal 2D
// OBS: Desabilite Texturas e Iluminação antes de entrar nesse modo de projeção
OrthoMode(0, 0, WIDTH, HEIGHT);
glPushMatrix();
glTranslatef(0.0f, HEIGHT - 700, 0.0f); // Move 1 unidade para dentro da tela (eixo Z)
// Cor da fonte
glColor3f(1.0f, 1.0f, 0.0f);
glRasterPos2f(10.0f, 10.0f); // Posicionando o texto na tela
pTexto->glPrint("SCORE:");
glRasterPos2f(10.0f, 30.0f); // Posicionando o texto na tela
pTexto->glPrint("Player Black: %d points", pBlackPoints);
glRasterPos2f(10.0f, 45.0f); // Posicionando o texto na tela
pTexto->glPrint("Player White: %d points", pWhitePoints);
if (winner != -1) {
glRasterPos2f(10.0f, 70.0f); // Posicionando o texto na tela
if (winner == 1) {
pTexto->glPrint("PLAYER WHITE WIN!");
}
else {
pTexto->glPrint("PLAYER BLACK WIN!");
}
}
/*if (!bIsWireframe) {
pTexto->glPrint("[TAB] Modo LINE"); // Imprime texto na tela
}
else {
pTexto->glPrint("[TAB] Modo FILL");
}*/
//// Camera LookAt
/*glRasterPos2f(10.0f, 40.0f);
pTexto->glPrint("Player LookAt : %f, %f, %f", pCamera->Forward[0], pCamera->Forward[1], pCamera->Forward[2]);
//// Posição do Player
glRasterPos2f(10.0f, 60.0f);
pTexto->glPrint("Player Position: %f, %f, %f", pCamera->Position[0], pCamera->Position[1], pCamera->Position[2]);
//// Imprime o FPS da aplicação e o Timer
glRasterPos2f(10.0f, 80.0f);
pTexto->glPrint("Frames-per-Second: %d ---- Timer: %.1f segundos", iFPS, (pTimer->GetTime()/1000));
//// Imprime o FPS da aplicação e o Timer
glRasterPos2f(10.0f, 100.0f);
pTexto->glPrint("Valor de I: %d ---- Valor de J: %d", R, C);*/
glPopMatrix();
// Muda para modo de projeção perspectiva 3D
PerspectiveMode();
return true;
}
void CScene1::DrawPecas()
{
float valorX = -12.10f;
float valorZ = 0.40f;
float x = valorX;
float z = valorZ;
float y = 0.5f;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (visible[i][j]) {
pecas[i][j] = new Peca(x, y, z, colors[i][j]);
}
else {
pecas[i][j] = new Peca(x, 0.0f, z, 0.0f);
}
x += 1.75f;
z -= 1.75;
}
valorX += 1.75f;
valorZ += 1.75f;
x = valorX;
z = valorZ;
}
}
bool CScene1::FlipPecas()
{
bool flip = false;
int peca_pos = -1;
// Confere peças a esquerda da posição
for (int c = C - 1; c >= 0 && visible[R][c] && peca_pos == -1; c--) {
// Se a peça está visível e é da cor q esta jogando, seta peca_pos
if (colors[R][c] == player) {
peca_pos = c;
}
}
// Garante que encontrou uma peça e ela está pelo menos duas posicoes longe
if (peca_pos != -1 && peca_pos < C - 1) {
// Seta todas as peças visíveis com a cor do player atual
for (int i = C - 1; i > peca_pos; i--) {
colors[R][i] = player;
}
flip = true;
}
peca_pos = -1;
// Confere peças a direita da posição
for (int i = C + 1; i <= 7 && visible[R][i] && peca_pos == -1; i++) {
if (colors[R][i] == player) {
peca_pos = i;
}
}
if (peca_pos != -1 && peca_pos > C + 1) {
for (int i = C + 1; i < peca_pos; i++) {
colors[R][i] = player;
}
flip = true;
}
peca_pos = -1;
// Confere peças acima da posição
for (int i = R - 1; i >= 0 && visible[i][C] && peca_pos == -1; i--) {
if (colors[i][C] == player) {
peca_pos = i;
}
}
if (peca_pos != -1 && peca_pos < R - 1) {
for (int i = R - 1; i > peca_pos; i--) {
colors[i][C] = player;
}
flip = true;
}
peca_pos = -1;
// Confere peças abaixo da posição
for (int i = R + 1; i <= 7 && visible[i][C] && peca_pos == -1; i++) {
if (colors[i][C] == player) {
peca_pos = i;
}
}
if (peca_pos != -1 && peca_pos > R + 1) {
for (int i = R + 1; i < peca_pos; i++) {
colors[i][C] = player;
}
flip = true;
}
peca_pos = -1;
int c = C - 1;
// Confere peças na diagonal superior esquerda da posição
for (int r = R - 1; c >= 0 && r >= 0 && visible[r][c] && peca_pos == -1; r--) {
if (colors[r][c] == player) {
peca_pos = r;
}
c--;
}
if (peca_pos != -1 && peca_pos < R - 1) {
c = C - 1;
for (int r = R - 1; r > peca_pos; r--) {
colors[r][c] = player;
c--;
}
flip = true;
}
peca_pos = -1;
c = C + 1;
// Confere peças na diagonal superior direita da posição
for (int r = R - 1; c <= 7 && r >= 0 && visible[r][c] && peca_pos == -1; r--) {
if (colors[r][c] == player) {
peca_pos = r;
}
c++;
}
// Make sure we found a piece and that it is at least 2 spots away
if (peca_pos != -1 && peca_pos < R - 1) {
c = C + 1;
for (int r = R - 1; r > peca_pos; r--) {
colors[r][c] = player;
c++;
}
flip = true;
}
peca_pos = -1;
c = C - 1;
// Confere peças na diagonal inferior esquerda da posição
for (int r = R + 1; c >= 0 && r <= 7 && visible[r][c] && peca_pos == -1; r++) {
if (colors[r][c] == player) {
peca_pos = r;
}
c--;
}
if (peca_pos != -1 && peca_pos > R + 1) {
c = C - 1;
for (int r = R + 1; r < peca_pos; r++) {
colors[r][c] = player;
c--;
}
flip = true;
}
peca_pos = -1;
c = C + 1;
// Confere peças na diagonal inferior direita da posição
for (int r = R + 1; c <= 7 && r <= 7 && visible[r][c] && peca_pos == -1; r++) {
if (colors[r][c] == player) {
peca_pos = r;
}
c++;
}
// Make sure we found a piece and that it is at least 2 spots away
if (peca_pos != -1 && peca_pos > R + 1) {
c = C + 1;
for (int r = R + 1; r < peca_pos; r++) {
colors[r][c] = player;
c++;
}
flip = true;
}
return flip;
}
void CScene1::CountPoints()
{
pWhitePoints = pBlackPoints = 0;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (visible[i][j] && colors[i][j] == 1.0f) {
pWhitePoints++;
}
else if (visible[i][j] && colors[i][j] == 0.0f) {
pBlackPoints++;
}
}
}
if (pBlackPoints + pWhitePoints == 64) {
if (pBlackPoints > pWhitePoints) {
winner = 0;
}
else {
winner = 1;
}
}else if (pWhitePoints == 0) {
winner = 0;
}else if (pBlackPoints == 0) {
winner = 1;
}
else {
winner = -1;
}
}
void CScene1::DrawCircle(GLdouble x, GLdouble y, GLdouble z, GLdouble raio, int num_linhas)
{
glPushMatrix();
glBegin(GL_TRIANGLE_FAN);
for (int i = 0; i < num_linhas; i++) {
angulo = i * 2 * M_PI / num_linhas;
glVertex3f(x + (cos(angulo) * raio), y + (sin(angulo) * raio), z);
}
glEnd();
glPopMatrix();
}
void CScene1::MouseMove(void) // Tratamento de movimento do mouse
{
// Realiza os cálculos de rotação da visão do Player (através das coordenadas
// X do mouse.
POINT mousePos;
int middleX = WIDTH >> 1;
int middleY = HEIGHT >> 1;
GetCursorPos(&mousePos);
if ((mousePos.x == middleX) && (mousePos.y == middleY)) return;
SetCursorPos(middleX, middleY);
fDeltaX = (float)((middleX - mousePos.x)) / 10;
fDeltaY = (float)((middleY - mousePos.y)) / 10;
// Rotaciona apenas a câmera
pCamera->rotateGlob(-fDeltaX, 0.0f, 1.0f, 0.0f);
pCamera->rotateLoc(-fDeltaY, 1.0f, 0.0f, 0.0f);
}
void CScene1::KeyPressed(void) // Tratamento de teclas pressionadas
{
// Verifica se a tecla 'W' foi pressionada e move o Player para frente
if (GetKeyState('W') & 0x80)
{
pCamera->moveGlob(pCamera->Forward[0], pCamera->Forward[1], pCamera->Forward[2]);
}
// Verifica se a tecla 'S' foi pressionada e move o Player para tras
else if (GetKeyState('S') & 0x80)
{
pCamera->moveGlob(-pCamera->Forward[0], -pCamera->Forward[1], -pCamera->Forward[2]);
}
// Verifica se a tecla 'A' foi pressionada e move o Player para esquerda
else if (GetKeyState('A') & 0x80)
{
pCamera->moveGlob(-pCamera->Right[0], -pCamera->Right[1], -pCamera->Right[2]);
}
// Verifica se a tecla 'D' foi pressionada e move o Player para direira
else if (GetKeyState('D') & 0x80)
{
pCamera->moveGlob(pCamera->Right[0], pCamera->Right[1], pCamera->Right[2]);
}
// Senão, interrompe movimento do Player
else
{
}
if (GetKeyState(VK_UP) & 0x80)
{
if (posR >= 0.0f) posR -= 0.1f;
R = rint(int(posR));
CheckAvailability(0);
}
if (GetKeyState(VK_DOWN) & 0x80)
{
if (posR <= 7.0f) posR += 0.1f;
R = rint(int(posR));
CheckAvailability(1);
}
if (GetKeyState(VK_LEFT) & 0x80)
{
if (posC >= 0.0f) posC -= 0.1f;
C = rint(int(posC));
CheckAvailability(2);
}
if (GetKeyState(VK_RIGHT) & 0x80)
{
if (posC <= 7.0f) posC += 0.1f;
C = rint(int(posC));
CheckAvailability(3);
}
if (GetKeyState(VK_PRIOR) & 0x80)
{
fPosY += fMovementFactor;
}
if (GetKeyState(VK_NEXT) & 0x80)
{
fPosY -= fMovementFactor;
}
}
void CScene1::KeyDownPressed(WPARAM wParam) // Tratamento de teclas pressionadas
{
switch (wParam)
{
case VK_TAB:
bIsWireframe = !bIsWireframe;
break;
case VK_SPACE:
{
bool flip = FlipPecas();
if (flip) {
visible[R][C] = true;
colors[R][C] = player;
CountPoints();
if (player == 1.0f) {
player = 0.0f;
}
else {
player = 1.0f;
}
}
}
break;
case VK_RETURN:
break;
}
}
void CScene1::CheckAvailability(int movement)
{
if (visible[R][C]) {
bool found = false;
// Pra cima
if (movement == 0) {
while (visible[R][C]) {
R--;
}
// Para baixo
} else if (movement == 1) {
while (visible[R][C]) {
R++;
}
// Para esquerda
} else if (movement == 2) {
while (visible[R][C]) {
C--;
}
// Para direita
} else if (movement == 3) {
while (visible[R][C]) {
C++;
}
}
}
}
// Cria um grid horizontal ao longo dos eixos X e Z
void CScene1::Draw3DSGrid()
{//float width, float length
pTextures->ApplyTexture(2);
glPushMatrix();
for (float i = -100; i <= 100; i += 20)
{
for (float j = -100; j <= 100; j += 20)
{
// Start drawing some lines
glBegin(GL_QUADS);
glNormal3f(0.0f, 50.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(i, 0.0f, j + 20);
glTexCoord2f(1.0f, 0.0f); glVertex3f(i + 20, 0.0f, j + 20);
glTexCoord2f(1.0f, 1.0f); glVertex3f(i + 20, 0.0f, j);
glTexCoord2f(0.0f, 1.0f); glVertex3f(i, 0.0f, j);
glEnd();
}
}
glPopMatrix();
/*glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glColor3f(0.0f, 0.3f, 0.0f);
glPushMatrix();
for (float i = -width; i <= length; i += 1)
{
for (float j = -width; j <= length; j += 1)
{
// inicia o desenho das linhas
glBegin(GL_QUADS);
glNormal3f(0.0f, 1.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(i, 0.0f, j + 1);
glTexCoord2f(1.0f, 0.0f); glVertex3f(i + 1, 0.0f, j + 1);
glTexCoord2f(1.0f, 1.0f); glVertex3f(i + 1, 0.0f, j);
glTexCoord2f(0.0f, 1.0f); glVertex3f(i, 0.0f, j);
glEnd();
}
}
glPopMatrix();*/
//glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
void CScene1::DrawCube(float pX, float pY, float pZ,
float rX, float rY, float rZ, float angle,
float sX, float sY, float sZ,
int texID)
{
// Seta a textura ativa
if (texID >= 0)
pTextures->ApplyTexture(texID);
glPushMatrix();
glTranslatef(pX, pY, pZ);
glRotatef(angle, rX, rY, rZ);
glScalef(sX, sY, sZ);
glBegin(GL_QUADS);
// face frente
glTexCoord2d(0.0f, 0.0f); glVertex3f(-0.5f, -0.5f, 0.5f);
glTexCoord2d(1.0f, 0.0f); glVertex3f( 0.5f, -0.5f, 0.5f);
glTexCoord2d(1.0f, 1.0f); glVertex3f( 0.5f, 0.5f, 0.5f);
glTexCoord2d(0.0f, 1.0f); glVertex3f(-0.5f, 0.5f, 0.5f);
// face trás
glTexCoord2d(0.0f, 0.0f); glVertex3f(0.5f, -0.5f, -0.5f);
glTexCoord2d(0.0f, 1.0f); glVertex3f(-0.5f, -0.5f, -0.5f);
glTexCoord2d(1.0f, 1.0f); glVertex3f(-0.5f, 0.5f, -0.5f);
glTexCoord2d(1.0f, 0.0f); glVertex3f(0.5f, 0.5f, -0.5f);
// face direita
glTexCoord2d(0.0f, 0.0f); glVertex3f(0.5f, -0.5f, 0.5f);
glTexCoord2d(0.0f, 1.0f); glVertex3f(0.5f, -0.5f, -0.5f);
glTexCoord2d(1.0f, 1.0f); glVertex3f(0.5f, 0.5f, -0.5f);
glTexCoord2d(1.0f, 0.0f); glVertex3f(0.5f, 0.5f, 0.5f);
// face esquerda
glTexCoord2d(0.0f, 0.0f); glVertex3f(-0.5f, -0.5f, -0.5f);
glTexCoord2d(0.0f, 1.0f); glVertex3f(-0.5f, -0.5f, 0.5f);
glTexCoord2d(1.0f, 1.0f); glVertex3f(-0.5f, 0.5f, 0.5f);
glTexCoord2d(1.0f, 0.0f); glVertex3f(-0.5f, 0.5f, -0.5f);
// face baixo
glTexCoord2d(0.0f, 0.0f); glVertex3f(-0.5f, -0.5f, -0.5f);
glTexCoord2d(0.0f, 1.0f); glVertex3f( 0.5f, -0.5f, -0.5f);
glTexCoord2d(1.0f, 1.0f); glVertex3f( 0.5f, -0.5f, 0.5f);
glTexCoord2d(1.0f, 0.0f); glVertex3f(-0.5f, -0.5f, 0.5f);
// face cima
glTexCoord2d(0.0f, 0.0f); glVertex3f(-0.5f, 0.5f, 0.5f);
glTexCoord2d(0.0f, 1.0f); glVertex3f( 0.5f, 0.5f, 0.5f);
glTexCoord2d(1.0f, 1.0f); glVertex3f( 0.5f, 0.5f, -0.5f);
glTexCoord2d(1.0f, 0.0f); glVertex3f(-0.5f, 0.5f, -0.5f);
glEnd();
glPopMatrix();
}
void CScene1::DrawAxis()
{
glPushMatrix();
glTranslatef(0.0f, 27.5f, 0.0f);
glBegin(GL_LINES);
// Eixo X
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(-1000.0f, 0.0f, 0.0f);
glVertex3f(1000.0f, 0.0f, 0.0f);
// Eixo Y
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(0.0f, 1000.0f, 0.0f);
glVertex3f(0.0f, -1000.0f, 0.0f);
// Eixo Z
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(0.0f, 0.0f, 1000.0f);
glVertex3f(0.0f, 0.0f, -1000.0f);
glEnd();
glPopMatrix();
} | [
"[email protected]"
] | |
14547fb9628b78707f2aa019b041bfde940821f6 | e363b63383c617acc55c5b43bd0fa524d9e64dff | /game/client/c_sunlightshadowcontrol.cpp | 77d0d05125766f9d324583f11d351590f52b180e | [] | no_license | paralin/hl2sdk-dota | 63a17b641e2cc9d6d030df9244c03d60e013737d | e0fe36f0132b36ba9b1ca56aa10f888f66e9b2bf | refs/heads/master | 2016-09-09T22:37:57.509357 | 2014-04-09T13:26:01 | 2014-04-09T13:26:01 | 18,719,255 | 4 | 2 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 8,007 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Sunlight shadow control entity.
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "c_baseplayer.h"
#ifdef INFESTED_DLL
#include "c_asw_marine.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
ConVar cl_sunlight_ortho_size("cl_sunlight_ortho_size", "0.0", FCVAR_CHEAT, "Set to values greater than 0 for ortho view render projections.");
ConVar cl_sunlight_depthbias( "cl_sunlight_depthbias", "0.02" );
//------------------------------------------------------------------------------
// Purpose : Sunlights shadow control entity
//------------------------------------------------------------------------------
class C_SunlightShadowControl : public C_BaseEntity
{
public:
DECLARE_CLASS( C_SunlightShadowControl, C_BaseEntity );
DECLARE_CLIENTCLASS();
virtual ~C_SunlightShadowControl();
void OnDataChanged( DataUpdateType_t updateType );
void Spawn();
bool ShouldDraw();
void ClientThink();
private:
Vector m_shadowDirection;
bool m_bEnabled;
char m_TextureName[ MAX_PATH ];
CTextureReference m_SpotlightTexture;
color32 m_LightColor;
Vector m_CurrentLinearFloatLightColor;
float m_flCurrentLinearFloatLightAlpha;
float m_flColorTransitionTime;
float m_flSunDistance;
float m_flFOV;
float m_flNearZ;
float m_flNorthOffset;
bool m_bEnableShadows;
bool m_bOldEnableShadows;
static ClientShadowHandle_t m_LocalFlashlightHandle;
};
ClientShadowHandle_t C_SunlightShadowControl::m_LocalFlashlightHandle = CLIENTSHADOW_INVALID_HANDLE;
IMPLEMENT_CLIENTCLASS_DT(C_SunlightShadowControl, DT_SunlightShadowControl, CSunlightShadowControl)
RecvPropVector(RECVINFO(m_shadowDirection)),
RecvPropBool(RECVINFO(m_bEnabled)),
RecvPropString(RECVINFO(m_TextureName)),
RecvPropInt(RECVINFO(m_LightColor), 0, RecvProxy_Int32ToColor32),
RecvPropFloat(RECVINFO(m_flColorTransitionTime)),
RecvPropFloat(RECVINFO(m_flSunDistance)),
RecvPropFloat(RECVINFO(m_flFOV)),
RecvPropFloat(RECVINFO(m_flNearZ)),
RecvPropFloat(RECVINFO(m_flNorthOffset)),
RecvPropBool(RECVINFO(m_bEnableShadows)),
END_RECV_TABLE()
C_SunlightShadowControl::~C_SunlightShadowControl()
{
if ( m_LocalFlashlightHandle != CLIENTSHADOW_INVALID_HANDLE )
{
g_pClientShadowMgr->DestroyFlashlight( m_LocalFlashlightHandle );
m_LocalFlashlightHandle = CLIENTSHADOW_INVALID_HANDLE;
}
}
void C_SunlightShadowControl::OnDataChanged( DataUpdateType_t updateType )
{
if ( updateType == DATA_UPDATE_CREATED )
{
m_SpotlightTexture.Init( m_TextureName, TEXTURE_GROUP_OTHER, true );
}
BaseClass::OnDataChanged( updateType );
}
void C_SunlightShadowControl::Spawn()
{
BaseClass::Spawn();
m_bOldEnableShadows = m_bEnableShadows;
SetNextClientThink( CLIENT_THINK_ALWAYS );
}
//------------------------------------------------------------------------------
// We don't draw...
//------------------------------------------------------------------------------
bool C_SunlightShadowControl::ShouldDraw()
{
return false;
}
void C_SunlightShadowControl::ClientThink()
{
VPROF("C_SunlightShadowControl::ClientThink");
if ( m_bEnabled )
{
Vector vLinearFloatLightColor( m_LightColor.r, m_LightColor.g, m_LightColor.b );
float flLinearFloatLightAlpha = m_LightColor.a;
if ( m_CurrentLinearFloatLightColor != vLinearFloatLightColor || m_flCurrentLinearFloatLightAlpha != flLinearFloatLightAlpha )
{
float flColorTransitionSpeed = gpGlobals->frametime * m_flColorTransitionTime * 255.0f;
m_CurrentLinearFloatLightColor.x = Approach( vLinearFloatLightColor.x, m_CurrentLinearFloatLightColor.x, flColorTransitionSpeed );
m_CurrentLinearFloatLightColor.y = Approach( vLinearFloatLightColor.y, m_CurrentLinearFloatLightColor.y, flColorTransitionSpeed );
m_CurrentLinearFloatLightColor.z = Approach( vLinearFloatLightColor.z, m_CurrentLinearFloatLightColor.z, flColorTransitionSpeed );
m_flCurrentLinearFloatLightAlpha = Approach( flLinearFloatLightAlpha, m_flCurrentLinearFloatLightAlpha, flColorTransitionSpeed );
}
FlashlightState_t state;
Vector vDirection = m_shadowDirection;
VectorNormalize( vDirection );
QAngle angView;
engine->GetViewAngles( angView );
//Vector vViewUp = Vector( 0.0f, 1.0f, 0.0f );
Vector vSunDirection2D = vDirection;
vSunDirection2D.z = 0.0f;
HACK_GETLOCALPLAYER_GUARD( "C_SunlightShadowControl::ClientThink" );
#ifdef INFESTED_DLL // shine sun on your current marine, rather than the player entity
C_ASW_Marine *pMarine = C_ASW_Marine::GetLocalMarine();
if ( !pMarine )
return;
Vector vPos = ( pMarine->GetAbsOrigin() + vSunDirection2D * m_flNorthOffset ) - vDirection * m_flSunDistance;
#else
if ( !C_BasePlayer::GetLocalPlayer() )
return;
Vector vPos = ( C_BasePlayer::GetLocalPlayer()->GetAbsOrigin() + vSunDirection2D * m_flNorthOffset ) - vDirection * m_flSunDistance;
#endif
QAngle angAngles;
VectorAngles( vDirection, angAngles );
Vector vForward, vRight, vUp;
AngleVectors( angAngles, &vForward, &vRight, &vUp );
state.m_fHorizontalFOVDegrees = m_flFOV;
state.m_fVerticalFOVDegrees = m_flFOV;
state.m_vecLightOrigin = vPos;
BasisToQuaternion( vForward, vRight, vUp, state.m_quatOrientation );
state.m_fQuadraticAtten = 0.0f;
state.m_fLinearAtten = m_flSunDistance / 2.0f;
state.m_fConstantAtten = 0.0f;
state.m_FarZAtten = m_flSunDistance + 300.0f;
state.m_Color[0] = m_CurrentLinearFloatLightColor.x * ( 1.0f / 255.0f ) * m_flCurrentLinearFloatLightAlpha;
state.m_Color[1] = m_CurrentLinearFloatLightColor.y * ( 1.0f / 255.0f ) * m_flCurrentLinearFloatLightAlpha;
state.m_Color[2] = m_CurrentLinearFloatLightColor.z * ( 1.0f / 255.0f ) * m_flCurrentLinearFloatLightAlpha;
state.m_Color[3] = 0.0f; // fixme: need to make ambient work m_flAmbient;
state.m_NearZ = fpmax( 4.0f, m_flSunDistance - m_flNearZ );
state.m_FarZ = m_flSunDistance + 300.0f;
float flOrthoSize = cl_sunlight_ortho_size.GetFloat();
if ( flOrthoSize > 0 )
{
state.m_bOrtho = true;
state.m_fOrthoLeft = -flOrthoSize;
state.m_fOrthoTop = -flOrthoSize;
state.m_fOrthoRight = flOrthoSize;
state.m_fOrthoBottom = flOrthoSize;
}
else
{
state.m_bOrtho = false;
}
state.m_flShadowSlopeScaleDepthBias = 2;
state.m_flShadowDepthBias = cl_sunlight_depthbias.GetFloat();
state.m_bEnableShadows = m_bEnableShadows;
state.m_pSpotlightTexture = m_SpotlightTexture;
state.m_pProjectedMaterial = NULL;
state.m_nSpotlightTextureFrame = 0;
state.m_nShadowQuality = 1; // Allow entity to affect shadow quality
state.m_bShadowHighRes = true;
if ( m_bOldEnableShadows != m_bEnableShadows )
{
// If they change the shadow enable/disable, we need to make a new handle
if ( m_LocalFlashlightHandle != CLIENTSHADOW_INVALID_HANDLE )
{
g_pClientShadowMgr->DestroyFlashlight( m_LocalFlashlightHandle );
m_LocalFlashlightHandle = CLIENTSHADOW_INVALID_HANDLE;
}
m_bOldEnableShadows = m_bEnableShadows;
}
if( m_LocalFlashlightHandle == CLIENTSHADOW_INVALID_HANDLE )
{
m_LocalFlashlightHandle = g_pClientShadowMgr->CreateFlashlight( state );
}
else
{
g_pClientShadowMgr->UpdateFlashlightState( m_LocalFlashlightHandle, state );
#ifndef INFESTED_DLL
#pragma message("TODO: rebuild sunlight projected texture after sunlight control changes.")
g_pClientShadowMgr->UpdateProjectedTexture( m_LocalFlashlightHandle, true );
#endif
}
}
else if ( m_LocalFlashlightHandle != CLIENTSHADOW_INVALID_HANDLE )
{
g_pClientShadowMgr->DestroyFlashlight( m_LocalFlashlightHandle );
m_LocalFlashlightHandle = CLIENTSHADOW_INVALID_HANDLE;
}
BaseClass::ClientThink();
}
| [
"[email protected]"
] | |
7c92861e53ea59b3b03d9d8bf914408af087fea3 | 77ed17782ed9c43a445994fe1c95572f4fc18991 | /src/tests/unitTests.cpp | 15fe15a46c5eb71e3d97be446e8b083b74eddb23 | [
"MIT"
] | permissive | WeyrSDev/GBEmu | 17c4515ef27b72d9ce1e9f5d77ebedf203e2e445 | c9fed0674829a8a727c3c12dd63e2732348c062d | refs/heads/master | 2020-04-16T22:26:46.852846 | 2018-12-01T22:19:21 | 2018-12-01T22:19:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,375 | cpp | #define CO_IMPL
#define CO_DEBUG
#include "../common.h"
#include "../config.cpp"
#define TEST_ASSERT_EQ(actual, expected, msg) do {\
if ((actual) != (expected)) {\
PRINT("Assertion failed on line %d -- Actual: %u, Expected: %u -- Msg: %s", __LINE__, (int)actual, (int)expected, msg);\
exit(1);\
}\
} while (0)
int main() {
if (!initMemory(MB(11),MB(10))) {
CO_LOG("Failed to init memeory for test");
return 1;
}
PRINT("************************************");
PRINT("****STARTING GBEMU UNIT TESTS******");
PRINT("************************************");
//utf8 tests
TEST_ASSERT_EQ(utf8FromUTF32(L'a').data, 'a', "Bad translation from utf8 to utf32");
TEST_ASSERT_EQ(utf32FromUTF8({'a'}), L'a', "Bad translation from utf32 to utf8");
TEST_ASSERT_EQ(utf8FromUTF32(L'ç').data, 0xA7C3, "Bad translation from utf8 to utf32");
TEST_ASSERT_EQ(utf32FromUTF8({0xA7C3}), L'ç', "Bad translation from utf32 to utf8");
TEST_ASSERT_EQ(utf8FromUTF32(L'⌣').data, 0xA38CE2 , "Bad translation from utf8 to utf32");
TEST_ASSERT_EQ(utf32FromUTF8({0xA38CE2}), L'⌣', "Bad translation from utf32 to utf8");
TEST_ASSERT_EQ(utf8FromUTF32(L'🎮').data, 0xAE8E9FF0 , "Bad translation from utf8 to utf32");
TEST_ASSERT_EQ(utf32FromUTF8({0xAE8E9FF0}), L'🎮', "Bad translation from utf32 to utf8");
//config tests
auto res = parseConfigFile("../src/tests/test.txt");
TEST_ASSERT_EQ(res.fsResultCode, FileSystemResultCode::OK, "File should exist");
TEST_ASSERT_EQ(res.status, ParserStatus::OK, "Parse should have succeded");
TEST_ASSERT_EQ(res.numConfigPairs, 5, "Incorrect number of configs");
TEST_ASSERT_EQ(res.configPairs[0].key.type, ConfigKeyType::A, "Wrong LHS value");
TEST_ASSERT_EQ(res.configPairs[0].numValues, 1, "Only mapped to one key");
TEST_ASSERT_EQ(res.configPairs[0].values[0].type, ConfigValueType::KeyMapping, "Should be key mapping");
TEST_ASSERT_EQ(res.configPairs[0].values[0].keyMapping.characterValue.data, '/', "Wrong key mapped");
TEST_ASSERT_EQ(res.configPairs[0].values[0].keyMapping.isCtrlHeld, false, "Ctrl not held");
TEST_ASSERT_EQ(res.configPairs[0].values[0].keyMapping.type, KeyMappingType::Character, "Wrong key type mapped");
TEST_ASSERT_EQ(res.configPairs[1].key.type, ConfigKeyType::B, "Wrong LHS value");
TEST_ASSERT_EQ(res.configPairs[1].numValues, 1, "Only mapped to one key");
TEST_ASSERT_EQ(res.configPairs[1].values[0].type, ConfigValueType::KeyMapping, "Should be key mapping");
TEST_ASSERT_EQ(res.configPairs[1].values[0].keyMapping.characterValue.data, '.', "Wrong key mapped");
TEST_ASSERT_EQ(res.configPairs[1].values[0].keyMapping.isCtrlHeld, false, "Ctrl not held");
TEST_ASSERT_EQ(res.configPairs[1].values[0].keyMapping.type, KeyMappingType::Character, "Wrong key type mapped");
TEST_ASSERT_EQ(res.configPairs[2].key.type, ConfigKeyType::Start, "Wrong LHS value");
TEST_ASSERT_EQ(res.configPairs[2].numValues, 3, "Wrong number of RHS values");
TEST_ASSERT_EQ(res.configPairs[2].values[0].type, ConfigValueType::GamepadMapping, "Wrong type of mapping");
TEST_ASSERT_EQ(res.configPairs[2].values[0].gamepadMapping.value, GamepadMappingValue::Start, "Wrong mapping");
TEST_ASSERT_EQ(res.configPairs[2].values[1].type, ConfigValueType::KeyMapping, "Should be key mapping");
TEST_ASSERT_EQ(res.configPairs[2].values[1].keyMapping.characterValue.data, '#', "Wrong key mapped");
TEST_ASSERT_EQ(res.configPairs[2].values[1].keyMapping.isCtrlHeld, false, "Ctrl not held");
TEST_ASSERT_EQ(res.configPairs[2].values[1].keyMapping.type, KeyMappingType::Character, "Wrong key type mapped");
TEST_ASSERT_EQ(res.configPairs[2].values[2].type, ConfigValueType::KeyMapping, "Should be key mapping");
TEST_ASSERT_EQ(res.configPairs[2].values[2].keyMapping.type, KeyMappingType::MovementKey, "Wrong key type mapped");
TEST_ASSERT_EQ(res.configPairs[2].values[2].keyMapping.movementKeyValue, MovementKeyMappingValue::Enter, "Wrong key type mapped");
TEST_ASSERT_EQ(res.configPairs[2].values[2].keyMapping.isCtrlHeld, false, "Ctrl not held");
PRINT();
PRINT("************************************");
PRINT("************PASSED!!!***************");
PRINT("************************************");
return 0;
}
| [
"[email protected]"
] | |
c2798ea04e24d33fbe49f1f35d91cbbd20c2c3d2 | a001cb019b91e0f14c9368deb70ff67d7ec14e03 | /MLiveAccountServer/src/mnetwork/MN_WriteMessage.cpp | 084cfd1e4a68c2ec215f7b389815e7ddbdc14afb | [] | no_license | Nukem9/WIC-MassgateServer | 8faa0036a828de4ee4aee884c5416df41e9b5d43 | 7afe35fde93ec0dc1c8b33aa7d36044b425d6911 | refs/heads/master | 2021-04-12T11:10:07.689611 | 2017-12-23T05:08:51 | 2017-12-23T05:08:51 | 16,091,666 | 3 | 4 | null | 2016-04-14T00:01:28 | 2014-01-21T03:37:10 | C | UTF-8 | C++ | false | false | 4,380 | cpp | #include "../stdafx.h"
void MN_WriteMessage::TypeCheck(ushort aType)
{
if (this->m_TypeChecks)
this->Write<ushort>(aType);
}
void MN_WriteMessage::WriteDelimiter(ushort aDelimiter)
{
this->TypeCheck('DL');
this->Write<ushort>(aDelimiter);
}
void MN_WriteMessage::WriteBool(bool aBool)
{
this->TypeCheck('BL');
this->Write<bool>(aBool);
}
void MN_WriteMessage::WriteUChar(uchar aUChar)
{
this->TypeCheck('UC');
this->Write<uchar>(aUChar);
}
void MN_WriteMessage::WriteUShort(ushort aUShort)
{
this->TypeCheck('US');
this->Write<ushort>(aUShort);
}
void MN_WriteMessage::WriteInt(int aInt)
{
this->TypeCheck('IN');
this->Write<int>(aInt);
}
void MN_WriteMessage::WriteUInt(uint aUInt)
{
this->TypeCheck('UI');
this->Write<uint>(aUInt);
}
void MN_WriteMessage::WriteULong(ulong aULong)
{
this->WriteUInt(aULong);
}
void MN_WriteMessage::WriteUInt64(uint64 aUInt64)
{
this->TypeCheck('U6');
this->Write<uint64>(aUInt64);
}
void MN_WriteMessage::WriteFloat(float aFloat)
{
this->TypeCheck('FL');
this->Write<float>(aFloat);
}
void MN_WriteMessage::WriteRawData(voidptr_t aBuffer, sizeptr_t aBufferSize)
{
assert(aBuffer && aBufferSize > 0);
assert(aBufferSize < MESSAGE_MAX_LENGTH);
this->TypeCheck('RD');
ushort bufferSize = (ushort)aBufferSize;
// Packet will exceed bounds before it exceeds ushort
this->Write<ushort>(bufferSize);// No typecheck
this->CheckWriteSize(bufferSize);
memcpy((voidptr_t)this->m_WritePtr, aBuffer, bufferSize);
this->IncWritePos(bufferSize);
}
void MN_WriteMessage::WriteString(char *aBuffer)
{
assert(aBuffer);
this->WriteString(aBuffer, strlen(aBuffer) + 1);
}
void MN_WriteMessage::WriteString(char *aBuffer, sizeptr_t aStringSize)
{
assert(aBuffer && aStringSize > 0);
assert((aStringSize * sizeof(char)) < MESSAGE_MAX_LENGTH);
// Calculate actual size from number of characters * sizeof(single char)
ushort stringSize = (ushort)aStringSize;
ushort bufferSize = (ushort)(stringSize * sizeof(char));
this->Write<ushort>(stringSize);// No typecheck
this->CheckWriteSize(bufferSize);
memcpy((voidptr_t)this->m_WritePtr, aBuffer, bufferSize);
this->IncWritePos(bufferSize);
}
void MN_WriteMessage::WriteString(wchar_t *aBuffer)
{
assert(aBuffer);
this->WriteString(aBuffer, wcslen(aBuffer) + 1);
}
void MN_WriteMessage::WriteString(wchar_t *aBuffer, sizeptr_t aStringSize)
{
assert(aBuffer && aStringSize > 0);
assert((aStringSize * sizeof(wchar_t)) < MESSAGE_MAX_LENGTH);
// Calculate actual size from number of characters * sizeof(single wchar)
ushort stringSize = (ushort)aStringSize;
ushort bufferSize = (ushort)(stringSize * sizeof(wchar_t));
this->Write<ushort>(stringSize);// No typecheck
this->CheckWriteSize(bufferSize);
memcpy((voidptr_t)this->m_WritePtr, aBuffer, bufferSize);
this->IncWritePos(bufferSize);
}
bool MN_WriteMessage::SendMe(SOCKET aSocket)
{
return this->SendMe(aSocket, true);
}
bool MN_WriteMessage::SendMe(SOCKET aSocket, bool aClearData)
{
// Windows sockets only supports int as the data size
if (this->m_DataLen >= INT_MAX)
return false;
bool retVal = send(aSocket, (const char *)this->m_PacketData, (int)this->m_DataLen, 0) != SOCKET_ERROR;
if (aClearData)
{
// We keep the old data but reset the writer position
this->m_WritePtr = this->m_PacketData + sizeof(ushort);
this->m_WritePos = 0;
this->m_DataLen = sizeof(ushort);
}
return retVal;
}
voidptr_t MN_WriteMessage::GetDataStream()
{
return (voidptr_t)this->m_PacketData;
}
sizeptr_t MN_WriteMessage::GetDataLength()
{
return this->m_DataLen;
}
bool MN_WriteMessage::CheckWriteSize(sizeptr_t aSize)
{
// Note that m_ReadPos is 0-based and must always be less than m_DataLen
if ((this->m_DataLen + aSize) > this->m_PacketMaxSize)
{
assert(false && "Packet write exceeded bounds. Increase packet allocation size.");
return false;
}
return true;
}
void MN_WriteMessage::IncWritePos(sizeptr_t aSize)
{
this->m_WritePtr = this->m_WritePtr + aSize;
this->m_WritePos += aSize;
this->m_DataLen += aSize;
// Write the message-specific information that is stored in the first 2 bytes
ushort packetInfo = 0;
// Packet length
packetInfo = (ushort)(this->m_DataLen - sizeof(ushort));
packetInfo &= MESSAGE_MAX_LENGTH;
// Packet flags
if (this->m_TypeChecks)
packetInfo |= MESSAGE_FLAG_TYPECHECKS;
*(ushort *)this->m_PacketData = packetInfo;
} | [
"[email protected]"
] | |
23dcfb3d3d63783695bef270705866cd7ff71472 | 46ad3be82210acd52a8592cc9ae2eacf0faf0be2 | /String/input line.cpp | 853cbc2b6c699128ee443ed3a5b7f34c7a4b885e | [] | no_license | almamuncsit/CPP-Programming | 5816ad206652e95a377a8968f437fddaafdff86e | c589075d39068fd348c1c1ab0cd2137fa80542ec | refs/heads/master | 2021-08-18T20:21:48.985169 | 2021-01-13T09:07:54 | 2021-01-13T09:07:54 | 36,181,433 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 232 | cpp | #include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
string name;
cin >> n;
cout << "Enter line ";
getline(cin, name);
cout << "Name is : " << name;
return 0;
}
| [
"[email protected]"
] | |
d2c1636b03b44e4784e0087fab8ce2409380d50d | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/InnerDetector/InDetRecTools/InDetMultipleVertexSeedFinder/InDetMultipleVertexSeedFinder/HistogrammingMultiSeedFinder.h | 0f4a651e8a15395a11db8f974304a86d2c2f4580 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,429 | h | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#ifndef InDetMultipleVertexSeedFinder_HistogrammingMultiSeedFinder_H
#define InDetMultipleVertexSeedFinder_HistogrammingMultiSeedFinder_H
#include "AthenaBaseComps/AthAlgTool.h"
#include "GaudiKernel/ToolHandle.h"
#include "InDetRecToolInterfaces/IMultiPVSeedFinder.h"
/**
* A multi seed finder for primary vertexing. Uses a
* histogramming method. Operates in a fixed range
* +/-15cm along z-axis.
*
* Configurables: number of histogram bins and
* maximal separation distance between bins to be
* merged. in a cluster.
*
* Kirill Prokodiev <[email protected]>
*
* Mai 2007
*/
class IBeamCondSvc;
namespace Trk
{
class Track;
class ITrackSelectorTool;
class IExtrapolator;
class IVertexSeedFinder;
}
namespace InDet
{
class InDetTrackClusterCleaningTool;
class HistogrammingMultiSeedFinder : public AthAlgTool, virtual public IMultiPVSeedFinder
{
public:
StatusCode initialize();
StatusCode finalize();
/**
* Constructor and destructor
*/
HistogrammingMultiSeedFinder(const std::string& t, const std::string& n, const IInterface* p);
~HistogrammingMultiSeedFinder();
/**
* Clustering method itself
*/
std::vector< std::vector<const Trk::Track *> > seeds(const std::vector<const Trk::Track*>& tracks )const;
std::vector< std::vector<const Trk::TrackParticleBase *> > seeds(const std::vector<const Trk::TrackParticleBase*>& tracks )const;
std::vector< std::vector<const Trk::TrackParameters *> > seeds(const std::vector<const xAOD::TrackParticle*>& tracks )const;
// std::pair<std::vector<const Trk::TrackParameters *>,
// std::vector<const xAOD::TrackParticle *> > m_clusterAndOutliers(std::vector<const xAOD::TrackParticle *> tracks_to_clean, xAOD::Vertex * beamposition) const;
private:
// tuning parameters
unsigned int m_sepNBins;
unsigned int m_nBins;
unsigned int m_nRemaining;
float m_histoRange;
bool m_ignoreBeamSpot;
//track filter and cleaning tool
ToolHandle<Trk::ITrackSelectorTool> m_trkFilter;
ToolHandle<InDetTrackClusterCleaningTool> m_cleaningTool;
ToolHandle<Trk::IVertexSeedFinder> m_vtxSeedFinder;
//beam spot finder
ServiceHandle< IBeamCondSvc > m_beamService;
ToolHandle<Trk::IExtrapolator> m_extrapolator; //<! Extrapolator tool
};
}//end of namespace definitions
#endif
| [
"[email protected]"
] | |
2a146d33f63181f9c7320487a63eeb1817cd395d | 518d333b37dc649842a1dc9153b2ea8a94174e0e | /LABO2/Discount.h | 77a050a7983dcb6785ec6bb2593677413ef9cee8 | [] | no_license | AndresPaul/Laboratorio-2 | 17db00295ba5958e34cbf1b314295284a5a8ddc0 | 1445bc2debbc2b38516c0deafbf9df07fe17ad6b | refs/heads/main | 2023-04-28T04:11:25.474800 | 2021-04-12T02:09:07 | 2021-04-12T02:09:07 | 357,029,548 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 105 | h | #include "Car.h"
class Discount
{
public:
Discount(){}
virtual double computeDiscount(Car* c)=0;
}; | [
"[email protected]"
] | |
2a63dcb30ba3666021ca2d6a62d89a9b1159fc2e | b4b677d38c8a362895f8115080c820769cb41d59 | /roads/gen/gen.cpp | 2ed9988d580a116d13cf812999068fcbc27d42cd | [] | no_license | Jur1jo/apio-2021 | 9d9118c75d6e572afc5a4faebc1546af7e77f0d4 | 66edf2a31000ff9ba65eed76f4fa43c269b5ea6c | refs/heads/master | 2023-05-03T04:36:21.111140 | 2021-05-26T15:24:13 | 2021-05-26T15:24:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,591 | cpp | #include "testlib.h"
#include "treegenerator.h"
#include <bits/stdc++.h>
using namespace std;
using namespace tree_generator_by_ouuan;
typedef pair<int, int> pii;
struct Test {
int N;
vector<int> U, V, W;
Test(int _N): N(_N) {};
Test() {};
void print() {
printf("%d\n", N);
for (int i = 0; i < N - 1; ++i) {
printf("%d %d %d\n", U[i], V[i], W[i]);
}
}
};
// This will assign each edges with weight between the pair W
void assignWeightRandomRange(Test &T, pii W) {
(T.W).resize(T.N - 1);
for (int &w : T.W) {
w = rnd.next(W.first, W.second);
}
}
void assignWeightToDegreeSum(Test &T, int div) {
(T.W).resize(T.N - 1);
vector <int> degree(T.N);
for (int i = 0; i < T.N - 1; i++) {
degree[T.U[i]]++;
degree[T.V[i]]++;
}
for (int i = 0; i < T.N - 1; i++) {
T.W[i] = degree[T.U[i]] + degree[T.V[i]];
T.W[i] /= div; if(T.W[i] == 0) T.W[i]++;
}
}
void assignWeightToDegreeMin(Test &T, int offset) {
(T.W).resize(T.N - 1);
vector <int> degree(T.N);
for (int i = 0; i < T.N - 1; i++) {
degree[T.U[i]]++;
degree[T.V[i]]++;
}
for (int i = 0; i < T.N - 1; i++) {
T.W[i] = min(degree[T.U[i]], degree[T.V[i]]) + rnd.next(-offset, offset);
if(T.W[i] <= 0) T.W[i] = 1;
}
}
// Start of Trees Generator --------------
// void get(vector <int> &U, vector <int> &V,
// bool ShuffleV = 1, bool ShuffleE = 1,
// bool swapV = 0);
// This will assign edges to U and V consecutively
// and shuffle accordingly. By default auto shuffle both, and dont swap edges. The generator bit weird for star...
// Random tree with size N
Test randomCase(int N) {
Test T(N);
Tree tree(N);
tree.get(T.U, T.V);
return T;
}
Test starCase(int N) {
Test T(N);
Tree tree;
tree.star(N, 0);
tree.get(T.U, T.V, 0, 1, 1);
return T;
}
// Generate line case
Test lineCase(int N) {
Test T(N);
Tree tree;
tree.chain(N, 0);
tree.get(T.U, T.V, 0, 0, 1);
return T;
}
// All nodes degree doesn't exceed K
Test maxDegreeCase(int N, int K) {
Test T(N);
Tree tree;
tree.maxDegree(N, K, 0);
tree.get(T.U, T.V);
return T;
}
// All non-leaf nodes degree in range [K, K + 5]
Test minDegreeCase(int N, int K) {
Test T(N);
Tree tree;
tree.minDegree(N, K, 5, 0);
tree.get(T.U, T.V);
return T;
}
// All nodes will try to make K-nary, will add accordingly if can't
Test knaryCase(int N, int K) {
Test T(N);
Tree tree;
tree.complete(N, K, 0);
tree.get(T.U, T.V);
return T;
}
// All nodes will try to make K-nary, with N/2 nodes and some offsets for the rest
Test flowerKnaryCase(int N, int K) {
Test T(N);
Tree tree;
tree.flowerKnary(N, N/2, K, 0);
tree.get(T.U, T.V);
return T;
}
Test silkwormCase(int N) {
Test T(N);
Tree tree;
tree.silkworm(N, 0);
tree.get(T.U, T.V);
return T;
}
Test starShuffleCase(int N) {
Test T(N);
Tree tree;
tree.star(N, 0);
tree.get(T.U, T.V);
return T;
}
Test distinctCase(int N) {
Test T(N);
Tree tree;
tree.distinctDegree(N, 0);
tree.get(T.U, T.V);
return T;
}
Test halvingCase(int N) {
Test T(N);
Tree tree;
tree.halvingDegree(N, 0);
tree.get(T.U, T.V);
return T;
}
// End of Trees Generator --------------
// Seed the default tree generator with first rnd.next of testlib.h
inline void setTreeGeneratorSeed(int seed) {
defaultRNG = mt19937(seed);
}
int main(int argc, char *argv[]) {
registerGen(argc, argv, 0);
setTreeGeneratorSeed(rnd.next(INT_MAX));
Test T;
int N = rnd.next(atoi(argv[2]), atoi(argv[3]));
if (strcmp(argv[1], "random") == 0)
T = randomCase(N);
if (strcmp(argv[1], "distinct") == 0)
T = distinctCase(N);
if (strcmp(argv[1], "halving") == 0)
T = halvingCase(N);
if (strcmp(argv[1], "star") == 0)
T = starCase(N);
if (strcmp(argv[1], "starshuffle") == 0)
T = starShuffleCase(N);
if (strcmp(argv[1], "line") == 0)
T = lineCase(N);
if (strcmp(argv[1], "silkworm") == 0)
T = silkwormCase(N);
if (strcmp(argv[1], "degree") == 0)
T = maxDegreeCase(N, atoi(argv[6]));
if (strcmp(argv[1], "mindegree") == 0)
T = minDegreeCase(N, atoi(argv[6]));
if (strcmp(argv[1], "knary") == 0)
T = knaryCase(N, atoi(argv[6]));
if (strcmp(argv[1], "flower") == 0)
T = flowerKnaryCase(N, atoi(argv[6]));
if(strcmp(argv[4], "sum") == 0){
assignWeightToDegreeSum(T, atoi(argv[5]));
}else if(strcmp(argv[4], "min") == 0){
assignWeightToDegreeMin(T, atoi(argv[5]));
}else{
pii W = {atoi(argv[4]), atoi(argv[5])};
assignWeightRandomRange(T, W);
}
T.print();
}
| [
"[email protected]"
] | |
22a441c9b6dc742e79d108f1567fdea8c696c5c0 | 8f6547391544ef2e1272d428f251959d0ddede4b | /decoder.cpp | f81665138683c0cc22825eaf19a595ff668774d9 | [] | no_license | amatur/wip | fef0b214c11f954939caadf75b4455a1d954414e | 0128d4f684108aed93e749fd9310a7e9031480a4 | refs/heads/master | 2020-05-30T11:45:33.840185 | 2019-10-28T01:42:15 | 2019-10-28T01:42:15 | 189,713,168 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,074 | cpp |
#include <cmath>
#include<cstring>
#include <fstream>
#include <iostream>
#include <vector>
#include <assert.h>
#include <stdint.h>
#include <unistd.h>
int K = 11;
using namespace std;
int get_data(int K, string UNITIG_FILE= "/Users/Sherlock/Documents/bcl/bcl/tipOutput.txt"){
ifstream unitigFile;
unitigFile.open(UNITIG_FILE);
ofstream outFile;
outFile.open("tip.fa");
string line;
bool startPrefCut = false;
bool startSufCut = false;
string pref;
string suf;
int walkid = 0;
while (getline(unitigFile, line)) {
cout<<line<<endl;
if (line.empty() || line.substr(0, 1).compare(">") == 0) {
} else {
walkid++;
startPrefCut = false;
startSufCut = false;
string tip = "";
string sbuf = "";
string lastk = "";
string pref = "";
string suf = "";
cout<<walkid-1<<" "<<line[0]<<endl;
for(int i = 0; i<line.length(); i++){
if(line[i]=='A'|| line[i]=='C' || line[i]=='G' || line[i]=='T'){
if(startPrefCut){
tip += line[i];
}else if(startSufCut){
tip += line[i];
}else{
sbuf += line[i];
if(lastk.length() < K - 1){
lastk += line[i];
}else{
lastk = lastk.substr(1, K-2) + line[i];
}
}
}else if(line[i]==']'){
if(startPrefCut){ //already has one
startPrefCut = false;
outFile<< "> pref: " << " " << endl;
outFile<< (pref + tip) << endl;
tip = "";
}else if(!startPrefCut){ //prefix is cut starts
startPrefCut = true;
pref = lastk;
}
}else if(line[i]=='['){ //suffix is cut
if(startSufCut){ //already has one
startSufCut = false;
outFile<< ">suf: " << " " << endl;
outFile<< (tip + suf) << endl;
tip = "";
}else if(!startSufCut){
startSufCut = true;
suf = lastk;
}
}
}
//print the tips before printing the contig
outFile<<">"<<walkid-1<<" : "<<"\n";
outFile<<sbuf << endl;
}
}
unitigFile.close();
outFile.close();
cout << "Complete conversion." << endl;
return EXIT_SUCCESS;
}
int main(int argc, char** argv){
const char* stringValue = "" ;
int c ;
///*
while( ( c = getopt (argc, argv, "i:k:m:d:f:") ) != -1 )
{
switch(c)
{
case 'i':
if(optarg) stringValue = optarg;
break;
case 'k':
if(optarg) {
K = std::atoi(optarg) ;
if(K<=0){
fprintf(stderr, "Error: Specify a positive k value.\n");
exit(EXIT_FAILURE);
}
}else{
fprintf(stderr, "Usage: %s -k <kmer size> -i <input-file-name>\n",
argv[0]);
exit(EXIT_FAILURE);
}
break;
default: //
fprintf(stderr, "Usage: %s -k <kmer size> -i <input-file-name>\n",
argv[0]);
exit(EXIT_FAILURE);
}
}
if(K==0 || strcmp(stringValue, "")==0){
fprintf(stderr, "Usage: %s -k <kmer size> -i <input-file-name>\n",
argv[0]);
exit(EXIT_FAILURE);
}
// */
get_data(K);
return 0;
}
| [
"[email protected]"
] | |
4e5f925bc978cce538f4e5ddbb9d1575a1d4d6a8 | 8982c709529d20dae5f46e95bbf0822b23ad4c40 | /Warden_lib/include/engine/data/TextRenderer.hpp | a4dca954daae611452075cc7d66be14bf3b5ce3b | [] | no_license | Solarius66/WardenEngine | 6da099039d19516bada5a10d5ec23a40f19a79fa | 28d27af99ea3cabbadcfae3131ffb0bd58f4c5c9 | refs/heads/master | 2020-12-26T05:33:28.863487 | 2020-06-14T09:58:07 | 2020-06-14T09:58:07 | 237,400,959 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,261 | hpp | /*
** EPITECH PROJECT, 2019
** TextRenderer.hpp
** File description:
** TextRenderer Component Class Declaration
*/
#ifndef TEXTRENDERER_HPP_
#define TEXTRENDERER_HPP_
/// @file include/engine/data/TextRenderer.hpp
#include <QString>
#include <QJsonObject>
#include "include/engine/data/AComponent.hpp"
///
/// TextRenderer Class, contain path for Textual, 2d & 3d textures
///
class TextRenderer : public AComponent
{
public:
///<Constructor, take 1 string as parameter
TextRenderer(const QString & str = ""); ///<
///<Destructor
~TextRenderer(); ///<
///<Update member Function
void update(event) final {} ///<
///<Return the Text Texture Path
const QString & getText() const {return _str;} ///<
///<Set _str value
void setText(const QString &); ///<
///<Set _str value
void addText(const QString &); ///<
///<Remove number of characters at the end of _str, equal to value taken as parameter
void removeText(int); ///<
///<Load a TextRenderer from a .json object
void read(const QJsonObject &json); ///<
///<Save a TextRenderer in a .json object
void write(QJsonObject &json) const; ///<
private:
QString _str;
};
#endif /* end of include guard: TEXTRENDERER_HPP_ */
| [
"[email protected]"
] | |
9446f980b7597c268894bf1b38f9bf1f45c41f24 | b8d0382836ff89b289526550c8d0efa6c28d4605 | /c++/karatsuba.cpp | 9106a8cf24f0b33832a13a9fed18956b0e060a13 | [] | no_license | TechSoc-MSIT/DS-ALGO-REPO-HACKTOBER | ebc9b026b9313d868129f1b20687d5a1b5364c50 | d49196c224a1fac02418c5aa34dc4f2e70692126 | refs/heads/master | 2023-08-25T23:36:39.085664 | 2020-10-25T20:02:24 | 2020-10-25T20:02:24 | 301,695,319 | 0 | 0 | null | 2023-01-22T07:11:35 | 2020-10-06T10:51:11 | Java | UTF-8 | C++ | false | false | 1,783 | cpp | #define ll long long
#define FAST \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
#include <bits/stdc++.h>
using namespace std;
int makeStrLenghtEqual(string &str1, string &str2)
{
int l1 = str1.length();
int l2 = str2.length();
if (l1 < l2)
{
for (int i(0); i < l2 - l1; i++)
{
str1 = '0' + str1;
}
return l2;
}
else if (l1 > l2)
{
for (int i(0); i < l1 - l2; i++)
{
str2 = '0' + str2;
}
}
return l1;
}
string addBits(string a, string b)
{
int len = makeStrLenghtEqual(a, b);
int carry = 0;
string res;
for (int i = len - 1; i >= 0; i--)
{
int bit1 = a[i] - '0';
int bit2 = b[i] - '0';
int sum = (bit1 ^ bit2 ^ carry) + '0';
res = (char)sum + res;
carry = (bit1 & bit2) | (bit1 & carry) | (bit2 & carry);
}
if (carry)
{
res = '1' + res;
}
return res;
}
size_t karatsubaFastMultiply(string num1, string num2)
{
auto multiplyOneBit = [&num1, &num2] { return (num1[0] - '0') * (num2[0] - '0'); };
int n = makeStrLenghtEqual(num1, num2);
if (n == 0)
return 0;
if (n == 1)
return multiplyOneBit();
int p1 = n / 2;
int p2 = n - p1;
string num1l = num1.substr(0, p1);
string num1r = num1.substr(p1, p2);
string num2l = num2.substr(0, p1);
string num2r = num2.substr(p1, p2);
size_t prod1 = karatsubaFastMultiply(num1l, num2l);
size_t prod2 = karatsubaFastMultiply(num1r, num2r);
size_t prod3 = karatsubaFastMultiply(addBits(num1l, num1r), addBits(num2l, num2r));
return prod1 * (1 << (2 * p2)) + (prod3 - prod1 - prod2) * (1 << p2) + prod2;
}
int main()
{
FAST;
string s1, s2;
cin >> s1 >> s2;
cout << karatsubaFastMultiply(s1, s2);
return 0;
}
| [
"[email protected]"
] | |
2d629449642913c71400c5823584018d6c628dbb | fdf6b5417ca8701824dd7562853e419633738391 | /ABC/ABC040/A.cpp | e4e28d9d055a03bdcd249603eed78d8cd093af4b | [] | no_license | canon4444/AtCoder | b2cdb61217c2cf9ba8c66cf703f8a6ad57e97a0e | 17c43cc10e25d2c7465b55e5cf7cf469bac7fd2b | refs/heads/master | 2021-05-22T08:54:40.428286 | 2020-11-08T17:39:11 | 2020-11-08T17:39:11 | 27,902,393 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 186 | cpp | #include <iostream>
using namespace std;
int main()
{
int n, x;
cin >> n >> x;
if( x*2 <= n ) cout << x-1 << endl;
else cout << n-x << endl;
return 0;
}
| [
"[email protected]"
] | |
12262b683ca5c5f136e37d445404f9a5d8280c79 | 8232bb98c0286e1c95babc6bebbbbd30ef204c29 | /a/src/a.cpp | 7b73ea75ca9a44a6f07efa4c984b5b8c4bdf73e8 | [] | no_license | njlr/buck-transitive-headers | c97bc09c1e0fd34052c67c569d7796978fa09564 | 8ea4d68e2106b8aaed09b600568457a4b6063fa1 | refs/heads/master | 2020-03-29T15:42:54.618414 | 2018-09-24T08:58:25 | 2018-09-24T08:58:25 | 150,076,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 148 | cpp | #include <a/a.hpp>
#include <b/b.hpp>
#include <c/c.hpp>
// extern std::string hidden();
std::string a() {
return "Hello from a and " + b();
}
| [
"[email protected]"
] | |
f4479367239bbee519d9a99555a2b9664e9cd9f6 | 627d4d432c86ad98f669214d9966ae2db1600b31 | /src/core/global/qendian.h | ed836c740a740860311b03f5c50833bc5134b06f | [] | no_license | fluxer/copperspice | 6dbab905f71843b8a3f52c844b841cef17f71f3f | 07e7d1315d212a4568589b0ab1bd6c29c06d70a1 | refs/heads/cs-1.1 | 2021-01-17T21:21:54.176319 | 2015-08-26T15:25:29 | 2015-08-26T15:25:29 | 39,802,091 | 6 | 0 | null | 2015-07-27T23:04:01 | 2015-07-27T23:04:00 | null | UTF-8 | C++ | false | false | 11,494 | h | /***********************************************************************
*
* Copyright (c) 2012-2015 Barbara Geller
* Copyright (c) 2012-2015 Ansel Sermersheim
* Copyright (c) 2012-2014 Digia Plc and/or its subsidiary(-ies).
* Copyright (c) 2008-2012 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* This file is part of CopperSpice.
*
* CopperSpice is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* CopperSpice is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with CopperSpice. If not, see
* <http://www.gnu.org/licenses/>.
*
***********************************************************************/
#ifndef QENDIAN_H
#define QENDIAN_H
#include <QtCore/qglobal.h>
// include stdlib.h and hope that it defines __GLIBC__ for glibc-based systems
#include <stdlib.h>
#ifdef __GLIBC__
#include <byteswap.h>
#endif
QT_BEGIN_NAMESPACE
/*
* ENDIAN FUNCTIONS
*/
inline void qbswap_helper(const uchar *src, uchar *dest, int size)
{
for (int i = 0; i < size ; ++i) {
dest[i] = src[size - 1 - i];
}
}
/*
* qbswap(const T src, const uchar *dest);
* Changes the byte order of \a src from big endian to little endian or vice versa
* and stores the result in \a dest.
* There is no alignment requirements for \a dest.
*/
template <typename T> inline void qbswap(const T src, uchar *dest)
{
qbswap_helper(reinterpret_cast<const uchar *>(&src), dest, sizeof(T));
}
// Used to implement a type-safe and alignment-safe copy operation
// If you want to avoid the memcopy, you must write specializations for this function
template <typename T> inline void qToUnaligned(const T src, uchar *dest)
{
memcpy(dest, &src, sizeof(T));
}
/* T qFromLittleEndian(const uchar *src)
* This function will read a little-endian encoded value from \a src
* and return the value in host-endian encoding.
* There is no requirement that \a src must be aligned.
*/
#if defined Q_CC_SUN
inline quint64 qFromLittleEndian_helper(const uchar *src, quint64 *dest)
{
return 0
| src[0]
| src[1] * Q_UINT64_C(0x0000000000000100)
| src[2] * Q_UINT64_C(0x0000000000010000)
| src[3] * Q_UINT64_C(0x0000000001000000)
| src[4] * Q_UINT64_C(0x0000000100000000)
| src[5] * Q_UINT64_C(0x0000010000000000)
| src[6] * Q_UINT64_C(0x0001000000000000)
| src[7] * Q_UINT64_C(0x0100000000000000);
}
inline quint32 qFromLittleEndian_helper(const uchar *src, quint32 *dest)
{
return 0
| src[0]
| src[1] * quint32(0x00000100)
| src[2] * quint32(0x00010000)
| src[3] * quint32(0x01000000);
}
inline quint16 qFromLittleEndian_helper(const uchar *src, quint16 *dest)
{
return 0
| src[0]
| src[1] * 0x0100;
}
inline qint64 qFromLittleEndian_helper(const uchar *src, qint64 *dest)
{
return static_cast<qint64>(qFromLittleEndian_helper(src, reinterpret_cast<quint64 *>(0)));
}
inline qint32 qFromLittleEndian_helper(const uchar *src, qint32 *dest)
{
return static_cast<qint32>(qFromLittleEndian_helper(src, reinterpret_cast<quint32 *>(0)));
}
inline qint16 qFromLittleEndian_helper(const uchar *src, qint16 *dest)
{
return static_cast<qint16>(qFromLittleEndian_helper(src, reinterpret_cast<quint16 *>(0)));
}
template <class T> inline T qFromLittleEndian(const uchar *src)
{
return qFromLittleEndian_helper(src, reinterpret_cast<T *>(0));
}
#else
template <typename T> inline T qFromLittleEndian(const uchar *src);
template <> inline quint64 qFromLittleEndian<quint64>(const uchar *src)
{
return 0
| src[0]
| src[1] * Q_UINT64_C(0x0000000000000100)
| src[2] * Q_UINT64_C(0x0000000000010000)
| src[3] * Q_UINT64_C(0x0000000001000000)
| src[4] * Q_UINT64_C(0x0000000100000000)
| src[5] * Q_UINT64_C(0x0000010000000000)
| src[6] * Q_UINT64_C(0x0001000000000000)
| src[7] * Q_UINT64_C(0x0100000000000000);
}
template <> inline quint32 qFromLittleEndian<quint32>(const uchar *src)
{
return 0
| src[0]
| src[1] * quint32(0x00000100)
| src[2] * quint32(0x00010000)
| src[3] * quint32(0x01000000);
}
template <> inline quint16 qFromLittleEndian<quint16>(const uchar *src)
{
return quint16(0
| src[0]
| src[1] * 0x0100);
}
// signed specializations
template <> inline qint64 qFromLittleEndian<qint64>(const uchar *src)
{
return static_cast<qint64>(qFromLittleEndian<quint64>(src));
}
template <> inline qint32 qFromLittleEndian<qint32>(const uchar *src)
{
return static_cast<qint32>(qFromLittleEndian<quint32>(src));
}
template <> inline qint16 qFromLittleEndian<qint16>(const uchar *src)
{
return static_cast<qint16>(qFromLittleEndian<quint16>(src));
}
#endif
/* This function will read a big-endian (also known as network order) encoded value from \a src
* and return the value in host-endian encoding.
* There is no requirement that \a src must be aligned.
*/
#if defined Q_CC_SUN
inline quint64 qFromBigEndian_helper(const uchar *src, quint64 *dest)
{
return 0
| src[7]
| src[6] * Q_UINT64_C(0x0000000000000100)
| src[5] * Q_UINT64_C(0x0000000000010000)
| src[4] * Q_UINT64_C(0x0000000001000000)
| src[3] * Q_UINT64_C(0x0000000100000000)
| src[2] * Q_UINT64_C(0x0000010000000000)
| src[1] * Q_UINT64_C(0x0001000000000000)
| src[0] * Q_UINT64_C(0x0100000000000000);
}
inline quint32 qFromBigEndian_helper(const uchar *src, quint32 *dest)
{
return 0
| src[3]
| src[2] * quint32(0x00000100)
| src[1] * quint32(0x00010000)
| src[0] * quint32(0x01000000);
}
inline quint16 qFromBigEndian_helper(const uchar *src, quint16 *des)
{
return 0
| src[1]
| src[0] * 0x0100;
}
inline qint64 qFromBigEndian_helper(const uchar *src, qint64 *dest)
{
return static_cast<qint64>(qFromBigEndian_helper(src, reinterpret_cast<quint64 *>(0)));
}
inline qint32 qFromBigEndian_helper(const uchar *src, qint32 *dest)
{
return static_cast<qint32>(qFromBigEndian_helper(src, reinterpret_cast<quint32 *>(0)));
}
inline qint16 qFromBigEndian_helper(const uchar *src, qint16 *dest)
{
return static_cast<qint16>(qFromBigEndian_helper(src, reinterpret_cast<quint16 *>(0)));
}
template <class T> inline T qFromBigEndian(const uchar *src)
{
return qFromBigEndian_helper(src, reinterpret_cast<T *>(0));
}
#else
template <class T> inline T qFromBigEndian(const uchar *src);
template<>
inline quint64 qFromBigEndian<quint64>(const uchar *src)
{
return 0
| src[7]
| src[6] * Q_UINT64_C(0x0000000000000100)
| src[5] * Q_UINT64_C(0x0000000000010000)
| src[4] * Q_UINT64_C(0x0000000001000000)
| src[3] * Q_UINT64_C(0x0000000100000000)
| src[2] * Q_UINT64_C(0x0000010000000000)
| src[1] * Q_UINT64_C(0x0001000000000000)
| src[0] * Q_UINT64_C(0x0100000000000000);
}
template<>
inline quint32 qFromBigEndian<quint32>(const uchar *src)
{
return 0
| src[3]
| src[2] * quint32(0x00000100)
| src[1] * quint32(0x00010000)
| src[0] * quint32(0x01000000);
}
template<>
inline quint16 qFromBigEndian<quint16>(const uchar *src)
{
return quint16( 0
| src[1]
| src[0] * quint16(0x0100));
}
// signed specializations
template <> inline qint64 qFromBigEndian<qint64>(const uchar *src)
{
return static_cast<qint64>(qFromBigEndian<quint64>(src));
}
template <> inline qint32 qFromBigEndian<qint32>(const uchar *src)
{
return static_cast<qint32>(qFromBigEndian<quint32>(src));
}
template <> inline qint16 qFromBigEndian<qint16>(const uchar *src)
{
return static_cast<qint16>(qFromBigEndian<quint16>(src));
}
#endif
/*
* T qbswap(T source).
* Changes the byte order of a value from big endian to little endian or vice versa.
* This function can be used if you are not concerned about alignment issues,
* and it is therefore a bit more convenient and in most cases more efficient.
*/
template <typename T> T qbswap(T source);
#ifdef __GLIBC__
template <> inline quint64 qbswap<quint64>(quint64 source)
{
return bswap_64(source);
}
template <> inline quint32 qbswap<quint32>(quint32 source)
{
return bswap_32(source);
}
template <> inline quint16 qbswap<quint16>(quint16 source)
{
return bswap_16(source);
}
#else
template <> inline quint64 qbswap<quint64>(quint64 source)
{
return 0
| ((source & Q_UINT64_C(0x00000000000000ff)) << 56)
| ((source & Q_UINT64_C(0x000000000000ff00)) << 40)
| ((source & Q_UINT64_C(0x0000000000ff0000)) << 24)
| ((source & Q_UINT64_C(0x00000000ff000000)) << 8)
| ((source & Q_UINT64_C(0x000000ff00000000)) >> 8)
| ((source & Q_UINT64_C(0x0000ff0000000000)) >> 24)
| ((source & Q_UINT64_C(0x00ff000000000000)) >> 40)
| ((source & Q_UINT64_C(0xff00000000000000)) >> 56);
}
template <> inline quint32 qbswap<quint32>(quint32 source)
{
return 0
| ((source & 0x000000ff) << 24)
| ((source & 0x0000ff00) << 8)
| ((source & 0x00ff0000) >> 8)
| ((source & 0xff000000) >> 24);
}
template <> inline quint16 qbswap<quint16>(quint16 source)
{
return quint16( 0
| ((source & 0x00ff) << 8)
| ((source & 0xff00) >> 8) );
}
#endif // __GLIBC__
// signed specializations
template <> inline qint64 qbswap<qint64>(qint64 source)
{
return qbswap<quint64>(quint64(source));
}
template <> inline qint32 qbswap<qint32>(qint32 source)
{
return qbswap<quint32>(quint32(source));
}
template <> inline qint16 qbswap<qint16>(qint16 source)
{
return qbswap<quint16>(quint16(source));
}
#if Q_BYTE_ORDER == Q_BIG_ENDIAN
template <typename T> inline T qToBigEndian(T source)
{
return source;
}
template <typename T> inline T qFromBigEndian(T source)
{
return source;
}
template <typename T> inline T qToLittleEndian(T source)
{
return qbswap<T>(source);
}
template <typename T> inline T qFromLittleEndian(T source)
{
return qbswap<T>(source);
}
template <typename T> inline void qToBigEndian(T src, uchar *dest)
{
qToUnaligned<T>(src, dest);
}
template <typename T> inline void qToLittleEndian(T src, uchar *dest)
{
qbswap<T>(src, dest);
}
#else // Q_LITTLE_ENDIAN
template <typename T> inline T qToBigEndian(T source)
{
return qbswap<T>(source);
}
template <typename T> inline T qFromBigEndian(T source)
{
return qbswap<T>(source);
}
template <typename T> inline T qToLittleEndian(T source)
{
return source;
}
template <typename T> inline T qFromLittleEndian(T source)
{
return source;
}
template <typename T> inline void qToBigEndian(T src, uchar *dest)
{
qbswap<T>(src, dest);
}
template <typename T> inline void qToLittleEndian(T src, uchar *dest)
{
qToUnaligned<T>(src, dest);
}
#endif // Q_BYTE_ORDER == Q_BIG_ENDIAN
template <> inline quint8 qbswap<quint8>(quint8 source)
{
return source;
}
QT_END_NAMESPACE
#endif // QENDIAN_H
| [
"[email protected]"
] | |
e0aa1b4c5e113bf14d1b767da7c73d4ed117af50 | 81cf157e25185df17b78ac09f5686c51198d8db7 | /Algorithm/提高/数据结构/AC自动机/修复DNA.cpp | c29e8567485b47f46e83bb90e2bdb09800dc4592 | [] | no_license | renyajie/Learning | 97e3263e6dbe4ccff37ad3fabd9a6490259ab2b7 | 5174b0e7120ef30c8834fe3d06fcd482240ac2f6 | refs/heads/master | 2023-03-22T01:28:40.647641 | 2021-03-23T02:41:20 | 2021-03-23T02:41:20 | 349,076,372 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,574 | cpp | #include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=60,M=1010;
int tr[N*20][4],cnt[N*20],idx;
int q[N*20],ne[N*20];
int dp[M][N*20];
char str[M];
int get(char c)
{
if(c=='A') return 0;
if(c=='G') return 1;
if(c=='C') return 2;
return 3;
}
void insert()
{
int p=0;
for(int i=0;str[i];i++)
{
int c=get(str[i]);
if(!tr[p][c]) tr[p][c]=++idx;
p=tr[p][c];
}
cnt[p]=1;
}
void build()
{
int hh=0,tt=-1;
for(int i=0;i<4;i++) if(tr[0][i]) q[++tt]=tr[0][i];
while(hh<=tt)
{
int t=q[hh++];
for(int i=0;i<4;i++)
{
int c=tr[t][i];
if(!c) tr[t][i]=tr[ne[t]][i];
else {ne[c]=tr[ne[t]][i]; q[++tt]=c;cnt[c]|=cnt[ne[c]];}
}
}
}
int main()
{
int n,T=1;
while(scanf("%d",&n),n)
{
memset(tr,0,sizeof tr),memset(cnt,0,sizeof cnt),memset(ne,0,sizeof ne),idx=0;
for(int i=0;i<n;i++){scanf("%s",str);insert();}
build();
scanf("%s",str+1);
memset(dp,0x3f,sizeof dp); dp[0][0]=0;
int m=strlen(str+1);
for(int i=0;i<m;i++)
for(int j=0;j<=idx;j++)
for(int k=0;k<4;k++)
{
int p=tr[j][k],t=get(str[i+1])!=k;
if(!cnt[p]) dp[i+1][p]=min(dp[i+1][p],dp[i][j]+t);
}
int ans=0x3f3f3f3f;
for(int i=0;i<=idx;i++) ans=min(ans,dp[m][i]);
if(ans==0x3f3f3f3f) ans=-1;
printf("Case %d: %d\n",T++,ans);
}
return 0;
}
| [
"[email protected]"
] | |
88c6cd304c1944b1817b63e1a76944929e332e2f | ba00f0d396694a16905ea5e7ea092f757dff72b3 | /Sucursal.h | c06984a0d980c9a1c727c0ce74fcf4ad52108fc2 | [] | no_license | JorgeJimenez1702/Proyecto-Integrador | b58b228dbb4f4e7039be2867b3a0bc11beaa8c88 | 51eb6c62171168cef651d946adb9bf06adaa6e4c | refs/heads/main | 2023-04-14T14:37:17.376010 | 2021-05-02T02:11:37 | 2021-05-02T02:11:37 | 361,911,632 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,054 | h | //Modificada
#include <string>
#include "Inventario.h"
//#include "Cliente.h"
#include "Empleado.h"
using namespace std;
class Sucursal
{
private:
int idSucursal; //Le cambie de string a int
string direcSucursal;
string ciudad;
string estado;
string pais;
Inventario inventarioGlobal;
Empleado*listaEmpleados;
int cntdEmp;
//sucursal*lista;
public:
Sucursal();
Sucursal(int ID, string dir,string ciu,
string est, string pa, Inventario global, Empleado*listaEmp);
/*void modificarSucursal(int ID, string dir,
string ciu,string est, string pa);
*/
int getIdSuc(){return idSucursal;}
string getdirecSucu(){return direcSucursal;}
string getCiu(){return ciudad;}
string getEst(){return estado;}
string getPai(){return pais;}
void agregarEmpleado(Empleado nuevo);
void quitarEmpleado(int idEmpleado);
int buscarEmpleado(int);
void setIdSuc(int i){idSucursal=i;}
void setdirecSucu(string d){direcSucursal=d;}
void setCiu(string c){ciudad=c;}
void setEst(string e){estado=e;}
void setPai(string p){pais=p;}
void SetInv(Inventario a){inventarioGlobal = a;}
//¿Como hago de una lista un get?
//Se debería agregar automaticamente a la lista de
//la sucursal correspodiente en el constructor de cada empleado.
//¿Como hago de una lista un get?
//Se debería agregar automaticamente a la lista de
//la sucursal correspodiente en el constructor de cada empleado.
//int buscarEmpleado(int idEmpleado);
//Estos metodos sería mejor implementarlos desde otra clase que guarde la lista de sucursales.
//void agregarSucursal(Sucursal nueva, Sucursal*list,int sucursalesExistentes);
//void quitarSucursal(string idSuc, Sucursal*list,int sucursalesExistentes);
//int buscarSucursal(string idSuc,Sucursal*list,int sucursalesExistentes);
}; | [
"[email protected]"
] | |
5524be9af4a952571cf115c495508fe46ff19f00 | d885ed5402ad7152b39e31239a56aa3abf800381 | /GETTING STARTED/c.STUDENT MARKS.cpp | 3abcfa67f8093fce45ae486a0fb05df7e42b236d | [] | no_license | shubhamnag14/Let-s-C | 6f9aa2aa497a796bb1e7d7fc119101f9bb4f0d3f | 359707e2e07804122001acee9bef9e199e9fb36e | refs/heads/main | 2023-04-04T06:34:56.244907 | 2021-04-07T18:57:57 | 2021-04-07T18:57:57 | 347,189,760 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 297 | cpp | #include<stdio.h>
main()
{
int m1,m2,m3,m4,m5,avg;
float per;
printf("Enter the marks of 5 subjects:");
scanf("%d%d%d%d%d",&m1,&m2,&m3,&m4,&m5);
avg = m1+m2+m3+m4+m5;
per = avg *(100.00/500.00);
printf("Aggregate marks :%d\n",avg);
printf("Percentage of student:%f\n",per);
}
| [
"[email protected]"
] | |
0b780b15118ef0f2e80f4f874eb6286b0bdcc2e9 | 9f92b132303b115bef455113f9bfff649bbf6ab6 | /gametech_assignment3/ScriptHandler.h | dc6d095eeb49501093ff7629984e852c099dcb1f | [] | no_license | jbanda11/ChiefAirJuice | 79c5564e5e6ee8796651c53b0362c51dca867961 | 9968c7306293ca908afbf2ba7dd27e370fe96f01 | refs/heads/master | 2020-04-05T13:57:34.819252 | 2018-12-10T23:38:30 | 2018-12-10T23:38:30 | 156,917,529 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 911 | h | /*
-----------------------------------------------------------------------------
Filename: ScriptHandler.h
-----------------------------------------------------------------------------
Created by: Benjamin Johnson
// File for abstract Script class, which allows for custom scripts
// to be added to game objects
*/
#ifndef _ScriptHandler_H_
#define _ScriptHandler_H_
class GameObject;
class ScriptHandler
{
protected:
GameObject* parent;
public:
// Defines how a script behaves on object collision
// Must override!
virtual void OnCollision(GameObject* other) {
return;
}
// Defines how a script behaves on a step of the physics engine
// Must override!
virtual void OnStep() {
return;
}
virtual void OnFrame(const Ogre::FrameEvent& fe) {
return;
}
ScriptHandler(GameObject* parentObject):
parent(parentObject)
{}
};
#endif
| [
"[email protected]"
] | |
46a2d5a75001a2e659089744272e99a2ad65e3f6 | e46b909cdf0361f6c336f532507573c2f592cdf4 | /util/string/type_ut.cpp | 011e7aff1e891abc95ea7af0c7b96af2f01738dc | [
"Apache-2.0"
] | permissive | exprmntr/test | d25b50881089640e8d94bc6817e9194fda452e85 | 170138c9ab62756f75882d59fb87447fc8b0f524 | refs/heads/master | 2022-11-01T16:47:25.276943 | 2018-03-31T20:56:25 | 2018-03-31T20:56:25 | 95,452,782 | 0 | 3 | Apache-2.0 | 2022-10-30T22:45:27 | 2017-06-26T14:04:21 | C++ | UTF-8 | C++ | false | false | 2,615 | cpp | #include "type.h"
#include <library/unittest/registar.h>
#include <util/charset/wide.h>
SIMPLE_UNIT_TEST_SUITE(TStringClassify) {
SIMPLE_UNIT_TEST(TestIsSpace) {
UNIT_ASSERT_EQUAL(IsSpace(" "), true);
UNIT_ASSERT_EQUAL(IsSpace("\t\r\n"), true);
UNIT_ASSERT_EQUAL(IsSpace(""), false);
UNIT_ASSERT_EQUAL(IsSpace(" a"), false);
}
SIMPLE_UNIT_TEST(TestIsTrue) {
UNIT_ASSERT(IsTrue("1"));
UNIT_ASSERT(IsTrue("yes"));
UNIT_ASSERT(IsTrue("YeS"));
UNIT_ASSERT(IsTrue("on"));
UNIT_ASSERT(IsTrue("true"));
UNIT_ASSERT(IsTrue("da"));
UNIT_ASSERT(!IsTrue("")); // IsTrue won't return true on empty strings anymore
UNIT_ASSERT(!IsTrue("foobar"));
}
SIMPLE_UNIT_TEST(TestIsFalse) {
UNIT_ASSERT(IsFalse("0"));
UNIT_ASSERT(IsFalse("no"));
UNIT_ASSERT(IsFalse("off"));
UNIT_ASSERT(IsFalse("false"));
UNIT_ASSERT(IsFalse("net"));
UNIT_ASSERT(!IsFalse("")); // IsFalse won't return true on empty strings anymore
UNIT_ASSERT(!IsFalse("foobar"));
}
SIMPLE_UNIT_TEST(TestIsNumber) {
UNIT_ASSERT(IsNumber("0"));
UNIT_ASSERT(IsNumber("12345678901234567890"));
UNIT_ASSERT(!IsNumber("1234567890a"));
UNIT_ASSERT(!IsNumber("12345xx67890a"));
UNIT_ASSERT(!IsNumber("foobar"));
UNIT_ASSERT(IsNumber(UTF8ToWide("0")));
UNIT_ASSERT(IsNumber(UTF8ToWide("12345678901234567890")));
UNIT_ASSERT(!IsNumber(UTF8ToWide("1234567890a")));
UNIT_ASSERT(!IsNumber(UTF8ToWide("12345xx67890a")));
UNIT_ASSERT(!IsNumber(UTF8ToWide("foobar")));
}
SIMPLE_UNIT_TEST(TestIsHexNumber) {
UNIT_ASSERT(IsHexNumber("0"));
UNIT_ASSERT(IsHexNumber("aaaadddAAAAA"));
UNIT_ASSERT(IsHexNumber("0123456789ABCDEFabcdef"));
UNIT_ASSERT(IsHexNumber("12345678901234567890"));
UNIT_ASSERT(IsHexNumber("1234567890a"));
UNIT_ASSERT(!IsHexNumber("12345xx67890a"));
UNIT_ASSERT(!IsHexNumber("foobar"));
UNIT_ASSERT(!IsHexNumber(TString()));
UNIT_ASSERT(IsHexNumber(UTF8ToWide("0")));
UNIT_ASSERT(IsHexNumber(UTF8ToWide("aaaadddAAAAA")));
UNIT_ASSERT(IsHexNumber(UTF8ToWide("0123456789ABCDEFabcdef")));
UNIT_ASSERT(IsHexNumber(UTF8ToWide("12345678901234567890")));
UNIT_ASSERT(IsHexNumber(UTF8ToWide("1234567890a")));
UNIT_ASSERT(!IsHexNumber(UTF8ToWide("12345xx67890a")));
UNIT_ASSERT(!IsHexNumber(UTF8ToWide("foobar")));
UNIT_ASSERT(!IsHexNumber(TUtf16String()));
}
}
| [
"[email protected]"
] | |
11f4f525e44544885dbfbb38a2ec3dab60b4b258 | f29b0fd8dee2c6f9beeac5f69aadebaa90f7735c | /src/stringtree.cpp | 43699b8c94b432bbbe712da7c327fcdbe07c596a | [
"MIT"
] | permissive | facontidavide/ros2_introspection | 1465413660506835c1d225b50bec082db2ebffdb | 331a09e64465b5fa625f6215190ce3fca60ec0eb | refs/heads/master | 2023-03-10T19:23:01.341915 | 2020-06-12T11:43:51 | 2020-06-12T11:43:51 | 260,559,230 | 16 | 6 | MIT | 2020-06-12T09:46:25 | 2020-05-01T21:11:38 | C++ | UTF-8 | C++ | false | false | 3,847 | cpp | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright 2016-2017 Davide Faconti
* 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 Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* *******************************************************************/
#include <ros2_introspection/stringtree.hpp>
namespace Ros2Introspection{
namespace details{
// Brutally faster for numbers below 100
inline int printNumber(char* buffer, uint16_t value)
{
const char DIGITS[] =
"00010203040506070809"
"10111213141516171819"
"20212223242526272829"
"30313233343536373839"
"40414243444546474849"
"50515253545556575859"
"60616263646566676869"
"70717273747576777879"
"80818283848586878889"
"90919293949596979899";
if (value < 10)
{
buffer[0] = static_cast<char>('0' + value);
return 1;
}
else if (value < 100) {
value *= 2;
buffer[0] = DIGITS[ value ];
buffer[1] = DIGITS[ value+1 ];
return 2;
}
else{
return sprintf( buffer,"%d", value );
}
}
} // end namespace details
int StringTreeLeaf::toStr(std::string& buffer_str) const
{
const StringTreeNode* leaf_node = this->node_ptr;
if( !leaf_node ){
return -1;
}
boost::container::static_vector<const std::string*, 16> strings_chain;
size_t num_bytes = 0;
while(leaf_node)
{
const auto& str = leaf_node->value();
const size_t S = str.size();
if( S == 1 && str[0] == NUM_PLACEHOLDER )
{
num_bytes += 4; // space for up to 999
}
else{
num_bytes += S+1;
}
strings_chain.push_back( &str );
leaf_node = leaf_node->parent();
};
std::reverse(strings_chain.begin(), strings_chain.end() );
size_t array_count = 0;
size_t offset = 0;
buffer_str.resize(num_bytes); // expand the buffer
char* buffer = &buffer_str.front();
for( const auto& str: strings_chain)
{
const size_t S = str->size();
if( S == 1 && (*str)[0] == NUM_PLACEHOLDER )
{
buffer[offset++] = '.';
offset += details::printNumber(&buffer[offset],
this->index_array[ array_count++ ] );
}
else{
if( offset != 0 ){
buffer[offset++] = SEPARATOR;
}
std::memcpy( &buffer[offset], str->data(), S );
offset += S;
}
}
buffer_str.resize(offset);
return int(offset);
}
}
| [
"Davide Faconti"
] | Davide Faconti |
9b9351fe2179235f41724c8ffb1909f9c7710ebd | 7fbb87a36e062f7f560b971d4d7f818e8ec7d031 | /lib/fuser.h | 55799c732a17c2e12bb76e78670496492e5cb769 | [
"Apache-2.0"
] | permissive | fieldplay/qsim | c0df510e1db661723cc0dea48575bc1beab2910c | 693e6e6d29961cee094d3cf1804c0b628eb559f7 | refs/heads/master | 2022-04-16T01:26:51.220605 | 2020-04-14T15:52:20 | 2020-04-14T15:52:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 980 | h | // Copyright 2019 Google LLC. 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef FUSER_H_
#define FUSER_H_
#include <vector>
#include "gate.h"
namespace qsim {
template <typename Gate>
struct GateFused {
typename Gate::GateKind kind; // kind of the (first) master gate.
unsigned time;
unsigned num_qubits;
unsigned qubits[3];
const Gate* pmaster;
std::vector<const Gate*> gates;
};
} // namespace qsim
#endif // FUSER_H_
| [
"[email protected]"
] | |
99982c999cd3714366099880a363032f7de7a12b | f4bbf75b8006d1ddce38ad43a376c5bb0af9af96 | /Labo C++/Labo5/133.cpp | 20f376cf61764b293992d53268be0f1dc8ec52e2 | [] | no_license | WillemDendauw/ProgrammereninCenCPP | e7ddfdbe32d01de3ec18a82e172f50435e2de2e8 | 02984835020a425275b7b0b2f6fb09d431c513ab | refs/heads/master | 2022-11-06T05:36:21.193096 | 2020-06-26T13:31:16 | 2020-06-26T13:31:16 | 258,452,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,424 | cpp | #include "figuren.h"
#include <memory>
class Blokkendoos: vector<unique_ptr<Figuur>>{
private:
unique_ptr<Figuur> max_opp;
void schrijf(ostream&) const;
public:
Blokkendoos();
Blokkendoos(const string& bestandsnaam);
unique_ptr<Figuur> geef_figuur_met_grootste_oppervlakte();
void push_back(unique_ptr<Figuur>& figuur);
friend ostream& operator<<(ostream& out, const Blokkendoos& l){
l.schrijf(out);
return out;
}
};
Blokkendoos::Blokkendoos() = default;
void Blokkendoos::push_back(unique_ptr<Figuur>& figuur){
if(max_opp==nullptr){
max_opp = move(figuur);
}
else{
vector<unique_ptr<Figuur>>::push_back(move(figuur));
if(max_opp->oppervlakte()<operator[](size()-1)->oppervlakte()){
max_opp.swap(operator[](size()-1));
}
}
}
Blokkendoos::Blokkendoos(const string& bestandsnaam){
unique_ptr<Figuur> up;
ifstream input(bestandsnaam);
string soort;
input >> soort;
while(!input.fail()){
if(soort == "rechthoek"){
double lengte, breedte;
input>>lengte>>breedte;
up = make_unique<Rechthoek>(lengte,breedte);
}
else if(soort == "vierkant"){
double zijde;
input >> zijde;
up = make_unique<Vierkant>(zijde);
}
else{
double straal;
input >> straal;
up = make_unique<Cirkel>(straal);
}
push_back(up);
input >> soort;
}
}
void Blokkendoos::schrijf(ostream& out)const{
for(int i=0; i<size(); i++){
out<<endl<<" "<<i<<" ";
out<<*(operator[](i));
}
out<<endl<<"MAX "<<*max_opp<<endl;
/*
for(const auto& ptr: *this){
out<<*ptr<<endl;
}*/
}
unique_ptr<Figuur> Blokkendoos::geef_figuur_met_grootste_oppervlakte(){
int index_tweedegrootste = 0;
for(int i=1; i<size(); i++){
if(operator[](i)->oppervlakte() > operator[](index_tweedegrootste)->oppervlakte()){
index_tweedegrootste =i;
}
}
operator[](index_tweedegrootste).swap(operator[](size()-1));
unique_ptr<Figuur> hulpptr;
hulpptr.swap(max_opp);
max_opp.swap((*this)[size()-1]);
resize(size()-1);
return move(hulpptr);
}
int main(){
Blokkendoos blokkendoos("figuren.txt");
cout<<endl<<"ALLE FIGUREN: ";
cout<<blokkendoos<<endl;
cout<<endl<<"De 3 Grootste, van groot naar klein: "<<endl;
for(int i=0; i<3; i++){
cout<<"figuur met grootste opp: "<<*blokkendoos.geef_figuur_met_grootste_oppervlakte()<<endl;
}
cout<<endl<<"De nieuwe blokkendoos bevat alleen nog de kleinere figuren: ";
cout<<blokkendoos<<endl;
return 0;
}
| [
"[email protected]"
] | |
53b7d1c73d88dc37ab82ca4f2127fb44d06593f3 | 6b8fff0eeb75ad266af0ec2b9e9aaf28462c2a73 | /Sapi_Dataset/Data/user5/labor9/feladat1/Manager.h | 3760581f5ada6f0da49a928c51fc1ca4496f66ad | [] | no_license | kotunde/SourceFileAnalyzer_featureSearch_and_classification | 030ab8e39dd79bcc029b38d68760c6366d425df5 | 9a3467e6aae5455142bc7a5805787f9b17112d17 | refs/heads/master | 2020-09-22T04:04:41.722623 | 2019-12-07T11:59:06 | 2019-12-07T11:59:06 | 225,040,703 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 423 | h | #pragma once
#include "Szemely.h"
#include "Alkalmazott.h"
#include <vector>
class Manager : public Alkalmazott {
private:
vector<Alkalmazott*> beosztottak;
public:
Manager(string vNev, string kNev, int szEv, string mk) : Alkalmazott(vNev, kNev, szEv, mk){}
void addAlkalmazott(Alkalmazott*);
void deleteAlkalmazott(Alkalmazott*);
int beosztottakSzama() const;
virtual void print(ostream& os) const;
}; | [
"[email protected]"
] | |
90bb67cda5b9304a26953e84c41982dd5bf8f3dd | 81f7a6b97ad614629baf50c2f7fafc3ce59c6036 | /C++/[2013] data_structure/binomial heap 1106/main.cpp | 34fbaaa7a5ba232a4a2d515c23d4bb22ecf24c5f | [] | no_license | sow0000/MyProject | 30737dc3d5bc157e69b6171a22ddf6fd79a83355 | 0b13e756698232a727e5de5a4ae19900d9a2f15c | refs/heads/master | 2016-09-05T21:07:21.890469 | 2015-03-22T08:17:13 | 2015-03-22T08:17:13 | 32,666,826 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 954 | cpp | #include "Bin_Heap.h"
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int main(void){
Bin_Heap bh;
ifstream file;
char getLine[10];
char *command=NULL;
char *ch_value=NULL;
file.open("input_data.in");
cout<<"-------------------------"<<endl;
while(!file.eof()){
memset(getLine, NULL, 10);
file.getline(getLine, 10);
if(!getLine){
continue;
}
command=strtok(getLine, " ");
ch_value=strtok(NULL, " ");
if(!strcmp(command,"INSERT")){
struct Bnode *pNew=new Bnode();
pNew->degree=0;
pNew->value=0;
pNew->pNext=NULL;
pNew->pChild=NULL;
bh.Insert(pNew);
}
/*else if(!strcmp(command,"Search")){
cout<<"Search : "<<ch_value<<endl;
if(bsTree.Search(ch_value))
cout<<"Search success!"<<endl;
else
cout<<"Search fail!"<<endl;
}*/
}
cout<<"-------------------------"<<endl;
/*bsTree.Print();
cout<<endl<<"-------------------------"<<endl;*/
file.close();
} | [
"[email protected]"
] | |
783247b7a882012db824dcde2060587b5e9e5c7f | b5d20ba5c51cbbabb8e8f67e64fec5f22abbf5b5 | /webrtc/rtc_base/checks.h | b53d7072964287d36e41ee8bc6392820165b2336 | [] | no_license | zeiger589/video-chat | 1f979e7f1e7ab543d4e36bef09175548c7528ec6 | 7c233388298057663cfbb65631b0d0d8b80530d4 | refs/heads/master | 2020-05-17T07:07:53.894612 | 2019-04-17T16:10:18 | 2019-04-17T16:10:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,901 | h | /*
* Copyright 2006 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_CHECKS_H_
#define RTC_BASE_CHECKS_H_
// If you for some reson need to know if DCHECKs are on, test the value of
// RTC_DCHECK_IS_ON. (Test its value, not if it's defined; it'll always be
// defined, to either a true or a false value.)
#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
#define RTC_DCHECK_IS_ON 1
#else
#define RTC_DCHECK_IS_ON 0
#endif
// Annotate a function that will not return control flow to the caller.
#if defined(_MSC_VER)
#define RTC_NORETURN __declspec(noreturn)
#elif defined(__GNUC__)
#define RTC_NORETURN __attribute__ ((__noreturn__))
#else
#define RTC_NORETURN
#endif
#ifdef __cplusplus
extern "C" {
#endif
RTC_NORETURN void rtc_FatalMessage(const char* file, int line, const char* msg);
#ifdef __cplusplus
} // extern "C"
#endif
#ifdef __cplusplus
// C++ version.
#include <string>
#include "absl/strings/string_view.h"
#include "rtc_base/numerics/safe_compare.h"
#include "rtc_base/system/inline.h"
// The macros here print a message to stderr and abort under various
// conditions. All will accept additional stream messages. For example:
// RTC_DCHECK_EQ(foo, bar) << "I'm printed when foo != bar.";
//
// - RTC_CHECK(x) is an assertion that x is always true, and that if it isn't,
// it's better to terminate the process than to continue. During development,
// the reason that it's better to terminate might simply be that the error
// handling code isn't in place yet; in production, the reason might be that
// the author of the code truly believes that x will always be true, but that
// she recognizes that if she is wrong, abrupt and unpleasant process
// termination is still better than carrying on with the assumption violated.
//
// RTC_CHECK always evaluates its argument, so it's OK for x to have side
// effects.
//
// - RTC_DCHECK(x) is the same as RTC_CHECK(x)---an assertion that x is always
// true---except that x will only be evaluated in debug builds; in production
// builds, x is simply assumed to be true. This is useful if evaluating x is
// expensive and the expected cost of failing to detect the violated
// assumption is acceptable. You should not handle cases where a production
// build fails to spot a violated condition, even those that would result in
// crashes. If the code needs to cope with the error, make it cope, but don't
// call RTC_DCHECK; if the condition really can't occur, but you'd sleep
// better at night knowing that the process will suicide instead of carrying
// on in case you were wrong, use RTC_CHECK instead of RTC_DCHECK.
//
// RTC_DCHECK only evaluates its argument in debug builds, so if x has visible
// side effects, you need to write e.g.
// bool w = x; RTC_DCHECK(w);
//
// - RTC_CHECK_EQ, _NE, _GT, ..., and RTC_DCHECK_EQ, _NE, _GT, ... are
// specialized variants of RTC_CHECK and RTC_DCHECK that print prettier
// messages if the condition doesn't hold. Prefer them to raw RTC_CHECK and
// RTC_DCHECK.
//
// - FATAL() aborts unconditionally.
//
// TODO(ajm): Ideally, checks.h would be combined with logging.h, but
// consolidation with system_wrappers/logging.h should happen first.
namespace rtc {
namespace webrtc_checks_impl {
enum class CheckArgType : int8_t {
kEnd = 0,
kInt,
kLong,
kLongLong,
kUInt,
kULong,
kULongLong,
kDouble,
kLongDouble,
kCharP,
kStdString,
kStringView,
kVoidP,
// kCheckOp doesn't represent an argument type. Instead, it is sent as the
// first argument from RTC_CHECK_OP to make FatalLog use the next two
// arguments to build the special CHECK_OP error message
// (the "a == b (1 vs. 2)" bit).
kCheckOp,
};
RTC_NORETURN void FatalLog(const char* file,
int line,
const char* message,
const CheckArgType* fmt,
...);
// Wrapper for log arguments. Only ever make values of this type with the
// MakeVal() functions.
template <CheckArgType N, typename T>
struct Val {
static constexpr CheckArgType Type() { return N; }
T GetVal() const { return val; }
T val;
};
inline Val<CheckArgType::kInt, int> MakeVal(int x) {
return {x};
}
inline Val<CheckArgType::kLong, long> MakeVal(long x) {
return {x};
}
inline Val<CheckArgType::kLongLong, long long> MakeVal(long long x) {
return {x};
}
inline Val<CheckArgType::kUInt, unsigned int> MakeVal(unsigned int x) {
return {x};
}
inline Val<CheckArgType::kULong, unsigned long> MakeVal(unsigned long x) {
return {x};
}
inline Val<CheckArgType::kULongLong, unsigned long long> MakeVal(
unsigned long long x) {
return {x};
}
inline Val<CheckArgType::kDouble, double> MakeVal(double x) {
return {x};
}
inline Val<CheckArgType::kLongDouble, long double> MakeVal(long double x) {
return {x};
}
inline Val<CheckArgType::kCharP, const char*> MakeVal(const char* x) {
return {x};
}
inline Val<CheckArgType::kStdString, const std::string*> MakeVal(
const std::string& x) {
return {&x};
}
inline Val<CheckArgType::kStringView, const absl::string_view*> MakeVal(
const absl::string_view& x) {
return {&x};
}
inline Val<CheckArgType::kVoidP, const void*> MakeVal(const void* x) {
return {x};
}
// The enum class types are not implicitly convertible to arithmetic types.
template <
typename T,
typename std::enable_if<std::is_enum<T>::value &&
!std::is_arithmetic<T>::value>::type* = nullptr>
inline decltype(MakeVal(std::declval<typename std::underlying_type<T>::type>()))
MakeVal(T x) {
return {static_cast<typename std::underlying_type<T>::type>(x)};
}
// Ephemeral type that represents the result of the logging << operator.
template <typename... Ts>
class LogStreamer;
// Base case: Before the first << argument.
template <>
class LogStreamer<> final {
public:
template <typename U,
typename std::enable_if<std::is_arithmetic<U>::value ||
std::is_enum<U>::value>::type* = nullptr>
RTC_FORCE_INLINE LogStreamer<decltype(MakeVal(std::declval<U>()))> operator<<(
U arg) const {
return LogStreamer<decltype(MakeVal(std::declval<U>()))>(MakeVal(arg),
this);
}
template <typename U,
typename std::enable_if<!std::is_arithmetic<U>::value &&
!std::is_enum<U>::value>::type* = nullptr>
RTC_FORCE_INLINE LogStreamer<decltype(MakeVal(std::declval<U>()))> operator<<(
const U& arg) const {
return LogStreamer<decltype(MakeVal(std::declval<U>()))>(MakeVal(arg),
this);
}
template <typename... Us>
RTC_NORETURN RTC_FORCE_INLINE static void Call(const char* file,
const int line,
const char* message,
const Us&... args) {
static constexpr CheckArgType t[] = {Us::Type()..., CheckArgType::kEnd};
FatalLog(file, line, message, t, args.GetVal()...);
}
template <typename... Us>
RTC_NORETURN RTC_FORCE_INLINE static void CallCheckOp(const char* file,
const int line,
const char* message,
const Us&... args) {
static constexpr CheckArgType t[] = {CheckArgType::kCheckOp, Us::Type()...,
CheckArgType::kEnd};
FatalLog(file, line, message, t, args.GetVal()...);
}
};
// Inductive case: We've already seen at least one << argument. The most recent
// one had type `T`, and the earlier ones had types `Ts`.
template <typename T, typename... Ts>
class LogStreamer<T, Ts...> final {
public:
RTC_FORCE_INLINE LogStreamer(T arg, const LogStreamer<Ts...>* prior)
: arg_(arg), prior_(prior) {}
template <typename U,
typename std::enable_if<std::is_arithmetic<U>::value ||
std::is_enum<U>::value>::type* = nullptr>
RTC_FORCE_INLINE LogStreamer<decltype(MakeVal(std::declval<U>())), T, Ts...>
operator<<(U arg) const {
return LogStreamer<decltype(MakeVal(std::declval<U>())), T, Ts...>(
MakeVal(arg), this);
}
template <typename U,
typename std::enable_if<!std::is_arithmetic<U>::value &&
!std::is_enum<U>::value>::type* = nullptr>
RTC_FORCE_INLINE LogStreamer<decltype(MakeVal(std::declval<U>())), T, Ts...>
operator<<(const U& arg) const {
return LogStreamer<decltype(MakeVal(std::declval<U>())), T, Ts...>(
MakeVal(arg), this);
}
template <typename... Us>
RTC_NORETURN RTC_FORCE_INLINE void Call(const char* file,
const int line,
const char* message,
const Us&... args) const {
prior_->Call(file, line, message, arg_, args...);
}
template <typename... Us>
RTC_NORETURN RTC_FORCE_INLINE void CallCheckOp(const char* file,
const int line,
const char* message,
const Us&... args) const {
prior_->CallCheckOp(file, line, message, arg_, args...);
}
private:
// The most recent argument.
T arg_;
// Earlier arguments.
const LogStreamer<Ts...>* prior_;
};
template <bool isCheckOp>
class FatalLogCall final {
public:
FatalLogCall(const char* file, int line, const char* message)
: file_(file), line_(line), message_(message) {}
// This can be any binary operator with precedence lower than <<.
template <typename... Ts>
RTC_NORETURN RTC_FORCE_INLINE void operator&(
const LogStreamer<Ts...>& streamer) {
isCheckOp ? streamer.CallCheckOp(file_, line_, message_)
: streamer.Call(file_, line_, message_);
}
private:
const char* file_;
int line_;
const char* message_;
};
} // namespace webrtc_checks_impl
// The actual stream used isn't important. We reference |ignored| in the code
// but don't evaluate it; this is to avoid "unused variable" warnings (we do so
// in a particularly convoluted way with an extra ?: because that appears to be
// the simplest construct that keeps Visual Studio from complaining about
// condition being unused).
#define RTC_EAT_STREAM_PARAMETERS(ignored) \
(true ? true : ((void)(ignored), true)) \
? static_cast<void>(0) \
: rtc::webrtc_checks_impl::FatalLogCall<false>("", 0, "") & \
rtc::webrtc_checks_impl::LogStreamer<>()
// Call RTC_EAT_STREAM_PARAMETERS with an argument that fails to compile if
// values of the same types as |a| and |b| can't be compared with the given
// operation, and that would evaluate |a| and |b| if evaluated.
#define RTC_EAT_STREAM_PARAMETERS_OP(op, a, b) \
RTC_EAT_STREAM_PARAMETERS(((void)rtc::Safe##op(a, b)))
// RTC_CHECK dies with a fatal error if condition is not true. It is *not*
// controlled by NDEBUG or anything else, so the check will be executed
// regardless of compilation mode.
//
// We make sure RTC_CHECK et al. always evaluates |condition|, as
// doing RTC_CHECK(FunctionWithSideEffect()) is a common idiom.
#define RTC_CHECK(condition) \
while (!(condition)) \
rtc::webrtc_checks_impl::FatalLogCall<false>(__FILE__, __LINE__, \
#condition) & \
rtc::webrtc_checks_impl::LogStreamer<>()
// Helper macro for binary operators.
// Don't use this macro directly in your code, use RTC_CHECK_EQ et al below.
#define RTC_CHECK_OP(name, op, val1, val2) \
while (!rtc::Safe##name((val1), (val2))) \
rtc::webrtc_checks_impl::FatalLogCall<true>(__FILE__, __LINE__, \
#val1 " " #op " " #val2) & \
rtc::webrtc_checks_impl::LogStreamer<>() << (val1) << (val2)
#define RTC_CHECK_EQ(val1, val2) RTC_CHECK_OP(Eq, ==, val1, val2)
#define RTC_CHECK_NE(val1, val2) RTC_CHECK_OP(Ne, !=, val1, val2)
#define RTC_CHECK_LE(val1, val2) RTC_CHECK_OP(Le, <=, val1, val2)
#define RTC_CHECK_LT(val1, val2) RTC_CHECK_OP(Lt, <, val1, val2)
#define RTC_CHECK_GE(val1, val2) RTC_CHECK_OP(Ge, >=, val1, val2)
#define RTC_CHECK_GT(val1, val2) RTC_CHECK_OP(Gt, >, val1, val2)
// The RTC_DCHECK macro is equivalent to RTC_CHECK except that it only generates
// code in debug builds. It does reference the condition parameter in all cases,
// though, so callers won't risk getting warnings about unused variables.
#if RTC_DCHECK_IS_ON
#define RTC_DCHECK(condition) RTC_CHECK(condition)
#define RTC_DCHECK_EQ(v1, v2) RTC_CHECK_EQ(v1, v2)
#define RTC_DCHECK_NE(v1, v2) RTC_CHECK_NE(v1, v2)
#define RTC_DCHECK_LE(v1, v2) RTC_CHECK_LE(v1, v2)
#define RTC_DCHECK_LT(v1, v2) RTC_CHECK_LT(v1, v2)
#define RTC_DCHECK_GE(v1, v2) RTC_CHECK_GE(v1, v2)
#define RTC_DCHECK_GT(v1, v2) RTC_CHECK_GT(v1, v2)
#else
#define RTC_DCHECK(condition) RTC_EAT_STREAM_PARAMETERS(condition)
#define RTC_DCHECK_EQ(v1, v2) RTC_EAT_STREAM_PARAMETERS_OP(Eq, v1, v2)
#define RTC_DCHECK_NE(v1, v2) RTC_EAT_STREAM_PARAMETERS_OP(Ne, v1, v2)
#define RTC_DCHECK_LE(v1, v2) RTC_EAT_STREAM_PARAMETERS_OP(Le, v1, v2)
#define RTC_DCHECK_LT(v1, v2) RTC_EAT_STREAM_PARAMETERS_OP(Lt, v1, v2)
#define RTC_DCHECK_GE(v1, v2) RTC_EAT_STREAM_PARAMETERS_OP(Ge, v1, v2)
#define RTC_DCHECK_GT(v1, v2) RTC_EAT_STREAM_PARAMETERS_OP(Gt, v1, v2)
#endif
#define RTC_UNREACHABLE_CODE_HIT false
#define RTC_NOTREACHED() RTC_DCHECK(RTC_UNREACHABLE_CODE_HIT)
// TODO(bugs.webrtc.org/8454): Add an RTC_ prefix or rename differently.
#define FATAL() \
rtc::webrtc_checks_impl::FatalLogCall<false>(__FILE__, __LINE__, \
"FATAL()") & \
rtc::webrtc_checks_impl::LogStreamer<>()
// Performs the integer division a/b and returns the result. CHECKs that the
// remainder is zero.
template <typename T>
inline T CheckedDivExact(T a, T b) {
RTC_CHECK_EQ(a % b, 0) << a << " is not evenly divisible by " << b;
return a / b;
}
} // namespace rtc
#else // __cplusplus not defined
// C version. Lacks many features compared to the C++ version, but usage
// guidelines are the same.
#define RTC_CHECK(condition) \
do { \
if (!(condition)) { \
rtc_FatalMessage(__FILE__, __LINE__, "CHECK failed: " #condition); \
} \
} while (0)
#define RTC_CHECK_EQ(a, b) RTC_CHECK((a) == (b))
#define RTC_CHECK_NE(a, b) RTC_CHECK((a) != (b))
#define RTC_CHECK_LE(a, b) RTC_CHECK((a) <= (b))
#define RTC_CHECK_LT(a, b) RTC_CHECK((a) < (b))
#define RTC_CHECK_GE(a, b) RTC_CHECK((a) >= (b))
#define RTC_CHECK_GT(a, b) RTC_CHECK((a) > (b))
#define RTC_DCHECK(condition) \
do { \
if (RTC_DCHECK_IS_ON && !(condition)) { \
rtc_FatalMessage(__FILE__, __LINE__, "DCHECK failed: " #condition); \
} \
} while (0)
#define RTC_DCHECK_EQ(a, b) RTC_DCHECK((a) == (b))
#define RTC_DCHECK_NE(a, b) RTC_DCHECK((a) != (b))
#define RTC_DCHECK_LE(a, b) RTC_DCHECK((a) <= (b))
#define RTC_DCHECK_LT(a, b) RTC_DCHECK((a) < (b))
#define RTC_DCHECK_GE(a, b) RTC_DCHECK((a) >= (b))
#define RTC_DCHECK_GT(a, b) RTC_DCHECK((a) > (b))
#endif // __cplusplus
#endif // RTC_BASE_CHECKS_H_
| [
"[email protected]"
] | |
b2b1a09d860311662bf71ba1458b23cc972aa4c1 | fd84c4c97bf33b99b063ec9d41fc00752ad45b86 | /mindspore/ccsrc/ir/dtype/empty.h | a13dc084ca014b27257e0dc8fc994c015802eabe | [
"Apache-2.0",
"AGPL-3.0-only",
"BSD-3-Clause-Open-MPI",
"MPL-1.1",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"MPL-2.0",
"LGPL-2.1-only",
"GPL-2.0-only",
"Libpng",
"BSL-1.0",
"MIT",
"MPL-2.0-no-copyleft-exception",
"IJG",
"Zlib",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"MPL-1.0",
"BSD-3-Clause"
] | permissive | zjd1988/mindspore | d9c283416bee6e18b6ca2b04ff0d9fd8f1473c2e | 10481470df2dd0c9713ce45e41b7c37a4050f643 | refs/heads/master | 2021-05-23T00:19:47.869207 | 2020-04-04T09:31:23 | 2020-04-04T09:31:23 | 253,152,063 | 1 | 0 | Apache-2.0 | 2020-04-05T04:01:54 | 2020-04-05T04:01:53 | null | UTF-8 | C++ | false | false | 2,466 | h | /**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* 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 MINDSPORE_CCSRC_IR_DTYPE_EMPTY_H_
#define MINDSPORE_CCSRC_IR_DTYPE_EMPTY_H_
#include <cstddef>
#include <iostream>
#include <initializer_list>
#include <map>
#include <memory>
#include <utility>
#include <sstream>
#include <string>
#include <vector>
#include <type_traits>
#include <unordered_map>
#include <algorithm>
#include "ir/base.h"
#include "ir/named.h"
#include "ir/dtype/type.h"
namespace mindspore {
class TypeAnything : public Type {
public:
TypeAnything() : Type(kMetaTypeAnything) {}
~TypeAnything() override {}
MS_DECLARE_PARENT(TypeAnything, Type)
TypeId generic_type_id() const override { return kMetaTypeAnything; }
TypePtr DeepCopy() const override;
std::string DumpText() const override { return "AnythingType"; }
};
using TypeAnythingPtr = std::shared_ptr<TypeAnything>;
class TypeNone : public Type {
public:
TypeNone() : Type(kMetaTypeNone) {}
~TypeNone() override {}
MS_DECLARE_PARENT(TypeNone, Type)
TypeId generic_type_id() const override { return kMetaTypeNone; }
TypePtr DeepCopy() const override { return std::make_shared<TypeNone>(); }
std::string ToReprString() const override { return "type_none"; }
std::string DumpText() const override { return "NoneType"; }
};
using TypeNonePtr = std::shared_ptr<TypeNone>;
class TypeNull : public Type {
public:
TypeNull() : Type(kMetaTypeNull) {}
~TypeNull() override {}
MS_DECLARE_PARENT(TypeNull, Type)
TypeId generic_type_id() const override { return kMetaTypeNull; }
TypePtr DeepCopy() const override { return std::make_shared<TypeNull>(); }
std::string DumpText() const override { return "NullType"; }
};
using TypeNullPtr = std::shared_ptr<TypeNull>;
extern const TypePtr kTypeNone;
extern const TypePtr kTypeAnything;
extern const TypePtr kAnyType;
} // namespace mindspore
#endif // MINDSPORE_CCSRC_IR_DTYPE_EMPTY_H_
| [
"[email protected]"
] | |
b6cbf7a88a93a9f47e0e8da0f5c495926a5269a3 | ab42ac51b609d1f1d1b6026034d21f065ae05998 | /easy_problems/calculate_distance.cpp | 4b7ee43371eca69541e88ca350de73b6fbdb96e7 | [] | no_license | arvgg/codeeval | d4bd5b9f00874123da1eea904d1dcd95b6db2cfb | f443272725129de226c40b6dd160b880efc27114 | refs/heads/master | 2016-09-09T20:15:45.619051 | 2015-07-29T18:11:04 | 2015-07-29T18:11:04 | 39,906,001 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 726 | cpp | #include <iostream>
#include <fstream>
#include <sstream>
#include <math.h>
using namespace std;
int main(int argc, char *argv[]) {
ifstream stream(argv[1]);
string line,tuple1,tuple2,num;
int x1, x2, y1, y2;
while(getline(stream,line)) {
stringstream s(line);
s.ignore();
getline(s, tuple1, ')');
s.ignore();
s.ignore();
getline(s, tuple2, ')');
stringstream s1(tuple1);
getline(s1,num,',');
x1=stoi(num);
getline(s1,num);
y1=stoi(num);
stringstream s2(tuple2);
getline(s2,num,',');
x2=stoi(num);
getline(s2,num);
y2=stoi(num);
int result=sqrt(pow((x2-x1),2) + pow((y2-y1),2));
cout << result << endl;
}
return 0;
}
| [
"[email protected]"
] | |
7b70f818d920f5081fc965ecceeea66f155adf03 | cd9256bdf7834c7723c7c36ad0cc87ff0ffbd4ad | /swea4014.cpp | 17e5255fc644ec06ad8e8c6dce8d9285b04d6b7d | [] | no_license | surinoel/boj | 23060000aeaaf789f0525d716d5ef048661d7b6c | 2b3a007cf4efaafc196cdd7c745a375b3f88e7e7 | refs/heads/master | 2020-05-02T09:02:07.434285 | 2020-02-20T01:10:00 | 2020-02-20T01:10:00 | 177,858,962 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,479 | cpp | #include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int mat[20][20];
bool rowbuild[20][20];
bool colbuild[20][20];
bool rowcheck[20];
bool colcheck[20];
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int tc;
cin >> tc;
for (int test_case = 1; test_case <= tc; test_case++) {
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> mat[i][j];
}
}
memset(rowbuild, false, sizeof(rowbuild));
memset(colbuild, false, sizeof(colbuild));
fill(rowcheck, rowcheck + n, true);
fill(colcheck, colcheck + n, true);
for (int i = 0; i < n; i++) {
bool ok = true;
int cmp;
for (int j = 0; j < n; j++) {
if (j == 0) {
cmp = mat[i][j];
continue;
}
if (mat[i][j] - cmp < 0) {
if (cmp - mat[i][j] == 1) {
bool ok = true;
for (int k = 0; k < m; k++) {
if (j + k >= n || mat[i][j + k] != mat[i][j] || rowbuild[i][j + k]) {
rowcheck[i] = false;
ok = false;
}
}
if (ok) {
for (int k = 0; k < m; k++) {
rowbuild[i][j + k] = true;
}
j += (m - 1);
}
}
else {
rowcheck[i] = false;
}
}
cmp = mat[i][j];
}
}
for (int i = 0; i < n; i++) {
bool ok = true;
int cmp;
if (!rowcheck[i]) continue;
for (int j = n - 1; j >= 0; j--) {
if (j == n -1) {
cmp = mat[i][j];
continue;
}
if (mat[i][j] - cmp < 0) {
if (cmp - mat[i][j] == 1) {
bool ok = true;
for (int k = 0; k < m; k++) {
if (j - k < 0 || mat[i][j - k] != mat[i][j] || rowbuild[i][j - k]) {
rowcheck[i] = false;
ok = false;
}
}
if (ok) {
for (int k = 0; k < m; k++) {
rowbuild[i][j - k] = true;
}
j -= m;
j += 1;
}
}
else {
rowcheck[i] = false;
}
}
cmp = mat[i][j];
}
}
for (int j = 0; j < n; j++) {
bool ok = true;
int cmp;
for (int i = 0; i < n; i++) {
if (i == 0) {
cmp = mat[i][j];
continue;
}
if (mat[i][j] - cmp < 0) {
if (cmp - mat[i][j] == 1) {
bool ok = true;
for (int k = 0; k < m; k++) {
if (i + k >= n || mat[i + k][j] != mat[i][j] || colbuild[i + k][j]) {
colcheck[j] = false;
ok = false;
}
}
if (ok) {
for (int k = 0; k < m; k++) {
colbuild[i + k][j] = true;
}
i += (m - 1);
}
}
else {
colcheck[j] = false;
}
}
cmp = mat[i][j];
}
}
for (int j = 0; j < n; j++) {
bool ok = true;
int cmp;
if (!colcheck[j]) continue;
for (int i = n - 1; i >= 0; i--) {
if (i == n - 1) {
cmp = mat[i][j];
continue;
}
if (mat[i][j] - cmp < 0) {
if (cmp - mat[i][j] == 1) {
bool ok = true;
for (int k = 0; k < m; k++) {
if (i - k < 0 || mat[i - k][j] != mat[i][j] || colbuild[i - k][j]) {
colcheck[j] = false;
ok = false;
}
}
if (ok) {
for (int k = 0; k < m; k++) {
colbuild[i - k][j] = true;
}
i -= m;
i += 1;
}
}
else {
colcheck[j] = false;
}
}
cmp = mat[i][j];
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
if (rowcheck[i]) {
ans += 1;
}
if (colcheck[i]) {
ans += 1;
}
}
cout << "#" << test_case << " " << ans << '\n';
}
return 0;
}
| [
"[email protected]"
] | |
f560a353eac531ba32677e8ba765721858ec2249 | b8bd7f3dd41f83b2f110fce3c82ed806e20289d2 | /Silk/src/Renderer/Scene.h | 0bd6e1fce17a11fba48fc6a481369a762dcb8d6e | [] | no_license | djdduty/Silk | d352dc07398d36f009ae75d44c0d93e75bab5100 | 0277b705ad3534bc0d3c5968c3f3c9af3825e9f9 | refs/heads/master | 2021-05-01T06:51:43.582441 | 2018-01-22T18:56:48 | 2018-01-22T18:56:48 | 37,571,193 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,464 | h | #pragma once
#include <vector>
#include <System/SilkTypes.h>
using namespace std;
namespace Silk
{
class Scene;
class Camera;
class Material;
class Renderer;
class ObjectList;
class RenderObject;
class CullingResult;
class CullingAlgorithm;
class Scene
{
public:
Scene(Renderer* r);
~Scene();
void SetActiveCamera(Camera* c) { m_ActiveCamera = c; }
Camera* GetActiveCamera() const { return m_ActiveCamera; }
void SetCullingAlgorithm(CullingAlgorithm* Algo) { m_CullingAlgorithm = Algo; }
CullingAlgorithm* GetCullingAlgorithm() const { return m_CullingAlgorithm; }
Renderer* GetRenderer() const { return m_Renderer; }
CullingResult* PerformCulling();
void AddRenderObject(RenderObject* Object);
void RemoveRenderObject(RenderObject* Object);
void AddToUpdateList(RenderObject* Object) { m_UpdatedObjects.push_back(Object); }
ObjectList* GetObjectList() const { return m_ObjectList; }
protected:
friend class CullingAlgorithm;
friend class Renderer;
Renderer* m_Renderer;
Camera* m_ActiveCamera;
CullingAlgorithm* m_CullingAlgorithm;
ObjectList* m_ObjectList;
vector<RenderObject*> m_UpdatedObjects;
};
};
| [
"[email protected]"
] | |
773999dedcdf092ad541505186943c1af8c999f3 | 04026a1b68ac9d598f078fc7a1b7ff16128cdfc5 | /src/main/java/AutoCommands/AutonomousCommands/RobotLeftScaleRight.h | 196d079fc55547df6633cafb90792f924defba43 | [
"MIT"
] | permissive | frc4646/2018-competition-code | 914f3bddac9d57e768bef16f109aba731aaac9c2 | 6fd8288c1789849ab3054de6186f2040161588a8 | refs/heads/master | 2021-09-28T20:12:00.543911 | 2018-10-21T21:04:19 | 2018-10-21T21:04:19 | 117,613,480 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 221 | h | #ifndef RobotLeftScaleRight_H
#define RobotLeftScaleRight_H
#include <Commands/2018CommandGroups.h>
class RobotLeftScaleRight : public CommandGroup {
public:
RobotLeftScaleRight();
};
#endif // RobotLeftScaleRight_H
| [
"[email protected]"
] | |
1d541f3dccc64120f4c85d8cd5abad7c14e5e75e | 52ca17dca8c628bbabb0f04504332c8fdac8e7ea | /boost/interprocess/interprocess_fwd.hpp | d379ea9fbe38d6481734c069ef1f5c58d7747969 | [] | no_license | qinzuoyan/thirdparty | f610d43fe57133c832579e65ca46e71f1454f5c4 | bba9e68347ad0dbffb6fa350948672babc0fcb50 | refs/heads/master | 2021-01-16T17:47:57.121882 | 2015-04-21T06:59:19 | 2015-04-21T06:59:19 | 33,612,579 | 0 | 0 | null | 2015-04-08T14:39:51 | 2015-04-08T14:39:51 | null | UTF-8 | C++ | false | false | 75 | hpp | #include "thirdparty/boost_1_58_0/boost/interprocess/interprocess_fwd.hpp"
| [
"[email protected]"
] | |
50e666d73bcd80db049a80e4231884dc9843c90b | a86ade533cf536de3b6fca4c5903d6954ec85df9 | /七月四日课堂作业/neat_gaaris1.ino | 4aa1e2c1371cb62cc8f3365c2535ec6bb7e8d3d5 | [] | no_license | ttbit1/Morse | b2a75908a98c2fb1a42dbdd686902f90a92a1330 | ac520b34938d7145a557f7b352298af441b5ed77 | refs/heads/master | 2020-06-14T18:59:09.307185 | 2019-07-08T14:43:03 | 2019-07-08T14:43:03 | 195,094,933 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,068 | ino |
//F:前进;B:后退;L:左转;L:右转;S:停止
void setup()
{
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
Serial.begin(9600);
}
int income;
void loop()
{
if(Serial.available()>0){
income=Serial.read();
}
switch(income){
case 'F':forward();break;
case 'B':backward();break;
case 'L':left();break;
case 'R':right();break;
case 'S':stop();break;
}
}
void forward()
{
digitalWrite(5,HIGH);
digitalWrite(6,LOW);
digitalWrite(9,HIGH);
digitalWrite(10,LOW);
}
void backward()
{
digitalWrite(5,LOW);
digitalWrite(6,HIGH);
digitalWrite(9,LOW);
digitalWrite(10,HIGH);
}
void left()
{
digitalWrite(5,HIGH);
digitalWrite(6,LOW);
digitalWrite(9,LOW);
digitalWrite(10,HIGH);
}
void right()
{
digitalWrite(5,LOW);
digitalWrite(6,HIGH);
digitalWrite(9,HIGH);
digitalWrite(10,LOW);
}
void stop()
{
digitalWrite(5,LOW);
digitalWrite(6,LOW);
digitalWrite(9,LOW);
digitalWrite(10,LOW);
}
| [
"[email protected]"
] | |
3d31e0d274444792997962fec450493707847eb8 | 57acc952c624b7a8e9e335bd03a42a580b30ea3c | /S11150A.CPP | d81dcc0259a1ad7eea3d149b04d5793e2151d9c1 | [] | no_license | dsanjoy58/ACM-problem-solutions | 096f53163eff53f52daea1b81d772b202ebceaef | a977481758db0aa5e8548703a29c941ee0789c92 | refs/heads/master | 2020-06-01T00:00:07.529292 | 2015-01-30T16:09:39 | 2015-01-30T16:09:39 | 30,079,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 168 | cpp | #include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
int main()
{
unsigned short int N;
while(cin>>N)
{
cout<<floor(N*1.5)<<endl;
}
}
| [
"[email protected]"
] | |
a751770266177025facce779545de0e6cb48dbfb | b2235f07aa792445ac4f8cf3e194f7d9363ce696 | /count.cpp | a73b540c2685848d5cfa8f9fed6d1c24c721dc3a | [] | no_license | GaryKZhu/C-StringMethods | 1c09008f3aee6483241684068c492af1404561f7 | 6740c0e724e10a833577381b1375ac20a0ed3a64 | refs/heads/master | 2020-04-26T09:46:57.494255 | 2019-03-02T18:12:07 | 2019-03-02T18:12:07 | 173,467,948 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 216 | cpp | #include <iostream>
#include <sstream>
#include <algorithm>"
using namespace std;
int main(){
string inputstr = "I like Evan";
size_t n = std::count(inputstr.begin(), inputstr.end(), 'e');
cout << n;
}
| [
"[email protected]"
] | |
dd46ef6bf3bf1a59111e8c5961c4e416899c0097 | 921fb7a09ecbf7d597a320e289979e70ded134e3 | /UnderconstrainedIK.hh | b1bb6cc0579eefbe2d09e28115d4789c89799195 | [
"BSD-3-Clause"
] | permissive | pvernaza/underconstrained-ik-simple | d7bca020cc46f4d2e3dd5c3bd90b67a4c808c272 | b8ac21428f2a4abf8a3d69c12b6aa5d38d85af12 | refs/heads/master | 2021-01-22T12:02:08.283750 | 2013-09-22T15:36:44 | 2013-09-22T15:36:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,396 | hh | #ifndef __UCInvKinematics_hh__
#define __UCInvKinematics_hh__
#include <Eigen/Dense>
#include <vector>
namespace underconstrained_ik {
struct UCJointIKState {
int index; // index of the joint
bool isKnown; // true iff. the joint angle is known
double angle; // the joint's known (or guessed) angle
};
typedef std::vector<UCJointIKState> UCJointIKStateVector;
template <typename KinModel, typename KinChainPt>
class KinematicModelOps {
public:
static
Eigen::Vector3d
ComputeCartesianFK(KinModel const& kinModel,
KinChainPt const& kinChainPt,
std::vector<UCJointIKState> const& jointIKStates);
static
Eigen::MatrixXd
ComputeJacobian(KinModel const& kinModel,
KinChainPt const& kinChainPt,
std::vector<UCJointIKState> const& jointIKStates);
};
/**
\tparam KinModel The type of the robot's kinematic model
\tparam KinChainPt The type of a point wrt. the robot's kinematic chain
*/
template <typename KinModel, typename KinChainPt>
class UCIKSolver {
public:
/**
Solves IK with an optional prior penalizing deviation from
a given set of joint angles.
\param kinModel The robot's kinematic model
\param jointIKStates Vector of IK states for each joint in group
\param kinChainPt A point on the robot's kinematic chain
\param kinChainPtBodyPos Body coordinates of the point
\param step Determines gradient descent step size
\param tol The tolerated distance error
\param priorReg The deviation penalty parameter
\param qPrior The joint angles wrt. which the penalty is computed
*/
static
UCJointIKStateVector
SolveIKPrior(KinModel const& kinModel,
UCJointIKStateVector const& jointIKStates,
KinChainPt const& kinChainPt,
Eigen::Vector3d const& kinChainPtBodyPos,
double step,
double tol = 1e-3,
double priorReg = 0.0,
std::vector<double> const& qPrior = std::vector<double>());
/**
Solves IK for an entire path. Optional smoothness prior penalizes
deviation between successive IK solutions.
\param kinModel The robot's kinematic model
\param initialJointIKState Initial IK state for each joint
\param kinChainPt A point on the robot's kinematic chain
\param kinChainPtBodyPosPath Sequence of body coordinates of the point
\param step Determines gradient descent step size
\param tol The tolerated distance error
\param priorReg The deviation penalty parameter
*/
static
std::vector<UCJointIKStateVector>
SolveIKPath(KinModel const& kinModel,
UCJointIKStateVector const& initialJointIKState,
KinChainPt const& kinChainPt,
std::vector<Eigen::Vector3d> const& kinChainPtBodyPosPath,
double step,
double tol = 1e-3,
double priorReg = 0.0);
};
template <typename KinModel, typename KinChainPt>
UCJointIKStateVector
UCIKSolver<KinModel,KinChainPt>::SolveIKPrior
(KinModel const& kinModel,
UCJointIKStateVector const& jointIKStates,
KinChainPt const& kinChainPt,
Eigen::Vector3d const& kinChainPtBodyPos,
double step,
double tol,
double priorReg,
std::vector<double> const& qPrior) {
// compute FK for known point on kinematic chain
Eigen::Vector3d const curPos =
KinematicModelOps<KinModel, KinChainPt>::
ComputeCartesianFK(kinModel, kinChainPt, jointIKStates);
// error in FK position
Eigen::MatrixXd const deltaPos = curPos - kinChainPtBodyPos;
// compute objective, terminate if necessary
if (deltaPos.norm() < tol) return jointIKStates;
// compute Jacobian wrt. unknown joint
Eigen::MatrixXd dwdq =
KinematicModelOps<KinModel, KinChainPt>::
ComputeJacobian(kinModel, kinChainPt, jointIKStates);
Eigen::MatrixXd const dxdq = dwdq.block(0, 0, 3, jointIKStates.size());
// compute gradient step
Eigen::MatrixXd grad = 2 * deltaPos * dxdq;
// compute contribution to gradient due to prior deviation penalty
if (priorReg > 0.) {
assert(qPrior.size() == jointIKStates.size());
Eigen::RowVectorXd priorDeviation(qPrior.size());
for (int ii = 0; ii < qPrior.size(); ii++)
priorDeviation(ii) = jointIKStates[ii].angle - qPrior[ii];
grad = grad - (2 * priorReg * priorDeviation);
}
// update guesses
std::vector<UCJointIKState> newJointIKStates(jointIKStates);
for (int iGrad = 0; iGrad < grad.size(); iGrad++) {
if (!jointIKStates[iGrad].isKnown)
newJointIKStates[iGrad].angle -= step * grad(iGrad);
}
// recurse
return SolveIKPrior(kinModel,
newJointIKStates,
kinChainPt,
kinChainPtBodyPos,
step,
tol,
priorReg,
qPrior);
}
template <typename KinModel, typename KinChainPt>
std::vector<UCJointIKStateVector>
SolveIKPath(KinModel const& kinModel,
UCJointIKStateVector const& initialJointIKStates,
KinChainPt const& kinChainPt,
std::vector<Eigen::Vector3d> const& kinChainPtBodyPosPath,
double step,
double tol,
double priorReg) {
// compute the initial IK solution
UCJointIKStateVector const jointIKStates1 =
UCIKSolver<KinModel,KinChainPt>
::SolveIKPrior(kinModel, initialJointIKStates, kinChainPt,
kinChainPtBodyPosPath[0], step, tol, 0.0);
// store the initial IK solution as a prior
std::vector<double> qPrior(initialJointIKStates.size());
for (int ii = 0; ii < qPrior.size(); ii++)
qPrior[ii] = jointIKStates1[ii].angle;
// loop over input path, computing IK
UCJointIKStateVector curJointIKState(initialJointIKStates);
std::vector<UCJointIKStateVector> ikStatePath;
for (int iPath = 0; iPath < kinChainPtBodyPosPath.size(); iPath++) {
UCJointIKStateVector newIK =
UCIKSolver<KinModel,KinChainPt>
::SolveIKPrior(kinModel, curJointIKState, kinChainPt,
kinChainPtBodyPosPath[iPath], step, tol,
priorReg, qPrior);
for (int ii = 0; ii < qPrior.size(); ii++)
qPrior[ii] = newIK[ii].angle;
ikStatePath.push_back(newIK);
}
return ikStatePath;
}
};
#endif
| [
"[email protected]"
] | |
d55300db39a18e8c3425c39c36e95b831c34c93d | 594855ca5b64696332206a44fe5e92a72d7a0a17 | /bfields/persons7.cpp | c389698f0b8f5bc0d094392b4aa4b6c7bd20fbcc | [] | no_license | dnichyparuk/bob-flight-sim | 2669e272507cc179512929c1bad9f911f9dd7d44 | 5e70a2d0b452bd2f6b1392c292d82bf757bb05e9 | refs/heads/master | 2021-05-17T00:38:34.429823 | 2014-10-15T14:27:15 | 2014-10-15T14:27:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,033 | cpp | /*
Battle of Britain
Copyright (C) 2000, 2001 Empire Interactive (Europe) Ltd,
677 High Road, North Finchley, London N12 0DA
Please see the document licence.doc for the full licence agreement
2. LICENCE
2.1
Subject to the provisions of this Agreement we now grant to you the
following rights in respect of the Source Code:
2.1.1
the non-exclusive right to Exploit the Source Code and Executable
Code on any medium; and
2.1.2
the non-exclusive right to create and distribute Derivative Works.
2.2
Subject to the provisions of this Agreement we now grant you the
following rights in respect of the Object Code:
2.2.1
the non-exclusive right to Exploit the Object Code on the same
terms and conditions set out in clause 3, provided that any
distribution is done so on the terms of this Agreement and is
accompanied by the Source Code and Executable Code (as
applicable).
3. GENERAL OBLIGATIONS
3.1
In consideration of the licence granted in clause 2.1 you now agree:
3.1.1
that when you distribute the Source Code or Executable Code or
any Derivative Works to Recipients you will also include the
terms of this Agreement;
3.1.2
that when you make the Source Code, Executable Code or any
Derivative Works ("Materials") available to download, you will
ensure that Recipients must accept the terms of this Agreement
before being allowed to download such Materials;
3.1.3
that by Exploiting the Source Code or Executable Code you may
not impose any further restrictions on a Recipient's subsequent
Exploitation of the Source Code or Executable Code other than
those contained in the terms and conditions of this Agreement;
3.1.4
not (and not to allow any third party) to profit or make any
charge for the Source Code, or Executable Code, any
Exploitation of the Source Code or Executable Code, or for any
Derivative Works;
3.1.5
not to place any restrictions on the operability of the Source
Code;
3.1.6
to attach prominent notices to any Derivative Works stating
that you have changed the Source Code or Executable Code and to
include the details anddate of such change; and
3.1.7
not to Exploit the Source Code or Executable Code otherwise than
as expressly permitted by this Agreement.
questions about this file may be asked at [email protected] a
better place to ask is http://www.simhq.com/ or even :-
http://www.simhq.com/cgi-bin/boards/cgi-bin/forumdisplay.cgi?action=topics&forum=Battle+of+Britain&number=40&DaysPrune=20&LastLogin=
*/
//
// Basic expression evaluator code...
// Used in both game and mission editor
//
//
//
//
//
#include "dosdefs.h"
#include "uniqueid.h"
//DEADCODE JIM 09/02/00 #include "text.h"
#include "mymath.h"
#ifndef __BCPLUSPLUS__
#include "files.g"
#include "flyinit.h"
#include "movement.h"
#include "package.h"
#include "nodebob.h"
#endif
#include "bfnumber.h"
#include "persons2.h"
int EventVal::minus1=-1;
int GlobRefExpr::Evaluate(int) //formpos is irrelevent
{
return Persons2::GetLoc(globrefind);
}
UniqueID GlobRefExpr::EvalW(Coords3D& w)
{
int uid=Persons2::GetLoc(globrefind);
if (uid<=0 || uid>int(IllegalSepID))
return IllegalSepID;
ItemBasePtr p=Persons2::ConvertPtrUID(UniqueID(uid));
if (!p)
return UniqueID(uid);
w=p->World;
return UID_Null;
}
UniqueID UIDExpr::EvalW(Coords3D& c)
{
int uid=val.Evaluate(0);
if (uid<0)
if (uid==ENABLE_COMPLEX_VAL)
return UniqueID(+ENABLE_COMPLEX_VAL+val.UsesGlobRef());
else
return UniqueID(uid);
ItemBasePtr p=Persons2::ConvertPtrUID(UniqueID(uid));
if (!p)
{
if (uid==ENABLE_COMPLEX_VAL)
return UniqueID(+ENABLE_COMPLEX_VAL+val.UsesGlobRef());
else
return UniqueID(uid); //target object not loaded yet!
}
else
{
if (p->World.Y&0x40000000) //target object's coords not set yet!
return UniqueID(val.Evaluate(0));
c=p->World;
if (p->Status.size==WAYPOINTSIZE)
{ //It may be a target relative waypoint!!!
WayPoint* w=*p;
if ((int)w->next!=-1 && w->target)
{
if ((int)w->target==-1) //outstanding warrant...
return UniqueID(val.Evaluate(0));
c.X+=w->target->World.X;
c.Y+=w->target->World.Y;
c.Z+=w->target->World.Z;
}
}
return UID_Null;
}
}
UniqueID UIDExpr::EvalA(HP& c)
{ ItemBasePtr p=Persons2::ConvertPtrUID(UniqueID(val.Evaluate(0)));
if (p && p->Status.size>=HPSIZE)
{
hpitem* q=*p;
c.H=q->hdg;
c.P=q->pitch;
return UID_Null;
}
return UniqueID(val.Evaluate(0));
}
UniqueID RotExpr::EvalA(HP& c)
{
if (icpt.complex)
{
HP a;
UniqueID t=icpt.EvalA(a);
if (t) RETURN(t);
int v1;
if ((v1=hdg.Evaluate())!=ENABLE_COMPLEX_VAL)
c.H=Angles(v1)+a.H;
if ((v1=pitch.Evaluate())!=ENABLE_COMPLEX_VAL)
c.P=Angles(v1)+a.P;
}
else
{
int v1;
if ((v1=hdg.Evaluate())!=ENABLE_COMPLEX_VAL)
c.H=Angles(v1);
if ((v1=pitch.Evaluate())!=ENABLE_COMPLEX_VAL)
c.P=Angles(v1);
}
return UID_Null;
}
UniqueID RotExpr::EvalW(Coords3D& p)
{
HP a;//={ANGLES_0Deg,ANGLES_0Deg};
UniqueID rv=EvalA(a);
if (rv)
RETURN(rv);
int r=range.Evaluate();
if (r!=ENABLE_COMPLEX_VAL)
{
if (rangeispercent)
{
int l=icpt.Evaluate(); //length of intercept.
if ((r&0x80000000) && !(r&0x40000000)) //bit 30 is toggled
{ //r is actually a fixed point number where 65536=1
r<<=2; //recover sign from bit 29
if (l==ENABLE_COMPLEX_VAL) //JIM 08/04/99
return IllegalSepID; //THIS CAN'T HAPPEN (I hope)!!!
else
r=MULSHSIN(l,r,18);
}
else
{ //r is a percentage. Poor accuracy for long ranges
if (l==ENABLE_COMPLEX_VAL) //JIM 08/04/99
return IllegalSepID; //THIS CAN'T HAPPEN (I hope)!!!
else
{
// INT3;
r=MULDIVSIN(l,r,100); //JIM 08/04/99
// INT3;
}
}
}
SWord s,c;
Math_Lib.high_sin_cos(a.P,s,c);
int l=MULSHSIN(r,c,ANGLES_SHIFT);
p.Y=MULSHSIN(r,s,ANGLES_SHIFT);
Math_Lib.high_sin_cos(a.H,s,c);
p.X=MULSHSIN(l,s,ANGLES_SHIFT);
p.Z=MULSHSIN(l,c,ANGLES_SHIFT);
return UID_Null;
}
else
return IllegalSepID;
}
int RotExpr::Evaluate(int)
{
int r=range.Evaluate();
if (r!=ENABLE_COMPLEX_VAL)
if (rangeispercent)
{
int l=icpt.Evaluate();
if (l==ENABLE_COMPLEX_VAL)
return l;
else
if ((r&0x80000000) && !(r&0x40000000)) //bit 30 is toggled
return MULSHSIN(r<<2,l,18);
else
return MULDIVSIN(l,r,100); //JIM 08/04/99
}
return r;
}
template <class rvtype> rvtype ReturnNonMatch(rvtype compare,rvtype a,rvtype b,rvtype c,rvtype d)
{
if (a!=compare)
return a;
if (b!=compare)
return b;
if (c!=compare)
return c;
if (d!=compare)
return d;
return compare;
}
int& RotExpr::UsesGlobRef()
{
return * ReturnNonMatch(&EventVal::minus1,&icpt.UsesGlobRef(),&range.UsesGlobRef(),&hdg.UsesGlobRef(),&pitch.UsesGlobRef());
}
Expr* RotExpr::UsesGlobRef(int GRI)
{
return ReturnNonMatch<Expr*>((Expr*)NULL,icpt.UsesGlobRef(GRI),range.UsesGlobRef(GRI),hdg.UsesGlobRef(GRI),pitch.UsesGlobRef(GRI));
}
EventVal* RotExpr::UsesUID(int UID)
{
return ReturnNonMatch<EventVal*>((EventVal*)NULL,icpt.UsesUID(UID),range.UsesUID(UID),hdg.UsesUID(UID),pitch.UsesUID(UID));
}
UniqueID IcptExpr::EvalW(Coords3D& c)
{
Coords3D a,b;
UniqueID rv;
if (objA.complex)
{
if (UID_NULL!=(rv=objA.EvalW(a)))
return (rv);
}
else
{
UIDExpr u;
u.val=objA.value;
if (UID_NULL!=(rv=u.EvalW(a)))
return rv;
}
if (objB.complex)
{
if (UID_NULL!=(rv=objB.EvalW(b)))
return (rv);
}
else
{
UIDExpr u;
u.val=objB.value;
if (UID_NULL!=(rv=u.EvalW(b)))
return rv;
}
c.X=b.X-a.X;
c.Y=b.Y-a.Y;
c.Z=b.Z-a.Z;
return UID_Null;
}
UniqueID IcptExpr::EvalA(HP& a)
{
Coords3D d;
UniqueID rv;
if (UID_NULL==(rv=EvalW(d)))
{
long range;
Math_Lib.HighIntercept(d.X,d.Y,d.Z,range,a.H,a.P);
return UID_Null;
}
else
return rv;
}
int IcptExpr::Evaluate(int)
{
Coords3D d;
if (!EvalW(d))
{
HP a;
long range;
Math_Lib.Intercept(d.X,d.Y,d.Z,range,a.H,a.P); //Using Intercept because runtime code uses intercept and result slightly different
// Math_Lib.HighIntercept(d.X,d.Y,d.Z,range,a.H,a.P);
return range;
}
else
return ENABLE_COMPLEX_VAL;
}
int& IcptExpr::UsesGlobRef()
{
return * ReturnNonMatch(&EventVal::minus1,&objA.UsesGlobRef(),&objB.UsesGlobRef(),&EventVal::minus1,&EventVal::minus1);
}
Expr* IcptExpr::UsesGlobRef(int GRI)
{
return ReturnNonMatch<Expr*>((Expr*)NULL,objA.UsesGlobRef(GRI),objB.UsesGlobRef(GRI),(Expr*)NULL,(Expr*)NULL);
}
EventVal* IcptExpr::UsesUID(int UID)
{
return ReturnNonMatch<EventVal*>((EventVal*)NULL,objA.UsesUID(UID),objB.UsesUID(UID),(EventVal*)NULL,(EventVal*)NULL);
}
int RndExpr::Evaluate(int)
{
int b=base.Evaluate(0);
if (b==ENABLE_COMPLEX_VAL)
b=0;
int s=stepsize.Evaluate(0);
if (s==ENABLE_COMPLEX_VAL)
s=1;
int m=maxsteps.Evaluate(0);
if (m==ENABLE_COMPLEX_VAL)
m=1;
return b+s*Math_Lib.rnd(m);
}
//TempCode CSB 18Jul00 int& RndExpr::UsesGlobRef()
//TempCode CSB 18Jul00 {
//TempCode CSB 18Jul00 return * ReturnNonMatch(&minus1,&base.UsesGlobRef(),&stepsize.UsesGlobRef(),maxsteps.UsesGlobRef(),&minus1);
//TempCode CSB 18Jul00 }
Expr* RndExpr::UsesGlobRef(int GRI)
{
return ReturnNonMatch<Expr*>((Expr*)NULL,base.UsesGlobRef(GRI),stepsize.UsesGlobRef(GRI),maxsteps.UsesGlobRef(GRI),(Expr*)NULL);
}
EventVal* RndExpr::UsesUID(int UID)
{
return ReturnNonMatch<EventVal*>((EventVal*)NULL,base.UsesUID(UID),stepsize.UsesUID(UID),maxsteps.UsesUID(UID),(EventVal*)NULL);
}
int SelExpr::Evaluate(int)
{
int b=base.Evaluate(0);
if (b==ENABLE_COMPLEX_VAL)
b=0;
int s=stepsize.Evaluate(0);
int m=steps.Evaluate(0);
int d=div.Evaluate(0);
if (s==ENABLE_COMPLEX_VAL)
if (m==ENABLE_COMPLEX_VAL)
s=0;
else
s=1;
else
if (m==ENABLE_COMPLEX_VAL)
m=1;
if (d==ENABLE_COMPLEX_VAL || d==0)
d=1;
return b+s*m/d;
}
int& SelExpr::UsesGlobRef()
{
return * ReturnNonMatch(&EventVal::minus1,&base.UsesGlobRef(),&stepsize.UsesGlobRef(),&steps.UsesGlobRef(),&div.UsesGlobRef());
}
Expr* SelExpr::UsesGlobRef(int GRI)
{
return ReturnNonMatch<Expr*>((Expr*)NULL,base.UsesGlobRef(GRI),stepsize.UsesGlobRef(GRI),steps.UsesGlobRef(GRI),div.UsesGlobRef(GRI));
}
EventVal* SelExpr::UsesUID(int UID)
{
return ReturnNonMatch<EventVal*>((EventVal*)NULL,base.UsesUID(UID),stepsize.UsesUID(UID),steps.UsesUID(UID),div.UsesUID(UID));
}
//list
//////////////////////////////////////////////////////////////////////
//
// Function: ListExpr
// Date: 28/07/00
// Author: CSB
//
//Description:
//
//////////////////////////////////////////////////////////////////////
int ListExpr::DeRefGlobRefs()
{
index.DeRefGlobRefs();
for (int i=0;i<maxentries;i++)
entries[i].DeRefGlobRefs();
return GOT_UNDEFINED_VAL;
}
int& ListExpr::UsesGlobRef()
{
int* rv=&index.UsesGlobRef();
if (rv!=&EventVal::minus1) return *rv;
for (int i=0;i<maxentries;i++)
{
rv=&entries[i].UsesGlobRef();
if (rv!=&EventVal::minus1) return *rv;
}
return *rv;
}
Expr* ListExpr::UsesGlobRef(int GRI)
{
Expr* rv=index.UsesGlobRef(GRI);
if (rv!=NULL) return rv;
for (int i=0;i<maxentries;i++)
{
rv=entries[i].UsesGlobRef(GRI);
if (rv!=NULL) return rv;
}
return rv;
}
EventVal* ListExpr::UsesUID(int UID)
{
EventVal* rv=index.UsesUID(UID);
if (rv!=NULL) return rv;
for (int i=0;i<maxentries;i++)
{
rv=entries[i].UsesUID(UID);
if (rv!=NULL) return rv;
}
return rv;
}
//////////////////////////////////////////////////////////////////////
//
// Function: listform
// Date: 28/07/00
// Author: CSB
//
//Description:
//
//////////////////////////////////////////////////////////////////////
int ListFormExpr::DeRefGlobRefs()
{
for (int i=0;i<maxentries;i++)
entries[i].DeRefGlobRefs();
return GOT_UNDEFINED_VAL;
}
int& ListFormExpr::UsesGlobRef()
{
int* rv=&EventVal::minus1;
for (int i=0;i<maxentries;i++)
{
rv=&entries[i].UsesGlobRef();
if (rv!=&EventVal::minus1) return *rv;
}
return *rv;
}
Expr* ListFormExpr::UsesGlobRef(int GRI)
{
Expr* rv=NULL;
for (int i=0;i<maxentries;i++)
{
rv=entries[i].UsesGlobRef(GRI);
if (rv!=NULL) return rv;
}
return rv;
}
EventVal* ListFormExpr::UsesUID(int UID)
{
EventVal* rv=NULL;
for (int i=0;i<maxentries;i++)
{
rv=entries[i].UsesUID(UID);
if (rv!=NULL) return rv;
}
return rv;
}
static Coords3D* test=NULL;
UniqueID WorldExpr::EvalW(Coords3D& c3) //return code is error
{ //UID refers to item not loaded
#ifndef __BCPLUSPLUS__
if (&c3==test)
INT3;
#endif
Coords3D a={0,0,0},b=a,c=b;c3=a;
UniqueID rv=UID_Null;
if (uniqueID.complex)
rv=uniqueID.complex->EvalW(a);
else if (uniqueID.value!=ENABLE_COMPLEX_VAL)
{
UIDExpr u;
u.val=uniqueID;
rv=u.EvalW(a);
}
if (rv)
return (rv);
if (deltaisabs && delta.complex && delta.complex->type==EXPR_XYZ)
{
XyzExpr* d=(XyzExpr*)delta.complex;
int v;
if ((v=d->X.Evaluate())!=ENABLE_COMPLEX_VAL)
if (v!=0)
a.X=v;
if ((v=d->Y.Evaluate())!=ENABLE_COMPLEX_VAL)
if (v!=0)
a.Y=v;
if ((v=d->Z.Evaluate())!=ENABLE_COMPLEX_VAL)
if (v!=0)
a.Z=v;
}
else
delta.EvalW(b);
if (rotate.complex)
rv=rotate.EvalW(c);
if (rv)
return rv;
c3.X=a.X+b.X+c.X;
c3.Y=a.Y+b.Y+c.Y;
c3.Z=a.Z+b.Z+c.Z;
return UID_Null;
}
int& WorldExpr::UsesGlobRef()
{
return * ReturnNonMatch(&EventVal::minus1,&uniqueID.UsesGlobRef(),&delta.UsesGlobRef(),&rotate.UsesGlobRef(),&EventVal::minus1);
}
Expr* WorldExpr::UsesGlobRef(int GRI)
{
return ReturnNonMatch<Expr*>((Expr*)NULL,uniqueID.UsesGlobRef(GRI),delta.UsesGlobRef(GRI),rotate.UsesGlobRef(GRI),(Expr*)NULL);
}
EventVal* WorldExpr::UsesUID(int UID)
{
return ReturnNonMatch<EventVal*>((EventVal*)NULL,uniqueID.UsesUID(UID,true),delta.UsesUID(UID),rotate.UsesUID(UID),(EventVal*)NULL);
}
//Xyz
int& XyzExpr::UsesGlobRef()
{
return * ReturnNonMatch(&EventVal::minus1,&X.UsesGlobRef(),&Y.UsesGlobRef(),&Z.UsesGlobRef(),&EventVal::minus1);
}
Expr* XyzExpr::UsesGlobRef(int GRI)
{
return ReturnNonMatch<Expr*>((Expr*)NULL,X.UsesGlobRef(GRI),Y.UsesGlobRef(GRI),Z.UsesGlobRef(GRI),(Expr*)NULL);
}
EventVal* XyzExpr::UsesUID(int UID)
{
return ReturnNonMatch<EventVal*>((EventVal*)NULL,X.UsesUID(UID),Y.UsesUID(UID),Z.UsesUID(UID),(EventVal*)NULL);
}
//////////////////////////////////////////////////////////////////////
//
// Function: RecalcDeltasToMatch
// Date: 08/04/99
// Author: JIM
//
//Description:
//
//////////////////////////////////////////////////////////////////////
bool EventVal::RecalcDeltasToMatch(COORDS3D c)
{
if (!complex || complex->type!=complex->EXPR_WORLD)
return FALSE;
WorldExpr* w=(WorldExpr*) complex;
int deltay=0;
if (w->uniqueID.complex)
{
COORDS3D base;
w->uniqueID.EvalW(base);
c.X-=base.X;
deltay=-base.Y;
c.Z-=base.Z;
}
XyzExpr* xyz=(XyzExpr*)w->delta.complex;
RotExpr* rot=(RotExpr*)w->rotate.complex;
if (rot)
{
HP baseang;
int baserange=-1;
if (rot->icpt.complex)
{
if (rot->icpt.EvalA(baseang))
INT3;
if (rot->rangeispercent)
baserange=rot->icpt.Evaluate(0);
}
if (xyz && ( (xyz->Y.Evaluate(0) && xyz->Y.Evaluate(0)!=GOT_UNDEFINED_VAL)
|| (!rot || rot->pitch.Evaluate(0)==GOT_UNDEFINED_VAL)
) )
{
if (!w->deltaisabs)
c.Y+=deltay;
xyz->Y=c.Y;
c.Y=0;
}
SLong range;
ANGLES h,p;
if (rot->pitch.Evaluate(0)==GOT_UNDEFINED_VAL)
Math_Lib.HighIntercept (c.X,0,c.Z, range,h,p);
else
Math_Lib.HighIntercept (c.X,c.Y,c.Z, range,h,p);
if (!baserange)
range=50; //if endpoints in same place then put at 50%
else
if (baserange!=-1)
if (range/baserange>=0x2000) //8200 times - if output is 800km, input is 100m
range=MULDIVSIN(range,100,baserange);
else
range=(SHDIVSIN(range,16,baserange)&0x3fffffff)|0x80000000;
//else use range as absolute
h-=baseang.H;
p-=baseang.P;
rot->range=range;
rot->hdg=h;
if (rot->pitch.Evaluate(0)!=GOT_UNDEFINED_VAL)
if (xyz && xyz->Y.Evaluate(0) && xyz->Y.Evaluate(0)!=GOT_UNDEFINED_VAL)
rot->pitch=0;
else
rot->pitch=p;
}
else
if (xyz)
{ //modify x,y,z fields to match requirement
xyz->X=c.X;
xyz->Y=c.Y+deltay;
xyz->Z=c.Z;
}
else
return FALSE;
return TRUE;
}
//////////////////////////////////////////////////////////////////////
//
// Function: MakeRndList
// Date: 09/02/00
// Author: JIM
//
//Description:
//
//////////////////////////////////////////////////////////////////////
ListExpr* EventVal::MakeRndList(int size)
{
ListExpr* L;
*this=L=new ListExpr;
if (size>(int)ListExpr::MAXENTRIES)
size=ListExpr::MAXENTRIES;
RndExpr* R;
L->index=R=new RndExpr;
R->base=0;
R->stepsize=1;
R->maxsteps=size;
L->maxentries=size;
return L;
}
//////////////////////////////////////////////////////////////////////
//
// Function: WorldExpr* EventVal::Make
// Date: 09/02/00
// Author: JIM
//
//Description:
//
//////////////////////////////////////////////////////////////////////
//
// Makes a world pos relative to another item
// Sets the delta X,Y,Z to zero
//
WorldExpr* EventVal::MakeRelWorldPos(UniqueID id1)
{
WorldExpr* W;
*this=W=new WorldExpr;
W->uniqueID=id1;
W->delta=new XyzExpr;
return W;
}
WorldExpr* EventVal::MakeGRRelWorldPos(int id1)
{
WorldExpr* W;
*this=W=new WorldExpr;
W->uniqueID=new GlobRefExpr(id1);
W->delta=new XyzExpr;
return W;
}
//
// Makes a world pos relative to another item
// Sets the X,Y,Z to zero
//
#ifdef PACKAGE_INCLUDED
void EventVal::MakeAngWorldPos(SavedGlobrefs a,int y)
{
WorldExpr* W;
*this=W=new WorldExpr;
GlobRefExpr* G;
UIDExpr* U;
G=new GlobRefExpr;
G->globrefind=a;
U=new UIDExpr;
U->val=G;
W->uniqueID=U;
XyzExpr* XYZ;
W->delta=XYZ=new XyzExpr;
RotExpr* R;
W->rotate=R=new RotExpr;
R->rangeispercent=FALSE;
R->hdg=0;
R->pitch=0;
W->deltaisabs=TRUE;
XYZ->Y=y;
}
#endif
void EventVal::MakeAbsWorldPos(int y)
{
WorldExpr* W;
*this=W=new WorldExpr;
W->delta=new XyzExpr;
this[0][0][1]=y;
}
//
// Makes a world pos as a percent intercept between two items
// The range is undefined
// The hdg and pitch are set to zero
//
void EventVal::MakeIcptIPCWorldPos(UniqueID id1,UniqueID id2)
{
WorldExpr* W;
*this=W=new WorldExpr;
W->uniqueID=id1;
RotExpr* R;
W->rotate=R=new RotExpr;
R->rangeispercent=TRUE;
R->hdg=0;
R->pitch=0;
IcptExpr* I;
R->icpt=I=new IcptExpr;
I->objA=id1;
I->objB=id2;
}
void EventVal::MakeIcptPCWorldPos()
{
WorldExpr* W;
*this=W=new WorldExpr;
W->uniqueID=new XyzExpr;
RotExpr* R;
W->rotate=R=new RotExpr;
R->rangeispercent=TRUE;
R->hdg=0;
R->pitch=0;
IcptExpr* I;
R->icpt=I=new IcptExpr;
I->objA=new XyzExpr;
I->objB=new XyzExpr;
}
#ifndef __BCPLUSPLUS__
#ifdef PACKAGE_INCLUDED
void EventVal::MakeIcptGRExpr(SavedGlobrefs a,SavedGlobrefs b,bool ispercent)
{
WorldExpr* W;
*this=W=new WorldExpr;
GlobRefExpr* G;
UIDExpr* U;
G=new GlobRefExpr;
G->globrefind=a;
U=new UIDExpr;
U->val=G;
W->uniqueID=U;
RotExpr* R;
W->delta=new XyzExpr;
W->deltaisabs=TRUE; //JIM 09/02/00
W->rotate=R=new RotExpr;
R->rangeispercent=ispercent;
R->hdg=0;
// R->pitch=0;
IcptExpr* I;
R->icpt=I=new IcptExpr;
G=new GlobRefExpr;
G->globrefind=a;
U=new UIDExpr;
U->val=G;
I->objA=U;
G=new GlobRefExpr;
G->globrefind=b;
U=new UIDExpr;
U->val=G;
I->objB=U;
}
#endif
#endif
| [
"[email protected]"
] | |
86b6b0e9d3b9015b4fdce0b0149023b69f640881 | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_5/Z6.1+poreleaserelease+poonceonce+poonceonce.c.cbmc_out.cpp | 80f4639a2f470179065bced5e7a956335dcf6d1f | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 36,478 | cpp | // Global variabls:
// 0:vars:3
// 3:atom_2_X0_1:1
// Local global variabls:
// 0:thr0:1
// 1:thr1:1
// 2:thr2:1
#define ADDRSIZE 4
#define LOCALADDRSIZE 3
#define NTHREAD 4
#define NCONTEXT 5
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// Declare arrays for intial value version in contexts
int local_mem[LOCALADDRSIZE];
// Dumping initializations
local_mem[0+0] = 0;
local_mem[1+0] = 0;
local_mem[2+0] = 0;
int cstart[NTHREAD];
int creturn[NTHREAD];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NTHREAD*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NTHREAD*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NTHREAD*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NTHREAD*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NTHREAD*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NTHREAD*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NTHREAD*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NTHREAD*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NTHREAD*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NTHREAD];
int cdy[NTHREAD];
int cds[NTHREAD];
int cdl[NTHREAD];
int cisb[NTHREAD];
int caddr[NTHREAD];
int cctrl[NTHREAD];
int r0= 0;
char creg_r0;
char creg__r0__1_;
int r1= 0;
char creg_r1;
int r2= 0;
char creg_r2;
int r3= 0;
char creg_r3;
int r4= 0;
char creg_r4;
int r5= 0;
char creg_r5;
char creg__r5__2_;
int r6= 0;
char creg_r6;
char creg__r6__2_;
int r7= 0;
char creg_r7;
int r8= 0;
char creg_r8;
int r9= 0;
char creg_r9;
char creg__r9__1_;
int r10= 0;
char creg_r10;
char old_cctrl= 0;
char old_cr= 0;
char old_cdy= 0;
char old_cw= 0;
char new_creg= 0;
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
buff(3,0) = 0;
pw(3,0) = 0;
cr(3,0) = 0;
iw(3,0) = 0;
cw(3,0) = 0;
cx(3,0) = 0;
is(3,0) = 0;
cs(3,0) = 0;
crmax(3,0) = 0;
buff(3,1) = 0;
pw(3,1) = 0;
cr(3,1) = 0;
iw(3,1) = 0;
cw(3,1) = 0;
cx(3,1) = 0;
is(3,1) = 0;
cs(3,1) = 0;
crmax(3,1) = 0;
buff(3,2) = 0;
pw(3,2) = 0;
cr(3,2) = 0;
iw(3,2) = 0;
cw(3,2) = 0;
cx(3,2) = 0;
is(3,2) = 0;
cs(3,2) = 0;
crmax(3,2) = 0;
buff(3,3) = 0;
pw(3,3) = 0;
cr(3,3) = 0;
iw(3,3) = 0;
cw(3,3) = 0;
cx(3,3) = 0;
is(3,3) = 0;
cs(3,3) = 0;
crmax(3,3) = 0;
cl[3] = 0;
cdy[3] = 0;
cds[3] = 0;
cdl[3] = 0;
cisb[3] = 0;
caddr[3] = 0;
cctrl[3] = 0;
cstart[3] = get_rng(0,NCONTEXT-1);
creturn[3] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(0+2,0) = 0;
mem(3+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
mem(0,1) = meminit(0,1);
co(0,1) = coinit(0,1);
delta(0,1) = deltainit(0,1);
mem(0,2) = meminit(0,2);
co(0,2) = coinit(0,2);
delta(0,2) = deltainit(0,2);
mem(0,3) = meminit(0,3);
co(0,3) = coinit(0,3);
delta(0,3) = deltainit(0,3);
mem(0,4) = meminit(0,4);
co(0,4) = coinit(0,4);
delta(0,4) = deltainit(0,4);
co(1,0) = 0;
delta(1,0) = -1;
mem(1,1) = meminit(1,1);
co(1,1) = coinit(1,1);
delta(1,1) = deltainit(1,1);
mem(1,2) = meminit(1,2);
co(1,2) = coinit(1,2);
delta(1,2) = deltainit(1,2);
mem(1,3) = meminit(1,3);
co(1,3) = coinit(1,3);
delta(1,3) = deltainit(1,3);
mem(1,4) = meminit(1,4);
co(1,4) = coinit(1,4);
delta(1,4) = deltainit(1,4);
co(2,0) = 0;
delta(2,0) = -1;
mem(2,1) = meminit(2,1);
co(2,1) = coinit(2,1);
delta(2,1) = deltainit(2,1);
mem(2,2) = meminit(2,2);
co(2,2) = coinit(2,2);
delta(2,2) = deltainit(2,2);
mem(2,3) = meminit(2,3);
co(2,3) = coinit(2,3);
delta(2,3) = deltainit(2,3);
mem(2,4) = meminit(2,4);
co(2,4) = coinit(2,4);
delta(2,4) = deltainit(2,4);
co(3,0) = 0;
delta(3,0) = -1;
mem(3,1) = meminit(3,1);
co(3,1) = coinit(3,1);
delta(3,1) = deltainit(3,1);
mem(3,2) = meminit(3,2);
co(3,2) = coinit(3,2);
delta(3,2) = deltainit(3,2);
mem(3,3) = meminit(3,3);
co(3,3) = coinit(3,3);
delta(3,3) = deltainit(3,3);
mem(3,4) = meminit(3,4);
co(3,4) = coinit(3,4);
delta(3,4) = deltainit(3,4);
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !34, metadata !DIExpression()), !dbg !43
// br label %label_1, !dbg !44
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !42), !dbg !45
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !35, metadata !DIExpression()), !dbg !46
// call void @llvm.dbg.value(metadata i64 2, metadata !38, metadata !DIExpression()), !dbg !46
// store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) release, align 8, !dbg !47
// ST: Guess
// : Release
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l19_c3
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l19_c3
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
ASSUME(cw(1,0+1*1) >= cr(1,0+0));
ASSUME(cw(1,0+1*1) >= cr(1,0+1));
ASSUME(cw(1,0+1*1) >= cr(1,0+2));
ASSUME(cw(1,0+1*1) >= cr(1,3+0));
ASSUME(cw(1,0+1*1) >= cw(1,0+0));
ASSUME(cw(1,0+1*1) >= cw(1,0+1));
ASSUME(cw(1,0+1*1) >= cw(1,0+2));
ASSUME(cw(1,0+1*1) >= cw(1,3+0));
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = 2;
mem(0+1*1,cw(1,0+1*1)) = 2;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
is(1,0+1*1) = iw(1,0+1*1);
cs(1,0+1*1) = cw(1,0+1*1);
ASSUME(creturn[1] >= cw(1,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !39, metadata !DIExpression()), !dbg !48
// call void @llvm.dbg.value(metadata i64 1, metadata !41, metadata !DIExpression()), !dbg !48
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) release, align 8, !dbg !49
// ST: Guess
// : Release
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l20_c3
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l20_c3
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
ASSUME(cw(1,0) >= cr(1,0+0));
ASSUME(cw(1,0) >= cr(1,0+1));
ASSUME(cw(1,0) >= cr(1,0+2));
ASSUME(cw(1,0) >= cr(1,3+0));
ASSUME(cw(1,0) >= cw(1,0+0));
ASSUME(cw(1,0) >= cw(1,0+1));
ASSUME(cw(1,0) >= cw(1,0+2));
ASSUME(cw(1,0) >= cw(1,3+0));
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 1;
mem(0,cw(1,0)) = 1;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
is(1,0) = iw(1,0);
cs(1,0) = cw(1,0);
ASSUME(creturn[1] >= cw(1,0));
// ret i8* null, !dbg !50
ret_thread_1 = (- 1);
goto T1BLOCK_END;
T1BLOCK_END:
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !53, metadata !DIExpression()), !dbg !61
// br label %label_2, !dbg !44
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !60), !dbg !63
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !54, metadata !DIExpression()), !dbg !64
// call void @llvm.dbg.value(metadata i64 2, metadata !56, metadata !DIExpression()), !dbg !64
// store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !47
// ST: Guess
iw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l26_c3
old_cw = cw(2,0);
cw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l26_c3
// Check
ASSUME(active[iw(2,0)] == 2);
ASSUME(active[cw(2,0)] == 2);
ASSUME(sforbid(0,cw(2,0))== 0);
ASSUME(iw(2,0) >= 0);
ASSUME(iw(2,0) >= 0);
ASSUME(cw(2,0) >= iw(2,0));
ASSUME(cw(2,0) >= old_cw);
ASSUME(cw(2,0) >= cr(2,0));
ASSUME(cw(2,0) >= cl[2]);
ASSUME(cw(2,0) >= cisb[2]);
ASSUME(cw(2,0) >= cdy[2]);
ASSUME(cw(2,0) >= cdl[2]);
ASSUME(cw(2,0) >= cds[2]);
ASSUME(cw(2,0) >= cctrl[2]);
ASSUME(cw(2,0) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0) = 2;
mem(0,cw(2,0)) = 2;
co(0,cw(2,0))+=1;
delta(0,cw(2,0)) = -1;
ASSUME(creturn[2] >= cw(2,0));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !57, metadata !DIExpression()), !dbg !66
// call void @llvm.dbg.value(metadata i64 1, metadata !59, metadata !DIExpression()), !dbg !66
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !49
// ST: Guess
iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l27_c3
old_cw = cw(2,0+2*1);
cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l27_c3
// Check
ASSUME(active[iw(2,0+2*1)] == 2);
ASSUME(active[cw(2,0+2*1)] == 2);
ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(iw(2,0+2*1) >= 0);
ASSUME(cw(2,0+2*1) >= iw(2,0+2*1));
ASSUME(cw(2,0+2*1) >= old_cw);
ASSUME(cw(2,0+2*1) >= cr(2,0+2*1));
ASSUME(cw(2,0+2*1) >= cl[2]);
ASSUME(cw(2,0+2*1) >= cisb[2]);
ASSUME(cw(2,0+2*1) >= cdy[2]);
ASSUME(cw(2,0+2*1) >= cdl[2]);
ASSUME(cw(2,0+2*1) >= cds[2]);
ASSUME(cw(2,0+2*1) >= cctrl[2]);
ASSUME(cw(2,0+2*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+2*1) = 1;
mem(0+2*1,cw(2,0+2*1)) = 1;
co(0+2*1,cw(2,0+2*1))+=1;
delta(0+2*1,cw(2,0+2*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+2*1));
// ret i8* null, !dbg !50
ret_thread_2 = (- 1);
goto T2BLOCK_END;
T2BLOCK_END:
// Dumping thread 3
int ret_thread_3 = 0;
cdy[3] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[3] >= cstart[3]);
T3BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !71, metadata !DIExpression()), !dbg !81
// br label %label_3, !dbg !46
goto T3BLOCK1;
T3BLOCK1:
// call void @llvm.dbg.label(metadata !80), !dbg !83
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !73, metadata !DIExpression()), !dbg !84
// %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !49
// LD: Guess
old_cr = cr(3,0+2*1);
cr(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM _l33_c15
// Check
ASSUME(active[cr(3,0+2*1)] == 3);
ASSUME(cr(3,0+2*1) >= iw(3,0+2*1));
ASSUME(cr(3,0+2*1) >= 0);
ASSUME(cr(3,0+2*1) >= cdy[3]);
ASSUME(cr(3,0+2*1) >= cisb[3]);
ASSUME(cr(3,0+2*1) >= cdl[3]);
ASSUME(cr(3,0+2*1) >= cl[3]);
// Update
creg_r0 = cr(3,0+2*1);
crmax(3,0+2*1) = max(crmax(3,0+2*1),cr(3,0+2*1));
caddr[3] = max(caddr[3],0);
if(cr(3,0+2*1) < cw(3,0+2*1)) {
r0 = buff(3,0+2*1);
ASSUME((!(( (cw(3,0+2*1) < 1) && (1 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,1)> 0));
ASSUME((!(( (cw(3,0+2*1) < 2) && (2 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,2)> 0));
ASSUME((!(( (cw(3,0+2*1) < 3) && (3 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,3)> 0));
ASSUME((!(( (cw(3,0+2*1) < 4) && (4 < crmax(3,0+2*1)) )))||(sforbid(0+2*1,4)> 0));
} else {
if(pw(3,0+2*1) != co(0+2*1,cr(3,0+2*1))) {
ASSUME(cr(3,0+2*1) >= old_cr);
}
pw(3,0+2*1) = co(0+2*1,cr(3,0+2*1));
r0 = mem(0+2*1,cr(3,0+2*1));
}
ASSUME(creturn[3] >= cr(3,0+2*1));
// call void @llvm.dbg.value(metadata i64 %0, metadata !75, metadata !DIExpression()), !dbg !84
// %conv = trunc i64 %0 to i32, !dbg !50
// call void @llvm.dbg.value(metadata i32 %conv, metadata !72, metadata !DIExpression()), !dbg !81
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !76, metadata !DIExpression()), !dbg !87
// call void @llvm.dbg.value(metadata i64 1, metadata !78, metadata !DIExpression()), !dbg !87
// store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !52
// ST: Guess
iw(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l34_c3
old_cw = cw(3,0+1*1);
cw(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l34_c3
// Check
ASSUME(active[iw(3,0+1*1)] == 3);
ASSUME(active[cw(3,0+1*1)] == 3);
ASSUME(sforbid(0+1*1,cw(3,0+1*1))== 0);
ASSUME(iw(3,0+1*1) >= 0);
ASSUME(iw(3,0+1*1) >= 0);
ASSUME(cw(3,0+1*1) >= iw(3,0+1*1));
ASSUME(cw(3,0+1*1) >= old_cw);
ASSUME(cw(3,0+1*1) >= cr(3,0+1*1));
ASSUME(cw(3,0+1*1) >= cl[3]);
ASSUME(cw(3,0+1*1) >= cisb[3]);
ASSUME(cw(3,0+1*1) >= cdy[3]);
ASSUME(cw(3,0+1*1) >= cdl[3]);
ASSUME(cw(3,0+1*1) >= cds[3]);
ASSUME(cw(3,0+1*1) >= cctrl[3]);
ASSUME(cw(3,0+1*1) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,0+1*1) = 1;
mem(0+1*1,cw(3,0+1*1)) = 1;
co(0+1*1,cw(3,0+1*1))+=1;
delta(0+1*1,cw(3,0+1*1)) = -1;
ASSUME(creturn[3] >= cw(3,0+1*1));
// %cmp = icmp eq i32 %conv, 1, !dbg !53
creg__r0__1_ = max(0,creg_r0);
// %conv1 = zext i1 %cmp to i32, !dbg !53
// call void @llvm.dbg.value(metadata i32 %conv1, metadata !79, metadata !DIExpression()), !dbg !81
// store i32 %conv1, i32* @atom_2_X0_1, align 4, !dbg !54, !tbaa !55
// ST: Guess
iw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l36_c15
old_cw = cw(3,3);
cw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l36_c15
// Check
ASSUME(active[iw(3,3)] == 3);
ASSUME(active[cw(3,3)] == 3);
ASSUME(sforbid(3,cw(3,3))== 0);
ASSUME(iw(3,3) >= creg__r0__1_);
ASSUME(iw(3,3) >= 0);
ASSUME(cw(3,3) >= iw(3,3));
ASSUME(cw(3,3) >= old_cw);
ASSUME(cw(3,3) >= cr(3,3));
ASSUME(cw(3,3) >= cl[3]);
ASSUME(cw(3,3) >= cisb[3]);
ASSUME(cw(3,3) >= cdy[3]);
ASSUME(cw(3,3) >= cdl[3]);
ASSUME(cw(3,3) >= cds[3]);
ASSUME(cw(3,3) >= cctrl[3]);
ASSUME(cw(3,3) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,3) = (r0==1);
mem(3,cw(3,3)) = (r0==1);
co(3,cw(3,3))+=1;
delta(3,cw(3,3)) = -1;
ASSUME(creturn[3] >= cw(3,3));
// ret i8* null, !dbg !59
ret_thread_3 = (- 1);
goto T3BLOCK_END;
T3BLOCK_END:
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// %thr2 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !103, metadata !DIExpression()), !dbg !133
// call void @llvm.dbg.value(metadata i8** %argv, metadata !104, metadata !DIExpression()), !dbg !133
// %0 = bitcast i64* %thr0 to i8*, !dbg !69
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !69
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !105, metadata !DIExpression()), !dbg !135
// %1 = bitcast i64* %thr1 to i8*, !dbg !71
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !71
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !109, metadata !DIExpression()), !dbg !137
// %2 = bitcast i64* %thr2 to i8*, !dbg !73
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !73
// call void @llvm.dbg.declare(metadata i64* %thr2, metadata !110, metadata !DIExpression()), !dbg !139
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !111, metadata !DIExpression()), !dbg !140
// call void @llvm.dbg.value(metadata i64 0, metadata !113, metadata !DIExpression()), !dbg !140
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !76
// ST: Guess
iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l45_c3
old_cw = cw(0,0+2*1);
cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l45_c3
// Check
ASSUME(active[iw(0,0+2*1)] == 0);
ASSUME(active[cw(0,0+2*1)] == 0);
ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(iw(0,0+2*1) >= 0);
ASSUME(cw(0,0+2*1) >= iw(0,0+2*1));
ASSUME(cw(0,0+2*1) >= old_cw);
ASSUME(cw(0,0+2*1) >= cr(0,0+2*1));
ASSUME(cw(0,0+2*1) >= cl[0]);
ASSUME(cw(0,0+2*1) >= cisb[0]);
ASSUME(cw(0,0+2*1) >= cdy[0]);
ASSUME(cw(0,0+2*1) >= cdl[0]);
ASSUME(cw(0,0+2*1) >= cds[0]);
ASSUME(cw(0,0+2*1) >= cctrl[0]);
ASSUME(cw(0,0+2*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+2*1) = 0;
mem(0+2*1,cw(0,0+2*1)) = 0;
co(0+2*1,cw(0,0+2*1))+=1;
delta(0+2*1,cw(0,0+2*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+2*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !114, metadata !DIExpression()), !dbg !142
// call void @llvm.dbg.value(metadata i64 0, metadata !116, metadata !DIExpression()), !dbg !142
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !78
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l46_c3
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l46_c3
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !117, metadata !DIExpression()), !dbg !144
// call void @llvm.dbg.value(metadata i64 0, metadata !119, metadata !DIExpression()), !dbg !144
// store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !80
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l47_c3
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l47_c3
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// store i32 0, i32* @atom_2_X0_1, align 4, !dbg !81, !tbaa !82
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l48_c15
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l48_c15
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !86
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call5 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !87
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %call6 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !88
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[3] >= cdy[0]);
// %3 = load i64, i64* %thr0, align 8, !dbg !89, !tbaa !90
r2 = local_mem[0];
// %call7 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !92
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %4 = load i64, i64* %thr1, align 8, !dbg !93, !tbaa !90
r3 = local_mem[1];
// %call8 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !94
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// %5 = load i64, i64* %thr2, align 8, !dbg !95, !tbaa !90
r4 = local_mem[2];
// %call9 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !96
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,0+2));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,0+2));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[3]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !121, metadata !DIExpression()), !dbg !158
// %6 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !98
// LD: Guess
old_cr = cr(0,0+1*1);
cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l58_c12
// Check
ASSUME(active[cr(0,0+1*1)] == 0);
ASSUME(cr(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cr(0,0+1*1) >= 0);
ASSUME(cr(0,0+1*1) >= cdy[0]);
ASSUME(cr(0,0+1*1) >= cisb[0]);
ASSUME(cr(0,0+1*1) >= cdl[0]);
ASSUME(cr(0,0+1*1) >= cl[0]);
// Update
creg_r5 = cr(0,0+1*1);
crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1));
caddr[0] = max(caddr[0],0);
if(cr(0,0+1*1) < cw(0,0+1*1)) {
r5 = buff(0,0+1*1);
ASSUME((!(( (cw(0,0+1*1) < 1) && (1 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,1)> 0));
ASSUME((!(( (cw(0,0+1*1) < 2) && (2 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,2)> 0));
ASSUME((!(( (cw(0,0+1*1) < 3) && (3 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,3)> 0));
ASSUME((!(( (cw(0,0+1*1) < 4) && (4 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,4)> 0));
} else {
if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) {
ASSUME(cr(0,0+1*1) >= old_cr);
}
pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1));
r5 = mem(0+1*1,cr(0,0+1*1));
}
ASSUME(creturn[0] >= cr(0,0+1*1));
// call void @llvm.dbg.value(metadata i64 %6, metadata !123, metadata !DIExpression()), !dbg !158
// %conv = trunc i64 %6 to i32, !dbg !99
// call void @llvm.dbg.value(metadata i32 %conv, metadata !120, metadata !DIExpression()), !dbg !133
// %cmp = icmp eq i32 %conv, 2, !dbg !100
creg__r5__2_ = max(0,creg_r5);
// %conv10 = zext i1 %cmp to i32, !dbg !100
// call void @llvm.dbg.value(metadata i32 %conv10, metadata !124, metadata !DIExpression()), !dbg !133
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !126, metadata !DIExpression()), !dbg !162
// %7 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !102
// LD: Guess
old_cr = cr(0,0);
cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l60_c12
// Check
ASSUME(active[cr(0,0)] == 0);
ASSUME(cr(0,0) >= iw(0,0));
ASSUME(cr(0,0) >= 0);
ASSUME(cr(0,0) >= cdy[0]);
ASSUME(cr(0,0) >= cisb[0]);
ASSUME(cr(0,0) >= cdl[0]);
ASSUME(cr(0,0) >= cl[0]);
// Update
creg_r6 = cr(0,0);
crmax(0,0) = max(crmax(0,0),cr(0,0));
caddr[0] = max(caddr[0],0);
if(cr(0,0) < cw(0,0)) {
r6 = buff(0,0);
ASSUME((!(( (cw(0,0) < 1) && (1 < crmax(0,0)) )))||(sforbid(0,1)> 0));
ASSUME((!(( (cw(0,0) < 2) && (2 < crmax(0,0)) )))||(sforbid(0,2)> 0));
ASSUME((!(( (cw(0,0) < 3) && (3 < crmax(0,0)) )))||(sforbid(0,3)> 0));
ASSUME((!(( (cw(0,0) < 4) && (4 < crmax(0,0)) )))||(sforbid(0,4)> 0));
} else {
if(pw(0,0) != co(0,cr(0,0))) {
ASSUME(cr(0,0) >= old_cr);
}
pw(0,0) = co(0,cr(0,0));
r6 = mem(0,cr(0,0));
}
ASSUME(creturn[0] >= cr(0,0));
// call void @llvm.dbg.value(metadata i64 %7, metadata !128, metadata !DIExpression()), !dbg !162
// %conv14 = trunc i64 %7 to i32, !dbg !103
// call void @llvm.dbg.value(metadata i32 %conv14, metadata !125, metadata !DIExpression()), !dbg !133
// %cmp15 = icmp eq i32 %conv14, 2, !dbg !104
creg__r6__2_ = max(0,creg_r6);
// %conv16 = zext i1 %cmp15 to i32, !dbg !104
// call void @llvm.dbg.value(metadata i32 %conv16, metadata !129, metadata !DIExpression()), !dbg !133
// %8 = load i32, i32* @atom_2_X0_1, align 4, !dbg !105, !tbaa !82
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l62_c12
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r7 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r7 = buff(0,3);
ASSUME((!(( (cw(0,3) < 1) && (1 < crmax(0,3)) )))||(sforbid(3,1)> 0));
ASSUME((!(( (cw(0,3) < 2) && (2 < crmax(0,3)) )))||(sforbid(3,2)> 0));
ASSUME((!(( (cw(0,3) < 3) && (3 < crmax(0,3)) )))||(sforbid(3,3)> 0));
ASSUME((!(( (cw(0,3) < 4) && (4 < crmax(0,3)) )))||(sforbid(3,4)> 0));
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r7 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i32 %8, metadata !130, metadata !DIExpression()), !dbg !133
// %and = and i32 %conv16, %8, !dbg !106
creg_r8 = max(creg__r6__2_,creg_r7);
r8 = (r6==2) & r7;
// call void @llvm.dbg.value(metadata i32 %and, metadata !131, metadata !DIExpression()), !dbg !133
// %and17 = and i32 %conv10, %and, !dbg !107
creg_r9 = max(creg__r5__2_,creg_r8);
r9 = (r5==2) & r8;
// call void @llvm.dbg.value(metadata i32 %and17, metadata !132, metadata !DIExpression()), !dbg !133
// %cmp18 = icmp eq i32 %and17, 1, !dbg !108
creg__r9__1_ = max(0,creg_r9);
// br i1 %cmp18, label %if.then, label %if.end, !dbg !110
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg__r9__1_);
if((r9==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([128 x i8], [128 x i8]* @.str.1, i64 0, i64 0), i32 noundef 65, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !111
// unreachable, !dbg !111
r10 = 1;
goto T0BLOCK_END;
T0BLOCK2:
// %9 = bitcast i64* %thr2 to i8*, !dbg !114
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !114
// %10 = bitcast i64* %thr1 to i8*, !dbg !114
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !114
// %11 = bitcast i64* %thr0 to i8*, !dbg !114
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !114
// ret i32 0, !dbg !115
ret_thread_0 = 0;
goto T0BLOCK_END;
T0BLOCK_END:
ASSUME(meminit(0,1) == mem(0,0));
ASSUME(coinit(0,1) == co(0,0));
ASSUME(deltainit(0,1) == delta(0,0));
ASSUME(meminit(0,2) == mem(0,1));
ASSUME(coinit(0,2) == co(0,1));
ASSUME(deltainit(0,2) == delta(0,1));
ASSUME(meminit(0,3) == mem(0,2));
ASSUME(coinit(0,3) == co(0,2));
ASSUME(deltainit(0,3) == delta(0,2));
ASSUME(meminit(0,4) == mem(0,3));
ASSUME(coinit(0,4) == co(0,3));
ASSUME(deltainit(0,4) == delta(0,3));
ASSUME(meminit(1,1) == mem(1,0));
ASSUME(coinit(1,1) == co(1,0));
ASSUME(deltainit(1,1) == delta(1,0));
ASSUME(meminit(1,2) == mem(1,1));
ASSUME(coinit(1,2) == co(1,1));
ASSUME(deltainit(1,2) == delta(1,1));
ASSUME(meminit(1,3) == mem(1,2));
ASSUME(coinit(1,3) == co(1,2));
ASSUME(deltainit(1,3) == delta(1,2));
ASSUME(meminit(1,4) == mem(1,3));
ASSUME(coinit(1,4) == co(1,3));
ASSUME(deltainit(1,4) == delta(1,3));
ASSUME(meminit(2,1) == mem(2,0));
ASSUME(coinit(2,1) == co(2,0));
ASSUME(deltainit(2,1) == delta(2,0));
ASSUME(meminit(2,2) == mem(2,1));
ASSUME(coinit(2,2) == co(2,1));
ASSUME(deltainit(2,2) == delta(2,1));
ASSUME(meminit(2,3) == mem(2,2));
ASSUME(coinit(2,3) == co(2,2));
ASSUME(deltainit(2,3) == delta(2,2));
ASSUME(meminit(2,4) == mem(2,3));
ASSUME(coinit(2,4) == co(2,3));
ASSUME(deltainit(2,4) == delta(2,3));
ASSUME(meminit(3,1) == mem(3,0));
ASSUME(coinit(3,1) == co(3,0));
ASSUME(deltainit(3,1) == delta(3,0));
ASSUME(meminit(3,2) == mem(3,1));
ASSUME(coinit(3,2) == co(3,1));
ASSUME(deltainit(3,2) == delta(3,1));
ASSUME(meminit(3,3) == mem(3,2));
ASSUME(coinit(3,3) == co(3,2));
ASSUME(deltainit(3,3) == delta(3,2));
ASSUME(meminit(3,4) == mem(3,3));
ASSUME(coinit(3,4) == co(3,3));
ASSUME(deltainit(3,4) == delta(3,3));
ASSERT(r10== 0);
}
| [
"[email protected]"
] | |
30e7d01e8316179cb23ab590f146ba6586b92ecb | 19d487f5bcd6cafe43ed6543495ad478735829f0 | /GameProjectCodeWeek/GameProjectCodeWeek/Update.cpp | 9b39fc820af079dee4073260253befdf8ea16655 | [] | no_license | K00201237/2020-SFML | 18f75e76d9f3640d96c0a7c3d71bb456c1ea6632 | c5f67ac3dbf6505b81ef335b805ffdaaf5316ebc | refs/heads/main | 2023-08-17T03:32:44.595414 | 2021-01-18T03:10:42 | 2021-01-18T03:10:42 | 302,042,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,008 | cpp | #include "stdafx.h"
#include "Engine.h"
#include <SFML/Graphics.hpp>
#include <sstream>
using namespace sf;
void Engine::update(float dtAsSeconds)
{
if (m_NewLevelRequired)
{
// These calls to spawn will be moved to a new
// LoadLevel function soon
// Spawn Thomas and Bob
p_playerChar.spawn(Vector2f(0, 0), GRAVITY);
// Make sure spawn is called only once
m_TimeRemaining = 10;
m_NewLevelRequired = false;
}
if (m_Playing)
{
m_MainView.setCenter(p_playerChar.getCenter());
// Update player
p_playerChar.update(dtAsSeconds);
// Count down the time the player has left
m_TimeRemaining -= dtAsSeconds;
// Have Thomas and Bob run out of time?
if (m_TimeRemaining <= 0)
{
m_NewLevelRequired = true;
}
}// End if playing
if (m_SplitScreen)
{
m_LeftView.setCenter(p_playerChar.getCenter());
}
else
{
// Centre full screen around appropriate character
if (m_Character1)
{
m_MainView.setCenter(p_playerChar.getCenter());
}
else
{
}
}
} | [
"[email protected]"
] | |
f50bcf35354863d19439c6f4897fff912ce71241 | 6a8404a9d79b4dee7b25fe13d583958bd37c68bd | /OSD_Ycc422.h | 3eab2278c6c18c1847a7eb7718785c9ce88d5fa0 | [] | no_license | AustinHsienROC/test02 | ee7924b541e76d2f66e04ae524f413be03fb81f1 | 2900b47d502e8e781e9ebd84c206fbabcd34ac90 | refs/heads/master | 2021-01-01T05:15:20.174776 | 2016-05-17T04:01:52 | 2016-05-17T04:01:52 | 58,986,505 | 0 | 0 | null | 2016-05-17T03:34:20 | 2016-05-17T03:12:02 | C++ | UTF-8 | C++ | false | false | 2,857 | h | /*
===================================================================
Name : OSD_Ycc422.h
Author : Austin
Version : v0.0010
Copyright : Copyright (C) 2014 By oToBrite Electronics Corp.
Description : This function implement OSD_Plot main process.
==================================================================
History
--------------+-------------+-----------------------------------------+------------
DATE |VERSION |DESCRIPTION | Author
--------------+-------------+-----------------------------------------+------------
2015/03/16 | v0.0010 |First setup functions | Austin
--------------+-------------+-----------------------------------------+------------
*/
#ifndef _OSD_Ycc422_H
#define _OSD_Ycc422_H
#ifdef WIN32 // PC
#include "CTA_Type.h"
#include "CTA_Def.h"
class OSD_Ycc422
{
public:
//---------------------Pencil_Draw---------------------
static void Rgb2Ycc(UCHAR R, UCHAR G, UCHAR B, UCHAR *Y, UCHAR *Cb, UCHAR *Cr);
static void OSD_SetColor(UCHAR R, UCHAR G, UCHAR B);
static void OSD_Draw_Pixel(UCHAR *o_ycc422, UINT32 dst_width, UINT32 dst_height, INT32 x, UINT32 y , FLOAT alpha = 1.0);
static void OSD_Draw_Line (UCHAR *o_ycc422, UINT32 dst_width, UINT32 dst_height, INT32 start_x, INT32 start_y, INT32 end_x, INT32 end_y, UINT32 thickness, FLOAT alpha = 1.0);
static void OSD_Draw_Rec (UCHAR *o_ycc422, UINT32 dst_width, UINT32 dst_height, INT32 start_x, INT32 start_y, INT32 end_x, INT32 end_y, UINT32 thickness, BOOL isFilled, FLOAT alpha = 1.0);
static void OSD_Draw_Digit(UCHAR *o_ycc422, UINT32 dst_width, UINT32 dst_height, INT32 start_x, INT32 start_y, UCHAR digitNum, UINT32 thickness ,UINT32 size);
static void OSD_Draw_INT32(INT32 value , UCHAR *o_ycc422, UINT32 dst_width, UINT32 dst_height, INT32 start_x, INT32 start_y, UINT32 thickness ,UINT32 size);
static void OSD_Draw_Text (CONST char *str , UCHAR *o_ycc422, UINT32 dst_width, UINT32 dst_height, INT32 start_x, INT32 start_y,UINT32 size);
static void OSD_Draw_Circle(UCHAR *o_ycc422, UINT32 dst_width, UINT32 dst_height, INT32 center_x, INT32 center_y, INT32 radius, UINT32 thickness, BOOL DrawPartial[4]);
//---------------------ImgPaste---------------------
static void ImgPaste_Y(UCHAR *o_ycc422, UCHAR *Y , UINT32 inWIDTH, UINT32 inHEIGHT);
static void ImgPaste_rgb444(UCHAR *o_ycc422, UCHAR *r, UCHAR *g, UCHAR *b , UINT32 inWIDTH, UINT32 inHEIGHT);
//---------------------ImgExtract/Transform---------------------
static void Extract_Y(UCHAR *o_Y, UCHAR *i_ycc422, INT32 img_width, INT32 img_height);
static void Extract_CC(UCHAR *o_Cb, UCHAR *o_Cr, UCHAR *i_ycc422, INT32 img_width, INT32 img_height);
static void Format_rgb444(UCHAR *o_R, UCHAR *o_G, UCHAR *o_B, UCHAR *i_ycc422, INT32 img_width, INT32 img_height);
};
#endif
#endif | [
"[email protected]"
] | |
4db1802d79b4dc7e96892e93a8ba64b4d116747b | ded20fbc375becdd1cc89017573aafb8f3d031da | /Zajecia_2/Zajecia2_4/main.cpp | 4b81973db55b94baf57bb45a2b370a74964f176a | [] | no_license | KKarola/PJC | 5e3b61cf0dc2804b014b140e113f3af932c9a998 | 11a26dda768e137e65defcf2227a9f1328b6471f | refs/heads/master | 2021-05-05T05:09:25.906927 | 2018-01-23T20:40:21 | 2018-01-23T20:40:21 | 118,665,974 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,273 | cpp | #include <iostream>
size_t monot(const int a[], size_t size, size_t& len) {
size_t koniec, poczatek;
size_t rosnacy = 1, dlugoscRosnacy = 1, koniecRosnacy;
size_t malejacy = 1, dlugoscMalejacy = 1, koniecMalejacy;
for(size_t i = 1; i < size; i++)
{
//nie malejacy
if(a[i-1] <= a[i])
{
rosnacy++;
if(a[i-1] < a[i])
malejacy = 1;
if(dlugoscRosnacy < rosnacy)
{
dlugoscRosnacy = rosnacy;
koniecRosnacy = i;
}
}
//nie rosnacy
if(a[i-1] >= a[i])
{
malejacy++;
if(a[i-1] > a[i])
rosnacy = 1;
if(dlugoscMalejacy < malejacy)
{
dlugoscMalejacy = malejacy;
koniecMalejacy = i;
}
}
}
if(dlugoscRosnacy > dlugoscMalejacy)
{
len = dlugoscRosnacy;
koniec = koniecRosnacy;
} else if(dlugoscRosnacy < dlugoscMalejacy)
{
len = dlugoscMalejacy;
koniec = koniecMalejacy;
} else
if(koniecRosnacy < koniecMalejacy)
{
len = dlugoscRosnacy;
koniec = koniecRosnacy;
} else {
len = dlugoscMalejacy;
koniec = koniecMalejacy;
}
poczatek = koniec + 1 - len;
return poczatek;
}
void printResult(const int a[], size_t size,
size_t ind, size_t len) {
using std::cout;
cout << "In array [ ";
for (size_t i = 0; i < size; ++i) cout << a[i] << " ";
cout << "]\nthe first longest "
"monotonic sequence is\n[ ";
for (size_t i = ind; i < ind+len; ++i)
cout << a[i] << " ";
cout << "] starting at index " << ind
<< " and of length " << len << "\n\n";
}
int main() {
size_t len = 0, ind = 0, size = 0;
int a1[] = {4,4,5,4,4};
size = sizeof(a1)/sizeof(*a1);
ind = monot(a1,size,len);
printResult(a1,size,ind,len);
int a2[] = {4,4,5,4,4,4};
size = sizeof(a2)/sizeof(*a2);
ind = monot(a2,size,len);
printResult(a2,size,ind,len);
int a3[] = {4,5,4,4,5};
size = sizeof(a3)/sizeof(*a3);
ind = monot(a3,size,len);
printResult(a3,size,ind,len);
}
| [
"[email protected]"
] | |
7d5e6ab2fad862776ce962eb181154ce76a5166f | 4d04b7b0a8e9418f729ddee54bda43484657d52f | /Моя бібліотека/space/TbSphericalSpace/TbSphericalSpace.h | 0d63d3e954ec3b9b0e52f900c45ee6294715992e | [] | no_license | BREAK350/myCProgram-old | 359c021d7bcfa9e44fa831498a417294703a0c1e | 10bbfdd3cadd8c8d91b078591d6d646da20b48cb | refs/heads/master | 2021-01-10T20:04:20.229647 | 2015-01-28T06:51:00 | 2015-01-28T06:51:00 | 29,954,421 | 0 | 0 | null | null | null | null | ISO-8859-8 | C++ | false | false | 1,916 | h | //---------------------------------------------------------------------------
#ifndef TbSphericalSpaceH
#define TbSphericalSpaceH
#include "TbVirtualSpace.h"
extern TColor cl;
extern double stZ;
//---------------------------------------------------------------------------
class TbSphericalSpace:public TbVirtualSpace
{
private:
double Radius,Eye,Projection,
Review; // מבחמנ
void SetReview();
void GetCoordinate(double &X,double &Y,double &Z,
const TbSpacePoint2Data &Point)const;
public:
TbSphericalSpace(const double &Eye,const double &Projection,
const double &Radius);
void SetRadius(const double &Radius);
void SetEye(const double &Eye);
void SetProjection(const double &Projection);
TPoint GetTPoint(const TbSpacePoint2Data &Point)const;
void Init(TbSpacePoint2Data &Point,
const double &X,const double &Y)const;
TbSpacePoint2Data Summ(const TbSpacePoint2Data &First,
const TbSpacePoint2Data &Second)const;
double GetModule(const TbSpacePoint2Data &Point)const;
double GetPeriod()const;
};
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#endif
| [
"[email protected]"
] | |
a63f6f3fbc480715712cc13ffd5d6715984fe9b5 | 31d3432b94eca3d9f44fe7883971b8de5ef89338 | /examples/special_matrices/Zeros.cpp | 5f072faac191d1568f6b3996c9722c73a6e0fdea | [] | no_license | ahmadia/elemental | 2ffa196b7e7ce26d21606cfe85159ea7be7ee5fc | 5e69b2dd00383b669857b0ee42782cf8efc2ce7b | refs/heads/master | 2016-09-05T14:57:24.314870 | 2012-05-05T22:05:18 | 2012-05-05T22:05:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,578 | cpp | /*
Copyright (c) 2009-2012, Jack Poulson
All rights reserved.
This file is part of Elemental.
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 owner 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.
*/
#include "elemental.hpp"
using namespace elem;
void Usage()
{
std::cout << "Zeros <m> <n>\n"
<< " m: Height of matrix, m >= 1\n"
<< " n: Width of matrix, n >= 1\n"
<< std::endl;
}
int
main( int argc, char* argv[] )
{
Initialize( argc, argv );
mpi::Comm comm = mpi::COMM_WORLD;
const int commRank = mpi::CommRank( comm );
const int commSize = mpi::CommSize( comm );
if( argc < 3 )
{
if( commRank == 0 )
Usage();
Finalize();
return 0;
}
const int m = atoi( argv[1] );
const int n = atoi( argv[2] );
try
{
DistMatrix<double> A;
Zeros( m, n, A );
A.Print("Zeros matrix:");
}
catch( std::exception& e )
{
#ifndef RELEASE
DumpCallStack();
#endif
std::cerr << "Process " << commRank << " caught error message:\n"
<< e.what() << std::endl;
}
Finalize();
return 0;
}
| [
"[email protected]"
] | |
7913a15a9fc89384d197cca9573f9fb41d429572 | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /third_party/blink/renderer/core/script/module_script.h | d106054a188eeba17af3b09c1da354708299948d | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 5,818 | h | // Copyright 2017 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.
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_MODULE_SCRIPT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_MODULE_SCRIPT_H_
#include "third_party/blink/renderer/bindings/core/v8/module_record.h"
#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/world_safe_v8_reference.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/script/modulator.h"
#include "third_party/blink/renderer/core/script/script.h"
#include "third_party/blink/renderer/platform/bindings/name_client.h"
#include "third_party/blink/renderer/platform/bindings/parkable_string.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/loader/fetch/cached_metadata_handler.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/kurl_hash.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"
#include "third_party/blink/renderer/platform/wtf/text/text_position.h"
#include "v8/include/v8.h"
namespace blink {
// ModuleScript is a model object for the "module script" spec concept.
// https://html.spec.whatwg.org/C/#module-script
class CORE_EXPORT ModuleScript : public Script {
public:
v8::Local<v8::Module> V8Module() const;
bool HasEmptyRecord() const;
// Note: ParseError-related methods should only be used from ModuleTreeLinker
// or unit tests. You probably want to check |*ErrorToRethrow*()|
// instead.
void SetParseErrorAndClearRecord(ScriptValue error);
bool HasParseError() const { return !parse_error_.IsEmpty(); }
// CreateParseError() retrieves |parse_error_| as a ScriptValue.
ScriptValue CreateParseError() const;
void SetErrorToRethrow(ScriptValue error);
bool HasErrorToRethrow() const { return !error_to_rethrow_.IsEmpty(); }
ScriptValue CreateErrorToRethrow() const;
// Resolves a module specifier with the module script's base URL.
KURL ResolveModuleSpecifier(const String& module_request,
String* failure_reason = nullptr) const;
void Trace(Visitor*) const override;
virtual void ProduceCache() {}
const KURL& SourceURL() const { return source_url_; }
protected:
ModuleScript(Modulator*,
v8::Local<v8::Module>,
const KURL& source_url,
const KURL& base_url,
const ScriptFetchOptions&);
Modulator* SettingsObject() const { return settings_object_; }
private:
mojom::ScriptType GetScriptType() const override {
return mojom::ScriptType::kModule;
}
void RunScript(LocalFrame*, const SecurityOrigin*) override;
void RunScriptOnWorker(WorkerGlobalScope&) override;
friend class ModuleTreeLinkerTestModulator;
// https://html.spec.whatwg.org/C/#settings-object
Member<Modulator> settings_object_;
// https://html.spec.whatwg.org/C/#concept-script-record
// TODO(keishi): Visitor only defines a trace method for v8::Value so this
// needs to be cast.
GC_PLUGIN_IGNORE("757708")
TraceWrapperV8Reference<v8::Module> record_;
// https://html.spec.whatwg.org/C/#concept-script-parse-error
//
// |record_|, |parse_error_| and |error_to_rethrow_| are wrapper traced and
// kept alive via one or more of following reference graphs:
// * non-inline module script case
// DOMWindow -> Modulator/ModulatorImpl -> ModuleMap -> ModuleMap::Entry
// -> ModuleScript
// * inline module script case, before the PendingScript is created.
// DOMWindow -> Modulator/ModulatorImpl -> ModuleTreeLinkerRegistry
// -> ModuleTreeLinker -> ModuleScript
// * inline module script case, after the PendingScript is created.
// HTMLScriptElement -> ScriptLoader -> ModulePendingScript
// -> ModulePendingScriptTreeClient -> ModuleScript.
// * inline module script case, queued in HTMLParserScriptRunner,
// when HTMLScriptElement is removed before execution.
// Document -> HTMLDocumentParser -> HTMLParserScriptRunner
// -> ModulePendingScript -> ModulePendingScriptTreeClient
// -> ModuleScript.
// * inline module script case, queued in ScriptRunner.
// Document -> ScriptRunner -> ScriptLoader -> ModulePendingScript
// -> ModulePendingScriptTreeClient -> ModuleScript.
// All the classes/references on the graphs above should be
// Member<>/etc.,
//
// A parse error and an error to rethrow belong to a script, not to a
// |parse_error_| and |error_to_rethrow_| should belong to a script (i.e.
// blink::Script) according to the spec, but are put here in ModuleScript,
// because:
// - Error handling for classic and module scripts are somehow separated and
// there are no urgent motivation for merging the error handling and placing
// the errors in Script, and
// - Classic scripts are handled according to the spec before
// https://github.com/whatwg/html/pull/2991. This shouldn't cause any
// observable functional changes, and updating the classic script handling
// will require moderate code changes (e.g. to move compilation timing).
WorldSafeV8Reference<v8::Value> parse_error_;
// https://html.spec.whatwg.org/C/#concept-script-error-to-rethrow
WorldSafeV8Reference<v8::Value> error_to_rethrow_;
mutable HashMap<String, KURL> specifier_to_url_cache_;
KURL source_url_;
};
CORE_EXPORT std::ostream& operator<<(std::ostream&, const ModuleScript&);
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_MODULE_SCRIPT_H_
| [
"[email protected]"
] | |
090656e1c3d647837a439e4a6e0acaca576cea8e | 0933754819d113e4a30538c6e1114704f76111b7 | /src/ShokoTD++/ModeMenu.cpp | 4fe47f9bda07d221a7a421fc0c22d13136cc34a2 | [] | no_license | danishcake/ShokoTD | ef178651217a7cc95cecb77058f48597ae5f01d8 | 481c280f6295dcc63b2ba394819a76d1e6870a76 | refs/heads/master | 2021-01-25T10:11:39.690626 | 2009-11-28T21:39:51 | 2009-11-28T21:39:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,017 | cpp | #include "ModeMenu.h"
#include "RenderItem.h"
#include <Widget.h>
#include "ModeTutorial.h"
ModeMenu::ModeMenu()
{
exitting_ = false;
}
IMode* ModeMenu::Teardown()
{
Widget::ClearRoot();
return IMode::Teardown();
}
void ModeMenu::Setup()
{
Widget* newGame = new Widget("Blank128x32.png");
newGame->SetText("New game", TextAlignment::Centre);
newGame->SetPosition(Vector2i(10, 20));
newGame->OnClick.connect(boost::bind(&ModeMenu::NewGameClick, this, _1));
Widget* loadGame = new Widget("Blank128x32.png");
loadGame->SetText("Load", TextAlignment::Centre);
loadGame->SetPosition(Vector2i(10, 62));
loadGame->OnClick.connect(boost::bind(&ModeMenu::LoadClick, this, _1));
Widget* options = new Widget("Blank128x32.png");
options->SetText("Options", TextAlignment::Centre);
options->SetPosition(Vector2i(10, 104));
options->OnClick.connect(boost::bind(&ModeMenu::OptionsClick, this, _1));
Widget* unlocks = new Widget("Blank128x32.png");
unlocks->SetText("Unlocks", TextAlignment::Centre);
unlocks->SetPosition(Vector2i(10, 146));
unlocks->OnClick.connect(boost::bind(&ModeMenu::UnlocksClick, this, _1));
Widget* exit = new Widget("Blank128x32.png");
exit->SetText("Exit", TextAlignment::Centre);
exit->SetPosition(Vector2i(10, 188));
exit->OnClick.connect(boost::bind(&ModeMenu::ExitClick, this, _1));
not_done_yet_ = new Widget("Blank600x200.png");
not_done_yet_->SetPosition(Vector2i(-700, 0));
not_done_yet_->SetText("Feature completion?\nBugger all chance of that, lad.\nA haiku instead.", TextAlignment::TopLeft);
not_done_yet_->SetRejectsFocus(true);
Widget* dismiss = new Widget("Blank128x32.png");
dismiss->SetPosition(Vector2i(462, 158));
dismiss->OnClick.connect(boost::bind(&ModeMenu::DismissClick, this, _1));
dismiss->SetText("Back", TextAlignment::Centre);
not_done_yet_->AddChild(dismiss);
}
ModeAction::Enum ModeMenu::Tick(float _dt)
{
ModeAction::Enum result = ModeAction::NoAction;
result = IMode::Tick(_dt);
if(!exitting_)
{
Widget::SetFade(fade_);
} else
{
Widget::SetFade((age_ - pend_time_) / pend_time_);
if(age_ - pend_time_ >= pend_time_)
result = ModeAction::Exit;
}
return result;
}
ModeType::Enum ModeMenu::GetType()
{
return ModeType::Menu;
}
std::vector<RenderItem> ModeMenu::Draw()
{
return std::vector<RenderItem>();
}
/* Event handlers */
void ModeMenu::NewGameClick(Widget* /*_widget*/)
{
if(!pend_mode_)
pend_mode_ = new ModeTutorial();
}
void ModeMenu::LoadClick(Widget* /*_widget*/)
{
NotDoneYet();
}
void ModeMenu::OptionsClick(Widget* /*_widget*/)
{
NotDoneYet();
}
void ModeMenu::UnlocksClick(Widget* /*_widget*/)
{
NotDoneYet();
}
void ModeMenu::ExitClick(Widget* /*_widget*/)
{
if(!exitting_)
{
exitting_ = true;
age_ = pend_time_;
}
}
void ModeMenu::NotDoneYet()
{
not_done_yet_->SetPosition(Vector2i(320 - 300, 240 - 100));
not_done_yet_->SetModal(true);
}
void ModeMenu::DismissClick(Widget* /*_widget*/)
{
not_done_yet_->SetPosition(Vector2i(-700, 0));
not_done_yet_->SetModal(false);
} | [
"[email protected]"
] | |
0f24afd44ec3f28fb645d8ab81314d533bf4e349 | fb5b25b4fbe66c532672c14dacc520b96ff90a04 | /export/release/windows/obj/include/flixel/FlxCameraFollowStyle.h | e4ee9ee50ef5d3f912be25961dff26b8505657cd | [
"Apache-2.0"
] | permissive | Tyrcnex/tai-mod | c3849f817fe871004ed171245d63c5e447c4a9c3 | b83152693bb3139ee2ae73002623934f07d35baf | refs/heads/main | 2023-08-15T07:15:43.884068 | 2021-09-29T23:39:23 | 2021-09-29T23:39:23 | 383,313,424 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,668 | h | #ifndef INCLUDED_flixel_FlxCameraFollowStyle
#define INCLUDED_flixel_FlxCameraFollowStyle
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS1(flixel,FlxCameraFollowStyle)
namespace flixel{
class FlxCameraFollowStyle_obj : public ::hx::EnumBase_obj
{
typedef ::hx::EnumBase_obj super;
typedef FlxCameraFollowStyle_obj OBJ_;
public:
FlxCameraFollowStyle_obj() {};
HX_DO_ENUM_RTTI;
static void __boot();
static void __register();
static bool __GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp);
::String GetEnumName( ) const { return HX_("flixel.FlxCameraFollowStyle",fb,4d,2f,fa); }
::String __ToString() const { return HX_("FlxCameraFollowStyle.",65,a9,b1,ad) + _hx_tag; }
static ::flixel::FlxCameraFollowStyle LOCKON;
static inline ::flixel::FlxCameraFollowStyle LOCKON_dyn() { return LOCKON; }
static ::flixel::FlxCameraFollowStyle NO_DEAD_ZONE;
static inline ::flixel::FlxCameraFollowStyle NO_DEAD_ZONE_dyn() { return NO_DEAD_ZONE; }
static ::flixel::FlxCameraFollowStyle PLATFORMER;
static inline ::flixel::FlxCameraFollowStyle PLATFORMER_dyn() { return PLATFORMER; }
static ::flixel::FlxCameraFollowStyle SCREEN_BY_SCREEN;
static inline ::flixel::FlxCameraFollowStyle SCREEN_BY_SCREEN_dyn() { return SCREEN_BY_SCREEN; }
static ::flixel::FlxCameraFollowStyle TOPDOWN;
static inline ::flixel::FlxCameraFollowStyle TOPDOWN_dyn() { return TOPDOWN; }
static ::flixel::FlxCameraFollowStyle TOPDOWN_TIGHT;
static inline ::flixel::FlxCameraFollowStyle TOPDOWN_TIGHT_dyn() { return TOPDOWN_TIGHT; }
};
} // end namespace flixel
#endif /* INCLUDED_flixel_FlxCameraFollowStyle */
| [
"[email protected]"
] | |
fb3504363c75c0146c792d432cbbcfdefe25fbdc | 5c0f282a4e3e8fec68b20317c9a07247bd8b4616 | /src/core/imported/vam/core/vamobject.h | 198072ad94ba2c264f3dc4d98756256fc83fe35a | [
"MIT"
] | permissive | PetarKirov/pal | b3baabdccb5df38e711fa3641d450e9c34f877ea | d535f5dc4179fc14249a5eb41e59aa96a5cd318f | refs/heads/master | 2021-08-31T19:50:18.201096 | 2017-12-21T13:40:00 | 2017-12-22T08:06:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,693 | h | /*
*******************************************************************************
*
* Copyright (c) 2009-2017 Advanced Micro Devices, Inc. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
/**
***************************************************************************************************
* @file vamobject.h
* @brief Contains the VamObject base class definition.
***************************************************************************************************
*/
#ifndef __VAMOBJECT_H__
#define __VAMOBJECT_H__
#include "vaminterface.h"
/**
***************************************************************************************************
* @brief This is the base class for all VAM class objects.
***************************************************************************************************
*/
class VamObject
{
public:
VamObject();
VamObject(VAM_CLIENT_HANDLE hClient);
virtual ~VamObject();
VOID* operator new(size_t size, VAM_CLIENT_HANDLE hClient);
VOID operator delete(VOID* pObj, VAM_CLIENT_HANDLE hClient);
VOID operator delete(VOID* pObj);
static VOID SetupSysMemFuncs( VAM_ALLOCSYSMEM allocSysMem,
VAM_FREESYSMEM freeSysMem );
protected:
VAM_CLIENT_HANDLE m_hClient;
static VAM_ALLOCSYSMEM m_allocSysMem;
static VAM_FREESYSMEM m_freeSysMem;
private:
// Disallow the copy constructor
VamObject(const VamObject& a);
// Disallow the assignment operator
VamObject& operator=(const VamObject& a);
};
#endif // __VAMOBJECT_H__
| [
"[email protected]"
] | |
f772bca08ddaaf445855ef86186a31a94c8e87ff | a209eba9ccfa5694d6f22d53865f65594af00dcc | /file handling/F16.CPP | d12d3df178d242a1cb8053a32cc5b16d76876440 | [] | no_license | agamsingh10/coding | 5a5fcbb185efb368f2848872c7428d450f6e5e8a | f089697ab345aab9d6109fe9a1215f53f98c0df6 | refs/heads/master | 2020-06-25T10:03:09.597045 | 2019-10-24T17:58:19 | 2019-10-24T17:58:19 | 199,279,127 | 1 | 0 | null | 2019-07-28T11:41:52 | 2019-07-28T11:32:07 | null | UTF-8 | C++ | false | false | 813 | cpp | #include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
class student
{ int ad;
char name[39];
float marks;
public:
void getdata()
{cout<<"enter info"<<endl;
cin>>ad;
cin>>marks;
gets(name); }
void display()
{cout<<"name .....";
cout<<ad<<" " <<name<<" "<<marks; }
};
/*void main()
{clrscr();
student g;
ofstream fcout("abc.dat", ios::binary|ios::out);
for(int i=0;i<3;i++)
{ g.getdata();
fcout.write((char*)&g, sizeof(g));
}
fcout.close();
getch();
} */
void main()
{clrscr();
student g;
ifstream fcin("abc.dat", ios::binary|ios::in);
while(!fcin.eof())
{ fcin.read((char*)&g, sizeof(g));
if(fcin.eof())
break;
g.display();
}
fcin.close();
getch();
} | [
"[email protected]"
] | |
49eba1f83b378efe58cb27b2df09ff4a6a280a4e | cd2bcd559fb8af7069c8e1a00133843a9e901875 | /genKeys.cpp | a5548b9bf07de42a56619125f3b0a04681eacb75 | [] | no_license | Samuel2145/Crypto-SAES | 92f5c341c8dfd35d59339d14144ce000ca3edbde | df832db0821ae28d484eb78a58a4490033556fc7 | refs/heads/main | 2023-03-24T22:14:35.124311 | 2021-03-07T04:32:55 | 2021-03-07T04:32:55 | 345,258,547 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,680 | cpp | /**
* CIS4362
* Intro to Cryptology
* Ex4 - genKeys
* Samuel Reina
* 11/17/2020
*/
#include "bPlate.cpp"
int main(int argc, char* argv[]){
if(argc < 2){
cerr << "Missing number of rounds" << endl;
return -1;
}
int numRounds = 0;
string input;
///Check validity of command line input
try{
double temp = stod(argv[1]);
int temp2 = (int)temp;
bool s = (temp == temp2);
if(!s){
cerr << "Invalid number of rounds" << endl;
return -1;
}
numRounds = temp2;
}catch(invalid_argument &e){
cerr << "Invalid number of rounds" << endl;
return -1;
}
if(numRounds < 2 || numRounds > 10){
cerr << "Invalid number of rounds" << endl;
return -1;
}
///Take user input (master key)
getline(cin, input);
input = input.substr(0,9);
///Check validity of key inputted
for(int i = 0; i < 9; i++){
char c = input.at(i);
if( !isalnum(c) && c != '.'){
cerr << "Invalid master key" << endl;
return -1;
}
}
vector<string> keys;
keys.push_back(input.substr(0,3));
keys.push_back(input.substr(3,3));
keys.push_back(input.substr(6,3));
for(int i = 0; i < numRounds; i++){
keys.push_back(generate(keys, keys[i]));
keys.push_back(sum(keys[i*3+1], keys[i*3+3]));
keys.push_back(sum(keys[i*3+2], keys[i*3+4]));
}
for(int i = 0; i < keys.size(); i+=3){
cout << keys[i] << keys[i+1] << keys[i+2] << endl;
}
return 0;
}
| [
"[email protected]"
] | |
5679106c21231e86c5c3ed83c8869f9e2338c986 | e91291f43149171ed8b927c3b9b980b38c4eec92 | /serverdemo/sanguo/game/player.cpp | ce43aa5ebc71fda281e4747e259c99f5fdab3f0b | [] | no_license | mengtest/private | f4153cde5ba9cebdf1ed6152dc7501d9cf689a19 | e3cd3e7929dd427746aee6769728e5ed8526e7c6 | refs/heads/master | 2021-06-11T14:15:12.267675 | 2016-12-13T11:46:23 | 2016-12-13T11:46:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,603 | cpp | // --------------------------------------------------------
/*Copyright KeyeLeo.All rights reserved.
*
*File : player.cpp
*Desc :
*Version : 1.0
*Program : KeyeLeo
*Date : 2012-8-14
*/
// --------------------------------------------------------
#include "stdafx.h"
#include "game/fwd.h"
#include "time.h"
#if defined(_USE_WEBSOCKETPP_)
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
#endif
using namespace vl;
Player::Player(std::weak_ptr<void> sh)
:_wsppsh(sh)
,_sock_type(ST_WEBSOCKET){
_client_id=(size_t)sh.lock().get();
Game::instance()->connects().add(_client_id,this);
}
/*
void Player::handle(svc_handler&,const keye::packet_t& p){
auto msg=(char*)&p;
auto len=p.length;
if(-1==client_onData(_client_id,msg,len,Game::instance()->getMysqlConn()))
_sh->close();
}
*/
void Player::send(const void* buf,size_t len){
typedef websocketpp::server<websocketpp::config::asio> server;
server::connection_ptr con = websocketpp::lib::static_pointer_cast<server::connection_type>(_wsppsh.lock());
con->send(buf,len);
auto ptr=(short*)buf;
LOG_INFO<<"send "<<*++ptr<<Endl;
}
int append_client(size_t clt_id, const char *data, size_t len)
{
Player* p=Game::instance()->players().find(clt_id);
if(!p)
p=Game::instance()->connects().find(clt_id);
if(p){
p->send(data,len);
// LOG_INFO<<"debug: --- send message( client="<<(long long)clt_id<<",cmd="<<(int)*((const short*)data+1)<<endf;
return (int)len;
}else
return 0;
}
void sendToOne(size_t client,void *pPak,size_t len)
{
static char buffer[20480];
memset(buffer,0,20480);
// char buffer[len+2];
SetShort(1,len+2,buffer);
memcpy(buffer+2,pPak,len);
append_client(client,buffer,len+2);
}
bool is_sameday(time_t tm0,time_t tm1){
tm *atm=localtime(&tm0);
int y=atm->tm_year,
m=atm->tm_mon,
d=atm->tm_mday;
atm=localtime(&tm1);
return (atm->tm_year==y&&
atm->tm_mon==m&&
atm->tm_mday==d);
}
void Player::Send(const void* buf,size_t len){
sendToOne(_client_id,(void*)buf,len);
}
void Player::update(){
}
void Player::update_Timer(){
}
void Player::close(){
typedef websocketpp::server<websocketpp::config::asio> server;
server::connection_ptr con = websocketpp::lib::static_pointer_cast<server::connection_type>(_wsppsh.lock());
if(con)con->close(0,"");
}
Player::~Player(){
logOut();
if(_sock_type!=ST_WEBSOCKET)
client_close(_client_id);
Game::instance()->connects().remove(_client_id);
}
void Player::release(){
if(_sock_type==ST_WEBSOCKET)
delete this;
}
void Player::login(int uid){
// _client_id=uid;
auto now=time(nullptr);
struct userData *curr=spData.get();
if(curr)curr->signal_flag=(is_sameday(now,time_signal))?1:0;
//proc online time
MYSQL* mysql=Game::instance()->getMysqlConn();
char sql[128];
if(!is_sameday(now,time_login)){
//clear online time
sprintf(sql,"UPDATE t_user SET time_online=0 WHERE user_id=%d;",uid);
// sprintf(sql,"UPDATE t_user SET time_total=time_total+time_online,time_online=0 WHERE user_id=%d;",uid);
exec(mysql,sql);
}
//update login time
time_login=now;
sprintf(sql,"UPDATE t_user SET time_login=%lld WHERE user_id=%d;",now,uid);
exec(mysql,sql);
#ifdef CARD_NEW
InitCheckGardGroup(uid);
LoadCardGroup(uid);
#endif
}
void Player::logOut()
{
if(!spData)return;
//proc online time
auto now=time(nullptr);
auto uid=spData->user_id;
MYSQL* mysql=Game::instance()->getMysqlConn();
MYSQL_RES *res=nullptr;
MYSQL_ROW row;
char sql[128];
const int AC_TIME=int(60.f*0.5f); //0.5hour in minite
int time_online=0,time_total=0,ac_day=0;
//read time_online
sprintf(sql,"SELECT time_online,ac_days FROM t_user WHERE user_id=%d;",uid);
if(res=query(mysql,sql)){
if(row=mysql_fetch_row(res)){
time_online=row[0]?atoi(row[0]):0;
ac_day=row[1]?atoi(row[1]):0;
}
FreeResult(res);
}
const time_t interval=(now-time_login);
bool ac_flag=true;
if(!is_sameday(now,time_login)){
tm* atm=localtime(&time_login);
int h0=atm->tm_hour,
m0=atm->tm_min;
atm=localtime(&now);
int h1=atm->tm_hour,
m1=atm->tm_min;
//calc ac day before
if(time_online<AC_TIME){
if(h0<23||(time_online+60-m0)>AC_TIME)
++ac_day;
}
int days=((interval/60-m1)/60-h1)/24; //more than one day
ac_day+=days;
//calc ac day of today
time_online=h1*60+m1;
if(time_online>=AC_TIME)
++ac_day;
//update time_login on today
time_login=now;
}else{
ac_flag=(time_online<AC_TIME);
time_online+=interval/60; //in minite
//calc ac day of today
if(ac_flag&&time_online>=AC_TIME)
++ac_day;
}
time_total=(int)interval/60;
sprintf(sql,"UPDATE t_user SET time_login=%lld,time_online=%d,time_total=time_total+%d,ac_days=%d WHERE user_id=%d;",
time_login,time_online,time_total,ac_day,uid);
exec(mysql,sql);
}
void Player::enter(){
}
// --------------------------------------------------------
void Players::add(size_t id,Player* r){
if(!find(id)){
_players.insert(std::make_pair(id,r));
}
}
void Players::remove(size_t id){
_players.erase(id);
}
void Players::update()
{
for(auto pp = _players.begin();pp!=_players.end() ; pp++)
pp->second->update_Timer();
}
Player* Players::find(size_t id){
auto i=_players.find(id);
return i==_players.end()?nullptr:i->second;
}
| [
"[email protected]"
] | |
4f49c7a75f3792272acb1cd20870908e4a788d12 | 4731b0e47e9930d8c08125cee6c5b170ea1afef5 | /weblayer/browser/browser_impl.h | 79f92f62c83111d5b93e429aa1636f9a8d3b766b | [
"BSD-3-Clause"
] | permissive | puresteelzhang/chromium | 686c99e26dda0f773f771abfab00d3f49a73fc5e | 82eda384a407ec68564e445f95663112c7e5e678 | refs/heads/master | 2022-12-12T21:38:24.153904 | 2020-09-15T07:49:39 | 2020-09-15T07:49:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,181 | h | // Copyright 2020 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.
#ifndef WEBLAYER_BROWSER_BROWSER_IMPL_H_
#define WEBLAYER_BROWSER_BROWSER_IMPL_H_
#include <memory>
#include <vector>
#include "base/callback.h"
#include "base/observer_list.h"
#include "build/build_config.h"
#include "weblayer/public/browser.h"
#if defined(OS_ANDROID)
#include "base/android/scoped_java_ref.h"
#endif
namespace base {
class FilePath;
}
namespace blink {
namespace web_pref {
struct WebPreferences;
}
} // namespace blink
namespace content {
class WebContents;
}
namespace weblayer {
class BrowserPersister;
class ProfileImpl;
class TabImpl;
class BrowserImpl : public Browser {
public:
// Prefix used for storing persistence state.
static constexpr char kPersistenceFilePrefix[] = "State";
BrowserImpl(const BrowserImpl&) = delete;
BrowserImpl& operator=(const BrowserImpl&) = delete;
~BrowserImpl() override;
BrowserPersister* browser_persister() { return browser_persister_.get(); }
ProfileImpl* profile() { return profile_; }
// Creates and adds a Tab from session restore. The returned tab is owned by
// this Browser.
TabImpl* CreateTabForSessionRestore(
std::unique_ptr<content::WebContents> web_contents,
const std::string& guid);
TabImpl* CreateTab(std::unique_ptr<content::WebContents> web_contents);
#if defined(OS_ANDROID)
bool CompositorHasSurface();
void AddTab(JNIEnv* env,
long native_tab);
void RemoveTab(JNIEnv* env,
long native_tab);
base::android::ScopedJavaLocalRef<jobjectArray> GetTabs(JNIEnv* env);
void SetActiveTab(JNIEnv* env,
long native_tab);
base::android::ScopedJavaLocalRef<jobject> GetActiveTab(JNIEnv* env);
void PrepareForShutdown(JNIEnv* env);
base::android::ScopedJavaLocalRef<jstring> GetPersistenceId(JNIEnv* env);
void SaveBrowserPersisterIfNecessary(JNIEnv* env);
base::android::ScopedJavaLocalRef<jbyteArray> GetBrowserPersisterCryptoKey(
JNIEnv* env);
base::android::ScopedJavaLocalRef<jbyteArray> GetMinimalPersistenceState(
JNIEnv* env);
void RestoreStateIfNecessary(
JNIEnv* env,
const base::android::JavaParamRef<jstring>& j_persistence_id,
const base::android::JavaParamRef<jbyteArray>& j_persistence_crypto_key,
const base::android::JavaParamRef<jbyteArray>&
j_minimal_persistence_state);
void WebPreferencesChanged(JNIEnv* env);
void OnFragmentStart(JNIEnv* env);
void OnFragmentResume(JNIEnv* env);
void OnFragmentPause(JNIEnv* env);
bool fragment_resumed() { return fragment_resumed_; }
#endif
// Used in tests to specify a non-default max (0 means use the default).
std::vector<uint8_t> GetMinimalPersistenceState(int max_size_in_bytes);
// Used by tests to specify a callback to listen to changes to visible
// security state.
void set_visible_security_state_callback_for_tests(
base::OnceClosure closure) {
visible_security_state_changed_callback_for_tests_ = std::move(closure);
}
bool GetPasswordEchoEnabled();
void SetWebPreferences(blink::web_pref::WebPreferences* prefs);
#if defined(OS_ANDROID)
// On Android the Java Tab class owns the C++ Tab. DestroyTab() calls to the
// Java Tab class to initiate deletion. This function is called from the Java
// side, and must not call DestroyTab(), otherwise we get stuck in infinite
// recursion.
void DestroyTabFromJava(Tab* tab);
#endif
// Browser:
void AddTab(Tab* tab) override;
void DestroyTab(Tab* tab) override;
void SetActiveTab(Tab* tab) override;
Tab* GetActiveTab() override;
std::vector<Tab*> GetTabs() override;
Tab* CreateTab() override;
void PrepareForShutdown() override;
std::string GetPersistenceId() override;
std::vector<uint8_t> GetMinimalPersistenceState() override;
void AddObserver(BrowserObserver* observer) override;
void RemoveObserver(BrowserObserver* observer) override;
void VisibleSecurityStateOfActiveTabChanged() override;
private:
// For creation.
friend class Browser;
#if defined(OS_ANDROID)
friend BrowserImpl* CreateBrowserForAndroid(
ProfileImpl*,
const base::android::JavaParamRef<jobject>&);
#endif
explicit BrowserImpl(ProfileImpl* profile);
void RestoreStateIfNecessary(const PersistenceInfo& persistence_info);
TabImpl* AddTab(std::unique_ptr<Tab> tab);
std::unique_ptr<Tab> RemoveTab(Tab* tab);
// Returns the path used by |browser_persister_|.
base::FilePath GetBrowserPersisterDataPath();
#if defined(OS_ANDROID)
void UpdateFragmentResumedState(bool state);
bool fragment_resumed_ = false;
base::android::ScopedJavaGlobalRef<jobject> java_impl_;
#endif
base::ObserverList<BrowserObserver> browser_observers_;
ProfileImpl* const profile_;
std::vector<std::unique_ptr<Tab>> tabs_;
TabImpl* active_tab_ = nullptr;
std::string persistence_id_;
std::unique_ptr<BrowserPersister> browser_persister_;
base::OnceClosure visible_security_state_changed_callback_for_tests_;
};
} // namespace weblayer
#endif // WEBLAYER_BROWSER_BROWSER_IMPL_H_
| [
"[email protected]"
] | |
680a0d7fba4b0cb4b188222d5ef529449596f5b7 | 86dae49990a297d199ea2c8e47cb61336b1ca81e | /c/资源/1. 算法部分/第2章 数据排序/1.明明的随机数(NOIP2006)/random.cpp | 415ca6899221068e09370f19d35d493b2c17c6e3 | [] | no_license | yingziyu-llt/OI | 7cc88f6537df0675b60718da73b8407bdaeb5f90 | c8030807fe46b27e431687d5ff050f2f74616bc0 | refs/heads/main | 2023-04-04T03:59:22.255818 | 2021-04-11T10:15:03 | 2021-04-11T10:15:03 | 354,771,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 475 | cpp | #include<cstdio>
#include<iostream>
using namespace std;
int main ()
{
int n,a[1000],s=0,i,j,t=0;
cin>>n;
for (i=1; i<=n; i++)
cin>>a[i];
for (j=1; j<=n-1; j++)
for (i=1; i<=n-j; i++)
if (a[i]>a[i+1])
{t=a[i]; a[i]=a[i+1];a[i+1]=t;}
for (i=1; i<=n; i++)
if (a[i]==a[i+1])
a[i]=0;
for (i=1; i<=n; i++)
if (a[i]!=0)
s=s+1;
cout<<s<<endl;
for (i=1; i<=n; i++)
if (a[i]!=0)
cout<<a[i]<<" ";
return 0;
}
| [
"[email protected]"
] | |
ce12bdded1a56d07568f64518d038fd7594a2ecf | 8ac1b220c3d534b8a1b5f10449c535cfefac9160 | /interface_cuda/set_get.cpp | d622a42435674800ac765dc1dc664debfc9905ac | [] | no_license | soulsheng/magma | aa83eea749c5108c607f4710f2905a8a1deb235e | 465fd5817498319db4cbce52cded86fd49b65274 | refs/heads/master | 2020-12-01T13:05:11.511847 | 2013-09-04T00:18:03 | 2013-09-04T00:18:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,095 | cpp | /*
-- MAGMA (version 1.4.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
August 2013
@author Mark Gates
@precisions normal z -> s d c
*/
#include <stdlib.h>
#include <stdio.h>
#include "magma.h"
#include "error.h"
#ifdef HAVE_CUBLAS
// generic, type-independent routines to copy data.
// type-safe versions which avoid the user needing sizeof(...) are in copy_[sdcz].cpp
// ========================================
// copying vectors
extern "C"
void magma_setvector_internal(
magma_int_t n, size_t elemSize,
void const* hx_src, magma_int_t incx,
void* dy_dst, magma_int_t incy,
const char* func, const char* file, int line )
{
cublasStatus_t status;
status = cublasSetVector(
n, elemSize,
hx_src, incx,
dy_dst, incy );
check_xerror( status, func, file, line );
}
// --------------------
extern "C"
void magma_getvector_internal(
magma_int_t n, size_t elemSize,
void const* dx_src, magma_int_t incx,
void* hy_dst, magma_int_t incy,
const char* func, const char* file, int line )
{
cublasStatus_t status;
status = cublasGetVector(
n, elemSize,
dx_src, incx,
hy_dst, incy );
check_xerror( status, func, file, line );
}
// --------------------
extern "C"
void magma_setvector_async_internal(
magma_int_t n, size_t elemSize,
void const* hx_src, magma_int_t incx,
void* dy_dst, magma_int_t incy,
cudaStream_t stream,
const char* func, const char* file, int line )
{
cublasStatus_t status;
status = cublasSetVectorAsync(
n, elemSize,
hx_src, incx,
dy_dst, incy, stream );
check_xerror( status, func, file, line );
}
// --------------------
extern "C"
void magma_getvector_async_internal(
magma_int_t n, size_t elemSize,
void const* dx_src, magma_int_t incx,
void* hy_dst, magma_int_t incy,
cudaStream_t stream,
const char* func, const char* file, int line )
{
cublasStatus_t status;
status = cublasGetVectorAsync(
n, elemSize,
dx_src, incx,
hy_dst, incy, stream );
check_xerror( status, func, file, line );
}
// ========================================
// copying sub-matrices (contiguous columns)
extern "C"
void magma_setmatrix_internal(
magma_int_t m, magma_int_t n, size_t elemSize,
void const* hA_src, magma_int_t lda,
void* dB_dst, magma_int_t ldb,
const char* func, const char* file, int line )
{
cublasStatus_t status;
status = cublasSetMatrix(
m, n, elemSize,
hA_src, lda,
dB_dst, ldb );
check_xerror( status, func, file, line );
}
// --------------------
extern "C"
void magma_getmatrix_internal(
magma_int_t m, magma_int_t n, size_t elemSize,
void const* dA_src, magma_int_t lda,
void* hB_dst, magma_int_t ldb,
const char* func, const char* file, int line )
{
cublasStatus_t status;
status = cublasGetMatrix(
m, n, elemSize,
dA_src, lda,
hB_dst, ldb );
check_xerror( status, func, file, line );
}
// --------------------
extern "C"
void magma_setmatrix_async_internal(
magma_int_t m, magma_int_t n, size_t elemSize,
void const* hA_src, magma_int_t lda,
void* dB_dst, magma_int_t ldb,
cudaStream_t stream,
const char* func, const char* file, int line )
{
cublasStatus_t status;
status = cublasSetMatrixAsync(
m, n, elemSize,
hA_src, lda,
dB_dst, ldb, stream );
check_xerror( status, func, file, line );
}
// --------------------
extern "C"
void magma_getmatrix_async_internal(
magma_int_t m, magma_int_t n, size_t elemSize,
void const* dA_src, magma_int_t lda,
void* hB_dst, magma_int_t ldb,
cudaStream_t stream,
const char* func, const char* file, int line )
{
cublasStatus_t status;
status = cublasGetMatrixAsync(
m, n, elemSize,
dA_src, lda,
hB_dst, ldb, stream );
check_xerror( status, func, file, line );
}
// --------------------
extern "C"
void magma_copymatrix_internal(
magma_int_t m, magma_int_t n, size_t elemSize,
void const* dA_src, magma_int_t lda,
void* dB_dst, magma_int_t ldb,
const char* func, const char* file, int line )
{
cudaError_t status;
status = cudaMemcpy2D(
dB_dst, ldb*elemSize,
dA_src, lda*elemSize,
m*elemSize, n, cudaMemcpyDeviceToDevice );
check_xerror( status, func, file, line );
}
// --------------------
extern "C"
void magma_copymatrix_async_internal(
magma_int_t m, magma_int_t n, size_t elemSize,
void const* dA_src, magma_int_t lda,
void* dB_dst, magma_int_t ldb,
cudaStream_t stream,
const char* func, const char* file, int line )
{
cudaError_t status;
status = cudaMemcpy2DAsync(
dB_dst, ldb*elemSize,
dA_src, lda*elemSize,
m*elemSize, n, cudaMemcpyDeviceToDevice, stream );
check_xerror( status, func, file, line );
}
#endif // HAVE_CUBLAS
| [
"[email protected]"
] | |
754e4f858f029aec0f485827134850a5787e9a19 | f4f9294e61db48b48c6de5e683715ddd21abd72f | /macrosim_tracer/ito_tracer/src/sample2.cpp | aafe042fce294d679e31d9949758334cef2e7f9f | [] | no_license | lessydien/ray2 | 7190d24aec1d86ba847db5876f4854fa1421594e | 4b837da5b772b383708fc6dd142d7b7b23adb61e | refs/heads/master | 2021-01-01T04:47:11.067183 | 2017-02-13T15:54:15 | 2017-02-13T15:54:15 | 97,242,094 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 21,993 | cpp | #define _CRTDBG_MAP_ALLOC
/**\file sample2.cpp
* \brief entry point to the application containing the main routine
*
*
* \author Mauch
*/
//#include <omp.h>
#include "TopObject.h"
#include "cuda_runtime.h"
#include <optix.h>
#include <vector_functions.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sutil.h>
#include <sampleConfig.h>
//#include <commonStructs.h>
#include "Group.h"
#include "Geometry.h"
#include "GeometryLib.h"
#include "MaterialLib.h"
#include "ScatterLib.h"
#include "CoatingLib.h"
#include "SimAssistantLib.h"
#include "DetectorLib.h"
//#include "Detector.h"
#include "Scatter.h"
#include "Coating.h"
#include "RayField.h"
#include "GeometricRayField.h"
#include <math.h>
#include "rayTracingMath.h"
#include <ctime>
#include "FlexZemax.h"
#include "GlobalConstants.h"
#include "DiffRayField.h"
#include "complex.h"
#include "Converter.h"
#include "ScalarLightField.h"
#include "VectorLightField.h"
#include "wavefrontIn.h"
#include "inputOutput.h"
#include "GlobalConstants.h"
#include "Parser.h"
#include "Parser_XML.h"
#include "PropagationMath.h"
#include "Interpolator.h"
//#include <fstream>
#include <iostream>
using namespace std;
//#pragma comment( lib, "Delayimp.lib" )
//#pragma comment( lib, "cuda.lib" )
//#pragma comment( lib, "cudart.lib" )
//#pragma comment( lib, "optix.1.lib" )
//#pragma comment(lib, "testdll.lib")
//// Importieren der Funktion aus der oben erstellten DLL
//extern "C" __declspec(dllimport)double testFunc (double a, double b);
/* define the size of ray structure */
unsigned long long width;
unsigned long long height;
/*definition of global constants*/
//constants for raytracing on CPU
int MAX_DEPTH_CPU=10;
const float MIN_FLUX_CPU=1e-8;
const double MAX_TOLERANCE=1e-10;
typedef struct struct_BoxExtent{
float min[3];
float max[3];
} BoxExtent;
// declare scene group
Group oGroup;
void testInterpolator();
void createContext( RTcontext* context, RTbuffer* buffer );
void printUsageAndExit( const char* argv0 );
//void doCPUTracing(Group &oGroup, GeometricRayField &oGeomRayField);
//void doCPUTracing(Group &oGroup, DiffRayField &oDiffRayField);
//void doCPUTracing(Group &oGroup, GaussBeamRayField &oGaussBeamRayField);
unsigned int createGaussianBeamRaysTest(GaussBeamRayField **ptrptrRayField, double2 width, double2 offset, long2 nrBeamlets, double lambda);
void initRayField_AsphereTestCPU(FILE *hfileQxy, FILE *hfilePxy, GeometricRayField* oGemRayFieldPtr, double RadiusSourceReference, double zSourceReference, double *MNmn, int width, int height, double lambda);
void initRayField_AsphereTestGPU(RTcontext &context, FILE *hfileQxy, FILE *hfilePxy, GeometricRayField* oGeomRayFieldPtr, double RadiusSourceReference, double zSourceReference, double *MNmn, int width, int height, double lambda);
bool doTheSimulation(Group *oGrouPtr, RayField **SourceListPtrPtr, bool RunOnCPU);
bool createSceneFromXML(Group *oGroupPtr, FILE *hfile, RayField ***sourceListPtr, Detector ***detListPtr);
void wait ()
{
// Löscht etwaige Fehlerzustände die das Einlesen verhindern könnten
cin.clear();
// Ignoriert soviele Zeichen im Puffer wie im Puffer vorhanden sind
// (= ignoriert alle Zeichen die derzeit im Puffer sind)
cin.ignore(cin.rdbuf()->in_avail());
// Füge alle eingelesenen Zeichen in den Puffer bis ein Enter gedrückt wird
// cin.get() liefert dann das erste Zeichen aus dem Puffer zurück, welches wir aber ignorieren (interessiert uns ja nicht)
cin.get();
}
int main(int argc, char* argv[])
{
// _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
clock_t start, end;
start=clock();
#ifdef _DEBUG
#else
if (argc <4)
{
cout << "error in main: too few arguments." << endl;
return (1);
}
#endif
// omp_set_num_threads(omp_get_max_threads()-1);
// #pragma comment( lib, "Delayimp.lib" )
// #pragma comment( lib, "cuda.lib" )
// #pragma comment( lib, "cudart.lib" )
// #pragma comment( lib, "optix.1.lib" )
/* create scene */
/*******************************************************/
/* create geometry from parsing Zemax description file */
/*******************************************************/
//char *test1, *test2;
/* get handle to Zemax description file */
//char filepath[512];
//char filepath;
char* filepath=(char*)malloc(512*sizeof(char));
#ifdef _DEBUG
sprintf(filepath, "%s" PATH_SEPARATOR "%s", INPUT_FILES_PATH, "BeamHomo_PhaseSpace.TXT");//prescription_Avinash_PathTrace.TXT");//PhaseSpaceTest_Stabmischer1D_CosineProfile.TXT");//DiffTest_f9mm_idealLense.TXT");//fiber_interferometer_opt50x05_in.TXT");//prescription_Geometry_test.TXT");//prescription_nonsequential_OptiX_FromSlit_CompleteHousing_Filter.TXT");//prescription_nonsequential_test.TXT");//prescription_nonsequential_OptiX_FromSlit_Housing.TXT");//OptiX_FromSlit_CompleteHousing.TXT");//scatMat.TXT");//test.TXT");//Sidelobe380.TXT");//CMIdeal1.TXT");//
MAX_DEPTH_CPU=3;
#else
sprintf(filepath, "%s" PATH_SEPARATOR "%s", INPUT_FILES_PATH, argv[1]);
MAX_DEPTH_CPU=atoi(argv[3]);
#endif
FILE *hfile = fopen( filepath, "r" ) ;
if (!hfile)
{
cout << "error in main: cannot open geometry prescription file:" << filepath << endl;
return (1);
}
// decide wether we want to do sequential or nonsequential simulations
simMode mode=SIM_GEOMRAYS_NONSEQ;
RayField** SourceList;
SourceList=NULL;
Detector** DetectorList;
DetectorList=NULL;
long sourceNumber, detNumber;
FILE *hfile_xml = fopen( "MyXml.xml", "r" ) ;
if (!hfile)
{
cout << "error in main: cannot open xml file:" << filepath << endl;
return (1);
}
createSceneFromXML(&oGroup, hfile_xml, &SourceList, &DetectorList);
oGroup.getGeometryGroup(0)->getGeometry(0)->getParamsPtr();
if (!createSceneFromZemax(&oGroup, hfile, &SourceList, &sourceNumber, &DetectorList, &detNumber, mode))
{
cout << "error in main: createSceneFromZemax returned an error" << endl;
fclose(hfile); // close file anyway
return (1);
}
fclose(hfile);
bool layoutMode;
#ifdef _DEBUG
layoutMode=true;
#else
// set wavelength from command line
if (argc>4)
{
SourceList[0]->setLambda(atof(argv[4])*1e-6);
cout << "lambda set from command line to: " << SourceList[0]->getParamsPtr()->lambda*1e6 << "nm" << endl;
}
if (argc>5)
{
if (atoi(argv[5]) == 1)
layoutMode=true;
else
layoutMode=false;
}
else
layoutMode=false;
#endif
/****************************************************************/
/* trace rays */
/****************************************************************/
simAssParams *oSimAssParamsPtr=NULL;
SimAssistant *oSimAssPtr=NULL;
if (!layoutMode)
{
oSimAssPtr = new SimAssistantSingleSim;
oSimAssParamsPtr = new simAssSingleSimParams();
}
else
{
oSimAssPtr = new SimAssistantLayout;
oSimAssParamsPtr = new simAssLayoutParams();
}
oSimAssParamsPtr->mode=mode;
#ifdef _DEBUG
oSimAssParamsPtr->RunOnCPU=true;
#else
if (atoi(argv[2])==0)
oSimAssParamsPtr->RunOnCPU=false;
else
oSimAssParamsPtr->RunOnCPU=true;
#endif
oSimAssPtr->setParamsPtr(oSimAssParamsPtr);
//simAssParamSweepParams *oSimAssParamsPtr = new simAssParamSweepParams();
//oSimAssParamsPtr->geomParamsSweepLength=1;
//oSimAssParamsPtr->geomObjectIndex=2;
//oSimAssParamsPtr->geometryParamsList=new Geometry_Params*[oSimAssParamsPtr->geomParamsSweepLength];
//PlaneSurface_Params *planeParamsPtr=new PlaneSurface_Params();
//planeParamsPtr->normal=make_double3(0,0,1);
//planeParamsPtr->root=make_double3(0,0,241.8);
//planeParamsPtr->apertureType=AT_ELLIPT;
//planeParamsPtr->apertureRadius=make_double2(15,15);
//planeParamsPtr->rotNormal=0;
//planeParamsPtr->geometryID=oSimAssParamsPtr->geomObjectIndex+1;
//oSimAssParamsPtr->geometryParamsList[0]=planeParamsPtr;
//oSimAssParamsPtr->detParamsSweepLength=0;
//oSimAssParamsPtr->srcParamsSweepLength=0;
//oSimAssParamsPtr->mode=SIM_GEOMRAYS_NONSEQ;
//oSimAssParamsPtr->RunOnCPU=true;
//SimAssistantParamSweep oSimAss(oSimAssParamsPtr);
if (SIMASS_NO_ERROR != oSimAssPtr->initSimulation(&oGroup, SourceList))
{
cout << "error in main(): SimAss.initSimulation() returned an error" << endl;
return( 1 );
}
if (SIMASS_NO_ERROR != oSimAssPtr->run(&oGroup, SourceList, DetectorList))
{
cout << "error in main(): SimAss.run() returned an error" << endl;
return( 1 );
}
end=clock();
double msecs;
msecs=((end-start)/(double)CLOCKS_PER_SEC*1000.0);
cout << endl;
cout << msecs <<"ms to run the whole simulation." << endl;
if (layoutMode)
{
// wait for user to hit enter to end the program
wait();
}
/************************************************************/
/* Clean Up */
/************************************************************/
if (SourceList != NULL)
{
for (int j=0; j<sourceNumber;j++)
{
delete SourceList[j];
SourceList[j]=NULL;
}
delete SourceList;
SourceList=NULL;
}
if (DetectorList != NULL)
{
for (int j=0; j<detNumber;j++)
{
delete (DetectorList[j]);
DetectorList[j]=NULL;
}
delete DetectorList;
DetectorList=NULL;
}
if (oSimAssPtr != NULL)
{
delete oSimAssPtr;
oSimAssPtr=NULL;
}
return( 0 );
}
bool runSimulation(char *xmlInput, Field** fieldOut_ptrptr, bool *breakCondition)
{
return true;
}
void printUsageAndExit( const char* argv0 )
{
fprintf( stderr, "Usage : %s [options]\n", argv0 );
fprintf( stderr, "Options: --help | -h Print this usage message\n" );
fprintf( stderr, " --dim=<width>x<height> Set image dimensions; defaults to 512x384\n" );
exit(0);
}
unsigned int createGaussianBeamRaysTest(GaussBeamRayField **ptrptrRayField, double2 width, double2 offsetIn, long2 nrBeamlets, double lambda)
{
unsigned long long ix=0;
unsigned long long iy=0;
if (*ptrptrRayField != NULL)
{
cout <<"error in createGaussianBeamRaysTest(): ptrptrRayField is not NULL." << endl;
return 0; // return error
}
*ptrptrRayField = new GaussBeamRayField(nrBeamlets.x*nrBeamlets.y);
gaussBeamRayStruct *rayList=(*(ptrptrRayField))->getRayList();
double2 offset=offsetIn;
//// waist ray in x
//rayList[0].waistRayX.position=make_double3(-750,0,500);
//rayList[0].waistRayX.direction=make_double3(0,0,1);
//// waist ray in y
//rayList[0].waistRayY.position=make_double3(0,-750,500);
//rayList[0].waistRayY.direction=make_double3(0,0,1);
//// div Ray in y
//rayList[0].divRayY.position=make_double3(0,-2.1220659078919,500);
//rayList[0].divRayY.direction=make_double3(0,-0.004244093592259,0.999990993794234);
//// div Ray in x
//rayList[0].divRayX.position=make_double3(-2.1220659078919,0,500);
//rayList[0].divRayX.direction=make_double3(-0.004244093592259,0,0.999990993794234);
//// base ray
//rayList[0].baseRay.position=make_double3(0,0,500);
//rayList[0].baseRay.direction=make_double3(0,0,1);
//rayList[0].baseRay.lambda=lambda;
//rayList[0].baseRay.flux=100000000000;
//rayList[0].baseRay.depth=0;
//rayList[0].baseRay.nImmersed=1;
//rayList[0].baseRay.currentGeometryID=0;
//rayList[0].baseRay.opl=500;
for (ix=0;ix<nrBeamlets.x;ix++)
{
for (iy=0;iy<nrBeamlets.y;iy++)
{
double z=0;
double3 r0;
double2 w0;
if (nrBeamlets.x==1)
{
r0.x=offset.x;
w0.x=width.x;
}
else
{
r0.x=-width.x/2+width.x/nrBeamlets.x*ix+offset.x;
w0.x=width.x/(nrBeamlets.x-1)*1.6;
}
if (nrBeamlets.y==1)
{
r0.y=offset.y;
w0.y=width.y;
}
else
{
r0.y=-width.y/2+width.y/nrBeamlets.y*iy+offset.y;
w0.y=width.y/(nrBeamlets.y-1)*1.6;
}
r0.z=z;
// create geometric rays representing the beamlets
// waist ray in x
rayList[ix+nrBeamlets.x*iy].waistRayX.position=make_double3((r0.x-w0.x),r0.y,r0.z);
rayList[ix+nrBeamlets.x*iy].waistRayX.direction=make_double3(0,0,1);
// waist ray in y
rayList[ix+nrBeamlets.x*iy].waistRayY.position=make_double3(r0.x,(r0.y-w0.y),r0.z);
rayList[ix+nrBeamlets.x*iy].waistRayY.direction=make_double3(0,0,1);
// div Ray in y
rayList[ix+nrBeamlets.x*iy].divRayY.position=r0;
rayList[ix+nrBeamlets.x*iy].divRayY.direction.x=0;
rayList[ix+nrBeamlets.x*iy].divRayY.direction.y=cos(PI/2+atan(lambda/(PI*w0.y)));
rayList[ix+nrBeamlets.x*iy].divRayY.direction.z=sqrt(1-pow(rayList[ix+nrBeamlets.x*iy].divRayY.direction.y,2));
// div Ray in x
rayList[ix+nrBeamlets.x*iy].divRayX.position=r0;
rayList[ix+nrBeamlets.x*iy].divRayX.direction.x=cos(PI/2+atan(lambda/(PI*w0.x)));
rayList[ix+nrBeamlets.x*iy].divRayX.direction.y=0;
rayList[ix+nrBeamlets.x*iy].divRayX.direction.z=sqrt(1-pow(rayList[ix+nrBeamlets.x*iy].divRayX.direction.x,2));
// base ray
rayList[ix+nrBeamlets.x*iy].baseRay.position=r0;
rayList[ix+nrBeamlets.x*iy].baseRay.direction=make_double3(0,0,1);
rayList[ix+nrBeamlets.x*iy].baseRay.lambda=lambda;
rayList[ix+nrBeamlets.x*iy].baseRay.flux=1;
rayList[ix+nrBeamlets.x*iy].baseRay.depth=0;
rayList[ix+nrBeamlets.x*iy].baseRay.nImmersed=1;
rayList[ix+nrBeamlets.x*iy].baseRay.currentGeometryID=0;
rayList[ix+nrBeamlets.x*iy].baseRay.opl=0;
}
}
return 1; // signal success
}
void testInterpolator()
{
unsigned long N=51;
double*x=(double*)calloc(N,sizeof(double));
double*y=(double*)calloc(N,sizeof(double));
double xmax=10;
double ymax=10;
double dx=2*xmax/N;
double dy=2*ymax/N;
for (unsigned int j=0;j<N;j++)
{
x[j]=-1.0*xmax+j*dx;
y[j]=-1.0*ymax+j*dy;
}
complex<double> *Uin=(complex<double>*)calloc(N*N,sizeof(complex<double>));
// double *UinAbs=(double*)calloc(N*N,sizeof(double));
double periodX=5;
double periodY=10;
for (unsigned int jx=0;jx<N;jx++)
{
for (unsigned int jy=0;jy<N;jy++)
{
Uin[jx+jy*N]=complex<double>(cos(2*M_PI/periodX*x[jx])+1,M_PI*cos(2*M_PI/periodY*y[jy]));
// UinAbs[jx+jy*N]=cos(2*M_PI/periodX*x[jx])+1;
}
}
char t_filename[512] = "Real.txt";
FILE* hFileReal;
hFileReal = fopen( t_filename, "w" ) ;
sprintf(t_filename, "Imag.txt");
FILE* hFileImag;
hFileImag = fopen( t_filename, "w" ) ;
// if ( (hFileReal == NULL) || (hFileImag == NULL) )
// return 1;
for (unsigned int jy=0;jy<N;jy++)
{
for (unsigned int jx=0;jx<N;jx++)
{
if (jx+1 == N)
{
// fprintf(hFileReal, " %.16e;\n", UinAbs[jx+jy*N]);
fprintf(hFileReal, " %.16e;\n", Uin[jx+jy*N].real());
fprintf(hFileImag, " %.16e;\n", Uin[jx+jy*N].imag());
}
else
{
// fprintf(hFileReal, " %.16e;", UinAbs[jx+jy*N]);
fprintf(hFileReal, " %.16e;", Uin[jx+jy*N].real());
fprintf(hFileImag, " %.16e;", Uin[jx+jy*N].imag());
}
}
}
fclose(hFileReal);
fclose(hFileImag);
Interpolator oInterp;
oInterp.initInterpolation(x, y, Uin, N, N);
//oInterp.initInterpolation(x, y, UinAbs, N, N);
sprintf(t_filename, "Real.txt");
hFileReal = fopen( t_filename, "w" ) ;
sprintf(t_filename, "Imag.txt");
hFileImag = fopen( t_filename, "w" ) ;
// if ( (hFileReal == NULL) || (hFileImag == NULL) )
// return 1;
for (unsigned int jy=0;jy<N;jy++)
{
for (unsigned int jx=0;jx<N;jx++)
{
if (jx+1 == N)
{
// fprintf(hFileReal, " %.16e;\n", UinAbs[jx+jy*N]);
fprintf(hFileReal, " %.16e;\n", oInterp.y2ca_ptr[jx+jy*N].real());
fprintf(hFileImag, " %.16e;\n", oInterp.y2ca_ptr[jx+jy*N].imag());
}
else
{
// fprintf(hFileReal, " %.16e;", UinAbs[jx+jy*N]);
fprintf(hFileReal, " %.16e;", oInterp.y2ca_ptr[jx+jy*N].real());
fprintf(hFileImag, " %.16e;", oInterp.y2ca_ptr[jx+jy*N].imag());
}
}
}
fclose(hFileReal);
fclose(hFileImag);
unsigned long NInterpX=256;
unsigned long NInterpY=256;
double*xInterp=(double*)calloc(NInterpX,sizeof(double));
double*yInterp=(double*)calloc(NInterpY,sizeof(double));
complex<double> *UinInterp=(complex<double>*)calloc(NInterpX*NInterpY,sizeof(complex<double>));
double *UinAbsInterp=(double*)calloc(NInterpX*NInterpY,sizeof(double));
double dxInterp=2*xmax/NInterpX;
double dyInterp=2*ymax/NInterpY;
for (unsigned int j=0;j<NInterpX;j++)
{
xInterp[j]=-1.0*xmax+j*dxInterp;
}
for (unsigned int j=0;j<NInterpY;j++)
{
yInterp[j]=-1.0*ymax+j*dyInterp;
}
for (unsigned int jy=0;jy<NInterpY;jy++)
{
for (unsigned int jx=0;jx<NInterpX;jx++)
{
oInterp.doInterpolation(x, y, N, N, Uin, xInterp[jx], yInterp[jy], &UinInterp[jx+jy*NInterpX]);
// oInterp.doInterpolation(x, y, N, N, UinAbs, xInterp[jx], yInterp[jy], &UinAbsInterp[jx+jy*NInterpX]);
}
}
sprintf(t_filename, "RealInterp.txt");
hFileReal = fopen( t_filename, "w" ) ;
sprintf(t_filename, "ImagInterp.txt");
hFileImag = fopen( t_filename, "w" ) ;
// if ( (hFileReal == NULL) || (hFileImag == NULL) )
// return 1;
for (unsigned int jy=0;jy<NInterpY;jy++)
{
for (unsigned int jx=0;jx<NInterpX;jx++)
{
if (jx+1 == NInterpY)
{
// fprintf(hFileReal, " %.16e;\n", UinAbsInterp[jx+jy*NInterp]);
fprintf(hFileReal, " %.16e;\n", UinInterp[jx+jy*NInterpX].real());
fprintf(hFileImag, " %.16e;\n", UinInterp[jx+jy*NInterpX].imag());
}
else
{
// fprintf(hFileReal, " %.16e;", UinAbsInterp[jx+jy*NInterp]);
fprintf(hFileReal, " %.16e;", UinInterp[jx+jy*NInterpX].real());
fprintf(hFileImag, " %.16e;", UinInterp[jx+jy*NInterpX].imag());
}
}
}
fclose(hFileReal);
fclose(hFileImag);
// cleanup
delete xInterp;
delete yInterp;
delete x;
delete y;
delete UinInterp;
delete Uin;
};
/**
* \detail createSceneFromXML
*
* parses the XML and creates an OptiX scene
*
* \param[in] Group *oGroupPtr, FILE *hfile, RayField ***sourceListPtr, long long *sourceNumberPtr, Detector ***detListPtr, long long *detNumberPtr, simMode mode
*
* \return bool
* \sa
* \remarks
* \author Mauch
*/
bool createSceneFromXML(Group *oGroupPtr, FILE *hfile, RayField ***sourceListPtr, Detector ***detListPtr)
{
cout <<"********************************************" << endl;
cout <<"starting to parse prescritpion files..." << endl;
xml_document doc;
xml_parse_result result=doc.load_file("myXml.xml");
// get the root element
xml_node scene =doc.first_child();
if (strcmp(scene.name(), "scene") != 0)
{
cout << "error in createSceneFromXML: Root element of file is not scene. File is not a valid scene description" << endl;
return false;
}
// create instance of xml parser
Parser_XML* l_pParser=new Parser_XML();
// read simulation mode from xml file
simMode l_mode;
const char* l_pModeString=l_pParser->attrValByName(scene, "mode");
if (strcmp(l_pModeString,"GEOMRAYS_SEQ") == 0)
l_mode=SIM_GEOMRAYS_SEQ;
if (strcmp(l_pModeString,"GEOMRAYS_NONSEQ") == 0)
l_mode=SIM_GEOMRAYS_NONSEQ;
// get number all geometryGroups
vector<xml_node>* l_pGeometryGroups;
l_pGeometryGroups=l_pParser->childsByTagName(scene, "geometryGroup");
/* set number of geometry groups */
if (GROUP_NO_ERR != oGroupPtr->setGeometryGroupListLength(l_pGeometryGroups->size()) )
{
std::cout <<"error in Parser.createSceneFromZemax(): group.setGeometryGroupListLength(1) returned an error" << std::endl;
return false;
}
/* create geometryGroups inside the group */
for (int i=0; i<l_pGeometryGroups->size(); i++)
{
if (GROUP_NO_ERR != oGroupPtr->createGeometryGroup(i) )
{
std::cout <<"error in Parser_XML.createSceneFromXML(): group.createGeometryGroup(" << i << ") returned an error" << std::endl;
return false;
}
// determine number of surfaces in the current geometryGroup
int nrSurfaces=0;
for (xml_node child = l_pGeometryGroups->at(i).first_child(); child; child=child.next_sibling())
{
// check wether child is geometry
if ( strcmp(child.name(), "geometry") == 0)
{
const char* t_str;
switch (l_mode)
{
case SIM_GEOMRAYS_SEQ:
t_str = l_pParser->attrValByName(child, "nrSurfacesSeq");
if (t_str==NULL)
{
cout << "error in createSceneFromXML: nrSurfacesSeq is not defined for current node." << endl;
return false;
}
nrSurfaces=nrSurfaces+atoi(t_str);
break;
case SIM_GEOMRAYS_NONSEQ:
t_str = l_pParser->attrValByName(child, "nrSurfacesNonSeq");
if (t_str==NULL)
{
cout << "error in createSceneFromXML: nrSurfacesNonSeq is not defined for current node." << endl;
return false;
}
nrSurfaces=nrSurfaces+atoi(t_str);
break;
default:
cout << "error in createSceneFromXML: unknown simulation mode." << endl;
}
}
}
// collect all geometry nodes from the current geometryGroup
vector<xml_node>* l_pGeometries = l_pParser->childsByTagName(l_pGeometryGroups->at(i),"geometry");
/* set number of geometries in current geometryGroup*/
if (GEOMGROUP_NO_ERR != oGroupPtr->getGeometryGroup(i)->setGeometryListLength(nrSurfaces) )
{
std::cout <<"error in Parser_XML.createSceneFromXML(): group.getGeometryGroup(" << i << ")->setGeometryListLength(" << nrSurfaces << ") returned an error" << std::endl;
return false;
}
GeometryFab l_GeomFab;
int globalSurfaceCount=0; // as some of the geometries consist of different number of surfaces in different simulation modes, we need to keep track of the number of surfaces in each geometryGroup here...
// now, create the objects and add them to current geometryGroup
for (int j=0; j<l_pGeometries->size(); j++)
{
vector<Geometry*> l_geomVec;
l_geomVec=l_GeomFab.createGeomInstFromXML(l_pGeometries->at(j), l_mode);
if (l_geomVec.size() == 0)
{
cout << "error in createSceneFromXML: l_GeomFab.createGeomInstFromXML() returned nothing for given XML node " << j << "in geometryGroup " << i << endl;
return false;
}
for (int k=0; k<l_geomVec.size(); k++)
{
if (GEOMGROUP_NO_ERR != oGroupPtr->getGeometryGroup(i)->setGeometry(l_geomVec.at(k),globalSurfaceCount))
{
cout << "error in createSceneFromXML: getGeometryGroup(i)->setGeometry() returned an error at index" << k << endl;
return false;
}
globalSurfaceCount++;
}
}
}
delete l_pParser;
return true;
} | [
"[email protected]"
] | |
431f3cc025e45dade03efa095592fa7438093e1e | 0c1611d72f22471338901d0b48d5b980f5aa62c1 | /C++/SBR_SPOTCheck_1.0_Sprint_26/lib/platform/Windows/GSystemImpl.cpp | 146af58145c8dd04db65033ff04665da25b0b9f2 | [] | no_license | marianovolker/jmps-public | 67319a34fa7e677292ed01d2767611b8d9259cc2 | b2ca4a6921974e78a2dd128688d42beca121eec6 | refs/heads/master | 2021-01-20T19:09:11.424069 | 2018-03-29T18:51:38 | 2018-03-29T18:51:38 | 62,237,468 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,883 | cpp | // GSystem.cpp
//
// Telium implementation of the GSystem class.
#include <stdio.h>
#include <sys/stat.h>
#include <time.h>
#include <algorithm>
#include <stdexcept>
#include "GWindows.h"
#include "GSystemImpl.h"
#include "GFile.h"
#include <stdarg.h>
#include <string.h>
// GSystemImpl
GSystemImpl::TimeStamp::TimeStamp (void)
: second(0),
minute(0),
hour(0),
day(0),
month(0),
year(0)
{
}
GSystemImpl::TimeStamp::~TimeStamp (void)
{
second = 0;
minute = 0;
hour = 0;
day = 0;
month = 0;
year = 0;
}
bool GSystemImpl::TimeStamp::operator == (GSystemImpl::TimeStamp const & rhs) const
{
return ((second == rhs.second) && (minute == rhs.minute) && (hour == rhs.hour) && (day == rhs.day) && (month == rhs.month) && (year == rhs.year));
}
bool GSystemImpl::TimeStamp::operator != (GSystemImpl::TimeStamp const & rhs) const
{
return !((*this) == rhs);
}
GMutex GSystemImpl::m_TraceMutex;
GTaskId GSystemImpl::GetTaskId(void)
{
GTaskId gTaskId(eInvalidTaskId);
{
DWORD dwTaskId(::GetCurrentThreadId());
if (dwTaskId != 0)
{
gTaskId = static_cast<GTaskId>(dwTaskId);
}
}
return gTaskId;
}
void GSystemImpl::Sleep(unsigned int msec)
{
::Sleep(msec);
}
void GSystemImpl::Yield(void)
{
::Sleep(0);
}
bool GSystemImpl::Trace(const char *pMsg)
{
GMutexLock Lock(m_TraceMutex);
printf(pMsg);
fflush(stdout);
return true;
}
// GetTickCount() - Get running tick count (in ms) since system startup.
unsigned long GSystemImpl::GetTickCount(void)
{
return ::GetTickCount();
}
bool GSystemImpl::RenameFile(const char *pOldPath, const char *pNewPath)
{
return (rename(pOldPath,pNewPath) == 0);
}
bool GSystemImpl::RemoveFile(const char *pPath)
{
std::string windowsStypePath = GSystemImpl::ConvertPathToWindowsStyle(pPath);
return (unlink(windowsStypePath.c_str()) == 0);
}
bool GSystemImpl::FileExist(const char *pPath)
{
struct stat buf;
return (stat(pPath,&buf) == 0);
}
bool GSystemImpl::MakeDir(const char *pPath)
{
return CreateDirectory(pPath, NULL)?true:false;
}
GSystemImpl::TimeStamp GSystemImpl::FileTime(const char *pPath)
{
GSystemImpl::TimeStamp res;
struct stat buf;
if(stat(pPath,&buf) == 0)
{
struct tm * pFileTimeStamp;
pFileTimeStamp = localtime(&buf.st_mtime);
if (pFileTimeStamp != NULL)
{
res.second = pFileTimeStamp->tm_sec;
res.minute = pFileTimeStamp->tm_min;
res.hour = pFileTimeStamp->tm_hour;
res.day = pFileTimeStamp->tm_mday;
res.month = pFileTimeStamp->tm_mon;
res.year = pFileTimeStamp->tm_year;
}
}
return res;
}
std::list < std::pair <std::string, bool> > GSystemImpl::GetDirEntryList (std::string sPath)
{
std::list < std::pair <std::string, bool> > lEntryList;
WIN32_FIND_DATA FindFileData;
std::string windowsStypePath = GSystemImpl::ConvertPathToWindowsStyle(sPath);
if( windowsStypePath[windowsStypePath.size()-1] != '\\') windowsStypePath += "\\";
windowsStypePath += "*";
HANDLE hFind = FindFirstFile(windowsStypePath.c_str(), &FindFileData);
if(hFind != INVALID_HANDLE_VALUE)
{
do
{
lEntryList.push_back(std::list < std::pair <std::string, bool> >::value_type(FindFileData.cFileName,false));
}
while (FindNextFile(hFind, &FindFileData) != 0);
}
return lEntryList;
}
std::string GSystemImpl::ConvertPathToWindowsStyle(std::string sPath)
{
std::string windowsStypePath(sPath);
std::replace(windowsStypePath.begin(), windowsStypePath.end(), '/', '\\');
return windowsStypePath;
}
bool GSystemImpl::CopyFile (std::string sSrc, std::string sDst)
{
GFile oSrc(GSystemImpl::ConvertPathToWindowsStyle(sSrc));
GFile oDst(GSystemImpl::ConvertPathToWindowsStyle(sDst));
bool bContinue(false);
if (!oSrc.Open(eOpenReadOnly))
{
return false;
//TODO: LOG? throw std::runtime_error("FileCopy cannot open file to read: " + GSystemImpl::ConvertPathToWindowsStyle(sSrc));
}
if (!oDst.Open(eOpenWriteNew))
{
return false;
//TODO: LOG? throw std::runtime_error("FileCopy cannot open file to write: " + GSystemImpl::ConvertPathToWindowsStyle(sDst));
}
static int const CBufferLength(1024);
unsigned char ucBuffer[CBufferLength];
int iBytesRead(0);
int iTotalBytesWrote(0);
bContinue = oSrc.Read(ucBuffer,CBufferLength,iBytesRead);
while ((iBytesRead > 0) && bContinue)
{
int iBytesOffset(0);
while ((iBytesRead > 0) && bContinue)
{
int iBytesWrote(0);
bContinue = oDst.Write(ucBuffer+iBytesOffset, iBytesRead, iBytesWrote);
if (bContinue == true)
{
iBytesRead -= iBytesWrote;
iBytesOffset += iBytesWrote;
}
iTotalBytesWrote += iBytesWrote;
}
bContinue = oSrc.Read(ucBuffer,CBufferLength,iBytesRead);
}
oDst.Close();
oSrc.Close();
return bContinue;
}
// HostIsBigEndian() - Return true if host is big endian.
bool GSystemImpl::HostIsBigEndian(void)
{
return false;
}
// HostIsLittleEndian() - Return true if host is little endian.
bool GSystemImpl::HostIsLittleEndian(void)
{
return true;
}
bool GSystemImpl::ReadLink(const std::string& sLinkName, std::string& sRealName, int maxLength)
{
(void)sLinkName;
(void)sRealName;
(void)maxLength;
return false;
}
struct tm* GSystemImpl::LocalTime(const time_t* pt, struct tm * ptm)
{
static GMutex AuxWinLocaltimeMutex;
AuxWinLocaltimeMutex.Lock();
// original struct is stored in static buffer into glibc !!!
// local stack copy is secured by mutex protection
*ptm = * localtime(pt);
AuxWinLocaltimeMutex.Unlock();
return ptm;
}
void GSystemImpl::Perror(const char *format, va_list args)
{
char arycbuffer[256];
memset(arycbuffer, 0, sizeof(arycbuffer));
vsnprintf(arycbuffer, (sizeof(arycbuffer)-1), format, args);
perror(arycbuffer);
}
| [
"[email protected]"
] | |
cb6624dd90ea500360a5f933926f83e6511a3c1c | 99b28144e25adde1cc633592329f67973fe133cc | /10. Arbol Binario Apuntadores/main.cpp | cfb400bfa16b223fcfb575c8f0a7b673d3f2c5a5 | [] | no_license | daniii3012/CienciasComputacion_I | 4f4d904af0345d4bfc0ff860af51977ec64f385f | 4198c1f2a49c511ee1ce12227c8cadfc7caa0767 | refs/heads/master | 2020-05-30T14:32:23.497531 | 2019-07-17T18:47:51 | 2019-07-17T18:47:51 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 650 | cpp | #include <iostream>
#include "Arbol.h"
#include "Estructura.h"
using namespace std;
int main(){
arbinor<int> a;
nodo<int> *p;
int i;
cout << "Número a insertar? (fin =999)..."<< endl;
cin >> i;
while(i!=999){
if (a.insertar(i)==-1)
cout<<"Ya existe"<< endl;
cout << "Número a insertar? (fin =999)..."<< endl;
cin >> i;
}
cout << "Número a retirar (fin=999)" << endl;
cin>>i;
while(i!=999){
if (a.eliminar(i)==-1)
cout << "No existe" << endl;
cout << "Número a retirar (fin=999)" << endl;
cin >> i;
}
a.inorden(a.reRaiz());
a.preorden(a.reRaiz());
a.posorden(a.reRaiz());
return 0;
}
| [
"[email protected]"
] | |
e0fff182331a4f21714d78ef54f959a5290cb17f | b32cd88c9dee5bbbc724f09224b6fde33d416e97 | /replay_pass3/replay_pass3.cpp | 4cb6277a48910b5d553eb298dfd9518d97cbac1a | [] | no_license | ballgeier/ParallelAnalyzer | 41138498dff257457fcf730ff23105038ac89dac | 6b602f112b352d06237eef65ab9f0e6c4985aec1 | refs/heads/master | 2021-01-10T21:10:10.376421 | 2015-05-19T16:44:39 | 2015-05-19T16:44:39 | 35,894,391 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,192 | cpp | #include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>
#include <sstream>
// ROOT libraries
#include "TRandom3.h"
#include <TTree.h>
#include <TFile.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TF1.h>
#include <TH1D.h>
#include "fullTreeVariables.h"
#include "MWPCGeometry.h"
#include "pedestals.h"
#include "cuts.h"
#include "basic_reconstruction.h"
#include "replay_pass2.h"
#include "replay_pass3.h"
using namespace std;
int main(int argc, char *argv[])
{
cout.setf(ios::fixed, ios::floatfield);
cout.precision(12);
// Position bins
int nPMT = 8;
int nPosBinsX = 43;
int nPosBinsY = 43;
double xBinWidth = 2.5;
double yBinWidth = 2.5;
double xBinLower[nPosBinsX];
double xBinUpper[nPosBinsX];
double xBinCenter[nPosBinsX];
double yBinLower[nPosBinsY];
double yBinUpper[nPosBinsY];
double yBinCenter[nPosBinsY];
int intXBinCenter[nPosBinsX];
int intYBinCenter[nPosBinsY];
for (int k=0; k<nPosBinsX; k++) {
xBinLower[k] = -(double)nPosBinsX*xBinWidth/2. + ((double) k)*xBinWidth;
xBinUpper[k] = -(double)nPosBinsX*xBinWidth/2. + ((double) k)*xBinWidth + xBinWidth;
xBinCenter[k] = (xBinLower[k] + xBinUpper[k])/2.;
intXBinCenter[k] = (int) xBinCenter[k];
//cout << xBinLower[k] << " " << intXBinCenter[k] << " " << xBinUpper[k] << endl;
}
for (int k=0; k<nPosBinsY; k++) {
yBinLower[k] = -(double)nPosBinsY*yBinWidth/2. + ((double) k)*yBinWidth;
yBinUpper[k] = -(double)nPosBinsY*yBinWidth/2. + ((double) k)*yBinWidth + yBinWidth;
yBinCenter[k] = (yBinLower[k] + yBinUpper[k])/2.;
intYBinCenter[k] = (int) yBinCenter[k];
//cout << yBinLower[k] << " " << intYBinCenter[k] << " " << yBinUpper[k] << endl;
}
// Run number integer
cout << "Run " << argv[1] << " ..." << endl;
cout << "... Applying Xe position map ..." << endl;
istringstream ss(argv[1]);
int runNumber;
ss >> runNumber;
// Determine position map to use
char tempFileXePositionMap[500];
if (runNumber < 18081) {
sprintf(tempFileXePositionMap, "../position_map/position_map_2.dat");
}
else if (runNumber < 18390) {
sprintf(tempFileXePositionMap, "../position_map/position_map_3.dat");
}
else if (runNumber < 18712) {
sprintf(tempFileXePositionMap, "../position_map/position_map_4.dat");
}
else if (runNumber < 19589) {
sprintf(tempFileXePositionMap, "../position_map/position_map_5.dat");
}
//else if (runNumber < 19873) {
//sprintf(tempFileXePositionMap, "../position_map/position_map_6.dat");
//}
else if (runNumber < 19967) {
sprintf(tempFileXePositionMap, "../position_map/position_map_7.dat");
}
cout << "... Reading: " << tempFileXePositionMap << endl;
// Read position map
double x, y;
double positionMap[nPMT][nPosBinsX][nPosBinsY];
ifstream fileXePositionMap(tempFileXePositionMap);
for (int i=0; i<nPosBinsX; i++) {
for (int j=0; j<nPosBinsY; j++) {
fileXePositionMap >> x >> y
>> positionMap[0][i][j]
>> positionMap[1][i][j]
>> positionMap[2][i][j]
>> positionMap[3][i][j]
>> positionMap[4][i][j]
>> positionMap[5][i][j]
>> positionMap[6][i][j]
>> positionMap[7][i][j];
}
}
// Calculate (x,y) correction factor: eta = 1/positionMap
double eta[nPMT][nPosBinsX][nPosBinsY];
for (int i=0; i<nPosBinsX; i++) {
for (int j=0; j<nPosBinsY; j++) {
eta[0][i][j] = 1. / positionMap[0][i][j];
eta[1][i][j] = 1. / positionMap[1][i][j];
eta[2][i][j] = 1. / positionMap[2][i][j];
eta[3][i][j] = 1. / positionMap[3][i][j];
eta[4][i][j] = 1. / positionMap[4][i][j];
eta[5][i][j] = 1. / positionMap[5][i][j];
eta[6][i][j] = 1. / positionMap[6][i][j];
eta[7][i][j] = 1. / positionMap[7][i][j];
}
}
// Open output ntuple
char tempOut[500];
sprintf(tempOut, "/extern/UCNA/replay_pass3_MB/replay_pass3_%s.root", argv[1]);
TFile *fileOut = new TFile(tempOut,"RECREATE");
TTree *Tout = new TTree("pass3", "pass3");
// Variables
Tout->Branch("pmt0_pass3", &pmt_pass3[0], "pmt0_pass3/D");
Tout->Branch("pmt1_pass3", &pmt_pass3[1], "pmt1_pass3/D");
Tout->Branch("pmt2_pass3", &pmt_pass3[2], "pmt2_pass3/D");
Tout->Branch("pmt3_pass3", &pmt_pass3[3], "pmt3_pass3/D");
Tout->Branch("pmt4_pass3", &pmt_pass3[4], "pmt4_pass3/D");
Tout->Branch("pmt5_pass3", &pmt_pass3[5], "pmt5_pass3/D");
Tout->Branch("pmt6_pass3", &pmt_pass3[6], "pmt6_pass3/D");
Tout->Branch("pmt7_pass3", &pmt_pass3[7], "pmt7_pass3/D");
Tout->Branch("xE_pass3", &xE_pass3, "xE_pass3/D");
Tout->Branch("yE_pass3", &yE_pass3, "yE_pass3/D");
Tout->Branch("xW_pass3", &xW_pass3, "xW_pass3/D");
Tout->Branch("yW_pass3", &yW_pass3, "yW_pass3/D");
Tout->Branch("PID_pass3", &PID_pass3, "PID_pass3/I");
Tout->Branch("type_pass3", &type_pass3, "type_pass3/I");
Tout->Branch("side_pass3", &side_pass3, "side_pass3/I");
Tout->Branch("posError_pass3", &posError_pass3, "posError_pass3/I");
// Open input ntuple
char tempIn[500];
sprintf(tempIn, "/extern/UCNA/replay_pass2/replay_pass2_%s.root", argv[1]);
TFile *fileIn = new TFile(tempIn, "READ");
TTree *Tin = (TTree*)(fileIn->Get("pass2"));
// Variables
Tin->SetBranchAddress("pmt0_pass2", &pmt_pass2[0]);
Tin->SetBranchAddress("pmt1_pass2", &pmt_pass2[1]);
Tin->SetBranchAddress("pmt2_pass2", &pmt_pass2[2]);
Tin->SetBranchAddress("pmt3_pass2", &pmt_pass2[3]);
Tin->SetBranchAddress("pmt4_pass2", &pmt_pass2[4]);
Tin->SetBranchAddress("pmt5_pass2", &pmt_pass2[5]);
Tin->SetBranchAddress("pmt6_pass2", &pmt_pass2[6]);
Tin->SetBranchAddress("pmt7_pass2", &pmt_pass2[7]);
Tin->SetBranchAddress("xE_pass2", &xE_pass2);
Tin->SetBranchAddress("yE_pass2", &yE_pass2);
Tin->SetBranchAddress("xW_pass2", &xW_pass2);
Tin->SetBranchAddress("yW_pass2", &yW_pass2);
Tin->SetBranchAddress("PID_pass2", &PID_pass2);
Tin->SetBranchAddress("type_pass2", &type_pass2);
Tin->SetBranchAddress("side_pass2", &side_pass2);
Tin->SetBranchAddress("posError_pass2", &posError_pass2);
int nEvents = Tin->GetEntries();
cout << "... Processing nEvents = " << nEvents << endl;
// Loop over events
for (int i=0; i<nEvents; i++) {
Tin->GetEvent(i);
// Determine (x,y) bin
int intEastBinX = -1;
int intEastBinY = -1;
int intWestBinX = -1;
int intWestBinY = -1;
for (int m=0; m<nPosBinsX; m++) {
if ( (xE_pass2 >= xBinLower[m]) && (xE_pass2 < xBinUpper[m]) ) intEastBinX = m;
if ( (xW_pass2 >= xBinLower[m]) && (xW_pass2 < xBinUpper[m]) ) intWestBinX = m;
}
for (int m=0; m<nPosBinsY; m++) {
if ( (yE_pass2 >= yBinLower[m]) && (yE_pass2 < yBinUpper[m]) ) intEastBinY = m;
if ( (yW_pass2 >= yBinLower[m]) && (yW_pass2 < yBinUpper[m]) ) intWestBinY = m;
}
// Apply (x,y) correction factor
if (intEastBinX > -1 && intEastBinY > -1) {
pmt_pass3[0] = pmt_pass2[0] * eta[0][intEastBinX][intEastBinY];
pmt_pass3[1] = pmt_pass2[1] * eta[1][intEastBinX][intEastBinY];
pmt_pass3[2] = pmt_pass2[2] * eta[2][intEastBinX][intEastBinY];
pmt_pass3[3] = pmt_pass2[3] * eta[3][intEastBinX][intEastBinY];
}
else {
pmt_pass3[0] = pmt_pass2[0];
pmt_pass3[1] = pmt_pass2[1];
pmt_pass3[2] = pmt_pass2[2];
pmt_pass3[3] = pmt_pass2[3];
}
if (intWestBinX > -1 && intWestBinY > -1) {
pmt_pass3[4] = pmt_pass2[4] * eta[4][intWestBinX][intWestBinY];
pmt_pass3[5] = pmt_pass2[5] * eta[5][intWestBinX][intWestBinY];
pmt_pass3[6] = pmt_pass2[6] * eta[6][intWestBinX][intWestBinY];
pmt_pass3[7] = pmt_pass2[7] * eta[7][intWestBinX][intWestBinY];
}
else {
pmt_pass3[4] = pmt_pass2[4];
pmt_pass3[5] = pmt_pass2[5];
pmt_pass3[6] = pmt_pass2[6];
pmt_pass3[7] = pmt_pass2[7];
}
// Pass other variables from pass2 to pass3
xE_pass3 = xE_pass2;
yE_pass3 = yE_pass2;
xW_pass3 = xW_pass2;
yW_pass3 = yW_pass2;
PID_pass3 = PID_pass2;
type_pass3 = type_pass2;
side_pass3 = side_pass2;
posError_pass3 = posError_pass2;
Tout->Fill();
}
// Write output ntuple
fileOut->Write();
fileOut->Close();
return 0;
}
| [
"[email protected]"
] | |
f4efd9277170d5d74765697e4a3652ec9e0f3fce | 4bb6596f5a9de84faca5a086b76c7a3ce3b3c162 | /PasteLineAction.h | a329d41c9dee3cffb2efb267f898d6d66abbfd76 | [] | no_license | donovan680/Paint-for-kids | a7b14417a661fdf393d1d7ac7286ce5517ba8bad | b83dca0ee953adc6040a96d85bfbd1aea5a27f27 | refs/heads/master | 2021-10-12T04:47:22.024286 | 2019-02-02T04:20:14 | 2019-02-02T04:20:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 294 | h | #pragma once
#include "Actions\Action.h"
class PasteLineAction:public Action
{
private:
Point temp;
Point P1;
Point P2;
GfxInfo LineGfxInfo;
public:
PasteLineAction(ApplicationManager *pApp);
void ReadActionParameters();
void Execute();
~PasteLineAction();
};
| [
"[email protected]"
] | |
695a9ba37591ca18c4bc415152b25c6e5f78467f | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /dms-enterprise/include/alibabacloud/dms-enterprise/model/SetOwnersRequest.h | 6467e11352fc2baf0d33d21de540e6a88426d6fd | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,703 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_DMS_ENTERPRISE_MODEL_SETOWNERSREQUEST_H_
#define ALIBABACLOUD_DMS_ENTERPRISE_MODEL_SETOWNERSREQUEST_H_
#include <alibabacloud/dms-enterprise/Dms_enterpriseExport.h>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <string>
#include <vector>
#include <map>
namespace AlibabaCloud {
namespace Dms_enterprise {
namespace Model {
class ALIBABACLOUD_DMS_ENTERPRISE_EXPORT SetOwnersRequest : public RpcServiceRequest {
public:
SetOwnersRequest();
~SetOwnersRequest();
std::string getOwnerIds() const;
void setOwnerIds(const std::string &ownerIds);
long getTid() const;
void setTid(long tid);
std::string getResourceId() const;
void setResourceId(const std::string &resourceId);
std::string getOwnerType() const;
void setOwnerType(const std::string &ownerType);
private:
std::string ownerIds_;
long tid_;
std::string resourceId_;
std::string ownerType_;
};
} // namespace Model
} // namespace Dms_enterprise
} // namespace AlibabaCloud
#endif // !ALIBABACLOUD_DMS_ENTERPRISE_MODEL_SETOWNERSREQUEST_H_
| [
"[email protected]"
] | |
882f39c0c31159b9f3184b7d14835244493c0957 | 24bc4990e9d0bef6a42a6f86dc783785b10dbd42 | /chrome/browser/autofill/automated_tests/cache_replayer.cc | 5761915fa44cf98ccab2dabb5fc18463110a7565 | [
"BSD-3-Clause"
] | permissive | nwjs/chromium.src | 7736ce86a9a0b810449a3b80a4af15de9ef9115d | 454f26d09b2f6204c096b47f778705eab1e3ba46 | refs/heads/nw75 | 2023-08-31T08:01:39.796085 | 2023-04-19T17:25:53 | 2023-04-19T17:25:53 | 50,512,158 | 161 | 201 | BSD-3-Clause | 2023-05-08T03:19:09 | 2016-01-27T14:17:03 | null | UTF-8 | C++ | false | false | 37,578 | cc | // Copyright 2019 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/autofill/automated_tests/cache_replayer.h"
#include <algorithm>
#include <type_traits>
#include <utility>
#include <vector>
#include "base/base64.h"
#include "base/base64url.h"
#include "base/cancelable_callback.h"
#include "base/command_line.h"
#include "base/containers/contains.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/memory/raw_ptr.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/test/bind.h"
#include "base/types/expected.h"
#include "base/values.h"
#include "net/base/url_util.h"
#include "services/network/public/cpp/data_element.h"
#include "services/network/public/cpp/resource_request.h"
#include "third_party/protobuf/src/google/protobuf/repeated_field.h"
#include "third_party/zlib/google/compression_utils.h"
namespace autofill::test {
using base::JSONParserOptions;
using base::JSONReader;
namespace {
constexpr char kHTTPBodySep[] = "\r\n\r\n";
constexpr char kApiServerDomain[] = "content-autofill.googleapis.com";
constexpr char kApiServerUrlGetPrefix[] =
"https://content-autofill.googleapis.com/v1/pages";
constexpr char kApiServerQueryPath[] = "/v1/pages";
template <typename T>
using ErrorOr = base::expected<T, std::string>;
// Container that represents a JSON node that contains a list of
// request/response pairs sharing the same URL.
struct QueryNode {
// Query URL.
GURL url;
// Value node with requests mapped with |url|.
raw_ptr<const base::Value> node = nullptr;
};
// Gets a hexadecimal representation of a string.
std::string GetHexString(const std::string& input) {
std::string output("0x");
for (auto byte : input) {
base::StringAppendF(&output, "%02x", static_cast<unsigned char>(byte));
}
return output;
}
// Makes HTTP request from a header and body
std::string MakeHTTPTextFromSplit(const std::string& header,
const std::string& body) {
return base::JoinString({header, body}, kHTTPBodySep);
}
// Determines whether replayer should fail if there is an invalid json record.
bool FailOnError(int options) {
return static_cast<bool>(options &
ServerCacheReplayer::kOptionFailOnInvalidJsonRecord);
}
// Determines whether replayer should fail if there is nothing to fill the cache
// with.
bool FailOnEmpty(int options) {
return static_cast<bool>(options & ServerCacheReplayer::kOptionFailOnEmpty);
}
// Determines whether replayer should split and cache each form individually.
bool SplitRequestsByForm(int options) {
return static_cast<bool>(options &
ServerCacheReplayer::kOptionSplitRequestsByForm);
}
// Checks the type of a json value node.
bool CheckNodeType(const base::Value* node,
const std::string& name,
base::Value::Type type) {
if (node == nullptr) {
VLOG(1) << "Did not find any " << name << "field in json";
return false;
}
if (node->type() != type) {
VLOG(1) << "Node value is not of type " << node->type()
<< " when it should be of type " << type;
return false;
}
return true;
}
// Parse AutofillQueryContents or AutofillQueryResponseContents from the given
// |http_text|.
template <class T>
ErrorOr<T> ParseProtoContents(const std::string& http_text) {
T proto_contents;
if (!proto_contents.ParseFromString(http_text)) {
return base::unexpected(
base::StrCat({"could not parse proto:`", proto_contents.GetTypeName(),
"` from raw data:`", GetHexString(http_text), "`."}));
}
return std::move(proto_contents);
}
// Gets base64 encoded query parameter from the URL.
ErrorOr<std::string> GetQueryParameter(const GURL& url) {
std::string value = url.path();
if (value.find(kApiServerQueryPath) != 0) {
// This situation will never happen if check for the query path is
// done before calling this function.
return base::unexpected(
base::StrCat({"could not get any value from query path in "
"Query GET URL: ",
url.spec()}));
}
size_t slash = value.find('/', strlen(kApiServerQueryPath));
if (slash != std::string::npos) {
return base::ok(value.substr(slash + 1));
} else {
return base::unexpected(
base::StrCat({"could not get any value from query path in "
"Query GET URL: ",
url.spec()}));
}
}
// Returns whether the |url| points to a GET or POST query, or neither.
RequestType GetRequestTypeFromURL(const GURL& url) {
if (url.host() != kApiServerDomain ||
url.path().find(kApiServerQueryPath) != 0) {
return RequestType::kNone;
}
std::string path = url.path().substr(strlen(kApiServerQueryPath));
return path == ":get" || path == ":get/" ? RequestType::kQueryProtoPOST
: RequestType::kQueryProtoGET;
}
// Gets query request protos from GET URL.
ErrorOr<AutofillPageQueryRequest> GetAutofillQueryFromGETQueryURL(
const GURL& url) {
ErrorOr<std::string> query_parameter = GetQueryParameter(url);
if (!query_parameter.has_value())
return base::unexpected(query_parameter.error());
// Base64-decode the query value.
std::string decoded_query;
if (!base::Base64UrlDecode(query_parameter.value(),
base::Base64UrlDecodePolicy::REQUIRE_PADDING,
&decoded_query)) {
return base::unexpected(base::StrCat(
{"could not base64-decode value of path in Query GET URL: \"",
query_parameter->c_str(), "\""}));
}
return ParseProtoContents<AutofillPageQueryRequest>(decoded_query);
}
// Puts all data elements within the request or response body together in a
// single DataElement and returns the buffered content as a string. This ensures
// that all the response body data is utilized.
std::string GetStringFromDataElements(
const std::vector<network::DataElement>* data_elements) {
std::string result;
for (const network::DataElement& element : *data_elements) {
DCHECK_EQ(element.type(), network::DataElement::Tag::kBytes);
// Provide the length of the bytes explicitly, not to rely on the null
// termination.
const auto piece = element.As<network::DataElementBytes>().AsStringPiece();
result.append(piece.data(), piece.size());
}
return result;
}
// Queries for the Api environment are special in the sense that the actual
// AutofillPageQueryRequest is base64 encoded and wrapped in an
// AutofillPageResourceQueryRequest.
ErrorOr<std::string> PeelAutofillPageResourceQueryRequestWrapper(
const std::string& text) {
ErrorOr<AutofillPageResourceQueryRequest> request =
ParseProtoContents<AutofillPageResourceQueryRequest>(text);
if (!request.has_value())
return base::unexpected(request.error());
std::string encoded_query = request->serialized_request();
std::string query;
if (!base::Base64UrlDecode(encoded_query,
base::Base64UrlDecodePolicy::REQUIRE_PADDING,
&query)) {
return base::unexpected(base::StrCat(
{"could not base64-decode serialized body of a POST request: \"",
encoded_query.c_str(), "\""}));
}
return base::ok(std::move(query));
}
// Gets Query request proto content from HTTP POST body.
ErrorOr<AutofillPageQueryRequest> GetAutofillQueryFromPOSTQuery(
const network::ResourceRequest& resource_request) {
ErrorOr<std::string> query = PeelAutofillPageResourceQueryRequestWrapper(
GetStringFromDataElements(resource_request.request_body->elements()));
if (!query.has_value())
return base::unexpected(query.error());
return ParseProtoContents<AutofillPageQueryRequest>(query.value());
}
bool IsSingleFormRequest(const AutofillPageQueryRequest& query) {
return query.forms_size() == 1;
}
// Validates, retrieves, and decodes node |node_name| from |request_node| and
// returns it in |decoded_value|. Returns false if unsuccessful.
bool RetrieveValueFromRequestNode(const base::Value::Dict& request_node,
const std::string node_name,
std::string* decoded_value) {
// Get and check field node string.
std::string serialized_value;
{
const base::Value* node = request_node.Find(node_name);
if (!CheckNodeType(node, node_name, base::Value::Type::STRING)) {
VLOG(1) << "Invalid Node in WPR archive";
return false;
}
serialized_value = node->GetString();
}
// Decode serialized request string.
{
if (!base::Base64Decode(serialized_value, decoded_value)) {
VLOG(1) << "Could not base64 decode serialized value: "
<< serialized_value;
return false;
}
}
return true;
}
// Gets AutofillQueryContents from WPR recorded HTTP request body for POST.
ErrorOr<AutofillPageQueryRequest> GetAutofillQueryFromRequestNode(
const base::Value::Dict& request_node) {
std::string decoded_request_text;
if (!RetrieveValueFromRequestNode(request_node, "SerializedRequest",
&decoded_request_text)) {
return base::unexpected(
"Unable to retrieve serialized request from WPR request_node");
}
std::string http_text = SplitHTTP(decoded_request_text).second;
ErrorOr<std::string> query =
PeelAutofillPageResourceQueryRequestWrapper(http_text);
if (!query.has_value()) {
return base::unexpected(query.error());
}
http_text = query.value();
return ParseProtoContents<AutofillPageQueryRequest>(http_text);
}
// Gets AutofillQueryResponseContents from WPR recorded HTTP response body.
// Also populates and returns the split |response_header_text|.
ErrorOr<AutofillQueryResponse> GetAutofillResponseFromRequestNode(
const base::Value::Dict& request_node,
std::string* response_header_text) {
std::string compressed_response_text;
if (!RetrieveValueFromRequestNode(request_node, "SerializedResponse",
&compressed_response_text)) {
return base::unexpected(
"Unable to retrieve serialized request from WPR request_node");
}
auto http_pair = SplitHTTP(compressed_response_text);
std::string decompressed_body;
if (!compression::GzipUncompress(http_pair.second, &decompressed_body)) {
return base::unexpected(
base::StrCat({"Could not gzip decompress HTTP response: ",
GetHexString(http_pair.second)}));
}
// Eventual response needs header information, so lift that as well.
*response_header_text = http_pair.first;
// The Api Environment expects the response to be base64 encoded.
std::string tmp;
if (!base::Base64Decode(decompressed_body, &tmp)) {
return base::unexpected("Unable to base64 decode the body");
}
decompressed_body = tmp;
return ParseProtoContents<AutofillQueryResponse>(decompressed_body);
}
// Fills |cache_to_fill| with the keys from a single |query_request| and
// |query_response| pair. Loops through each form in request and creates an
// individual response of just the associated fields for that request. Uses
// |response_header_text| to build and store well-formed and backwards
// compatible http text in the cache.
bool FillFormSplitCache(const AutofillPageQueryRequest& query_request,
const std::string& response_header_text,
const AutofillQueryResponse& query_response,
ServerCache* cache_to_fill) {
VLOG(2) << "Full Request Key is:" << GetKeyFromQuery(query_request);
VLOG(2) << "Matching keys from Query request proto:\n" << query_request;
VLOG(2) << "To field types from Query response proto:\n" << query_response;
if (query_request.forms_size() != query_response.form_suggestions_size()) {
VLOG(1) << "Response did not contain the same number of forms as the query";
return false;
}
for (int i = 0; i < query_request.forms_size(); ++i) {
const auto& query_form = query_request.forms(i);
const auto& response_form = query_response.form_suggestions(i);
std::string key = base::NumberToString(query_form.signature());
// If already stored a respones for this key, then just advance the
// current_field by that offset and continue.
if (base::Contains((*cache_to_fill), key)) {
VLOG(2) << "Already added key: " << key;
continue;
}
// Grab fields for this form from overall response and add to unique form
// object.
AutofillQueryResponse individual_form_response;
individual_form_response.add_form_suggestions()->CopyFrom(response_form);
// Compress that form response to a string and gzip it.
std::string serialized_response;
if (!individual_form_response.SerializeToString(&serialized_response)) {
VLOG(1) << "Unable to serialize the new response for key! " << key;
continue;
}
// Chrome expects the response to be base64 encoded.
std::string serialized_response_base64;
base::Base64Encode(serialized_response, &serialized_response_base64);
std::string compressed_response_body;
if (!compression::GzipCompress(serialized_response_base64,
&compressed_response_body)) {
VLOG(1) << "Unable to compress the new response for key! " << key;
continue;
}
// Final http text is header_text concatenated with a compressed body.
std::string http_text =
MakeHTTPTextFromSplit(response_header_text, compressed_response_body);
VLOG(1) << "Adding key:" << key
<< "\nAnd response:" << individual_form_response;
(*cache_to_fill)[key] = std::move(http_text);
}
return true;
}
// Populates |cache_to_fill| with content from |query_node| that contains a
// list of single request node that share the same URL field (e.g.,
// https://clients1.google.com/tbproxy/af/query) in the WPR capture json cache.
// Returns Status with message when there is an error when parsing the requests
// and OPTION_FAIL_ON_INVALID_JSON is flipped in |options|. Returns status ok
// regardless of errors if OPTION_FAIL_ON_INVALID_JSON is not flipped in
// |options| where bad nodes will be skipped. Keeps a log trace whenever there
// is an error even if OPTION_FAIL_ON_INVALID_JSON is not flipped. Uses only the
// form combinations seen in recorded session if OPTION_SPLIT_REQUESTS_BY_FORM
// is false, fill cache with individual form keys (and expect
// ServerCacheReplayer to be able to split incoming request by key and stitch
// results together).
ServerCacheReplayer::Status PopulateCacheFromQueryNode(
const QueryNode& query_node,
int options,
ServerCache* cache_to_fill) {
bool fail_on_error = FailOnError(options);
bool split_requests_by_form = SplitRequestsByForm(options);
for (const base::Value& request : query_node.node->GetList()) {
// Get AutofillQueryContents from request.
bool is_post_request =
GetRequestTypeFromURL(query_node.url) == RequestType::kQueryProtoPOST;
ErrorOr<AutofillPageQueryRequest> query_request_statusor =
is_post_request ? GetAutofillQueryFromRequestNode(request.GetDict())
: GetAutofillQueryFromGETQueryURL(GURL(query_node.url));
// Only proceed if successfully parse the query request proto, else drop to
// failure space.
if (query_request_statusor.has_value()) {
VLOG(2) << "Getting key from Query request proto:\n "
<< query_request_statusor.value();
std::string key = GetKeyFromQuery(query_request_statusor.value());
bool is_single_form_request =
IsSingleFormRequest(query_request_statusor.value());
// Switch to store forms as individuals or only in the groupings that they
// were sent on recording. If only a single form in request then can use
// old behavior still and skip decompression and combination steps.
if (!split_requests_by_form || is_single_form_request) {
std::string compressed_response_text;
if (RetrieveValueFromRequestNode(request.GetDict(),
"SerializedResponse",
&compressed_response_text)) {
(*cache_to_fill)[key] = compressed_response_text;
VLOG(1) << "Cached response content for key: " << key;
continue;
}
} else {
// Get AutofillQueryResponseContents and response header text.
std::string response_header_text;
ErrorOr<AutofillQueryResponse> query_response_statusor =
GetAutofillResponseFromRequestNode(request.GetDict(),
&response_header_text);
if (!query_response_statusor.has_value()) {
VLOG(1) << "Unable to get AutofillQueryResponse from WPR node"
<< "SerializedResponse for request:" << key;
continue;
}
// We have a proper request and a proper response, we can populate for
// each form in the AutofillQueryContents.
if (FillFormSplitCache(
query_request_statusor.value(), response_header_text,
query_response_statusor.value(), cache_to_fill)) {
continue;
}
}
}
// If we've fallen to this level, something went bad with adding the request
// node. If fail_on_error is set then abort, else log and try the next one.
constexpr base::StringPiece status_msg =
"could not cache query node content";
if (fail_on_error) {
return ServerCacheReplayer::Status{
ServerCacheReplayer::StatusCode::kBadNode, std::string(status_msg)};
} else {
// Keep a trace when not set to fail on bad node.
VLOG(1) << status_msg;
}
}
return ServerCacheReplayer::Status{ServerCacheReplayer::StatusCode::kOk, ""};
}
// Finds the Autofill server Query nodes in a dictionary node. The |domain| has
// to outlive any usage of the returned value node pointers.
std::vector<QueryNode> FindQueryNodesInDomainDict(
const base::Value::Dict& domain,
const std::string& url_prefix) {
std::vector<QueryNode> nodes;
for (auto pair : domain) {
if (pair.first.find(url_prefix) != std::string::npos) {
nodes.push_back(QueryNode{GURL(pair.first), &pair.second});
}
}
return nodes;
}
// Populates the cache mapping request keys to their corresponding compressed
// response.
ServerCacheReplayer::Status PopulateCacheFromJSONFile(
const base::FilePath& json_file_path,
int options,
ServerCache* cache_to_fill) {
// Read json file.
std::string json_text;
{
if (!base::ReadFileToString(json_file_path, &json_text)) {
return ServerCacheReplayer::Status{
ServerCacheReplayer::StatusCode::kBadRead,
"Could not read json file: "};
}
}
// Decompress the json text from gzip.
std::string decompressed_json_text;
if (!compression::GzipUncompress(json_text, &decompressed_json_text)) {
return ServerCacheReplayer::Status{
ServerCacheReplayer::StatusCode::kBadRead,
"Could not gzip decompress json in file: "};
}
// Parse json text content to json value node.
base::Value root_node;
{
auto value_with_error = JSONReader::ReadAndReturnValueWithError(
decompressed_json_text, JSONParserOptions::JSON_PARSE_RFC);
if (!value_with_error.has_value()) {
return ServerCacheReplayer::Status{
ServerCacheReplayer::StatusCode::kBadRead,
base::StrCat({"Could not load cache from json file ",
"because: ", value_with_error.error().message})};
}
root_node = std::move(*value_with_error);
}
{
std::vector<QueryNode> query_nodes;
const base::Value::Dict* root_node_dict = root_node.GetIfDict();
if (root_node_dict) {
const base::Value::Dict* requests = root_node_dict->FindDict("Requests");
if (requests) {
const base::Value::Dict* domain_node =
requests->FindDict(kApiServerDomain);
if (domain_node) {
query_nodes =
FindQueryNodesInDomainDict(*domain_node, kApiServerUrlGetPrefix);
}
}
}
// Fill cache with the content of each Query node. There are 3 possible
// situations: (1) there is a single Query node that contains POST requests
// that share the same URL, (2) there is one Query node per GET request
// where each Query node only contains one request, and (3) a mix of (1) and
// (2). Exit early with false whenever there is an error parsing a node.
for (auto query_node : query_nodes) {
if (!CheckNodeType(query_node.node,
"Requests->content-autofill.googleapis.com->"
"content-autofill.googleapis.com/v1/pages:get*",
base::Value::Type::LIST)) {
return ServerCacheReplayer::Status{
ServerCacheReplayer::StatusCode::kBadNode,
base::StrCat({"could not read node content for node with URL ",
query_node.url.spec()})};
}
// Populate cache from Query node content.
// The template parameters specify the reading and writing format.
auto status =
PopulateCacheFromQueryNode(query_node, options, cache_to_fill);
if (!status.Ok())
return status;
VLOG(1) << "Filled cache with " << cache_to_fill->size()
<< " requests for Query node with URL: " << query_node.url;
}
}
// Return error iff there are no Query nodes and replayer is set to fail on
// empty.
if (cache_to_fill->empty() && FailOnEmpty(options)) {
return ServerCacheReplayer::Status{
ServerCacheReplayer::StatusCode::kEmpty,
"there were no nodes with autofill query content for autofill server "
"domains in JSON"};
}
return ServerCacheReplayer::Status{ServerCacheReplayer::StatusCode::kOk, ""};
}
} // namespace
// Decompressed HTTP response read from WPR capture file. Will set
// |decompressed_http| to "" and return false if there is an error.
bool RetrieveAndDecompressStoredHTTP(const ServerCache& cache,
const std::string& key,
std::string* decompressed_http) {
// Safe to use at() here since we looked for key's presence and there is no
// mutation done when there is concurrency.
const std::string& http_text = cache.at(key);
auto header_and_body = SplitHTTP(http_text);
if (header_and_body.first == "") {
*decompressed_http = "";
VLOG(1) << "No header found in supposed HTTP text: " << http_text;
return false;
}
// Look if there is a body to decompress, if not just return HTTP text as is.
if (header_and_body.second == "") {
*decompressed_http = http_text;
VLOG(1) << "There is no HTTP body to decompress: " << http_text;
return true;
}
// TODO(crbug.com/945925): Add compression format detection, return an
// error if not supported format.
// Decompress the body.
std::string decompressed_body;
if (!compression::GzipUncompress(header_and_body.second,
&decompressed_body)) {
VLOG(1) << "Could not gzip decompress HTTP response: "
<< GetHexString(header_and_body.second);
return false;
}
// Rebuild the response HTTP text by using the new decompressed body.
*decompressed_http =
MakeHTTPTextFromSplit(header_and_body.first, decompressed_body);
return true;
}
// Determines the Autofill Server Behavior from command line parameter.
AutofillServerBehaviorType ParseAutofillServerBehaviorType() {
std::string autofill_server_option =
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
kAutofillServerBehaviorParam);
VLOG(1) << "Autofill Server Behavior was:`" << autofill_server_option << "`.";
if (autofill_server_option.empty() ||
base::EqualsCaseInsensitiveASCII(autofill_server_option, "SavedCache")) {
return AutofillServerBehaviorType::kSavedCache;
} else if (base::EqualsCaseInsensitiveASCII(autofill_server_option,
"ProductionServer")) {
return AutofillServerBehaviorType::kProductionServer;
} else if (base::EqualsCaseInsensitiveASCII(autofill_server_option,
"OnlyLocalHeuristics")) {
return AutofillServerBehaviorType::kOnlyLocalHeuristics;
} else {
CHECK(false) << "Unrecognized command line value give for `"
<< kAutofillServerBehaviorParam << "` argument: `"
<< autofill_server_option << "`";
return AutofillServerBehaviorType::kSavedCache;
}
}
// Gives a pair that contains the HTTP text split in 2, where the first
// element is the HTTP head and the second element is the HTTP body.
std::pair<std::string, std::string> SplitHTTP(const std::string& http_text) {
const size_t split_index = http_text.find(kHTTPBodySep);
if (split_index != std::string::npos) {
const size_t sep_length = std::string(kHTTPBodySep).size();
std::string head = http_text.substr(0, split_index);
std::string body =
http_text.substr(split_index + sep_length, std::string::npos);
return std::make_pair(std::move(head), std::move(body));
}
return std::make_pair("", "");
}
// Streams in text format. For consistency, taken from anonymous namespace in
// components/autofill/core/browser/autofill_download_manager.cc
std::ostream& operator<<(std::ostream& out,
const autofill::AutofillPageQueryRequest& query) {
for (const auto& form : query.forms()) {
out << "\nForm\n signature: " << form.signature();
for (const auto& field : form.fields()) {
out << "\n Field\n signature: " << field.signature();
if (!field.name().empty())
out << "\n name: " << field.name();
if (!field.control_type().empty())
out << "\n control_type: " << field.control_type();
}
}
return out;
}
// Streams in text format. For consistency, taken from anonymous namespace in
// components/autofill/core/browser/form_structure.cc
std::ostream& operator<<(std::ostream& out,
const autofill::AutofillQueryResponse& response) {
for (const auto& form : response.form_suggestions()) {
out << "\nForm";
for (const auto& field : form.field_suggestions()) {
out << "\n Field\n signature: " << field.field_signature();
for (const auto& prediction : field.predictions())
out << "\n prediction: " << prediction.type();
}
}
return out;
}
// Gets a key for cache lookup from a query request.
std::string GetKeyFromQuery(const AutofillPageQueryRequest& query_request) {
std::vector<std::string> form_ids;
for (const auto& form : query_request.forms()) {
form_ids.push_back(base::NumberToString(form.signature()));
}
std::sort(form_ids.begin(), form_ids.end());
return base::JoinString(form_ids, "_");
}
ServerCacheReplayer::~ServerCacheReplayer() = default;
ServerCacheReplayer::ServerCacheReplayer(const base::FilePath& json_file_path,
int options)
: split_requests_by_form_(SplitRequestsByForm(options)) {
// If the behavior type is not cache, we can skip setup.
if (test::ParseAutofillServerBehaviorType() !=
AutofillServerBehaviorType::kSavedCache)
return;
// Using CHECK is fine here since ServerCacheReplayer will only be used for
// testing and we prefer the test to crash than being in an inconsistent
// state when the cache could not be properly populated from the JSON file.
ServerCacheReplayer::Status status =
PopulateCacheFromJSONFile(json_file_path, options, &cache_);
CHECK(status.Ok()) << status.message;
}
ServerCacheReplayer::ServerCacheReplayer(ServerCache server_cache,
bool split_requests_by_form)
: cache_(std::move(server_cache)),
split_requests_by_form_(split_requests_by_form) {}
// Retrieve forms of an api server response.
const ::google::protobuf::RepeatedPtrField<AutofillPageQueryRequest_Form>&
GetFormsRef(const AutofillPageQueryRequest& query) {
return query.forms();
}
void CreateEmptyResponseForFormQuery(const AutofillPageQueryRequest_Form& form,
AutofillQueryResponse* response) {
auto* new_form = response->add_form_suggestions();
for (int i = 0; i < form.fields_size(); i++) {
auto* new_field = new_form->add_field_suggestions();
new_field->add_predictions()->set_type(0);
}
}
void AppendSingleFormResponse(const AutofillQueryResponse& single_form_response,
AutofillQueryResponse* response) {
auto* new_form = response->add_form_suggestions();
new_form->CopyFrom(single_form_response.form_suggestions(0));
}
bool GetResponseForQuery(const ServerCacheReplayer& cache_replayer,
const AutofillPageQueryRequest& query,
std::string* http_text) {
if (http_text == nullptr) {
VLOG(1) << "Cannot fill |http_text| because null";
return false;
}
const ServerCache& cache = cache_replayer.cache();
bool split_requests_by_form = cache_replayer.split_requests_by_form();
std::string combined_key = GetKeyFromQuery(query);
if (base::Contains(cache, combined_key)) {
VLOG(1) << "Retrieving response for " << combined_key;
std::string decompressed_http_response;
if (!RetrieveAndDecompressStoredHTTP(cache, combined_key,
&decompressed_http_response)) {
return false;
}
*http_text = decompressed_http_response;
return true;
}
// If we didn't find a single-form match and we're not splitting requests by
// form, we failed to find a response for this query.
if (!split_requests_by_form) {
VLOG(1) << "Did not match any response for " << combined_key;
return false;
}
// Assemble a new response from single form requests.
AutofillQueryResponse combined_form_response;
std::string response_header_text;
bool first_loop = true;
for (const auto& form : GetFormsRef(query)) {
std::string key = base::NumberToString(form.signature());
if (!base::Contains(cache, key)) {
VLOG(2) << "Stubbing in fields for uncached key `" << key << "`.";
CreateEmptyResponseForFormQuery(form, &combined_form_response);
continue;
}
std::string decompressed_http_response;
if (!RetrieveAndDecompressStoredHTTP(cache, key,
&decompressed_http_response)) {
return false;
}
if (first_loop) {
response_header_text = SplitHTTP(decompressed_http_response).first;
first_loop = false;
}
std::string body = SplitHTTP(decompressed_http_response).second;
// The Api Environment expects the response to be base64 encoded.
std::string tmp;
if (!base::Base64Decode(body, &tmp)) {
VLOG(1) << "Unable to base64 decode contents for key: " << key
<< ", contents: " << body;
return false;
}
body = tmp;
ErrorOr<AutofillQueryResponse> single_form_response =
ParseProtoContents<AutofillQueryResponse>(body);
if (!single_form_response.has_value()) {
VLOG(1) << "Unable to parse result contents for key:" << key;
return false;
}
AppendSingleFormResponse(single_form_response.value(),
&combined_form_response);
}
// If all we got were stubbed forms, return false as not a single match.
if (first_loop) {
VLOG(1) << "Did not match any response for " << combined_key;
return false;
}
std::string serialized_response;
if (!combined_form_response.SerializeToString(&serialized_response)) {
VLOG(1) << "Unable to serialize the new response for keys!";
return false;
}
// The Api Environment expects the response body to be base64 encoded.
std::string tmp;
base::Base64Encode(serialized_response, &tmp);
serialized_response = tmp;
VLOG(1) << "Retrieving stitched response for " << combined_key;
*http_text = MakeHTTPTextFromSplit(response_header_text, serialized_response);
return true;
}
bool ServerCacheReplayer::GetApiServerResponseForQuery(
const AutofillPageQueryRequest& query,
std::string* http_text) const {
return GetResponseForQuery(*this, query, http_text);
}
ServerUrlLoader::ServerUrlLoader(
std::unique_ptr<ServerCacheReplayer> cache_replayer)
: cache_replayer_(std::move(cache_replayer)),
autofill_server_behavior_type_(ParseAutofillServerBehaviorType()),
interceptor_(base::BindLambdaForTesting(
[&](content::URLLoaderInterceptor::RequestParams* params) -> bool {
return InterceptAutofillRequest(params);
})) {
// Using CHECK is fine here since ServerCacheReplayer will only be used for
// testing and we prefer the test to crash with a CHECK rather than
// segfaulting with a stack trace that can be hard to read.
CHECK(cache_replayer_);
}
ServerUrlLoader::~ServerUrlLoader() {}
bool WriteNotFoundResponse(
content::URLLoaderInterceptor::RequestParams* params) {
// Give back 404 error to the server if there is not match in cache.
constexpr char kNoKeyMatchHTTPErrorHeaders[] = "HTTP/2.0 404 Not Found";
constexpr char kNoKeyMatchHTTPErrorBody[] =
"could not find response matching request";
VLOG(1) << "Served Autofill error response: " << kNoKeyMatchHTTPErrorBody;
content::URLLoaderInterceptor::WriteResponse(
std::string(kNoKeyMatchHTTPErrorHeaders),
std::string(kNoKeyMatchHTTPErrorBody), params->client.get());
return true;
}
// Return a 400 Bad Request message to |client|.
void SendBadRequest(network::mojom::URLLoaderClient* client) {
constexpr char kNoBodyHTTPErrorHeaders[] = "HTTP/2.0 400 Bad Request";
constexpr char kNoBodyHTTPErrorBody[] =
"there is no body data in the request";
VLOG(1) << "Served Autofill error response: " << kNoBodyHTTPErrorBody;
content::URLLoaderInterceptor::WriteResponse(
std::string(kNoBodyHTTPErrorHeaders), std::string(kNoBodyHTTPErrorBody),
client);
}
bool InterceptAutofillRequestHelper(
const ServerCacheReplayer& cache_replayer,
content::URLLoaderInterceptor::RequestParams* params) {
const network::ResourceRequest& resource_request = params->url_request;
RequestType request_type = GetRequestTypeFromURL(resource_request.url);
CHECK_NE(request_type, RequestType::kNone);
// Intercept autofill query and serve back response from cache.
// Parse HTTP request body to proto.
VLOG(1) << "Intercepted in-flight request to Autofill Server: "
<< resource_request.url.spec();
bool is_post_request = (request_type == RequestType::kQueryProtoPOST);
// Look if the body has data if it is a POST request.
if (is_post_request && resource_request.request_body == nullptr) {
SendBadRequest(params->client.get());
return true;
}
ErrorOr<AutofillPageQueryRequest> query_request_statusor =
is_post_request ? GetAutofillQueryFromPOSTQuery(resource_request)
: GetAutofillQueryFromGETQueryURL(resource_request.url);
// Using CHECK is fine here since ServerCacheReplayer will only be used for
// testing and we prefer the test to crash rather than missing the cache
// because the request content could not be parsed back to a Query request
// proto, which can be caused by bad data in the request from the browser
// during capture replay.
CHECK(query_request_statusor.has_value()) << query_request_statusor.error();
// Get response from cache using query request proto as key.
std::string http_response;
if (!GetResponseForQuery(cache_replayer, query_request_statusor.value(),
&http_response)) {
return WriteNotFoundResponse(params);
}
// Give back cache response HTTP content.
auto http_pair = SplitHTTP(http_response);
content::URLLoaderInterceptor::WriteResponse(
http_pair.first, http_pair.second, params->client.get());
VLOG(1) << "Giving back response from cache";
return true;
}
bool ServerUrlLoader::InterceptAutofillRequest(
content::URLLoaderInterceptor::RequestParams* params) {
const network::ResourceRequest& resource_request = params->url_request;
const GURL& request_url = resource_request.url;
bool api_query_request = (request_url.host() == kApiServerDomain &&
request_url.path().find(kApiServerQueryPath) == 0);
if (api_query_request) {
// Check what the set behavior type is.
// For Production Server, return false to say don't intercept.
// For Only Local Heuristics, write empty server response.
// For Saved Cache, continue on and look for a response in the cache.
switch (autofill_server_behavior_type_) {
case AutofillServerBehaviorType::kProductionServer:
return false;
case AutofillServerBehaviorType::kOnlyLocalHeuristics:
return WriteNotFoundResponse(params);
case AutofillServerBehaviorType::kSavedCache:
default:
break;
}
return InterceptAutofillRequestHelper(*cache_replayer_, params);
}
// Let all requests that are not autofill queries go to WPR.
return false;
}
} // namespace autofill::test
| [
"[email protected]"
] | |
3b780c07e898d2b6918ce36fef691891f3666dc6 | b178d5702818c97bf18a44c4aacb1c1582290307 | /phoenix/base/extension/thread/thread_manager.cpp | b5eb112974886d1245d2bdcb8aa2d1b250958461 | [] | no_license | netease-im/phoenix | 735b20a4ac6dc58232a0658ff28565ea66bede1b | a4ef3b068801af2ebf87ba7c80f884f57f09b3e3 | refs/heads/master | 2023-07-19T18:33:50.808072 | 2023-07-17T02:11:51 | 2023-07-17T02:11:51 | 224,381,540 | 53 | 25 | null | null | null | null | UTF-8 | C++ | false | false | 10,876 | cpp | #include "base/atomicops.h"
#include "base/thread_task_runner_handle.h"
#include "base/task_runner_util.h"
#include "extension/thread/thread_manager.h"
EXTENSION_BEGIN_DECLS
bool ThreadMap::AquireAccess()
{
FrameworkThreadTlsData *tls = FrameworkThread::GetTlsData();
if (!tls || tls->managed < 1)
return false;
return true;
}
bool ThreadMap::RegisterThread(int64_t self_identifier)
{
//DCHECK(self_identifier >= 0);
if (self_identifier < 0)
return false;
FrameworkThreadTlsData *tls = FrameworkThread::GetTlsData();
DCHECK(tls);
if (!tls)
return false;
base::AutoLock lock(lock_);
auto pr = threads_.insert(
std::make_pair(self_identifier, tls->self));
if (!pr.second)
{
if (pr.first->second != tls->self)
{
DCHECK(false); // another thread has registered with the same id
return false;
}
// yes, it's me, check logic error
DCHECK(tls->managed > 0);
DCHECK(tls->managed_thread_id == self_identifier);
}
// 'self' is registered
tls->managed++;
tls->managed_thread_id = self_identifier;
return true;
}
bool ThreadMap::UnregisterThread()
{
FrameworkThreadTlsData *tls = FrameworkThread::GetTlsData();
DCHECK(tls); // should be called by a Framework thread
DCHECK(tls->managed > 0); // should be managed
if (!tls || tls->managed < 1)
return false;
// remove from internal thread map
// here, since tls->managed is greater than zero,
// we must have a reference of the glabal ThreadManager instance (see RegisterThread)
if (--tls->managed == 0)
{
base::AutoLock lock(lock_);
auto iter = threads_.find(tls->managed_thread_id);
if (iter != threads_.end()){
threads_.erase(iter);
}
else{
DCHECK(false); // logic error, we should not come here
}
tls->managed_thread_id = -1;
}
return true;
}
// no lock
FrameworkThread* ThreadMap::InternalQueryThread(int64_t identifier) const
{
auto iter = threads_.find(identifier);
if (iter == threads_.end())
return nullptr;
return iter->second;
}
int64_t ThreadMap::GetManagedThreadId(const FrameworkThread *thread)
{
if (!AquireAccess()) {
DCHECK(false);
return -1;
}
base::AutoLock lock(lock_);
for (auto iter = threads_.begin();iter != threads_.end(); iter++) {
if (iter->second == thread)
return iter->first;
}
return -1;
}
scoped_refptr<base::SingleThreadTaskRunner> ThreadMap::task_runner(int64_t identifier) const
{
FrameworkThread* thread = InternalQueryThread(identifier);
if (!thread)
{
return nullptr;
}
return thread->task_runner();
}
ThreadManager::ThreadManager()
{
_threadMap = std::make_shared<ThreadMap>();
}
ThreadManager* ThreadManager::GetInstance()
{
return base::Singleton<ThreadManager, base::LeakySingletonTraits<ThreadManager>>::get();
}
bool ThreadManager::RegisterThread(int64_t self_identifier)
{
auto thread_map = ThreadManager::GetInstance()->_threadMap;
if (!thread_map)
{
return false;
}
return thread_map->RegisterThread(self_identifier);
}
bool ThreadManager::UnregisterThread()
{
auto thread_map = ThreadManager::GetInstance()->_threadMap;
if (!thread_map)
{
return false;
}
return thread_map->UnregisterThread();
}
FrameworkThread* ThreadManager::CreateFrameworkThread(int64_t identifier, const std::string& name)
{
auto thread = new FrameworkThread(name);
thread->SetManagerRegister([identifier](bool reg) {
if (reg)
RegisterThread(identifier);
else
UnregisterThread();
});
return thread;
}
std::shared_ptr<FrameworkThread> ThreadManager::GlobalTimerThreadRef()
{
auto weak_thread = ThreadManager::GetInstance()->_global_timer_thread;
auto shared_thread = weak_thread.lock();
if (!shared_thread) {
shared_thread = std::make_shared<FrameworkThread>("global_timer_thread");
ThreadManager::GetInstance()->SetGlobalTimerThread(shared_thread);
bool success = shared_thread->Start();
DCHECK(success);
if (!success) {
return nullptr;
}
shared_thread->WaitUntilThreadStarted();
}
return shared_thread;
}
scoped_refptr<base::SingleThreadTaskRunner> ThreadManager::GlobalTimerTaskRunner()
{
auto weak_thread = ThreadManager::GetInstance()->_global_timer_thread;
if (weak_thread.expired())
{
return nullptr;
}
auto thread = weak_thread.lock();
return thread->task_runner();
}
base::PlatformThreadId ThreadManager::GlobalTimerThreadID()
{
auto weak_thread = ThreadManager::GetInstance()->_global_timer_thread;
if (weak_thread.expired())
{
return 0;
}
auto thread = weak_thread.lock();
return thread->GetThreadId();
}
int64_t ThreadManager::QueryThreadId(const FrameworkThread *thread)
{
auto thread_map = ThreadManager::GetInstance()->_threadMap;
if (!thread_map)
{
return -1;
}
return thread_map->GetManagedThreadId(thread);
}
FrameworkThread* ThreadManager::CurrentThread()
{
FrameworkThreadTlsData *tls = FrameworkThread::GetTlsData();
//DCHECK(tls); // should be called by a Framework thread
//DCHECK(tls->managed > 0); // should be managed
if (!tls || tls->managed < 1)
return nullptr;
return tls->self;
}
bool ThreadManager::PostTask(const StdClosure &task)
{
//MessageLoop::current()->PostTask(task);
DCHECK(base::ThreadTaskRunnerHandle::IsSet());
auto closure = base::Bind(base::extension::InvokeCallback<typename std::result_of<StdClosure()>::type>, task);
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,closure);
return true;
}
bool ThreadManager::PostTimerTask(const StdClosure &task, const StdClosure &cb, TimeDelta delay)
{
auto task_runner = base::ThreadTaskRunnerHandle::Get();
task_runner = task_runner ? task_runner : GlobalTimerTaskRunner();
auto timer_task = [task, cb, task_runner, delay]() {
NS_EXTENSION::WeakCallbackFlag timer_;
StdClosure time_out_task = timer_.ToWeakCallback([cb]()
{
cb();
});
auto closure = base::Bind(base::extension::InvokeCallback<typename std::result_of<StdClosure()>::type>, time_out_task);
task_runner->PostDelayedTask(FROM_HERE,closure, delay);
task();
if (timer_.HasUsed())
timer_.Cancel();
};
auto closure = base::Bind(base::extension::InvokeCallback<typename std::result_of<StdClosure()>::type>, timer_task);
task_runner->PostTask(FROM_HERE,closure);
return true;
}
bool ThreadManager::PostTaskAndReply(int64_t identifier, const StdClosure &task, const StdClosure &reply)
{
auto thread_map = ThreadManager::GetInstance()->_threadMap;
auto task_runner = thread_map ? thread_map->task_runner(identifier) : nullptr;
if (!task_runner)
{
return false;
}
auto closure = base::Bind(base::extension::InvokeCallback<typename std::result_of<StdClosure()>::type>, task);
auto reply_closure = base::Bind(base::extension::InvokeCallback<typename std::result_of<StdClosure()>::type>, reply);
task_runner->PostTaskAndReply(FROM_HERE, closure,reply_closure);
return true;
}
bool ThreadManager::PostTask(int64_t identifier, const StdClosure &task)
{
// std::shared_ptr<MessageLoopProxy> message_loop =
// ThreadMap::GetInstance()->GetMessageLoop(identifier);
// if (message_loop == NULL)
// return false;
// message_loop->PostTask(task);
auto thread_map = ThreadManager::GetInstance()->_threadMap;
auto task_runner = thread_map ? thread_map->task_runner(identifier) : nullptr;
if (!task_runner)
{
return false;
}
auto closure = base::Bind(base::extension::InvokeCallback<typename std::result_of<StdClosure()>::type>, task);
task_runner->PostTask(FROM_HERE, closure);
return true;
}
bool ThreadManager::PostDelayedTask(const StdClosure &task, TimeDelta delay)
{
//MessageLoop::current()->PostDelayedTask(task, delay);
DCHECK(base::ThreadTaskRunnerHandle::IsSet());
auto closure = base::Bind(base::extension::InvokeCallback<typename std::result_of<StdClosure()>::type>, task);
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, closure,delay);
return true;
}
bool ThreadManager::PostDelayedTask(int64_t identifier, const StdClosure &task, TimeDelta delay)
{
// std::shared_ptr<MessageLoopProxy> message_loop =
// ThreadMap::GetInstance()->GetMessageLoop(identifier);
// if (message_loop == NULL)
// return false;
// message_loop->PostDelayedTask(task, delay);
auto thread_map = ThreadManager::GetInstance()->_threadMap;
auto task_runner = thread_map ? thread_map->task_runner(identifier) : nullptr;
if (!task_runner)
{
return false;
}
auto closure = base::Bind(base::extension::InvokeCallback<typename std::result_of<StdClosure()>::type>, task);
task_runner->PostDelayedTask(FROM_HERE, closure,delay);
return true;
}
bool ThreadManager::PostNonNestableTask(const StdClosure &task)
{
// MessageLoop::current()->PostNonNestableTask(task);
DCHECK(base::ThreadTaskRunnerHandle::IsSet());
auto closure = base::Bind(base::extension::InvokeCallback<typename std::result_of<StdClosure()>::type>, task);
base::ThreadTaskRunnerHandle::Get()->PostNonNestableTask(FROM_HERE, closure);
return true;
}
bool ThreadManager::PostNonNestableTask(int64_t identifier, const StdClosure &task)
{
// std::shared_ptr<MessageLoopProxy> message_loop =
// ThreadMap::GetInstance()->GetMessageLoop(identifier);
// if (message_loop == NULL)
// return false;
// message_loop->PostNonNestableTask(task);
auto thread_map = ThreadManager::GetInstance()->_threadMap;
auto task_runner = thread_map ? thread_map->task_runner(identifier) : nullptr;
if (!task_runner)
{
return false;
}
auto closure = base::Bind(base::extension::InvokeCallback<typename std::result_of<StdClosure()>::type>, task);
task_runner->PostNonNestableTask(FROM_HERE, closure);
return true;
}
bool ThreadManager::PostNonNestableDelayedTask(const StdClosure &task, TimeDelta delay)
{
// MessageLoop::current()->PostNonNestableDelayedTask(task, delay);
DCHECK(base::ThreadTaskRunnerHandle::IsSet());
auto closure = base::Bind(base::extension::InvokeCallback<typename std::result_of<StdClosure()>::type>, task);
base::ThreadTaskRunnerHandle::Get()->PostNonNestableDelayedTask(FROM_HERE, closure,delay);
return true;
}
bool ThreadManager::PostNonNestableDelayedTask(int64_t identifier, const StdClosure &task, TimeDelta delay)
{
// std::shared_ptr<MessageLoopProxy> message_loop =
// ThreadMap::GetInstance()->GetMessageLoop(identifier);
// if (message_loop == NULL)
// return false;
// message_loop->PostNonNestableDelayedTask(task, delay);
auto thread_map = ThreadManager::GetInstance()->_threadMap;
auto task_runner = thread_map ? thread_map->task_runner(identifier) : nullptr;
if (!task_runner)
{
return false;
}
auto closure = base::Bind(base::extension::InvokeCallback<typename std::result_of<StdClosure()>::type>, task);
task_runner->PostNonNestableDelayedTask(FROM_HERE, closure,delay);
return true;
}
void ThreadManager::Cleanup()
{
// if (GlobalTimerThread::GetInstance()->IsRunning())
// GlobalTimerThread::GetInstance()->Stop();
}
void ThreadManager::SetGlobalTimerThread(std::weak_ptr<FrameworkThread> thread)
{
_global_timer_thread = thread;
}
EXTENSION_END_DECLS
| [
"[email protected]"
] | |
03b3c150d17e98b7d94d79967edd972e98bb249d | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/LArCalorimeter/LArCalibTools/src/LArOFC2Ntuple.cxx | 6e36aaa71480a99134b1c609a966b3faba00b89d | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,543 | cxx | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#include "LArCalibTools/LArOFC2Ntuple.h"
#include "LArRawConditions/LArOFCComplete.h"
#include "CaloIdentifier/CaloGain.h"
#include "LArIdentifier/LArOnlineID.h"
#include "StoreGate/StoreGateSvc.h"
#include "LArCabling/LArCablingService.h"
LArOFC2Ntuple::LArOFC2Ntuple(const std::string& name, ISvcLocator* pSvcLocator):
LArCond2NtupleBase(name, pSvcLocator)
{
declareProperty("ContainerKey", m_contKey = "LArOFC");
//declareProperty("Nsamples", m_nSamples = 5);
//declareProperty("Nphases", m_nPhases = 50);
declareProperty("NtupleName", m_ntName = "OFC");
declareProperty("NtupleFile", m_ntFile = "FILE1");
declareProperty("IsMC", m_isMC=false);
declareProperty("OFCTool", m_OFCTool );
}
LArOFC2Ntuple::~LArOFC2Ntuple()
{}
StatusCode LArOFC2Ntuple::initialize() {
m_ntTitle="Optimal Filtering Coefficients";
m_ntpath=std::string("/NTUPLES/")+m_ntFile+std::string("/")+m_ntName;
if ( LArCond2NtupleBase::initialize().isFailure() ) {
return StatusCode::FAILURE;
}
if ( m_isMC && m_OFCTool.retrieve().isFailure() ) {
ATH_MSG_ERROR( "OFC tool required for MC conditions but not available" );
return StatusCode::FAILURE;
}
return StatusCode::SUCCESS;
}
StatusCode LArOFC2Ntuple::stop() {
StatusCode sc;
// Ntuple booking: Specific
NTuple::Item<long> gain, phase, nSamples;
NTuple::Item<float> timeOffset, phasetime;
NTuple::Array<float> OFCa, OFCb;
sc=m_nt->addItem("Gain",gain,-1,2);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "addItem 'gain' failed" );
return StatusCode::FAILURE;
}
//Specific:
sc=m_nt->addItem("TimeOffset",timeOffset,0,100);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "addItem 'TimeOffset' failed" );
return StatusCode::FAILURE;
}
sc=m_nt->addItem("Phase",phase,0,49);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "addItem 'phase' failed" );
return StatusCode::FAILURE;
}
sc=m_nt->addItem("PhaseTime",phasetime,0,800);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "addItem 'PhaseTime' failed" );
return StatusCode::FAILURE;
}
sc=m_nt->addItem("nSamples",nSamples,0,100);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "addItem 'nSamples' failed" );
return StatusCode::FAILURE;
}
sc=m_nt->addItem("OFCa",nSamples,OFCa);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "addItem 'OFCa' failed" );
return StatusCode::FAILURE;
}
sc=m_nt->addItem("OFCb",nSamples,OFCb);
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "addItem 'OFCb' failed" );
return StatusCode::FAILURE;
}
// retrieve OFC object
const ILArOFC* larOFC = NULL ;
//const LArOFCComplete* larOFC = NULL ;
if ( !m_isMC ) {
ATH_MSG_DEBUG( "Retrieving ILArOFC object with key " << m_contKey );
sc = m_detStore->retrieve(larOFC,m_contKey);
if (sc.isFailure()) {
ATH_MSG_ERROR( "Can't retrieve ILArOFC with key " << m_contKey << " from Conditions Store" );
return StatusCode::FAILURE;
}
}
unsigned cellCounter=0;
for ( unsigned igain=CaloGain::LARHIGHGAIN;
igain<CaloGain::LARNGAIN ; ++igain ) {
std::vector<HWIdentifier>::const_iterator it = m_onlineId->channel_begin();
std::vector<HWIdentifier>::const_iterator it_e = m_onlineId->channel_end();
if ( m_isMC ) {
for (;it!=it_e;it++) {
const HWIdentifier chid = *it;
if (!m_larCablingSvc->isOnlineConnected(chid)) continue;
ATH_MSG_VERBOSE( "Dumping OFC for channel 0x" << MSG::hex
<< chid.get_compact() << MSG::dec );
ILArOFC::OFCRef_t ofc_a=m_OFCTool->OFC_a(chid,igain);
ILArOFC::OFCRef_t ofc_b=m_OFCTool->OFC_b(chid,igain);
fillFromIdentifier(chid);
gain = (long)igain ;
phase = (long)0 ;
nSamples=ofc_a.size();
for (int k=0;k<nSamples;k++ ) {
OFCa[k] = ofc_a[k] ;
OFCb[k] = ofc_b[k] ;
}
timeOffset = 0;
phasetime = 0;
sc = ntupleSvc()->writeRecord(m_nt);
cellCounter++;
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "writeRecord failed" );
return StatusCode::FAILURE;
}
}//loop over channels
} else { // is_MC
for (;it!=it_e;it++) {
const HWIdentifier chid = *it;
if ( !m_larCablingSvc->isOnlineConnected(chid)) continue;
ATH_MSG_VERBOSE( "Dumping OFC for channel 0x" << MSG::hex
<< chid.get_compact() << MSG::dec );
for (unsigned iphase=0;iphase<larOFC->nTimeBins(chid,igain);iphase++) {
ILArOFC::OFCRef_t ofc_a=larOFC->OFC_a(chid,igain,iphase);
//Check if we have OFC for this channel and gain
//if (!ofc_a.size()) break;//No more phases
ILArOFC::OFCRef_t ofc_b=larOFC->OFC_b(chid,igain,iphase);
fillFromIdentifier(chid);
gain = (long)igain ;
phase = (long)iphase ;
nSamples=ofc_a.size();
for (int k=0;k<nSamples;k++ ) {
OFCa[k] = ofc_a[k] ;
OFCb[k] = ofc_b[k] ;
}
timeOffset = larOFC->timeOffset(chid,igain);
phasetime = phase*larOFC->timeBinWidth(chid,igain);
sc = ntupleSvc()->writeRecord(m_nt);
cellCounter++;
if (sc!=StatusCode::SUCCESS) {
ATH_MSG_ERROR( "writeRecord failed" );
return StatusCode::FAILURE;
}
}//loop over phases
}//loop over channels
}
}//loop over gains
ATH_MSG_INFO( "Total number of cells = " << cellCounter );
ATH_MSG_INFO( "LArOFC2Ntuple has finished." );
return StatusCode::SUCCESS;
} // end finalize-method.
| [
"[email protected]"
] | |
6e0170fc7a61dd33cd93f2b5e217ee923db2e42d | a2ffbab3aef11aeb082145fe5c08764e98495bce | /src/dom/protobuf/protobuf_plugin.h | c38327c680b6bcb66d5998d510b03d69a1157d9d | [
"MIT"
] | permissive | ggeorgiev/dbs | 1baf86ae815dde17ff5bac81b273d571ae787f54 | 27f33b05c1c6e98b3735942586b7426fd36c1237 | refs/heads/master | 2021-01-21T04:47:57.702675 | 2016-07-15T04:14:05 | 2016-07-15T04:14:05 | 44,683,331 | 0 | 0 | null | 2016-05-09T13:25:15 | 2015-10-21T14:49:53 | C++ | UTF-8 | C++ | false | false | 690 | h | // Copyright © 2015-2016 George Georgiev. All rights reserved.
//
#pragma once
#include "dom/element.hpp"
#include "doim/fs/fs_file.h"
#include "err/err.h"
#include <shared_ptr>
#include <unordered>
namespace dom
{
class ProtobufPlugin;
typedef shared_ptr<ProtobufPlugin> ProtobufPluginSPtr;
typedef unordered_set<ProtobufPluginSPtr> ProtobufPluginSet;
typedef shared_ptr<ProtobufPluginSet> ProtobufPluginSetSPtr;
class ProtobufPlugin : public Element<ProtobufPlugin>
{
public:
ProtobufPlugin();
doim::FsFileSPtr binary()
{
return mBinary;
}
// Updates
ECode updateBinary(const doim::FsFileSPtr& binary);
private:
doim::FsFileSPtr mBinary;
};
}
| [
"[email protected]"
] | |
41bf7f2eeb79c917b3dff92962c0458022f1fa13 | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/chromium_org/third_party/WebKit/Source/bindings/v8/custom/V8MessageEventCustom.cpp | 9060e643728f40367c20cf7436610219e4f14d20 | [
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"Apache-2.0",
"MIT",
"BSD-3-Clause"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 6,311 | cpp | /*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "V8MessageEvent.h"
#include "V8Blob.h"
#include "V8MessagePort.h"
#include "V8Window.h"
#include "bindings/v8/SerializedScriptValue.h"
#include "bindings/v8/V8Binding.h"
#include "bindings/v8/V8HiddenPropertyName.h"
#include "bindings/v8/custom/V8ArrayBufferCustom.h"
#include "core/events/MessageEvent.h"
namespace WebCore {
void V8MessageEvent::dataAttributeGetterCustom(const v8::PropertyCallbackInfo<v8::Value>& info)
{
MessageEvent* event = V8MessageEvent::toNative(info.Holder());
v8::Handle<v8::Value> result;
switch (event->dataType()) {
case MessageEvent::DataTypeScriptValue: {
result = info.Holder()->GetHiddenValue(V8HiddenPropertyName::data(info.GetIsolate()));
if (result.IsEmpty()) {
if (!event->dataAsSerializedScriptValue()) {
// If we're in an isolated world and the event was created in the main world,
// we need to find the 'data' property on the main world wrapper and clone it.
v8::Local<v8::Value> mainWorldData = getHiddenValueFromMainWorldWrapper(info.GetIsolate(), event, V8HiddenPropertyName::data(info.GetIsolate()));
if (!mainWorldData.IsEmpty())
event->setSerializedData(SerializedScriptValue::createAndSwallowExceptions(mainWorldData, info.GetIsolate()));
}
if (event->dataAsSerializedScriptValue())
result = event->dataAsSerializedScriptValue()->deserialize(info.GetIsolate());
else
result = v8::Null(info.GetIsolate());
}
break;
}
case MessageEvent::DataTypeSerializedScriptValue:
if (SerializedScriptValue* serializedValue = event->dataAsSerializedScriptValue()) {
MessagePortArray ports = event->ports();
result = serializedValue->deserialize(info.GetIsolate(), &ports);
} else {
result = v8::Null(info.GetIsolate());
}
break;
case MessageEvent::DataTypeString: {
String stringValue = event->dataAsString();
result = v8String(info.GetIsolate(), stringValue);
break;
}
case MessageEvent::DataTypeBlob:
result = toV8(event->dataAsBlob(), info.Holder(), info.GetIsolate());
break;
case MessageEvent::DataTypeArrayBuffer:
result = toV8(event->dataAsArrayBuffer(), info.Holder(), info.GetIsolate());
break;
}
// Overwrite the data attribute so it returns the cached result in future invocations.
// This custom handler (dataAccessGetter) will not be called again.
v8::PropertyAttribute dataAttr = static_cast<v8::PropertyAttribute>(v8::DontDelete | v8::ReadOnly);
info.Holder()->ForceSet(v8AtomicString(info.GetIsolate(), "data"), result, dataAttr);
v8SetReturnValue(info, result);
}
void V8MessageEvent::initMessageEventMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
{
MessageEvent* event = V8MessageEvent::toNative(info.Holder());
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, typeArg, info[0]);
V8TRYCATCH_VOID(bool, canBubbleArg, info[1]->BooleanValue());
V8TRYCATCH_VOID(bool, cancelableArg, info[2]->BooleanValue());
v8::Handle<v8::Value> dataArg = info[3];
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, originArg, info[4]);
V8TRYCATCH_FOR_V8STRINGRESOURCE_VOID(V8StringResource<>, lastEventIdArg, info[5]);
DOMWindow* sourceArg = 0;
if (info[6]->IsObject()) {
v8::Handle<v8::Object> wrapper = v8::Handle<v8::Object>::Cast(info[6]);
v8::Handle<v8::Object> window = wrapper->FindInstanceInPrototypeChain(V8Window::domTemplate(info.GetIsolate(), worldTypeInMainThread(info.GetIsolate())));
if (!window.IsEmpty())
sourceArg = V8Window::toNative(window);
}
OwnPtr<MessagePortArray> portArray;
const int portArrayIndex = 7;
if (!isUndefinedOrNull(info[portArrayIndex])) {
portArray = adoptPtr(new MessagePortArray);
if (!getMessagePortArray(info[portArrayIndex], portArrayIndex + 1, *portArray, info.GetIsolate()))
return;
}
event->initMessageEvent(typeArg, canBubbleArg, cancelableArg, originArg, lastEventIdArg, sourceArg, portArray.release());
if (!dataArg.IsEmpty()) {
info.Holder()->SetHiddenValue(V8HiddenPropertyName::data(info.GetIsolate()), dataArg);
if (isolatedWorldForIsolate(info.GetIsolate()))
event->setSerializedData(SerializedScriptValue::createAndSwallowExceptions(dataArg, info.GetIsolate()));
}
}
void V8MessageEvent::webkitInitMessageEventMethodCustom(const v8::FunctionCallbackInfo<v8::Value>& info)
{
initMessageEventMethodCustom(info);
}
} // namespace WebCore
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.