blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
listlengths 1
1
| author_id
stringlengths 0
158
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
51876bbffd356a65aa2b76d8d2a7ccc766ba8731
|
92f1c33f2909f3f39ab7eecddeb879518c2e534e
|
/wezel.cpp
|
c29e8cda2c57e092106fa96a72dc286158cda739
|
[] |
no_license
|
kiug/lsp
|
c0b35b1000237d9a6ce66ec2081c6cdf045a670d
|
74af2c6ec6ba402ed00d54f25db8d13cf2de7c39
|
refs/heads/master
| 2016-09-06T05:45:53.101103
| 2015-08-14T07:46:18
| 2015-08-14T07:46:18
| 40,702,191
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 100
|
cpp
|
#include "wezel.h"
#include "widok.h"
#include <QDebug>
Wezel::Wezel()
{
}
Wezel::~Wezel()
{
}
|
[
"karoldro@gmail.com"
] |
karoldro@gmail.com
|
7aa1b63810ed03544e193bb26f6b4f5a2eb1c7bb
|
d1c1eea01b817e6bc39bd7fbcf74188f3dd8d622
|
/A - HTML /main.cpp
|
042d7314b98f9dddff01d68c2942c93081980e61
|
[] |
no_license
|
kamol7/Online-Judge-Problems-solved
|
93d488341a2b0299fdd638b1615d1fee8de82e31
|
3d135f288b2001a8372fa3df101284a6cc8a3ff0
|
refs/heads/master
| 2020-07-30T19:29:23.900029
| 2019-09-23T11:00:10
| 2019-09-23T11:00:10
| 210,332,744
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,236
|
cpp
|
#include <iostream>
#include <string>
using namespace std;
int main() {
//std::cout << "Hello, World!" << std::endl;
std::string x="";
for(int i=0;i<80;i++) x+="-";
int line=0;
int size=0;
string takeInput;
while(cin>>takeInput){
if(takeInput== "<br>"){
cout<<endl;
line=0;
}
else if( takeInput== "<hr>"){
if(line==0) {
cout<<x<<endl;
}
else {
cout<<"\n"<<x<<endl;
}
line=0;
}
else {
size= takeInput.size();
if(size==80){
if(line ==0)cout<<takeInput<<endl;
else {
line=0;
cout<<"\n"<<takeInput<<endl;
}
}
else if(line+size<80){
if(line==0){
cout<<takeInput;
line--;
}
else cout<<" "<<takeInput;
line+=size+1;
}
else{
cout<<"\n"<<takeInput;
line=size;
}
}
takeInput.clear();
}
if(line>0) cout<<endl;
return 0;
}
|
[
"ckamol7@gmail.com"
] |
ckamol7@gmail.com
|
fdc13350162fb71760ddf8cc8c93a7229a6832e9
|
bb24e332a82af41807c9b67c85d5d15336dc0470
|
/src/Rifle.hpp
|
b4c97c6a5547aa414456be813fda6fd5782cd1f5
|
[
"MIT"
] |
permissive
|
Muikkunen/Lieburo
|
04fa604ac9585539ba0b9566e9ab971a99f64650
|
48216f2cbf8c8d96687581f595c2822136b614b4
|
refs/heads/master
| 2021-01-13T16:20:45.473695
| 2017-01-23T19:53:43
| 2017-01-23T19:53:43
| 79,841,610
| 0
| 0
| null | 2017-01-23T19:51:34
| 2017-01-23T19:51:34
| null |
UTF-8
|
C++
| false
| false
| 199
|
hpp
|
#pragma once
#include "Weapon.hpp"
#include "Game.hpp"
class Rifle : public Weapon {
public:
Rifle(Game* game);
virtual void shoot(float angle, b2Vec2 position, b2Vec2 preSpeed, Game* game);
};
|
[
"alvar.martti@gmail.com"
] |
alvar.martti@gmail.com
|
c2ae790deea334a86b0f3716174081126f5e86eb
|
5a075cc56820038a97d225b9f4a17a003021fa78
|
/uva/401.cpp
|
c98a11af403da2606e40aba05f535c64af10888e
|
[] |
no_license
|
nahid0335/Problem-solving
|
e5f1fc9d70c10992655c8dceceec6eb89da953c0
|
89c1e94048b9f8fb7259294b8f5a3176723041e7
|
refs/heads/master
| 2020-11-26T07:02:56.944184
| 2019-12-19T09:33:58
| 2019-12-19T09:33:58
| 228,997,106
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,187
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
string s,x,y;
char m[3000];
int k=1;
memset(m,NULL,sizeof(m));
m['A']='A';
m['E']='3';
m['H']='H';
m['I']='I';
m['J']='L';
m['L']='J';
m['M']='M';
m['O']='O';
m['S']='2';
m['T']='T';
m['U']='U';
m['V']='V';
m['W']='W';
m['X']='X';
m['Y']='Y';
m['Z']='5';
m['1']='1';
m['2']='S';
m['3']='E';
m['5']='Z';
m['8']='8';
while(cin>>s)
{
x=y="";
int l;
l=s.size();
for(int i=l-1;i>=0;i--)
{
x+=s[i];
y+=m[s[i]];
}
if (s==x && s==y)
{
cout<<s<<" -- is a mirrored palindrome."<<endl;
}
else if(s==x && s!=y)
{
cout<<s<<" -- is a regular palindrome."<<endl;
}
else if(s!=x && s==y)
{
cout<<s<<" -- is a mirrored string."<<endl;
}
else if(s!=x && s!=y)
{
cout<<s<<" -- is not a palindrome."<<endl;
}
cout<<endl;
}
return 0;
}
|
[
"nahid0335@gmail.com"
] |
nahid0335@gmail.com
|
0f682df95b7ce1b3b66fd627035b60a9878c40c1
|
ecfb2256ddb3febd10f8b732c25eaf07b0de52fb
|
/54_Movement_detection_Optical_Flow/main.cpp
|
2cd662a602e3578a955e75de0ca4b66310d1a690
|
[] |
no_license
|
inovision/visioncomputador
|
65900fab1647012e3af82ea96bea99f65475ea96
|
ca90cfc6d00375608af474183af7be905c6c437c
|
refs/heads/master
| 2021-04-03T09:29:14.794279
| 2018-04-11T19:08:23
| 2018-04-11T19:08:23
| 124,695,174
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,860
|
cpp
|
#include <iostream>
#include <opencv/cv.hpp>
using namespace std;
using namespace cv;
#define MAX_CORNERS 500
#define ESCAPE 27
int main()
{
//Mat frame, back, fore, dest;
VideoCapture capture("c://edx//IcabMovimientoEscenaEstatica.mp4");
//Ptr<BackgroundSubtractorMOG2> bg = createBackgroundSubtractorMOG2(500, 16, true);
//VideoCapture capture;
// Objects
Mat frame;
// keyboard pressed
char keypressed = 0;
bool success;
// Load image from disk
//capture.open(0);
// if not success, exit program
// if (!capture.isOpened()){
// cout << "error in VideoCapture: check path file" << endl;
// getchar();
// return 1;
// }
/// Parameters for Shi-Tomasi algorithm
vector<Point2f> cornersA, cornersB;
double qualityLevel = 0.01;
double minDistance = 10;
int blockSize = 3;
bool useHarrisDetector = false;
double k = 0.04;
int maxCorners = MAX_CORNERS;
// winsize has to be 11 or 13, otherwise nothing is found
vector<uchar> status;
vector<float> error;
int winsize = 11;
int maxlvl = 5;
// Objects
Mat img_prev, img_next, grayA, grayB;
success = capture.read(frame);
// if no success exit program
if (success == false){
cout << "Cannot read the frame from file" << endl;
getchar();
return 1;
}
img_prev = frame.clone();
// Windows for all the images
namedWindow("Corners A", CV_WINDOW_AUTOSIZE);
namedWindow("Corners B", CV_WINDOW_AUTOSIZE);
while (keypressed != ESCAPE)
{
// read frame by frame in a loop
success = capture.read(frame);
// if no success exit program
if (success == false){
cout << "Cannot read the frame from file" << endl;
return 1;
}
img_next = frame.clone();
// convert to grayScale
cvtColor(img_prev, grayA, CV_RGB2GRAY);
cvtColor(img_next, grayB, CV_RGB2GRAY);
/// Apply corner detection
goodFeaturesToTrack(grayA,
cornersA,
maxCorners,
qualityLevel,
minDistance,
Mat(),
blockSize,
useHarrisDetector,
k);
calcOpticalFlowPyrLK(grayA, grayB, cornersA, cornersB, status, error,
Size(winsize, winsize), maxlvl);
/// Draw corners detected
//cout << "Number of cornersA detected: " << cornersA.size() << endl;
//cout << "Optical Flow corners detected: " << cornersB.size() << endl;
for (uint i = 0; i < cornersA.size(); i++)
{
line(img_prev, cornersA[i], cornersB[i], Scalar(0, 255, 0), 2);
}
// Show image in the name of the window
imshow("Corners A", img_prev);
imshow("Corners B", img_next);
// Function for show the image in ms.
keypressed = waitKey(1);
img_prev = img_next;
}
// Free memory
img_prev.release();
img_next.release();
grayA.release();
grayB.release();
destroyAllWindows();
// End of the program
return 0;
}
|
[
"pablo.an@gmail.com"
] |
pablo.an@gmail.com
|
11405f404ae3eb7503bfc75212ef27d2fa6dad10
|
5c0f282a4e3e8fec68b20317c9a07247bd8b4616
|
/src/core/hw/gfxip/computeCmdBuffer.cpp
|
2c74c651be85c9286dbc85ce0cc3860f1f54d347
|
[
"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
| 9,802
|
cpp
|
/*
*******************************************************************************
*
* Copyright (c) 2015-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.
******************************************************************************/
#include "core/cmdAllocator.h"
#include "core/device.h"
#include "core/hw/gfxip/computeCmdBuffer.h"
#include "core/hw/gfxip/gfxDevice.h"
#include "core/hw/gfxip/pipeline.h"
#include "palShader.h"
#include <limits.h>
using namespace Util;
namespace Pal
{
// =====================================================================================================================
// Dummy function for catching illegal attempts to set graphics user-data entries on a Compute command buffer.
static void PAL_STDCALL DummyCmdSetUserDataGfx(
ICmdBuffer* pCmdBuffer,
uint32 firstEntry,
uint32 entryCount,
const uint32* pEntryValues)
{
PAL_ASSERT_ALWAYS();
}
// =====================================================================================================================
ComputeCmdBuffer::ComputeCmdBuffer(
const GfxDevice& device,
const CmdBufferCreateInfo& createInfo,
PrefetchMgr* pPrefetchMgr,
GfxCmdStream* pCmdStream)
:
GfxCmdBuffer(device, createInfo, pPrefetchMgr, pCmdStream),
m_device(device),
m_pCmdStream(pCmdStream)
{
PAL_ASSERT(createInfo.queueType == QueueTypeCompute);
memset(&m_computeState, 0, sizeof(m_computeState));
memset(&m_computeRestoreState, 0, sizeof(m_computeRestoreState));
SwitchCmdSetUserDataFunc(PipelineBindPoint::Compute, &GfxCmdBuffer::CmdSetUserDataCs);
SwitchCmdSetUserDataFunc(PipelineBindPoint::Graphics, &DummyCmdSetUserDataGfx);
}
// =====================================================================================================================
// Resets the command buffer's previous contents and state, then puts it into a building state allowing new commands
// to be recorded.
// Also starts command buffer dumping, if it is enabled.
Result ComputeCmdBuffer::Begin(
const CmdBufferBuildInfo& info)
{
const Result result = GfxCmdBuffer::Begin(info);
#if PAL_ENABLE_PRINTS_ASSERTS
if ((result == Result::Success) && (IsDumpingEnabled()))
{
char filename[MaxFilenameLength] = {};
// filename is: computexx_yyyyy, where "xx" is the number of compute command buffers that have been created so
// far (one based) and "yyyyy" is the number of times this command buffer has been begun (also
// one based).
//
// All streams associated with this command buffer are included in this one file.
Snprintf(filename, MaxFilenameLength, "compute%02d_%05d", UniqueId(), NumBegun());
OpenCmdBufDumpFile(&filename[0]);
}
#endif
return result;
}
// =====================================================================================================================
// Puts the command stream into a state that is ready for command building.
Result ComputeCmdBuffer::BeginCommandStreams(
CmdStreamBeginFlags cmdStreamFlags,
bool doReset)
{
Result result = GfxCmdBuffer::BeginCommandStreams(cmdStreamFlags, doReset);
if (doReset)
{
m_pCmdStream->Reset(nullptr, true);
}
if (result == Result::Success)
{
result = m_pCmdStream->Begin(cmdStreamFlags, m_pMemAllocator);
}
return result;
}
// =====================================================================================================================
// Completes recording of a command buffer in the building state, making it executable.
// Also ends command buffer dumping, if it is enabled.
Result ComputeCmdBuffer::End()
{
Result result = GfxCmdBuffer::End();
if (result == Result::Success)
{
result = m_pCmdStream->End();
}
if (result == Result::Success)
{
#if PAL_ENABLE_PRINTS_ASSERTS
if (IsDumpingEnabled() && DumpFile()->IsOpen())
{
if (m_device.Parent()->Settings().submitTimeCmdBufDumpMode == CmdBufDumpModeBinaryHeaders)
{
const CmdBufferDumpFileHeader fileHeader =
{
static_cast<uint32>(sizeof(CmdBufferDumpFileHeader)), // Structure size
1, // Header version
m_device.Parent()->ChipProperties().familyId, // ASIC family
m_device.Parent()->ChipProperties().deviceId, // Reserved, but use for PCI device ID
0 // Reserved
};
DumpFile()->Write(&fileHeader, sizeof(fileHeader));
CmdBufferListHeader listHeader =
{
static_cast<uint32>(sizeof(CmdBufferListHeader)), // Structure size
0, // Engine index
0 // Number of command buffer chunks
};
listHeader.count = m_pCmdStream->GetNumChunks();
DumpFile()->Write(&listHeader, sizeof(listHeader));
}
DumpCmdStreamsToFile(DumpFile(), m_device.Parent()->Settings().submitTimeCmdBufDumpMode);
DumpFile()->Close();
}
#endif
}
return result;
}
// =====================================================================================================================
// Explicitly resets a command buffer, releasing any internal resources associated with it and putting it in the reset
// state.
Result ComputeCmdBuffer::Reset(
ICmdAllocator* pCmdAllocator,
bool returnGpuMemory)
{
Result result = GfxCmdBuffer::Reset(pCmdAllocator, returnGpuMemory);
m_pCmdStream->Reset(static_cast<CmdAllocator*>(pCmdAllocator), returnGpuMemory);
return result;
}
// =====================================================================================================================
// Resets all of the command buffer state tracked. After a reset there should be no state bound.
void ComputeCmdBuffer::ResetState()
{
GfxCmdBuffer::ResetState();
memset(&m_computeState, 0, sizeof(m_computeState));
memset(&m_computeRestoreState, 0, sizeof(m_computeRestoreState));
}
// =====================================================================================================================
void ComputeCmdBuffer::CmdBindPipeline(
const PipelineBindParams& params)
{
PAL_ASSERT(params.pipelineBindPoint == PipelineBindPoint::Compute);
m_computeState.pipelineState.pPipeline = static_cast<const Pipeline*>(params.pPipeline);
m_computeState.pipelineState.dirtyFlags.pipelineDirty = 1;
m_computeState.dynamicCsInfo = params.cs;
}
#if PAL_ENABLE_PRINTS_ASSERTS
// =====================================================================================================================
// Dumps this command buffer's single command stream to the given file with an appropriate header.
void ComputeCmdBuffer::DumpCmdStreamsToFile(
File* pFile,
CmdBufDumpMode mode
) const
{
m_pCmdStream->DumpCommands(pFile, "# Compute Queue - Command length = ", mode);
}
#endif
// =====================================================================================================================
CmdStream* ComputeCmdBuffer::GetCmdStreamByEngine(
uint32 engineType)
{
return TestAnyFlagSet(m_engineSupport, engineType) ? m_pCmdStream : nullptr;
}
// =====================================================================================================================
// Helper method for handling the state "leakage" from a nested command buffer back to its caller. Since the callee has
// tracked its own state during the building phase, we can access the final state of the command buffer since its stored
// in the ComputeCmdBuffer object itself.
void ComputeCmdBuffer::LeakNestedCmdBufferState(
const ComputeCmdBuffer& cmdBuffer) // [in] Nested command buffer whose state we're absorbing.
{
LeakPerPipelineStateChanges(cmdBuffer.m_computeState.pipelineState,
cmdBuffer.m_computeState.csUserDataEntries,
&m_computeState.pipelineState,
&m_computeState.csUserDataEntries);
// NOTE: Compute command buffers shouldn't have changed either of their CmdSetUserData callbacks.
PAL_ASSERT(memcmp(&m_funcTable, &cmdBuffer.m_funcTable, sizeof(m_funcTable)) == 0);
}
} // Pal
|
[
"jacob.he@amd.com"
] |
jacob.he@amd.com
|
ba331fa56a80ffb26c85720f47afc19a4b2b2380
|
d83cfab7bea45f6f553cf7ab87e3b7d9ac9c8721
|
/src/ui/Tools/ToolsPanelHandler.cpp
|
b49c36926a598a30950391aeab7a3398af76bb22
|
[] |
no_license
|
edherbert/Rockpool
|
f40b0e1ea9c39fdd0c957597af61d62c80c75405
|
47ce54779c4690e73aaf4cd67d5e9061bc41f1df
|
refs/heads/master
| 2021-08-14T14:03:34.749396
| 2017-11-15T23:33:12
| 2017-11-15T23:33:12
| 107,127,160
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,743
|
cpp
|
#include "ToolsPanelHandler.h"
#include "../wxIDs.h"
#include "ToolPreferencesHandler.h"
ToolsPanelHandler::ToolsPanelHandler(MainFrame *mainFrame, wxAuiManager *auiManager) : wxApp(){
this->auiManager = auiManager;
this->mainFrame = mainFrame;
wxBitmap bitmap(wxT("../media/img/icon.png"));
toolbar = new wxAuiToolBar(mainFrame, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxAUI_TB_DEFAULT_STYLE);
toolbar->SetToolBitmapSize(wxSize(20, 23));
toolbar->AddTool(TOOL_PANEL_TERRAIN_EDIT, bitmap, bitmap, true);
toolbar->AddTool(TOOL_PANEL_TERRAIN_TEXTURE, bitmap, bitmap, true);
toolbar->AddTool(TOOL_PANEL_TERRAIN_HEIGHT, bitmap, bitmap, true);
toolbar->AddTool(TOOL_PANEL_TERRAIN_SMOOTH, bitmap, bitmap, true);
tools[0] = TOOL_PANEL_TERRAIN_EDIT;
tools[1] = TOOL_PANEL_TERRAIN_TEXTURE;
tools[2] = TOOL_PANEL_TERRAIN_HEIGHT;
tools[3] = TOOL_PANEL_TERRAIN_SMOOTH;
auiManager->AddPane(toolbar, wxAuiPaneInfo().Name(wxT("Terrains Toolbar")).Caption(wxT("Terrains Toolbar")).ToolbarPane().Top());
toolbar->Realize();
Connect(TOOL_PANEL_TERRAIN_EDIT, wxEVT_TOOL, wxCommandEventHandler(ToolsPanelHandler::terrainEditToolCallback));
Connect(TOOL_PANEL_TERRAIN_TEXTURE, wxEVT_TOOL, wxCommandEventHandler(ToolsPanelHandler::terrainTextureToolCallback));
Connect(TOOL_PANEL_TERRAIN_HEIGHT, wxEVT_TOOL, wxCommandEventHandler(ToolsPanelHandler::terrainHeightToolCallback));
Connect(TOOL_PANEL_TERRAIN_SMOOTH, wxEVT_TOOL, wxCommandEventHandler(ToolsPanelHandler::terrainSmoothToolCallback));
//setTool(TOOL_PANEL_TERRAIN_EDIT);
setTool(TOOL_PANEL_TERRAIN_TEXTURE);
setToolPanelVisibility(false);
}
ToolsPanelHandler::~ToolsPanelHandler(){
}
void ToolsPanelHandler::setTool(int toolId){
for(int i = 0; i < sizeof(tools) / sizeof(int); i++){
toolbar->ToggleTool(tools[i], false);
}
currentTool = toolId;
toolbar->ToggleTool(toolId, true);
mainFrame->getToolPreferencesHandler()->setToolPreference(toolId);
}
void ToolsPanelHandler::terrainEditToolCallback(wxCommandEvent &event){
setTool(TOOL_PANEL_TERRAIN_EDIT);
}
void ToolsPanelHandler::terrainTextureToolCallback(wxCommandEvent &event){
setTool(TOOL_PANEL_TERRAIN_TEXTURE);
}
void ToolsPanelHandler::terrainHeightToolCallback(wxCommandEvent &event){
setTool(TOOL_PANEL_TERRAIN_HEIGHT);
}
void ToolsPanelHandler::terrainSmoothToolCallback(wxCommandEvent &event){
setTool(TOOL_PANEL_TERRAIN_SMOOTH);
}
int ToolsPanelHandler::getCurrentTool(){
return currentTool;
}
void ToolsPanelHandler::setToolPanelVisibility(bool val){
if(val) toolbar->Show();
else toolbar->Hide();
mainFrame->showTerrainToolbar->Check(val);
auiManager->Update();
}
|
[
"edwardherbert802@yahoo.com"
] |
edwardherbert802@yahoo.com
|
353e6e8b67cd99fa2b157b838f789f2e2f6a973e
|
a1faa72eea32203df772b03d1940129a9fdfd0e5
|
/tutorial-3/include/glhelper.h
|
dbb4daa863bcec5c4722eb1653c2c459a1c26e74
|
[] |
no_license
|
ChuaSTGrace/CSD2100_OpenGL-Dev
|
e47d6fd0922d6cbba10b4d9c7628ae55e6d22ac4
|
b7b40b4ea88b4d9637c5a2b035417dacd0930d2f
|
refs/heads/master
| 2023-07-22T12:01:36.893814
| 2021-09-10T02:13:07
| 2021-09-10T02:13:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,988
|
h
|
/* !
@file glhelper.h
@author pghali@digipen.edu
@date 10/11/2016
This file contains the declaration of namespace Helper that encapsulates the
functionality required to create an OpenGL context using GLFW; use GLEW
to load OpenGL extensions; initialize OpenGL state; and finally initialize
the OpenGL application by calling initalization functions associated with
objects participating in the application.
*//*__________________________________________________________________________*/
/* guard
----------------------------------------------------------------------------- */
#ifndef GLHELPER_H
#define GLHELPER_H
/* includes
----------------------------------------------------------------------------- */
#include <GL/glew.h> // for access to OpenGL API declarations
#include <GLFW/glfw3.h>
#include <string>
/* _________________________________________________________________________ */
struct GLHelper
/*! GLHelper structure to encapsulate initialization stuff ...
*/
{
static bool init(GLint w, GLint h, std::string t);
static void cleanup();
// callbacks ...
static void error_cb(int error, char const* description);
static void fbsize_cb(GLFWwindow *ptr_win, int width, int height);
// I/O callbacks ...
static void key_cb(GLFWwindow *pwin, int key, int scancode, int action, int mod);
static void mousebutton_cb(GLFWwindow *pwin, int button, int action, int mod);
static void mousescroll_cb(GLFWwindow *pwin, double xoffset, double yoffset);
static void mousepos_cb(GLFWwindow *pwin, double xpos, double ypos);
static double update_time(double fpsCalcInt = 1.0);
static GLboolean mouseLeft;
static GLboolean keystateP;
static GLint width, height;
static GLdouble fps;
static std::string title;
static GLFWwindow *ptr_window;
static void print_specs ();
};
#endif /* GLHELPER_H */
|
[
"jeejiamin@gmail.com"
] |
jeejiamin@gmail.com
|
a9b4ec4bbf73a176419d703c5139049d8639eb85
|
f83ef53177180ebfeb5a3e230aa29794f52ce1fc
|
/ACE/ACE_wrappers/TAO/orbsvcs/orbsvcs/Notify/MonitorControlExt/MonitorEventChannelFactory.h
|
311fb73d097ce5f23e9517a77da624429f126cde
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-sun-iiop"
] |
permissive
|
msrLi/portingSources
|
fe7528b3fd08eed4a1b41383c88ee5c09c2294ef
|
57d561730ab27804a3172b33807f2bffbc9e52ae
|
refs/heads/master
| 2021-07-08T01:22:29.604203
| 2019-07-10T13:07:06
| 2019-07-10T13:07:06
| 196,183,165
| 2
| 1
|
Apache-2.0
| 2020-10-13T14:30:53
| 2019-07-10T10:16:46
| null |
UTF-8
|
C++
| false
| false
| 3,006
|
h
|
#ifndef MONITOREVENTCHANNELFACTORY_H
#define MONITOREVENTCHANNELFACTORY_H
#include /**/ "ace/pre.h"
#include "ace/Hash_Map_Manager_T.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include "ace/Vector_T.h"
#include "ace/Monitor_Base.h"
#include "orbsvcs/Notify/EventChannelFactory.h"
#include "orbsvcs/Notify/MonitorControl/Timestamp_Monitor.h"
#include "orbsvcs/Notify/MonitorControlExt/NotifyMonitoringExtS.h"
#if defined (TAO_HAS_MONITOR_FRAMEWORK) && (TAO_HAS_MONITOR_FRAMEWORK == 1)
using namespace ACE_VERSIONED_NAMESPACE_NAME::ACE::Monitor_Control;
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
class TAO_Notify_MC_Ext_Export TAO_MonitorEventChannelFactory
: public TAO_Notify_EventChannelFactory,
public virtual POA_NotifyMonitoringExt::EventChannelFactory
{
public:
/// Construct a named event channel factory and associate various
/// statistic objects with it in the statistic registry
TAO_MonitorEventChannelFactory (const char* name);
/// Remove the factory name from the factory names statistic
~TAO_MonitorEventChannelFactory (void);
/// Create a named event channel and associate various statistic
/// objects with it in the statistic registry
virtual CosNotifyChannelAdmin::EventChannel_ptr
create_named_channel(const CosNotification::QoSProperties& initial_qos,
const CosNotification::AdminProperties& initial_admin,
CosNotifyChannelAdmin::ChannelID_out id,
const char* name);
/// Create an event channel and use the id as the name.
virtual CosNotifyChannelAdmin::EventChannel_ptr
create_channel(const CosNotification::QoSProperties& initial_qos,
const CosNotification::AdminProperties& initial_admin,
CosNotifyChannelAdmin::ChannelID_out id);
/// Hook into the remove() call from the base class and remove it from
/// our map before passing control back to the base.
virtual void remove (TAO_Notify_EventChannel* channel);
// This is public to allow the Unbinder class access
// for SunCC 5.5 and above
typedef ACE_Hash_Map_Manager<ACE_CString,
CosNotifyChannelAdmin::ChannelID,
ACE_SYNCH_NULL_MUTEX> Map;
private:
size_t get_consumers (CosNotifyChannelAdmin::ChannelID id);
size_t get_suppliers (CosNotifyChannelAdmin::ChannelID id);
size_t get_ecs (Monitor_Control_Types::NameList* names, bool active);
friend class EventChannels;
class Unbinder
{
public:
Unbinder (Map& map,
const ACE_CString& name);
~Unbinder (void);
void release (void);
private:
Map& map_;
const ACE_CString& name_;
bool released_;
};
TAO_SYNCH_RW_MUTEX mutex_;
ACE_CString name_;
Map map_;
ACE_Vector<ACE_CString> stat_names_;
};
TAO_END_VERSIONED_NAMESPACE_DECL
#endif /* TAO_HAS_MONITOR_FRAMEWORK==1 */
#include /**/ "ace/post.h"
#endif /* MONITOREVENTCHANNELFACTORY_H */
|
[
"lihuibin705@163.com"
] |
lihuibin705@163.com
|
6d079461e1fa6dab33301bd518685ad4eb612bec
|
2e41d302378e32ed9cf9e3c61c0d228c4a89373c
|
/Seminarski/main.cpp
|
8fefe9cb9d50333b8c6bbc59a735a6c339cb30f2
|
[] |
no_license
|
SKantar/Reversi
|
44534082170b5100a3ece3920785c4fc13d830a1
|
569d05357df1f874b96056c1f70976f241f108a9
|
refs/heads/master
| 2020-04-29T13:47:20.454480
| 2016-10-26T10:53:30
| 2016-10-26T10:53:30
| 30,535,276
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,593
|
cpp
|
#define WINVER 0x500
#include <windows.h>
#include <iostream>
#include "Application.h"
#include "Dragndrop.h"
#include "Board.h"
#include "Reversi.h"
#include <vector>
//#include "MS_IKSOKS.h"
using namespace std;
int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nCmdShow)
{
application.initialize(hThisInstance, hPrevInstance, lpszArgument, nCmdShow);
application.setTitle("Reversi");
application.setBackgroundColor(RGB(20,100,50));
application.setDimensions(770,800);
/* vector <ReversiFigura> f;
for(int i = 0; i < MAXN; i++)
for(int j = 0; j < MAXM; j++)
if(i == 3 && j == 4) f.push_back(new ReversiFigura(1,i,j));
else if(i == 4 && j == 3) f.push_back(new ReversiFigura(1,i,j));
else if(i == 3 && j == 3) f.push_back(new ReversiFigura(2,i,j));
else if(i == 4 && j == 4) f.push_back(new ReversiFigura(2,i,j));
else f.push_back(new ReversiFigura(0,i,j));*/
Reversi reversi;
ReversiFigura f1(0, 0, 0);
ReversiFigura f2(0, 0, 1);
ReversiFigura f3(0, 0, 2);
ReversiFigura f4(0, 0, 3);
ReversiFigura f5(0, 0, 4);
ReversiFigura f6(0, 0, 5);
ReversiFigura f7(0, 0, 6);
ReversiFigura f8(0, 0, 7);
ReversiFigura f9(0, 1, 0);
ReversiFigura f10(0, 1, 1);
ReversiFigura f11(0, 1, 2);
ReversiFigura f12(0, 1, 3);
ReversiFigura f13(0, 1, 4);
ReversiFigura f14(0, 1, 5);
ReversiFigura f15(0, 1, 6);
ReversiFigura f16(0, 1, 7);
ReversiFigura f17(0, 2, 0);
ReversiFigura f18(0, 2, 1);
ReversiFigura f19(0, 2, 2);
ReversiFigura f20(0, 2, 3);
ReversiFigura f21(0, 2, 4);
ReversiFigura f22(0, 2, 5);
ReversiFigura f23(0, 2, 6);
ReversiFigura f24(0, 2, 7);
ReversiFigura f25(0, 3, 0);
ReversiFigura f26(0, 3, 1);
ReversiFigura f27(0, 3, 2);
ReversiFigura f28(1, 3, 3);
ReversiFigura f29(2, 3, 4);
ReversiFigura f30(0, 3, 5);
ReversiFigura f31(0, 3, 6);
ReversiFigura f32(0, 3, 7);
ReversiFigura f33(0, 4, 0);
ReversiFigura f34(0, 4, 1);
ReversiFigura f35(0, 4, 2);
ReversiFigura f36(2, 4, 3);
ReversiFigura f37(1, 4, 4);
ReversiFigura f38(0, 4, 5);
ReversiFigura f39(0, 4, 6);
ReversiFigura f40(0, 4, 7);
ReversiFigura f41(0, 5, 0);
ReversiFigura f42(0, 5, 1);
ReversiFigura f43(0, 5, 2);
ReversiFigura f44(0, 5, 3);
ReversiFigura f45(0, 5, 4);
ReversiFigura f46(0, 5, 5);
ReversiFigura f47(0, 5, 6);
ReversiFigura f48(0, 5, 7);
ReversiFigura f49(0, 6, 0);
ReversiFigura f50(0, 6, 1);
ReversiFigura f51(0, 6, 2);
ReversiFigura f52(0, 6, 3);
ReversiFigura f53(0, 6, 4);
ReversiFigura f54(0, 6, 5);
ReversiFigura f55(0, 6, 6);
ReversiFigura f56(0, 6, 7);
ReversiFigura f57(0, 7, 0);
ReversiFigura f58(0, 7, 1);
ReversiFigura f59(0, 7, 2);
ReversiFigura f60(0, 7, 3);
ReversiFigura f61(0, 7, 4);
ReversiFigura f62(0, 7, 5);
ReversiFigura f63(0, 7, 6);
ReversiFigura f64(0, 7, 7);
//ReversiFigura c1(1, -1, 0);
//ReversiFigura c2(2, 8, 0);
/*
IksOksFigura f1(false, 100,100);
IksOksFigura f12(true, 100,100);
IksOksFigura f13(false, 100,100);
IksOksFigura f4(true, 100,100);
IksOksFigura f2(false, 100,100);
IksOksFigura f3(true, 100,100);
IksOksFigura f5(false, 100,100);
IksOksFigura f6(true, 100,100);
IksOksFigura f7(false, 100,100);
*/
application.run();
return 0;
}
|
[
"skantar12@gmail.com"
] |
skantar12@gmail.com
|
ce29b5a15442c851cf288b440d6a24847878a041
|
54b9e1d9945cbcd39aa0fbc955d81e402042a471
|
/src/components/IF/httpd_protocol.h
|
662569501ca7e7b5a2b56240a19f4b02f8993c74
|
[] |
no_license
|
huangdeng525/dcop
|
17364e209cac590a7f2c2f7ba57a4526d38cf670
|
e7f254d2a4c99743b32d436d974ef5cef3a1caaf
|
refs/heads/master
| 2021-06-18T18:47:42.665179
| 2020-12-30T09:23:12
| 2020-12-30T09:23:12
| 144,436,513
| 1
| 0
| null | 2018-08-12T04:03:47
| 2018-08-12T04:03:46
| null |
GB18030
|
C++
| false
| false
| 3,360
|
h
|
/// -------------------------------------------------
/// httpd_protocol.h : 超文本协议私有头文件
/// -------------------------------------------------
/// Copyright (c) 2015, Wang Yujia <combo.xy@163.com>
/// All rights reserved.
/// -------------------------------------------------
#ifndef _HTTPD_PROTOCOL_H_
#define _HTTPD_PROTOCOL_H_
#include "BaseClass.h"
#include "httpd_handle.h"
#include "stream/dstream.h"
/// -------------------------------------------------
/// 超文本请求对象接口类
/// -------------------------------------------------
INTF_VER(IHttpRequest, 1, 0, 0);
interface IHttpRequest : public Instance
{
/// 输入请求
virtual void Input(IHttpHandle *http, const char *req) = 0;
};
/// -------------------------------------------------
/// 超文本响应对象接口类
/// -------------------------------------------------
INTF_VER(IHttpResponse, 1, 0, 0);
interface IHttpResponse : public Instance
{
/// 输出响应
virtual void Output(IHttpHandle *http, CDStream &rsp, DWORD *pdwHeadSize = 0) = 0;
};
/// -------------------------------------------------
/// 超文本请求对象实现类
/// -------------------------------------------------
class CHttpRequest : public IHttpRequest
{
public:
/// 命令组成定义
enum HEAD_LINE
{
HEAD_LINE_METHOD = 0,
HEAD_LINE_URI,
HEAD_LINE_PROTOCOL,
};
/// 请求方法(文本)
static const char *Method[];
/// 协议版本(文本)
static const char *Protocol[];
public:
static void StrDecode(char *str);
static int hexit(char c);
public:
CHttpRequest(Instance *piParent, int argc, char **argv);
~CHttpRequest();
DCOP_DECLARE_INSTANCE;
void Input(IHttpHandle *http, const char *req);
private:
void Analyze(IHttpHandle *http, const char *req);
DWORD GetHeadLine(IHttpHandle *http, const char *head);
DWORD GetMethod(const char *head, IHttpHandle::METHOD &method);
DWORD GetProtocol(const char *head, IHttpHandle::PROTOCOL &protocol);
void GetHeadItem(IHttpHandle *http, CDString *head);
};
/// -------------------------------------------------
/// 超文本响应对象实现类
/// -------------------------------------------------
class CHttpResponse : public IHttpResponse
{
public:
/// 协议版本(服务器支持的最高版本)
static const char *Protocol;
/// 状态码(文本)
static const char *Status[];
/// 服务器信息
static const char *Server;
/// HTTP已经规定了使用RFC1123时间格式
static const char *RFC1123FMT;
/// MIME(文本)
static const char *MIME[];
/// 内容压缩(文本)
static const char *Compress[];
public:
static const char *GetStatus(IHttpHandle *http);
static const char *GetContentType(IHttpHandle *http);
static const char *GetContentType(const char *name);
public:
CHttpResponse(Instance *piParent, int argc, char **argv);
~CHttpResponse();
DCOP_DECLARE_INSTANCE;
void Output(IHttpHandle *http, CDStream &rsp, DWORD *pdwHeadSize);
private:
void GetHeadItem(IHttpHandle *http, CDStream &rsp);
bool IsCompressSupport(IHttpHandle *http, IHttpHandle::COMPRESS compress);
void DeflateContent(IHttpHandle *http);
void GzipContent(IHttpHandle *http);
};
#endif // #ifndef _HTTPD_PROTOCOL_H_
|
[
"combo.xy@163.com"
] |
combo.xy@163.com
|
89873794754d2917234829eb370a518aa0a33999
|
8e151199d01e1918a4bb1ee7bb1509061ccd327b
|
/Classes/Options.h
|
b5dfb3ad77e076aa80cc8b2e0a989c3d841cc6e7
|
[] |
no_license
|
zhaozw/gods-invader
|
8a7cc9b449ef861dd2f4495f4060ee0f0af90695
|
089ecbfde7d0fd8aa55f696548a4736eab91b4d8
|
refs/heads/master
| 2021-01-21T11:23:59.057483
| 2013-04-10T09:54:32
| 2013-04-10T09:54:32
| 9,603,862
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 505
|
h
|
#ifndef CONST_OPTIONS_H
#define CONST_OPTIONS_H
class Entity;
class Options
{
public:
static int CENTER_X;
static int CENTER_Y;
static int SCREEN_WIDTH;
static int SCREEN_HEIGHT;
static int SCREEN_CENTER_X;
static int SCREEN_CENTER_Y;
static int CAMERA_WIDTH;
static int CAMERA_HEIGHT;
static int CAMERA_CENTER_X;
static int CAMERA_CENTER_Y;
static float MIN_Z;
static float MAX_Z;
static bool MUSIC_ENABLE;
static bool SOUND_ENABLE;
static Entity* BASE;
};
#endif
|
[
"igor.mats@yandex.ru"
] |
igor.mats@yandex.ru
|
843ab3ccdbf662827d3f5c88dc1c2f3a24a15459
|
2f4cee019d13607191758faedddc8b88130be52d
|
/Paradis_Hydrogen/ParadisJHU06012020/ParadisJHU06012020/ezmath/Face.h
|
2f8746b11aea1dfa26a130b7aec8857ba2ae251e
|
[] |
no_license
|
JinnyJingLuo/Expanse
|
ee0ed9f448fb230a09af049ac673c26d3397a76a
|
207059c02868a6e1881a6748396e248e16d2e995
|
refs/heads/master
| 2023-05-06T13:17:38.859013
| 2021-05-26T07:11:04
| 2021-05-26T07:11:04
| 370,536,257
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 460
|
h
|
#ifndef FACE_H_
#define FACE_H_
#include "GeometricComponent.h"
#include "Point.h"
#include "string"
using namespace EZ;
using namespace std;
namespace GeometrySystem
{
class Face : public GeometricComponent
{
public:
Face();
Face(const Face& oFace);
virtual ~Face();
Face& operator=(const Face& oFace);
void Reset();
virtual bool IsVisibleFromPoint(const Point& oPoint) const = 0;
private:
protected:
void Initialize();
};
}
#endif
|
[
"jluo32@login02.expanse.sdsc.edu"
] |
jluo32@login02.expanse.sdsc.edu
|
d979e55629a2b99b60faa8d7812c017587563248
|
41bc79f836e2aead9bdc0bade84dc06397d9b3d2
|
/Arduino_Software/libraries/Adafruit_LED_Backpack_Library/Adafruit_LEDBackpack.cpp
|
0767d2bbb71e53655307fb80b43b5bf9a70d1ebb
|
[
"MIT"
] |
permissive
|
edinnen/Thanksgiving_Intranet
|
44ffce06913139d50bd171993ab271ec615c0c69
|
1e2b4a3f705228e9a92e82ce42217cb9ba6f07b0
|
refs/heads/master
| 2023-01-06T18:36:51.544023
| 2022-12-28T19:15:50
| 2022-12-28T19:15:50
| 94,859,889
| 2
| 0
|
MIT
| 2020-11-10T05:49:29
| 2017-06-20T06:58:57
|
Raku
|
UTF-8
|
C++
| false
| false
| 16,636
|
cpp
|
/*!
* @file Adafruit_LEDBackpack.cpp
*
* @mainpage Adafruit LED Backpack library for Arduino.
*
* @section intro_sec Introduction
*
* This is an Arduino library for our I2C LED Backpacks:
* ----> http://www.adafruit.com/products/
* ----> http://www.adafruit.com/products/
*
* These displays use I2C to communicate, 2 pins are required to
* interface. There are multiple selectable I2C addresses. For backpacks
* with 2 Address Select pins: 0x70, 0x71, 0x72 or 0x73. For backpacks
* with 3 Address Select pins: 0x70 thru 0x77
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* @section dependencies Dependencies
*
* This library depends on <a
* href="https://github.com/adafruit/Adafruit-GFX-Library"> Adafruit_GFX</a>
* being present on your system. Please make sure you have installed the latest
* version before using this library.
*
* @section author Author
*
* Written by Limor Fried/Ladyada for Adafruit Industries.
*
* @section license License
*
* MIT license, all text above must be included in any redistribution
*
*/
#include <Wire.h>
#include "Adafruit_GFX.h"
#include "Adafruit_LEDBackpack.h"
#ifndef _BV
#define _BV(bit) (1 << (bit)) ///< Bit-value if not defined by Arduino
#endif
#ifndef _swap_int16_t
#define _swap_int16_t(a, b) \
{ \
int16_t t = a; \
a = b; \
b = t; \
} ///< 16-bit var swap
#endif
static const uint8_t numbertable[] = {
0x3F, /* 0 */
0x06, /* 1 */
0x5B, /* 2 */
0x4F, /* 3 */
0x66, /* 4 */
0x6D, /* 5 */
0x7D, /* 6 */
0x07, /* 7 */
0x7F, /* 8 */
0x6F, /* 9 */
0x77, /* a */
0x7C, /* b */
0x39, /* C */
0x5E, /* d */
0x79, /* E */
0x71, /* F */
};
static const uint16_t alphafonttable[] PROGMEM = {
0b0000000000000001, 0b0000000000000010, 0b0000000000000100,
0b0000000000001000, 0b0000000000010000, 0b0000000000100000,
0b0000000001000000, 0b0000000010000000, 0b0000000100000000,
0b0000001000000000, 0b0000010000000000, 0b0000100000000000,
0b0001000000000000, 0b0010000000000000, 0b0100000000000000,
0b1000000000000000, 0b0000000000000000, 0b0000000000000000,
0b0000000000000000, 0b0000000000000000, 0b0000000000000000,
0b0000000000000000, 0b0000000000000000, 0b0000000000000000,
0b0001001011001001, 0b0001010111000000, 0b0001001011111001,
0b0000000011100011, 0b0000010100110000, 0b0001001011001000,
0b0011101000000000, 0b0001011100000000,
0b0000000000000000, //
0b0000000000000110, // !
0b0000001000100000, // "
0b0001001011001110, // #
0b0001001011101101, // $
0b0000110000100100, // %
0b0010001101011101, // &
0b0000010000000000, // '
0b0010010000000000, // (
0b0000100100000000, // )
0b0011111111000000, // *
0b0001001011000000, // +
0b0000100000000000, // ,
0b0000000011000000, // -
0b0000000000000000, // .
0b0000110000000000, // /
0b0000110000111111, // 0
0b0000000000000110, // 1
0b0000000011011011, // 2
0b0000000010001111, // 3
0b0000000011100110, // 4
0b0010000001101001, // 5
0b0000000011111101, // 6
0b0000000000000111, // 7
0b0000000011111111, // 8
0b0000000011101111, // 9
0b0001001000000000, // :
0b0000101000000000, // ;
0b0010010000000000, // <
0b0000000011001000, // =
0b0000100100000000, // >
0b0001000010000011, // ?
0b0000001010111011, // @
0b0000000011110111, // A
0b0001001010001111, // B
0b0000000000111001, // C
0b0001001000001111, // D
0b0000000011111001, // E
0b0000000001110001, // F
0b0000000010111101, // G
0b0000000011110110, // H
0b0001001000000000, // I
0b0000000000011110, // J
0b0010010001110000, // K
0b0000000000111000, // L
0b0000010100110110, // M
0b0010000100110110, // N
0b0000000000111111, // O
0b0000000011110011, // P
0b0010000000111111, // Q
0b0010000011110011, // R
0b0000000011101101, // S
0b0001001000000001, // T
0b0000000000111110, // U
0b0000110000110000, // V
0b0010100000110110, // W
0b0010110100000000, // X
0b0001010100000000, // Y
0b0000110000001001, // Z
0b0000000000111001, // [
0b0010000100000000, //
0b0000000000001111, // ]
0b0000110000000011, // ^
0b0000000000001000, // _
0b0000000100000000, // `
0b0001000001011000, // a
0b0010000001111000, // b
0b0000000011011000, // c
0b0000100010001110, // d
0b0000100001011000, // e
0b0000000001110001, // f
0b0000010010001110, // g
0b0001000001110000, // h
0b0001000000000000, // i
0b0000000000001110, // j
0b0011011000000000, // k
0b0000000000110000, // l
0b0001000011010100, // m
0b0001000001010000, // n
0b0000000011011100, // o
0b0000000101110000, // p
0b0000010010000110, // q
0b0000000001010000, // r
0b0010000010001000, // s
0b0000000001111000, // t
0b0000000000011100, // u
0b0010000000000100, // v
0b0010100000010100, // w
0b0010100011000000, // x
0b0010000000001100, // y
0b0000100001001000, // z
0b0000100101001001, // {
0b0001001000000000, // |
0b0010010010001001, // }
0b0000010100100000, // ~
0b0011111111111111,
};
void Adafruit_LEDBackpack::setBrightness(uint8_t b) {
if (b > 15)
b = 15;
Wire.beginTransmission(i2c_addr);
Wire.write(HT16K33_CMD_BRIGHTNESS | b);
Wire.endTransmission();
}
void Adafruit_LEDBackpack::blinkRate(uint8_t b) {
Wire.beginTransmission(i2c_addr);
if (b > 3)
b = 0; // turn off if not sure
Wire.write(HT16K33_BLINK_CMD | HT16K33_BLINK_DISPLAYON | (b << 1));
Wire.endTransmission();
}
Adafruit_LEDBackpack::Adafruit_LEDBackpack(void) {}
void Adafruit_LEDBackpack::begin(uint8_t _addr = 0x70) {
i2c_addr = _addr;
Wire.begin();
Wire.beginTransmission(i2c_addr);
Wire.write(0x21); // turn on oscillator
Wire.endTransmission();
// internal RAM powers up with garbage/random values.
// ensure internal RAM is cleared before turning on display
// this ensures that no garbage pixels show up on the display
// when it is turned on.
clear();
writeDisplay();
blinkRate(HT16K33_BLINK_OFF);
setBrightness(15); // max brightness
}
void Adafruit_LEDBackpack::writeDisplay(void) {
Wire.beginTransmission(i2c_addr);
Wire.write((uint8_t)0x00); // start at address $00
for (uint8_t i = 0; i < 8; i++) {
Wire.write(displaybuffer[i] & 0xFF);
Wire.write(displaybuffer[i] >> 8);
}
Wire.endTransmission();
}
void Adafruit_LEDBackpack::clear(void) {
for (uint8_t i = 0; i < 8; i++) {
displaybuffer[i] = 0;
}
}
/******************************* QUAD ALPHANUM OBJECT */
Adafruit_AlphaNum4::Adafruit_AlphaNum4(void) {}
void Adafruit_AlphaNum4::writeDigitRaw(uint8_t n, uint16_t bitmask) {
displaybuffer[n] = bitmask;
}
void Adafruit_AlphaNum4::writeDigitAscii(uint8_t n, uint8_t a, bool d) {
uint16_t font = pgm_read_word(alphafonttable + a);
displaybuffer[n] = font;
/*
Serial.print(a, DEC);
Serial.print(" / '"); Serial.write(a);
Serial.print("' = 0x"); Serial.println(font, HEX);
*/
if (d)
displaybuffer[n] |= (1 << 14);
}
/******************************* 24 BARGRAPH OBJECT */
Adafruit_24bargraph::Adafruit_24bargraph(void) {}
void Adafruit_24bargraph::setBar(uint8_t bar, uint8_t color) {
uint16_t a, c;
if (bar < 12)
c = bar / 4;
else
c = (bar - 12) / 4;
a = bar % 4;
if (bar >= 12)
a += 4;
// Serial.print("Ano = "); Serial.print(a); Serial.print(" Cath = ");
// Serial.println(c);
if (color == LED_RED) {
// Turn on red LED.
displaybuffer[c] |= _BV(a);
// Turn off green LED.
displaybuffer[c] &= ~_BV(a + 8);
} else if (color == LED_YELLOW) {
// Turn on red and green LED.
displaybuffer[c] |= _BV(a) | _BV(a + 8);
} else if (color == LED_OFF) {
// Turn off red and green LED.
displaybuffer[c] &= ~_BV(a) & ~_BV(a + 8);
} else if (color == LED_GREEN) {
// Turn on green LED.
displaybuffer[c] |= _BV(a + 8);
// Turn off red LED.
displaybuffer[c] &= ~_BV(a);
}
}
/******************************* 16x8 MATRIX OBJECT */
Adafruit_8x16matrix::Adafruit_8x16matrix(void) : Adafruit_GFX(8, 16) {}
void Adafruit_8x16matrix::drawPixel(int16_t x, int16_t y, uint16_t color) {
// check rotation, move pixel around if necessary
switch (getRotation()) {
case 2:
_swap_int16_t(x, y);
x = 16 - x - 1;
break;
case 3:
x = 16 - x - 1;
y = 8 - y - 1;
break;
case 0:
_swap_int16_t(x, y);
y = 8 - y - 1;
break;
}
/*
Serial.print("("); Serial.print(x);
Serial.print(","); Serial.print(y);
Serial.println(")");
*/
if ((y < 0) || (y >= 8))
return;
if ((x < 0) || (x >= 16))
return;
if (color) {
displaybuffer[y] |= 1 << x;
} else {
displaybuffer[y] &= ~(1 << x);
}
}
/******************************* 16x8 MINI MATRIX OBJECT */
Adafruit_8x16minimatrix::Adafruit_8x16minimatrix(void) : Adafruit_GFX(8, 16) {}
void Adafruit_8x16minimatrix::drawPixel(int16_t x, int16_t y, uint16_t color) {
if ((y < 0) || (x < 0))
return;
if ((getRotation() % 2 == 0) && ((y >= 16) || (x >= 8)))
return;
if ((getRotation() % 2 == 1) && ((x >= 16) || (y >= 8)))
return;
// check rotation, move pixel around if necessary
switch (getRotation()) {
case 2:
if (y >= 8) {
x += 8;
y -= 8;
}
_swap_int16_t(x, y);
break;
case 3:
x = 16 - x - 1;
if (x >= 8) {
x -= 8;
y += 8;
}
break;
case 0:
y = 16 - y - 1;
x = 8 - x - 1;
if (y >= 8) {
x += 8;
y -= 8;
}
_swap_int16_t(x, y);
break;
case 1:
y = 8 - y - 1;
if (x >= 8) {
x -= 8;
y += 8;
}
break;
}
if (color) {
displaybuffer[x] |= 1 << y;
} else {
displaybuffer[x] &= ~(1 << y);
}
}
/******************************* 8x8 MATRIX OBJECT */
Adafruit_8x8matrix::Adafruit_8x8matrix(void) : Adafruit_GFX(8, 8) {}
void Adafruit_8x8matrix::drawPixel(int16_t x, int16_t y, uint16_t color) {
if ((y < 0) || (y >= 8))
return;
if ((x < 0) || (x >= 8))
return;
// check rotation, move pixel around if necessary
switch (getRotation()) {
case 1:
_swap_int16_t(x, y);
x = 8 - x - 1;
break;
case 2:
x = 8 - x - 1;
y = 8 - y - 1;
break;
case 3:
_swap_int16_t(x, y);
y = 8 - y - 1;
break;
}
// wrap around the x
x += 7;
x %= 8;
if (color) {
displaybuffer[y] |= 1 << x;
} else {
displaybuffer[y] &= ~(1 << x);
}
}
/******************************* 8x8 BICOLOR MATRIX OBJECT */
Adafruit_BicolorMatrix::Adafruit_BicolorMatrix(void) : Adafruit_GFX(8, 8) {}
void Adafruit_BicolorMatrix::drawPixel(int16_t x, int16_t y, uint16_t color) {
if ((y < 0) || (y >= 8))
return;
if ((x < 0) || (x >= 8))
return;
switch (getRotation()) {
case 1:
_swap_int16_t(x, y);
x = 8 - x - 1;
break;
case 2:
x = 8 - x - 1;
y = 8 - y - 1;
break;
case 3:
_swap_int16_t(x, y);
y = 8 - y - 1;
break;
}
if (color == LED_GREEN) {
// Turn on green LED.
displaybuffer[y] |= 1 << x;
// Turn off red LED.
displaybuffer[y] &= ~(1 << (x + 8));
} else if (color == LED_RED) {
// Turn on red LED.
displaybuffer[y] |= 1 << (x + 8);
// Turn off green LED.
displaybuffer[y] &= ~(1 << x);
} else if (color == LED_YELLOW) {
// Turn on green and red LED.
displaybuffer[y] |= (1 << (x + 8)) | (1 << x);
} else if (color == LED_OFF) {
// Turn off green and red LED.
displaybuffer[y] &= ~(1 << x) & ~(1 << (x + 8));
}
}
/******************************* 7 SEGMENT OBJECT */
Adafruit_7segment::Adafruit_7segment(void) { position = 0; }
void Adafruit_7segment::print(unsigned long n, int base) {
if (base == 0)
write(n);
else
printNumber(n, base);
}
void Adafruit_7segment::print(char c, int base) { print((long)c, base); }
void Adafruit_7segment::print(unsigned char b, int base) {
print((unsigned long)b, base);
}
void Adafruit_7segment::print(int n, int base) { print((long)n, base); }
void Adafruit_7segment::print(unsigned int n, int base) {
print((unsigned long)n, base);
}
void Adafruit_7segment::println(void) { position = 0; }
void Adafruit_7segment::println(char c, int base) {
print(c, base);
println();
}
void Adafruit_7segment::println(unsigned char b, int base) {
print(b, base);
println();
}
void Adafruit_7segment::println(int n, int base) {
print(n, base);
println();
}
void Adafruit_7segment::println(unsigned int n, int base) {
print(n, base);
println();
}
void Adafruit_7segment::println(long n, int base) {
print(n, base);
println();
}
void Adafruit_7segment::println(unsigned long n, int base) {
print(n, base);
println();
}
void Adafruit_7segment::println(double n, int digits) {
print(n, digits);
println();
}
void Adafruit_7segment::print(double n, int digits) { printFloat(n, digits); }
size_t Adafruit_7segment::write(uint8_t c) {
uint8_t r = 0;
if (c == '\n')
position = 0;
if (c == '\r')
position = 0;
if ((c >= '0') && (c <= '9')) {
writeDigitNum(position, c - '0');
r = 1;
}
position++;
if (position == 2)
position++;
return r;
}
void Adafruit_7segment::writeDigitRaw(uint8_t d, uint8_t bitmask) {
if (d > 4)
return;
displaybuffer[d] = bitmask;
}
void Adafruit_7segment::drawColon(bool state) {
if (state)
displaybuffer[2] = 0x2;
else
displaybuffer[2] = 0;
}
void Adafruit_7segment::writeColon(void) {
Wire.beginTransmission(i2c_addr);
Wire.write((uint8_t)0x04); // start at address $02
Wire.write(displaybuffer[2] & 0xFF);
Wire.write(displaybuffer[2] >> 8);
Wire.endTransmission();
}
void Adafruit_7segment::writeDigitNum(uint8_t d, uint8_t num, bool dot) {
if (d > 4)
return;
writeDigitRaw(d, numbertable[num] | (dot << 7));
}
void Adafruit_7segment::print(long n, int base) { printNumber(n, base); }
void Adafruit_7segment::printNumber(long n, uint8_t base) {
printFloat(n, 0, base);
}
void Adafruit_7segment::printFloat(double n, uint8_t fracDigits, uint8_t base) {
uint8_t numericDigits = 4; // available digits on display
bool isNegative = false; // true if the number is negative
// is the number negative?
if (n < 0) {
isNegative = true; // need to draw sign later
--numericDigits; // the sign will take up one digit
n *= -1; // pretend the number is positive
}
// calculate the factor required to shift all fractional digits
// into the integer part of the number
double toIntFactor = 1.0;
for (int i = 0; i < fracDigits; ++i)
toIntFactor *= base;
// create integer containing digits to display by applying
// shifting factor and rounding adjustment
uint32_t displayNumber = n * toIntFactor + 0.5;
// calculate upper bound on displayNumber given
// available digits on display
uint32_t tooBig = 1;
for (int i = 0; i < numericDigits; ++i)
tooBig *= base;
// if displayNumber is too large, try fewer fractional digits
while (displayNumber >= tooBig) {
--fracDigits;
toIntFactor /= base;
displayNumber = n * toIntFactor + 0.5;
}
// did toIntFactor shift the decimal off the display?
if (toIntFactor < 1) {
printError();
} else {
// otherwise, display the number
int8_t displayPos = 4;
if (displayNumber) // if displayNumber is not 0
{
for (uint8_t i = 0; displayNumber || i <= fracDigits; ++i) {
bool displayDecimal = (fracDigits != 0 && i == fracDigits);
writeDigitNum(displayPos--, displayNumber % base, displayDecimal);
if (displayPos == 2)
writeDigitRaw(displayPos--, 0x00);
displayNumber /= base;
}
} else {
writeDigitNum(displayPos--, 0, false);
}
// display negative sign if negative
if (isNegative)
writeDigitRaw(displayPos--, 0x40);
// clear remaining display positions
while (displayPos >= 0)
writeDigitRaw(displayPos--, 0x00);
}
}
void Adafruit_7segment::printError(void) {
for (uint8_t i = 0; i < SEVENSEG_DIGITS; ++i) {
writeDigitRaw(i, (i == 2 ? 0x00 : 0x40));
}
}
|
[
"stuartdehaas@gmail.com"
] |
stuartdehaas@gmail.com
|
682fc09686bdff6f101e90cfe72bbbe759a01cee
|
77e82ee53d0284f8297f3c952e60bd614bafb40f
|
/topcoder/Unblur.cxx
|
c77b4851e066e75c22862fc5dc67e2986dc32de9
|
[] |
no_license
|
jackytck/practice
|
04ae4e5deef2af942cea605d3a599441b9c5db96
|
d022660003fa248fd159f9a4c4c1816b7b4688a4
|
refs/heads/master
| 2021-01-01T05:30:41.570650
| 2012-07-22T11:53:53
| 2012-07-22T11:53:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,585
|
cxx
|
#line 2 "Unblur.cxx"
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#define sz size()
#define PB push_back
#define clr(x) memset(x, 0, sizeof(x))
#define forn(i,n) for(__typeof(n) i = 0; i < (n); i++)
#define ford(i,n) for(int i = (n) - 1; i >= 0; i--)
#define forv(i,v) forn(i, v.sz)
#define For(i, st, en) for(__typeof(en) i = (st); i < (en); i++)
using namespace std;
class Unblur
{
public:
vector <string> original(vector <string> blurred)
{
vector <string> ret;
int h = blurred.sz, w = blurred[0].sz;
vector <vector <int> > un(h, vector <int> (w, 0));
forn(y, h)
forn(x, w)
{
if(x == 0 || x == w-1 || y == 0 || y == h-1)
continue;
int sum = blurred[y-1][x-1] - '0';
un[y][x] = sum;
forn(i, 3)
forn(j, 3)
{
if(i==0 && j==0)
continue;
int px = x-i, py = y-j;
if(px >= 0 && py >= 0)
un[y][x] -= un[py][px];
}
}
forv(i, un)
{
string s = "";
forv(j, un[i])
s += un[i][j] == 0 ? "." : "#";
ret.PB(s);
}
return ret;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const vector <string> &Expected, const vector <string> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } }
void test_case_0() { string Arr0[] = { "1221",
"1221",
"1221" }; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { "....", ".##.", "...." }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(0, Arg1, original(Arg0)); }
void test_case_1() { string Arr0[] = { "00000",
"00000",
"00000",
"00000" }; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { ".....", ".....", ".....", "....." }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(1, Arg1, original(Arg0)); }
void test_case_2() { string Arr0[] = { "0011212121100",
"0123333333210",
"0123333333210",
"1233333333321",
"1233333333321",
"1233333333321",
"0112121212110" } ; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { ".............", "...#.#.#.#...", "..#.#.#.#.#..", ".............", ".#.#.#.#.#.#.", "..#.#.#.#.#..", "............." }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(2, Arg1, original(Arg0)); }
void test_case_3() { string Arr0[] = { "1233321000000000123332100000000000000000000",
"1244422233222332334343323322232112332223321",
"1255523344343443545343434434343233432334432",
"0033303455465775633011445546454355753457753",
"0033303333364543533011433336333364521346542",
"0033303455464532445343545546454355753446542",
"0022202344342200234343434434343233432323221",
"0011101233221100123332223322232112332211111" } ; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { "...........................................", ".#####...........#####.....................", "...#...####.####.#...#.####.###..####.####.", "...#...#..#.#..#.#.....#..#.#..#.#....#..#.", "...#...#..#.####.#.....#..#.#..#.###..####.", "...#...#..#.#....#...#.#..#.#..#.#....#.#..", "...#...####.#....#####.####.###..####.#..#.", "..........................................." }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(3, Arg1, original(Arg0)); }
void test_case_4() { string Arr0[] = { "0000123210000",
"0012456542100",
"0135789875310",
"0258988898520",
"1479865689741",
"2589742479852",
"2589742479852",
"1479865689741",
"0258988898520",
"0135789875310",
"0012456542100",
"0000123210000" }
; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = { ".............", ".....###.....", "...#######...", "..#########..", "..####.####..", ".####...####.", ".####...####.", "..####.####..", "..#########..", "...#######...", ".....###.....", "............." }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(4, Arg1, original(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
Unblur ___test;
___test.run_test(-1);
}
// END CUT HERE
|
[
"jackytck@gmail.com"
] |
jackytck@gmail.com
|
1be81eac83eb2e87991954b55ecda2d121ba12dd
|
c5e8b8d8bc38d6f1df7668ac185795d99a4ae31a
|
/emJetAnalysis/src/EjCalculateAN.cxx
|
4dc4edf2c0d834719d21e1745db761faaf714569
|
[] |
no_license
|
xilinliang/STAR-1
|
3bc7ddffa9a9a05f108a4dd66e32a1a417cd9e54
|
32e74b318e64ef9e5cc5cda410b20425031dbf6a
|
refs/heads/master
| 2023-07-26T21:28:00.157084
| 2021-01-24T04:35:25
| 2021-01-24T04:35:25
| 315,710,751
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,942
|
cxx
|
// Filename: EjCalculateAN.cxx
// Description:
// Author: Latif Kabir < kabir@bnl.gov >
// Created: Fri May 8 15:08:25 2020 (-0400)
// URL: jlab.org/~latif
#include <iostream>
#include "RootInclude.h"
#include "cppInclude.h"
#include "BrightStInclude.h"
#include "Hists.h"
using namespace std;
void EjCalculateAN(TString inFileName, TString outName, TString det)
{
/*
We need to bin in: energy (5), number of photons (6), phi (16), spin (2), pt(6).
Let's create TH2D histograms of array size [2(spin)][4(energy)][#photon(5)]. The 2D histogram to be filled with phi bins along x and pt bins along y.
We need another similar array for yellow beam as well.
*/
TString inFile = inFileName;
if(gSystem->AccessPathName(inFile))
{
cout << "Input file not found: "<< inFile <<endl;
return;
}
TFile *file = new TFile(inFile);
const Int_t kSpinBins = 2;
const Int_t kEnergyBins = 5;
const Int_t kPhotonBins = 6;
TH2D *bHist[kSpinBins][kEnergyBins][kPhotonBins]; // [spin][energy bin][#photons]
TH2D *yHist[kSpinBins][kEnergyBins][kPhotonBins]; // [spin][energy bin][#photons]
Double_t ptBins[] = {2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 6.0, 8.0, 10.0}; //For info only
Double_t engBins[] = {0.0, 20.0, 40.0, 60.0, 80.0, 100.0}; //For info only
Double_t photonBins[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};// Last bin contains 6 or more photons
//Int_t nPtBins = sizeof(ptBins) / sizeof(Double_t) - 1;
for(Int_t i = 0; i < kSpinBins; ++i)
{
for(Int_t j = 0; j < kEnergyBins; ++j)
{
for(Int_t k = 0; k < kPhotonBins; ++k)
{
TString bTitle = Form("bHist_%i_%i_%i", i, j, k);
TString yTitle = Form("yHist_%i_%i_%i", i, j, k);
bHist[i][j][k] = (TH2D*)file->Get(bTitle);
yHist[i][j][k] = (TH2D*)file->Get(yTitle);
}
}
}
const Int_t nHalfPhiBins = bHist[0][0][0]->GetNbinsX() / 2; //Phi bins per hemisphere
const Int_t nPtBins = bHist[0][0][0]->GetNbinsY();
//Note: left-right is with respect to the beam (here blue beam)
Int_t phiBins_left[] = {9, 10, 11, 12, 13, 14, 15, 16}; //<----------- Update here if nPhiBins changes
Int_t phiBins_right[] = {1, 2, 3, 4, 5, 6, 7, 8}; //<----------- Update here if nPhiBins changes
Double_t phiValues[nHalfPhiBins];
Double_t bAnRaw[kEnergyBins][kPhotonBins][nHalfPhiBins][nPtBins];
Double_t bAnRawError[kEnergyBins][kPhotonBins][nHalfPhiBins][nPtBins];
Double_t bAn[kEnergyBins][kPhotonBins][nPtBins];
Double_t bAnError[kEnergyBins][kPhotonBins][nPtBins];
memset(bAn, 0, sizeof(bAn));
memset(bAnError, 0, sizeof(bAnError));
Double_t yAnRaw[kEnergyBins][kPhotonBins][nHalfPhiBins][nPtBins];
Double_t yAnRawError[kEnergyBins][kPhotonBins][nHalfPhiBins][nPtBins];
Double_t yAn[kEnergyBins][kPhotonBins][nPtBins]; // A_N with polarization correction
Double_t yAnError[kEnergyBins][kPhotonBins][nPtBins]; // A_N error with polarization correction
memset(yAn, 0, sizeof(yAn));
memset(yAnError, 0, sizeof(yAnError));
Double_t bNu_l;
Double_t bNu_r;
Double_t bNd_l;
Double_t bNd_r;
Double_t yNu_l;
Double_t yNu_r;
Double_t yNd_l;
Double_t yNd_r;
Double_t numer;
Double_t denom;
Double_t numerErrSq;
Double_t denomErrSq;
for(Int_t i = 0; i < kEnergyBins; ++i)
{
for(Int_t j = 0; j < kPhotonBins; ++j)
{
for(Int_t k = 0; k < nHalfPhiBins; ++k)
{
for(Int_t l = 0; l < nPtBins; ++l)
{
if(i == 0 && j == 0 && l == 0)
phiValues[k] = bHist[0][i][j]->GetXaxis()->GetBinCenter(phiBins_left[k]);
bNd_l = bHist[0][i][j]->GetBinContent(phiBins_left[k], l + 1);
bNu_l = bHist[1][i][j]->GetBinContent(phiBins_left[k], l + 1);
bNd_r = bHist[0][i][j]->GetBinContent((phiBins_right[k]), l + 1);
bNu_r = bHist[1][i][j]->GetBinContent((phiBins_right[k]), l + 1);
yNd_l = yHist[0][i][j]->GetBinContent(phiBins_left[k], l + 1);
yNu_l = yHist[1][i][j]->GetBinContent(phiBins_left[k], l + 1);
yNd_r = yHist[0][i][j]->GetBinContent((phiBins_right[k]), l + 1);
yNu_r = yHist[1][i][j]->GetBinContent((phiBins_right[k]), l + 1);
//You need to ensure that the Left-Right pairing is done exactly as in the formula
//----- Blue beam measured asymmetry ------------
numer = sqrt(bNu_l*bNd_r) - sqrt(bNd_l*bNu_r);
denom = sqrt(bNu_l*bNd_r) + sqrt(bNd_l*bNu_r);
numerErrSq = (bNd_l + bNu_r + bNu_l + bNd_r) / 4.0;
denomErrSq = (bNd_l + bNu_r + bNu_l + bNd_r) / 4.0;
if(denom == 0)
{
bAnRaw[i][j][k][l] = -999;
bAnRawError[i][j][k][l] = -999;
}
else
{
bAnRaw[i][j][k][l] = numer / denom;
bAnRawError[i][j][k][l] = fabs( bAnRaw[i][j][k][l]) * sqrt( numerErrSq / pow(numer, 2) + denomErrSq / pow(denom, 2)); //See error propagation in the analysis note
}
//cout << "Raw Asym:"<< bAnRaw[i][j][k][l] << " +- "<< bAnRawError[i][j][k][l] <<endl;
//----- Yellow beam measured asymmetry ------------
numer = sqrt(yNu_l*yNd_r) - sqrt(yNd_l*yNu_r);
denom = sqrt(yNu_l*yNd_r) + sqrt(yNd_l*yNu_r);
numerErrSq = (yNd_l + yNu_r + yNu_l + yNd_r) / 4.0;
denomErrSq = (yNd_l + yNu_r + yNu_l + yNd_r) / 4.0;
if(denom == 0)
{
yAnRaw[i][j][k][l] = -999;
yAnRawError[i][j][k][l] = -999;
}
else
{
yAnRaw[i][j][k][l] = numer / denom;
yAnRawError[i][j][k][l] = fabs(yAnRaw[i][j][k][l]) * sqrt( numerErrSq / pow(numer, 2) + denomErrSq / pow(denom, 2)); //See error propagation in the analysis note
}
}
}
}
}
gROOT->SetBatch(kTRUE);
TFile *outFile = new TFile(outName, "recreate");
TGraphErrors *bGr[kEnergyBins][kPhotonBins][nPtBins];
TGraphErrors *yGr[kEnergyBins][kPhotonBins][nPtBins];
TF1 *bFitFnc[kEnergyBins][kPhotonBins][nPtBins];
TF1 *yFitFnc[kEnergyBins][kPhotonBins][nPtBins];
TGraphErrors *bGrPhy[kEnergyBins][kPhotonBins];
TGraphErrors *yGrPhy[kEnergyBins][kPhotonBins];
Int_t nPointsB;
Int_t nPointsY;
Int_t nPointsPhyB;
Int_t nPointsPhyY;
Double_t polB = 0.5365 ; // RMS: 0.0403 in fraction
Double_t polY = 0.5614; // RMS: 0.0380
if(det == "fms")
{
polB = 0.5365; // RMS: 0.0403 in fraction
polY = 0.5614; // RMS: 0.0380
}
else if(det == "eemc")
{
polB = 0.5365; // RMS: 0.0403 in fraction
polY = 0.5614; // RMS: 0.0380
}
else
{
cout << "Invalid detector" <<endl;
return;
}
for(Int_t i = 0; i < kEnergyBins; ++i)
{
for(Int_t j = 0; j < kPhotonBins; ++j)
{
bGrPhy[i][j] = new TGraphErrors();
yGrPhy[i][j] = new TGraphErrors();
bGrPhy[i][j]->SetName(Form("bEbin%i_PhotonBin%i", i, j));
bGrPhy[i][j]->SetTitle(Form("%.1f GeV < E < %.1f GeV, No. of Photons %i; P_{T} [GeV/c]; A_{N}", engBins[i], engBins[i + 1], j + 1));
yGrPhy[i][j]->SetName(Form("yEbin%i_PhotonBin%i", i, j));
yGrPhy[i][j]->SetTitle(Form(" %.1f GeV < E < %.1f GeV, No. of Photons %i; P_{T} [GeV/c]; A_{N}", engBins[i], engBins[i + 1], j + 1));
bGrPhy[i][j]->SetMarkerColor(kBlack);
bGrPhy[i][j]->SetLineColor(kBlack);
bGrPhy[i][j]->SetMarkerStyle(kFullCircle);
bGrPhy[i][j]->SetMaximum(0.1);
bGrPhy[i][j]->SetMinimum(-0.1);
yGrPhy[i][j]->SetMaximum(0.1);
yGrPhy[i][j]->SetMinimum(-0.1);
yGrPhy[i][j]->SetMarkerColor(kRed);
yGrPhy[i][j]->SetLineColor(kRed);
yGrPhy[i][j]->SetMarkerStyle(kOpenCircle);
nPointsPhyB = 0;
nPointsPhyY = 0;
for(Int_t k = 0; k < nPtBins; ++k)
{
bGr[i][j][k] = new TGraphErrors();
yGr[i][j][k] = new TGraphErrors();
bGr[i][j][k]->SetName(Form("bEbin%i_PhotonBin%i_PtBin%i", i, j, k));
bGr[i][j][k]->SetTitle(Form("Blue Beam, %.1f GeV < E < %.1f GeV, No. of Photons %i, %.1f GeV/c < Pt < %.1f GeV/c; #phi [rad]; A_{raw}", engBins[i], engBins[i + 1] , j + 1, ptBins[k], ptBins[k + 1]));
yGr[i][j][k]->SetName(Form("yEbin%i_PhotonBin%i_PtBin%i", i, j, k));
yGr[i][j][k]->SetTitle(Form("Yellow Beam, %.1f GeV < E < %.1f GeV, No. of Photons %i, %.1f GeV/c < Pt < %.1f GeV/c; #phi [rad]; A_{raw}", engBins[i], engBins[i + 1] , j + 1, ptBins[k], ptBins[k + 1]));
bGr[i][j][k]->SetMaximum(0.1);
bGr[i][j][k]->SetMinimum(-0.1);
yGr[i][j][k]->SetMaximum(0.1);
yGr[i][j][k]->SetMinimum(-0.1);
bFitFnc[i][j][k] = new TF1(Form("bFitFnc_%i_%i_%i", i, j, k), "[0]*cos(x) + [1]");
yFitFnc[i][j][k] = new TF1(Form("yFitFnc_%i_%i_%i", i, j, k), "[0]*cos(x) + [1]");
nPointsB = 0;
nPointsY = 0;
for(Int_t l = 0; l < nHalfPhiBins; ++l)
{
if(bAnRaw[i][j][l][k] != -999)
{
bGr[i][j][k]->SetPoint(nPointsB, phiValues[l], bAnRaw[i][j][l][k]);
bGr[i][j][k]->SetPointError(nPointsB, 0, bAnRawError[i][j][l][k]);
++nPointsB;
}
if(yAnRaw[i][j][l][k] != -999)
{
yGr[i][j][k]->SetPoint(nPointsY, phiValues[l], yAnRaw[i][j][l][k]);
yGr[i][j][k]->SetPointError(nPointsY, 0, yAnRawError[i][j][l][k]);
++nPointsY;
}
}
bGr[i][j][k]->Fit(Form("bFitFnc_%i_%i_%i", i, j, k));
yGr[i][j][k]->Fit(Form("yFitFnc_%i_%i_%i", i, j, k));
if(bGr[i][j][k]->GetN() >= 0.5*nHalfPhiBins)
{
bAn[i][j][k] = bFitFnc[i][j][k]->GetParameter(0) / polB;
bAnError[i][j][k] = bFitFnc[i][j][k]->GetParError(0) / polB;
bGrPhy[i][j]->SetPoint(nPointsPhyB, (ptBins[k] + ptBins[k+1])*0.5 , bAn[i][j][k]);
bGrPhy[i][j]->SetPointError(nPointsPhyB, 0, bAnError[i][j][k]);
++nPointsPhyB;
}
if(yGr[i][j][k]->GetN() >= 0.5*nHalfPhiBins)
{
yAn[i][j][k] = yFitFnc[i][j][k]->GetParameter(0) / polY;
yAnError[i][j][k] = yFitFnc[i][j][k]->GetParError(0) / polY;
yGrPhy[i][j]->SetPoint(nPointsPhyY, (ptBins[k] + ptBins[k+1])*0.5 , yAn[i][j][k]);
yGrPhy[i][j]->SetPointError(nPointsPhyY, 0, yAnError[i][j][k]);
++nPointsPhyY;
}
bGr[i][j][k]->Write();
yGr[i][j][k]->Write();
}
bGrPhy[i][j]->Write();
yGrPhy[i][j]->Write();
}
}
//------------------ Plot physics A_N --------------------
Int_t canvasCount = 1;
//------------- For FMS --------------------
if(det == "fms")
{
TCanvas *c1 = new TCanvas("EMjet_A_N_fms", "EM Jet A_{N}");
c1->Divide(kEnergyBins -1, kPhotonBins -1);
for(Int_t i = 0; i < kPhotonBins - 1; ++i)
{
for(Int_t j = 1; j < kEnergyBins; ++j)
{
c1->cd(canvasCount);
bGrPhy[j][i]->Draw("AP");
yGrPhy[j][i]->Draw("P");
TLine* L1Temp = new TLine(1.5, 0, 9.5, 0);
L1Temp->Draw("same");
++canvasCount;
}
}
c1->Write();
//This area is just for plotting final physics result ----------------
//--- For Fms ---
//only consider energy ranges 20 -40, 40 - 60, 60 - 80 i.e. bin index 1, 2, 3 and nPhotons = 1 - 5
TCanvas* c2 = new TCanvas("asym_fms","Asymmetries",1000,600);
float varMins[5] = { 1.8, 1.8, 1.8, 1.8, 1.8};
float varMaxs[5] = { 8.2, 8.2, 8.2, 8.2, 8.2};
const char* xTitles[3] = { "p_{T} [GeV/c]","p_{T} [GeV/c]","p_{T} [GeV/c]" };
const char* yTitles[5] = { "A_{N}", "A_{N}", "A_{N}", "A_{N}", "A_{N}" };
PanelPlot* asymPlot = new PanelPlot(c2, 3, 5, 2, "asym_fms", xTitles, yTitles);
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
asymPlot->GetPlot(j,i)->SetXRange( varMins[i], varMaxs[i]);
asymPlot->GetPlot(j,i)->SetYRange( -0.05, 0.05);
// if(i == 4 && j == 0) // legend causes shift in x axis base for the panel
// {
// asymPlot->GetPlot(j,i)->Add(bGrPhy[j+1][4 - i], Plot::Point | Plot::Erry, 0, "x_{F} > 0");
// asymPlot->GetPlot(j,i)->Add(yGrPhy[j+1][4 - i], Plot::Point | Plot::Erry, 8, "x_{F} < 0");
// }
// else
{
asymPlot->GetPlot(j,i)->Add(bGrPhy[j+1][4 - i], Plot::Point | Plot::Erry, 0);
asymPlot->GetPlot(j,i)->Add(yGrPhy[j+1][4 - i], Plot::Point | Plot::Erry, 8);
}
if(i == 0 && j == 0)
asymPlot->GetPlot(j,i)->AddText(2.5, -0.04, "Preliminary", 0.10);
}
}
asymPlot->Draw();
c2->Write();
}
//---------- For EEMC Jet -----------------------
if(det == "eemc")
{
TCanvas *c3 = new TCanvas("EMjet_A_N_eemc", "EM Jet A_{N}");
canvasCount = 1;
c3->Divide(5, 2);
for(Int_t i = 0; i < 2; ++i)
{
for(Int_t j = 0; j < 5; ++j)
{
c3->cd(canvasCount);
bGrPhy[i][j]->Draw("AP");
yGrPhy[i][j]->Draw("P");
TLine* L1Temp = new TLine(2.5, 0, 9.5, 0);
L1Temp->Draw("same");
++canvasCount;
}
}
c3->Write();
//--- For Eemc ---
//only consider energy ranges 0 - 20, i.e. bin index 0, 1 and nPhotons = 1 - 5
TCanvas* c4 = new TCanvas("asym_eemc","Asymmetries", 1000, 600);
float varMins_e[] = { 1.8, 4.5, 1.8, 1.8, 1.8};
float varMaxs_e[] = { 9.2, 9.2, 9.2, 9.2, 9.2};
const char* xTitles_e[] = { "p_{T} [GeV/c]","p_{T} [GeV/c]"};
const char* yTitles_e[] = { "A_{N}", "A_{N}", "A_{N}", "A_{N}", "A_{N}" };
PanelPlot* asymPlot_e = new PanelPlot(c4, 1, 5, 2, "asym_eemc", xTitles_e, yTitles_e);
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 1; j++)
{
asymPlot_e->GetPlot(j,i)->SetXRange( varMins_e[j], varMaxs_e[j]);
asymPlot_e->GetPlot(j,i)->SetYRange( -0.005, 0.005);
// if(i == 4 && j == 0)
// {
// asymPlot_e->GetPlot(j,i)->Add(bGrPhy[j][4 - i], Plot::Point | Plot::Erry, 0, "x_{F} > 0");
// asymPlot_e->GetPlot(j,i)->Add(yGrPhy[j][4 - i], Plot::Point | Plot::Erry, 8, "x_{F} < 0");
// }
// else
{
asymPlot_e->GetPlot(j,i)->Add(bGrPhy[j][4 - i], Plot::Point | Plot::Erry, 0);
asymPlot_e->GetPlot(j,i)->Add(yGrPhy[j][4 - i], Plot::Point | Plot::Erry, 8);
}
if(i == 0 && j == 0)
asymPlot_e->GetPlot(j,i)->AddText(2.5, -0.004, "Preliminary", 0.10);
}
}
asymPlot_e->Draw();
c4->Write();
}
/*
Plot the saved fitted graphs as:
gStyle->SetOptFit(1)
bEbin1_PhotonBin0_PtBin0->Draw("AP*")
*/
//outFile->Write();
}
|
[
"siplukabir@gmail.com"
] |
siplukabir@gmail.com
|
b43b0272a94ccaf3416bd8adf0169fe84c1094dd
|
83dd4a88a518784300b340b221427f26b05edc5d
|
/Techgig/Code Gladiator 2019/Stage 1/Solution_2_new.cpp
|
914822e23d3c7c8f6b3635d6ba46482f5ddf13cf
|
[] |
no_license
|
abhishek09091/competitive-programming
|
0671ca18e9ea90b31f7c10c5339bdb5a47f9f307
|
56f40c4ea60a5f599e6bd562d400e77a91cb5d02
|
refs/heads/master
| 2020-05-03T13:12:40.693399
| 2020-01-14T20:28:59
| 2020-01-14T20:28:59
| 178,647,746
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,125
|
cpp
|
/**
Input :
5
5
-1 7 8 -5 4
4
3 2 1 -1
4
11 12 -2 -1
4
4 5 4 3
4
5 10 4 -1
Output:
48
13
12
44
10
**/
#include<bits/stdc++.h>
using namespace std;
bool** dp;
vector<vector<int>> display(const vector<int>& v, vector<vector<int>> result) {
vector<int> temp;
for (int i = 0; i < v.size(); ++i) {
cout<<v[i];
temp.push_back(v[i]);
}
result.push_back(temp);
cout<<endl;
return result;
}
vector<vector<int>> printSubsetsRec(int arr[], int i, int sum, vector<int>& p, vector<vector<int>> result) {
if (i == 0 && sum != 0 && dp[0][sum]) {
p.push_back(arr[i]);
result = display(p,result);
return result;
}
if (i == 0 && sum == 0) {
result = display(p,result);
return result;
}
if (dp[i-1][sum]){
vector<int> b = p;
printSubsetsRec(arr, i-1, sum, b,result);
}
if (sum >= arr[i] && dp[i-1][sum-arr[i]]) {
p.push_back(arr[i]);
printSubsetsRec(arr, i-1, sum-arr[i], p,result);
}
}
vector<vector<int>> printAllSubsets(int arr[], int n, int sum) {
vector<vector<int>> result;
if (n == 0 || sum < 0)
return result;
dp = new bool*[n];
for (int i=0; i<n; ++i) {
dp[i] = new bool[sum + 1];
dp[i][0] = true;
}
if (arr[0] <= sum)
dp[0][arr[0]] = true;
for (int i = 1; i < n; ++i)
for (int j = 0; j < sum + 1; ++j)
dp[i][j] = (arr[i] <= j) ? dp[i-1][j] ||
dp[i-1][j-arr[i]]
: dp[i - 1][j];
if (dp[n-1][sum] == false) {
printf("There are no subsets with sum %d\n", sum);
return result;
}
vector<int> p;
result = printSubsetsRec(arr, n-1, sum, p,result);
return result;
}
int findMaxSum(int arr[], int n)
{
int in = arr[0];
int ex = 0;
int exNew;
int i;
for (i = 1; i < n; i++) {
exNew = (in > ex)? in: ex;
in = ex + arr[i];
ex = exNew;
}
return ((in > ex)? in : ex);
}
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
int result = findMaxSum(arr,n);
vector<vector<int>> result_vector = printAllSubsets(arr,n,result);
}
return 0;
}
|
[
"abhishek.09091@gmail.com"
] |
abhishek.09091@gmail.com
|
c977bd3f66596533ccca364d72843aa96e0a30d9
|
98e5fd588b356aff074e907c27aede0b609aae85
|
/programming/codeforce/327/b.cpp
|
bda3b4e9898ab00d77beaaba8714f61f9401debf
|
[] |
no_license
|
ayushshukla92/algorithms
|
060521612773e93bf4804abd5644fc35d4d32eb7
|
a3d5baa3c71de5fa9a8049d436c802c75ad32cd2
|
refs/heads/master
| 2016-08-12T02:01:53.233754
| 2015-11-04T11:09:00
| 2015-11-04T11:09:00
| 45,024,626
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,747
|
cpp
|
#include <iostream>
#include <algorithm>
#include <string>
#include <queue>
#include <list>
#include <stack>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <cstdlib>
#include <sstream>
#include <cmath>
#include <cctype>
#include <cstdio>
#include <cstring>
using namespace std;
typedef pair <int, int> PII;
typedef vector <int> VI;
typedef vector<vector<int> > VVI;
typedef vector<vector<char> > VVC;
typedef vector <bool> VB;
typedef vector < pair<int,int> > VP;
typedef vector <double> VD;
typedef long long ll;
typedef long double ld;
// Input macros
#define SC(n) scanf(" %c",&n)
#define SD(n) scanf("%d",&n)
#define SF(n) scanf("%f",&n)
#define SLF(n) scanf("%lf",&n)
#define ALL(a) a.begin(), a.end()
#define IN(a,b) ( (b).find(a) != (b).end())
#define error(x) cerr << #x << " = " << (x) <<endl
#define Error(a,b) cerr<<"( "<<#a<<" , "<<#b<<" ) = ( "<<(a)<<" , "<<(b)<<" )\n";
#define PB push_back
#define PF push_front
#define EL endl
#define CO cout
#define F first
#define S second
#define MAX 1000000007
template <typename T>
void print(vector<T> &v)
{
for(T t : v){
cout<<t<<' ';
}
CO<<EL;
}
//-----------------------------------------utilities end---------------------------
int main()
{
int n,m;
SD(n);
SD(m);
string s;
cin>>s;
unordered_map<char,int> mp;
std::vector<char> v(26);
for (int i = 0; i < 26; ++i)
{
char c= 'a'+i;
mp[c] = i;
v[i] = c;
}
while(m--){
char x,y;
cin>>x>>y;
int ix = mp[x];
int iy = mp[y];
swap(v[ix],v[iy]);
mp[ x ] = iy;
mp[y] = ix;
}
for (int i = 0; i < s.length(); ++i)
{
s[i] = v[ s[i]-'a' ];
}
cout<<s;
return 0;
}
|
[
"ayush.shukla92@gmail.com"
] |
ayush.shukla92@gmail.com
|
20414b07af67557b11362212239f0871ede679b0
|
6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849
|
/sstd_boost/sstd/boost/qvm/gen/mat_operations3.hpp
|
d32dca11ac2e96edddf491d3176e41bca4d2b2a6
|
[
"BSL-1.0"
] |
permissive
|
KqSMea8/sstd_library
|
9e4e622e1b01bed5de7322c2682539400d13dd58
|
0fcb815f50d538517e70a788914da7fbbe786ce1
|
refs/heads/master
| 2020-05-03T21:07:01.650034
| 2019-04-01T00:10:47
| 2019-04-01T00:10:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 71,477
|
hpp
|
//Copyright (c) 2008-2017 Emil Dotchevski and Reverge Studios, Inc.
//Distributed under the Boost Software License, Version 1.0. (See accompanying
//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_QVM_B3A6DB3C87C3E99245ED1C6B747DE
#define BOOST_QVM_B3A6DB3C87C3E99245ED1C6B747DE
//This file was generated by a program. Do not edit manually.
#include <sstd/boost/qvm/assert.hpp>
#include <sstd/boost/qvm/deduce_mat.hpp>
#include <sstd/boost/qvm/deduce_vec.hpp>
#include <sstd/boost/qvm/error.hpp>
#include <sstd/boost/qvm/gen/mat_assign3.hpp>
#include <sstd/boost/qvm/quat_traits.hpp>
#include <sstd/boost/qvm/scalar_traits.hpp>
#include <sstd/boost/qvm/throw_exception.hpp>
namespace
boost
{
namespace
qvm
{
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
deduce_mat2<A,B,3,3> >::type
operator+( A const & a, B const & b )
{
typedef typename deduce_mat2<A,B,3,3>::type R;
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==3);
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==3);
R r;
mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)+mat_traits<B>::template read_element<0,0>(b);
mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)+mat_traits<B>::template read_element<0,1>(b);
mat_traits<R>::template write_element<0,2>(r)=mat_traits<A>::template read_element<0,2>(a)+mat_traits<B>::template read_element<0,2>(b);
mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)+mat_traits<B>::template read_element<1,0>(b);
mat_traits<R>::template write_element<1,1>(r)=mat_traits<A>::template read_element<1,1>(a)+mat_traits<B>::template read_element<1,1>(b);
mat_traits<R>::template write_element<1,2>(r)=mat_traits<A>::template read_element<1,2>(a)+mat_traits<B>::template read_element<1,2>(b);
mat_traits<R>::template write_element<2,0>(r)=mat_traits<A>::template read_element<2,0>(a)+mat_traits<B>::template read_element<2,0>(b);
mat_traits<R>::template write_element<2,1>(r)=mat_traits<A>::template read_element<2,1>(a)+mat_traits<B>::template read_element<2,1>(b);
mat_traits<R>::template write_element<2,2>(r)=mat_traits<A>::template read_element<2,2>(a)+mat_traits<B>::template read_element<2,2>(b);
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator+;
}
namespace
qvm_detail
{
template <int R,int C>
struct plus_mm_defined;
template <>
struct
plus_mm_defined<3,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==1 && mat_traits<B>::cols==1,
deduce_mat2<A,B,3,1> >::type
operator+( A const & a, B const & b )
{
typedef typename deduce_mat2<A,B,3,1>::type R;
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==3);
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==1);
R r;
mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)+mat_traits<B>::template read_element<0,0>(b);
mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)+mat_traits<B>::template read_element<1,0>(b);
mat_traits<R>::template write_element<2,0>(r)=mat_traits<A>::template read_element<2,0>(a)+mat_traits<B>::template read_element<2,0>(b);
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator+;
}
namespace
qvm_detail
{
template <int R,int C>
struct plus_mm_defined;
template <>
struct
plus_mm_defined<3,1>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==1 && mat_traits<B>::rows==1 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
deduce_mat2<A,B,1,3> >::type
operator+( A const & a, B const & b )
{
typedef typename deduce_mat2<A,B,1,3>::type R;
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==1);
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==3);
R r;
mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)+mat_traits<B>::template read_element<0,0>(b);
mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)+mat_traits<B>::template read_element<0,1>(b);
mat_traits<R>::template write_element<0,2>(r)=mat_traits<A>::template read_element<0,2>(a)+mat_traits<B>::template read_element<0,2>(b);
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator+;
}
namespace
qvm_detail
{
template <int R,int C>
struct plus_mm_defined;
template <>
struct
plus_mm_defined<1,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
deduce_mat2<A,B,3,3> >::type
operator-( A const & a, B const & b )
{
typedef typename deduce_mat2<A,B,3,3>::type R;
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==3);
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==3);
R r;
mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)-mat_traits<B>::template read_element<0,0>(b);
mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)-mat_traits<B>::template read_element<0,1>(b);
mat_traits<R>::template write_element<0,2>(r)=mat_traits<A>::template read_element<0,2>(a)-mat_traits<B>::template read_element<0,2>(b);
mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)-mat_traits<B>::template read_element<1,0>(b);
mat_traits<R>::template write_element<1,1>(r)=mat_traits<A>::template read_element<1,1>(a)-mat_traits<B>::template read_element<1,1>(b);
mat_traits<R>::template write_element<1,2>(r)=mat_traits<A>::template read_element<1,2>(a)-mat_traits<B>::template read_element<1,2>(b);
mat_traits<R>::template write_element<2,0>(r)=mat_traits<A>::template read_element<2,0>(a)-mat_traits<B>::template read_element<2,0>(b);
mat_traits<R>::template write_element<2,1>(r)=mat_traits<A>::template read_element<2,1>(a)-mat_traits<B>::template read_element<2,1>(b);
mat_traits<R>::template write_element<2,2>(r)=mat_traits<A>::template read_element<2,2>(a)-mat_traits<B>::template read_element<2,2>(b);
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator-;
}
namespace
qvm_detail
{
template <int R,int C>
struct minus_mm_defined;
template <>
struct
minus_mm_defined<3,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==1 && mat_traits<B>::cols==1,
deduce_mat2<A,B,3,1> >::type
operator-( A const & a, B const & b )
{
typedef typename deduce_mat2<A,B,3,1>::type R;
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==3);
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==1);
R r;
mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)-mat_traits<B>::template read_element<0,0>(b);
mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)-mat_traits<B>::template read_element<1,0>(b);
mat_traits<R>::template write_element<2,0>(r)=mat_traits<A>::template read_element<2,0>(a)-mat_traits<B>::template read_element<2,0>(b);
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator-;
}
namespace
qvm_detail
{
template <int R,int C>
struct minus_mm_defined;
template <>
struct
minus_mm_defined<3,1>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==1 && mat_traits<B>::rows==1 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
deduce_mat2<A,B,1,3> >::type
operator-( A const & a, B const & b )
{
typedef typename deduce_mat2<A,B,1,3>::type R;
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==1);
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==3);
R r;
mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)-mat_traits<B>::template read_element<0,0>(b);
mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)-mat_traits<B>::template read_element<0,1>(b);
mat_traits<R>::template write_element<0,2>(r)=mat_traits<A>::template read_element<0,2>(a)-mat_traits<B>::template read_element<0,2>(b);
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator-;
}
namespace
qvm_detail
{
template <int R,int C>
struct minus_mm_defined;
template <>
struct
minus_mm_defined<1,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
A &>::type
operator+=( A & a, B const & b )
{
mat_traits<A>::template write_element<0,0>(a)+=mat_traits<B>::template read_element<0,0>(b);
mat_traits<A>::template write_element<0,1>(a)+=mat_traits<B>::template read_element<0,1>(b);
mat_traits<A>::template write_element<0,2>(a)+=mat_traits<B>::template read_element<0,2>(b);
mat_traits<A>::template write_element<1,0>(a)+=mat_traits<B>::template read_element<1,0>(b);
mat_traits<A>::template write_element<1,1>(a)+=mat_traits<B>::template read_element<1,1>(b);
mat_traits<A>::template write_element<1,2>(a)+=mat_traits<B>::template read_element<1,2>(b);
mat_traits<A>::template write_element<2,0>(a)+=mat_traits<B>::template read_element<2,0>(b);
mat_traits<A>::template write_element<2,1>(a)+=mat_traits<B>::template read_element<2,1>(b);
mat_traits<A>::template write_element<2,2>(a)+=mat_traits<B>::template read_element<2,2>(b);
return a;
}
namespace
sfinae
{
using ::boost::qvm::operator+=;
}
namespace
qvm_detail
{
template <int R,int C>
struct plus_eq_mm_defined;
template <>
struct
plus_eq_mm_defined<3,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==1 && mat_traits<B>::cols==1,
A &>::type
operator+=( A & a, B const & b )
{
mat_traits<A>::template write_element<0,0>(a)+=mat_traits<B>::template read_element<0,0>(b);
mat_traits<A>::template write_element<1,0>(a)+=mat_traits<B>::template read_element<1,0>(b);
mat_traits<A>::template write_element<2,0>(a)+=mat_traits<B>::template read_element<2,0>(b);
return a;
}
namespace
sfinae
{
using ::boost::qvm::operator+=;
}
namespace
qvm_detail
{
template <int R,int C>
struct plus_eq_mm_defined;
template <>
struct
plus_eq_mm_defined<3,1>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==1 && mat_traits<B>::rows==1 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
A &>::type
operator+=( A & a, B const & b )
{
mat_traits<A>::template write_element<0,0>(a)+=mat_traits<B>::template read_element<0,0>(b);
mat_traits<A>::template write_element<0,1>(a)+=mat_traits<B>::template read_element<0,1>(b);
mat_traits<A>::template write_element<0,2>(a)+=mat_traits<B>::template read_element<0,2>(b);
return a;
}
namespace
sfinae
{
using ::boost::qvm::operator+=;
}
namespace
qvm_detail
{
template <int R,int C>
struct plus_eq_mm_defined;
template <>
struct
plus_eq_mm_defined<1,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
A &>::type
operator-=( A & a, B const & b )
{
mat_traits<A>::template write_element<0,0>(a)-=mat_traits<B>::template read_element<0,0>(b);
mat_traits<A>::template write_element<0,1>(a)-=mat_traits<B>::template read_element<0,1>(b);
mat_traits<A>::template write_element<0,2>(a)-=mat_traits<B>::template read_element<0,2>(b);
mat_traits<A>::template write_element<1,0>(a)-=mat_traits<B>::template read_element<1,0>(b);
mat_traits<A>::template write_element<1,1>(a)-=mat_traits<B>::template read_element<1,1>(b);
mat_traits<A>::template write_element<1,2>(a)-=mat_traits<B>::template read_element<1,2>(b);
mat_traits<A>::template write_element<2,0>(a)-=mat_traits<B>::template read_element<2,0>(b);
mat_traits<A>::template write_element<2,1>(a)-=mat_traits<B>::template read_element<2,1>(b);
mat_traits<A>::template write_element<2,2>(a)-=mat_traits<B>::template read_element<2,2>(b);
return a;
}
namespace
sfinae
{
using ::boost::qvm::operator-=;
}
namespace
qvm_detail
{
template <int R,int C>
struct minus_eq_mm_defined;
template <>
struct
minus_eq_mm_defined<3,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==1 && mat_traits<B>::cols==1,
A &>::type
operator-=( A & a, B const & b )
{
mat_traits<A>::template write_element<0,0>(a)-=mat_traits<B>::template read_element<0,0>(b);
mat_traits<A>::template write_element<1,0>(a)-=mat_traits<B>::template read_element<1,0>(b);
mat_traits<A>::template write_element<2,0>(a)-=mat_traits<B>::template read_element<2,0>(b);
return a;
}
namespace
sfinae
{
using ::boost::qvm::operator-=;
}
namespace
qvm_detail
{
template <int R,int C>
struct minus_eq_mm_defined;
template <>
struct
minus_eq_mm_defined<3,1>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==1 && mat_traits<B>::rows==1 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
A &>::type
operator-=( A & a, B const & b )
{
mat_traits<A>::template write_element<0,0>(a)-=mat_traits<B>::template read_element<0,0>(b);
mat_traits<A>::template write_element<0,1>(a)-=mat_traits<B>::template read_element<0,1>(b);
mat_traits<A>::template write_element<0,2>(a)-=mat_traits<B>::template read_element<0,2>(b);
return a;
}
namespace
sfinae
{
using ::boost::qvm::operator-=;
}
namespace
qvm_detail
{
template <int R,int C>
struct minus_eq_mm_defined;
template <>
struct
minus_eq_mm_defined<1,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==3 && mat_traits<A>::cols==3 && is_scalar<B>::value,
deduce_mat<A> >::type
operator*( A const & a, B b )
{
typedef typename deduce_mat<A>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)*b;
mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)*b;
mat_traits<R>::template write_element<0,2>(r)=mat_traits<A>::template read_element<0,2>(a)*b;
mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)*b;
mat_traits<R>::template write_element<1,1>(r)=mat_traits<A>::template read_element<1,1>(a)*b;
mat_traits<R>::template write_element<1,2>(r)=mat_traits<A>::template read_element<1,2>(a)*b;
mat_traits<R>::template write_element<2,0>(r)=mat_traits<A>::template read_element<2,0>(a)*b;
mat_traits<R>::template write_element<2,1>(r)=mat_traits<A>::template read_element<2,1>(a)*b;
mat_traits<R>::template write_element<2,2>(r)=mat_traits<A>::template read_element<2,2>(a)*b;
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator*;
}
namespace
qvm_detail
{
template <int R,int C>
struct mul_ms_defined;
template <>
struct
mul_ms_defined<3,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
is_scalar<A>::value && mat_traits<B>::rows==3 && mat_traits<B>::cols==3,
deduce_mat<B> >::type
operator*( A a, B const & b )
{
typedef typename deduce_mat<B>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)=a*mat_traits<B>::template read_element<0,0>(b);
mat_traits<R>::template write_element<0,1>(r)=a*mat_traits<B>::template read_element<0,1>(b);
mat_traits<R>::template write_element<0,2>(r)=a*mat_traits<B>::template read_element<0,2>(b);
mat_traits<R>::template write_element<1,0>(r)=a*mat_traits<B>::template read_element<1,0>(b);
mat_traits<R>::template write_element<1,1>(r)=a*mat_traits<B>::template read_element<1,1>(b);
mat_traits<R>::template write_element<1,2>(r)=a*mat_traits<B>::template read_element<1,2>(b);
mat_traits<R>::template write_element<2,0>(r)=a*mat_traits<B>::template read_element<2,0>(b);
mat_traits<R>::template write_element<2,1>(r)=a*mat_traits<B>::template read_element<2,1>(b);
mat_traits<R>::template write_element<2,2>(r)=a*mat_traits<B>::template read_element<2,2>(b);
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator*;
}
namespace
qvm_detail
{
template <int R,int C>
struct mul_sm_defined;
template <>
struct
mul_sm_defined<3,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==3 && mat_traits<A>::cols==1 && is_scalar<B>::value,
deduce_mat<A> >::type
operator*( A const & a, B b )
{
typedef typename deduce_mat<A>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)*b;
mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)*b;
mat_traits<R>::template write_element<2,0>(r)=mat_traits<A>::template read_element<2,0>(a)*b;
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator*;
}
namespace
qvm_detail
{
template <int R,int C>
struct mul_ms_defined;
template <>
struct
mul_ms_defined<3,1>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
is_scalar<A>::value && mat_traits<B>::rows==3 && mat_traits<B>::cols==1,
deduce_mat<B> >::type
operator*( A a, B const & b )
{
typedef typename deduce_mat<B>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)=a*mat_traits<B>::template read_element<0,0>(b);
mat_traits<R>::template write_element<1,0>(r)=a*mat_traits<B>::template read_element<1,0>(b);
mat_traits<R>::template write_element<2,0>(r)=a*mat_traits<B>::template read_element<2,0>(b);
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator*;
}
namespace
qvm_detail
{
template <int R,int C>
struct mul_sm_defined;
template <>
struct
mul_sm_defined<3,1>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==1 && mat_traits<A>::cols==3 && is_scalar<B>::value,
deduce_mat<A> >::type
operator*( A const & a, B b )
{
typedef typename deduce_mat<A>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)*b;
mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)*b;
mat_traits<R>::template write_element<0,2>(r)=mat_traits<A>::template read_element<0,2>(a)*b;
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator*;
}
namespace
qvm_detail
{
template <int R,int C>
struct mul_ms_defined;
template <>
struct
mul_ms_defined<1,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
is_scalar<A>::value && mat_traits<B>::rows==1 && mat_traits<B>::cols==3,
deduce_mat<B> >::type
operator*( A a, B const & b )
{
typedef typename deduce_mat<B>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)=a*mat_traits<B>::template read_element<0,0>(b);
mat_traits<R>::template write_element<0,1>(r)=a*mat_traits<B>::template read_element<0,1>(b);
mat_traits<R>::template write_element<0,2>(r)=a*mat_traits<B>::template read_element<0,2>(b);
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator*;
}
namespace
qvm_detail
{
template <int R,int C>
struct mul_sm_defined;
template <>
struct
mul_sm_defined<1,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==3 && mat_traits<A>::cols==3 && is_scalar<B>::value,
A &>::type
operator*=( A & a, B b )
{
mat_traits<A>::template write_element<0,0>(a)*=b;
mat_traits<A>::template write_element<0,1>(a)*=b;
mat_traits<A>::template write_element<0,2>(a)*=b;
mat_traits<A>::template write_element<1,0>(a)*=b;
mat_traits<A>::template write_element<1,1>(a)*=b;
mat_traits<A>::template write_element<1,2>(a)*=b;
mat_traits<A>::template write_element<2,0>(a)*=b;
mat_traits<A>::template write_element<2,1>(a)*=b;
mat_traits<A>::template write_element<2,2>(a)*=b;
return a;
}
namespace
sfinae
{
using ::boost::qvm::operator*=;
}
namespace
qvm_detail
{
template <int R,int C>
struct mul_eq_ms_defined;
template <>
struct
mul_eq_ms_defined<3,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==3 && mat_traits<A>::cols==1 && is_scalar<B>::value,
A &>::type
operator*=( A & a, B b )
{
mat_traits<A>::template write_element<0,0>(a)*=b;
mat_traits<A>::template write_element<1,0>(a)*=b;
mat_traits<A>::template write_element<2,0>(a)*=b;
return a;
}
namespace
sfinae
{
using ::boost::qvm::operator*=;
}
namespace
qvm_detail
{
template <int R,int C>
struct mul_eq_ms_defined;
template <>
struct
mul_eq_ms_defined<3,1>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==1 && mat_traits<A>::cols==3 && is_scalar<B>::value,
A &>::type
operator*=( A & a, B b )
{
mat_traits<A>::template write_element<0,0>(a)*=b;
mat_traits<A>::template write_element<0,1>(a)*=b;
mat_traits<A>::template write_element<0,2>(a)*=b;
return a;
}
namespace
sfinae
{
using ::boost::qvm::operator*=;
}
namespace
qvm_detail
{
template <int R,int C>
struct mul_eq_ms_defined;
template <>
struct
mul_eq_ms_defined<1,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==3 && mat_traits<A>::cols==3 && is_scalar<B>::value,
deduce_mat<A> >::type
operator/( A const & a, B b )
{
typedef typename deduce_mat<A>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)/b;
mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)/b;
mat_traits<R>::template write_element<0,2>(r)=mat_traits<A>::template read_element<0,2>(a)/b;
mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)/b;
mat_traits<R>::template write_element<1,1>(r)=mat_traits<A>::template read_element<1,1>(a)/b;
mat_traits<R>::template write_element<1,2>(r)=mat_traits<A>::template read_element<1,2>(a)/b;
mat_traits<R>::template write_element<2,0>(r)=mat_traits<A>::template read_element<2,0>(a)/b;
mat_traits<R>::template write_element<2,1>(r)=mat_traits<A>::template read_element<2,1>(a)/b;
mat_traits<R>::template write_element<2,2>(r)=mat_traits<A>::template read_element<2,2>(a)/b;
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator/;
}
namespace
qvm_detail
{
template <int R,int C>
struct div_ms_defined;
template <>
struct
div_ms_defined<3,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
is_scalar<A>::value && mat_traits<B>::rows==3 && mat_traits<B>::cols==3,
deduce_mat<B> >::type
operator/( A a, B const & b )
{
typedef typename deduce_mat<B>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)=a/mat_traits<B>::template read_element<0,0>(b);
mat_traits<R>::template write_element<0,1>(r)=a/mat_traits<B>::template read_element<0,1>(b);
mat_traits<R>::template write_element<0,2>(r)=a/mat_traits<B>::template read_element<0,2>(b);
mat_traits<R>::template write_element<1,0>(r)=a/mat_traits<B>::template read_element<1,0>(b);
mat_traits<R>::template write_element<1,1>(r)=a/mat_traits<B>::template read_element<1,1>(b);
mat_traits<R>::template write_element<1,2>(r)=a/mat_traits<B>::template read_element<1,2>(b);
mat_traits<R>::template write_element<2,0>(r)=a/mat_traits<B>::template read_element<2,0>(b);
mat_traits<R>::template write_element<2,1>(r)=a/mat_traits<B>::template read_element<2,1>(b);
mat_traits<R>::template write_element<2,2>(r)=a/mat_traits<B>::template read_element<2,2>(b);
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator/;
}
namespace
qvm_detail
{
template <int R,int C>
struct div_sm_defined;
template <>
struct
div_sm_defined<3,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==3 && mat_traits<A>::cols==1 && is_scalar<B>::value,
deduce_mat<A> >::type
operator/( A const & a, B b )
{
typedef typename deduce_mat<A>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)/b;
mat_traits<R>::template write_element<1,0>(r)=mat_traits<A>::template read_element<1,0>(a)/b;
mat_traits<R>::template write_element<2,0>(r)=mat_traits<A>::template read_element<2,0>(a)/b;
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator/;
}
namespace
qvm_detail
{
template <int R,int C>
struct div_ms_defined;
template <>
struct
div_ms_defined<3,1>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
is_scalar<A>::value && mat_traits<B>::rows==3 && mat_traits<B>::cols==1,
deduce_mat<B> >::type
operator/( A a, B const & b )
{
typedef typename deduce_mat<B>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)=a/mat_traits<B>::template read_element<0,0>(b);
mat_traits<R>::template write_element<1,0>(r)=a/mat_traits<B>::template read_element<1,0>(b);
mat_traits<R>::template write_element<2,0>(r)=a/mat_traits<B>::template read_element<2,0>(b);
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator/;
}
namespace
qvm_detail
{
template <int R,int C>
struct div_sm_defined;
template <>
struct
div_sm_defined<3,1>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==1 && mat_traits<A>::cols==3 && is_scalar<B>::value,
deduce_mat<A> >::type
operator/( A const & a, B b )
{
typedef typename deduce_mat<A>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)=mat_traits<A>::template read_element<0,0>(a)/b;
mat_traits<R>::template write_element<0,1>(r)=mat_traits<A>::template read_element<0,1>(a)/b;
mat_traits<R>::template write_element<0,2>(r)=mat_traits<A>::template read_element<0,2>(a)/b;
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator/;
}
namespace
qvm_detail
{
template <int R,int C>
struct div_ms_defined;
template <>
struct
div_ms_defined<1,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==3 && mat_traits<A>::cols==3 && is_scalar<B>::value,
A &>::type
operator/=( A & a, B b )
{
mat_traits<A>::template write_element<0,0>(a)/=b;
mat_traits<A>::template write_element<0,1>(a)/=b;
mat_traits<A>::template write_element<0,2>(a)/=b;
mat_traits<A>::template write_element<1,0>(a)/=b;
mat_traits<A>::template write_element<1,1>(a)/=b;
mat_traits<A>::template write_element<1,2>(a)/=b;
mat_traits<A>::template write_element<2,0>(a)/=b;
mat_traits<A>::template write_element<2,1>(a)/=b;
mat_traits<A>::template write_element<2,2>(a)/=b;
return a;
}
namespace
sfinae
{
using ::boost::qvm::operator/=;
}
namespace
qvm_detail
{
template <int R,int C>
struct div_eq_ms_defined;
template <>
struct
div_eq_ms_defined<3,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==3 && mat_traits<A>::cols==1 && is_scalar<B>::value,
A &>::type
operator/=( A & a, B b )
{
mat_traits<A>::template write_element<0,0>(a)/=b;
mat_traits<A>::template write_element<1,0>(a)/=b;
mat_traits<A>::template write_element<2,0>(a)/=b;
return a;
}
namespace
sfinae
{
using ::boost::qvm::operator/=;
}
namespace
qvm_detail
{
template <int R,int C>
struct div_eq_ms_defined;
template <>
struct
div_eq_ms_defined<3,1>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==1 && mat_traits<A>::cols==3 && is_scalar<B>::value,
A &>::type
operator/=( A & a, B b )
{
mat_traits<A>::template write_element<0,0>(a)/=b;
mat_traits<A>::template write_element<0,1>(a)/=b;
mat_traits<A>::template write_element<0,2>(a)/=b;
return a;
}
namespace
sfinae
{
using ::boost::qvm::operator/=;
}
namespace
qvm_detail
{
template <int R,int C>
struct div_eq_ms_defined;
template <>
struct
div_eq_ms_defined<1,3>
{
static bool const value=true;
};
}
template <class R,class A>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<R>::rows==3 && mat_traits<A>::rows==3 &&
mat_traits<R>::cols==3 && mat_traits<A>::cols==3,
R>::type
convert_to( A const & a )
{
R r;
mat_traits<R>::template write_element<0,0>(r) = mat_traits<A>::template read_element<0,0>(a);
mat_traits<R>::template write_element<0,1>(r) = mat_traits<A>::template read_element<0,1>(a);
mat_traits<R>::template write_element<0,2>(r) = mat_traits<A>::template read_element<0,2>(a);
mat_traits<R>::template write_element<1,0>(r) = mat_traits<A>::template read_element<1,0>(a);
mat_traits<R>::template write_element<1,1>(r) = mat_traits<A>::template read_element<1,1>(a);
mat_traits<R>::template write_element<1,2>(r) = mat_traits<A>::template read_element<1,2>(a);
mat_traits<R>::template write_element<2,0>(r) = mat_traits<A>::template read_element<2,0>(a);
mat_traits<R>::template write_element<2,1>(r) = mat_traits<A>::template read_element<2,1>(a);
mat_traits<R>::template write_element<2,2>(r) = mat_traits<A>::template read_element<2,2>(a);
return r;
}
template <class R,class A>
BOOST_QVM_INLINE
typename enable_if_c<
is_mat<R>::value && is_quat<A>::value &&
mat_traits<R>::rows==3 && mat_traits<R>::cols==3,
R>::type
convert_to( A const & q )
{
typedef typename mat_traits<R>::scalar_type T;
T const a=quat_traits<A>::template read_element<0>(q);
T const b=quat_traits<A>::template read_element<1>(q);
T const c=quat_traits<A>::template read_element<2>(q);
T const d=quat_traits<A>::template read_element<3>(q);
T const bb = b*b;
T const cc = c*c;
T const dd = d*d;
T const bc = b*c;
T const bd = b*d;
T const cd = c*d;
T const ab = a*b;
T const ac = a*c;
T const ad = a*d;
T const one = scalar_traits<T>::value(1);
T const two = one+one;
R r;
mat_traits<R>::template write_element<0,0>(r) = one - two*(cc+dd);
mat_traits<R>::template write_element<0,1>(r) = two*(bc-ad);
mat_traits<R>::template write_element<0,2>(r) = two*(bd+ac);
mat_traits<R>::template write_element<1,0>(r) = two*(bc+ad);
mat_traits<R>::template write_element<1,1>(r) = one - two*(bb+dd);
mat_traits<R>::template write_element<1,2>(r) = two*(cd-ab);
mat_traits<R>::template write_element<2,0>(r) = two*(bd-ac);
mat_traits<R>::template write_element<2,1>(r) = two*(cd+ab);
mat_traits<R>::template write_element<2,2>(r) = one - two*(bb+cc);
return r;
}
namespace
sfinae
{
using ::boost::qvm::convert_to;
}
namespace
qvm_detail
{
template <int R,int C>
struct convert_to_m_defined;
template <>
struct
convert_to_m_defined<3,3>
{
static bool const value=true;
};
}
template <class R,class A>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<R>::rows==3 && mat_traits<A>::rows==3 &&
mat_traits<R>::cols==1 && mat_traits<A>::cols==1,
R>::type
convert_to( A const & a )
{
R r;
mat_traits<R>::template write_element<0,0>(r) = mat_traits<A>::template read_element<0,0>(a);
mat_traits<R>::template write_element<1,0>(r) = mat_traits<A>::template read_element<1,0>(a);
mat_traits<R>::template write_element<2,0>(r) = mat_traits<A>::template read_element<2,0>(a);
return r;
}
namespace
sfinae
{
using ::boost::qvm::convert_to;
}
namespace
qvm_detail
{
template <int R,int C>
struct convert_to_m_defined;
template <>
struct
convert_to_m_defined<3,1>
{
static bool const value=true;
};
}
template <class R,class A>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<R>::rows==1 && mat_traits<A>::rows==1 &&
mat_traits<R>::cols==3 && mat_traits<A>::cols==3,
R>::type
convert_to( A const & a )
{
R r;
mat_traits<R>::template write_element<0,0>(r) = mat_traits<A>::template read_element<0,0>(a);
mat_traits<R>::template write_element<0,1>(r) = mat_traits<A>::template read_element<0,1>(a);
mat_traits<R>::template write_element<0,2>(r) = mat_traits<A>::template read_element<0,2>(a);
return r;
}
namespace
sfinae
{
using ::boost::qvm::convert_to;
}
namespace
qvm_detail
{
template <int R,int C>
struct convert_to_m_defined;
template <>
struct
convert_to_m_defined<1,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
bool>::type
operator==( A const & a, B const & b )
{
return
mat_traits<A>::template read_element<0,0>(a)==mat_traits<B>::template read_element<0,0>(b) &&
mat_traits<A>::template read_element<0,1>(a)==mat_traits<B>::template read_element<0,1>(b) &&
mat_traits<A>::template read_element<0,2>(a)==mat_traits<B>::template read_element<0,2>(b) &&
mat_traits<A>::template read_element<1,0>(a)==mat_traits<B>::template read_element<1,0>(b) &&
mat_traits<A>::template read_element<1,1>(a)==mat_traits<B>::template read_element<1,1>(b) &&
mat_traits<A>::template read_element<1,2>(a)==mat_traits<B>::template read_element<1,2>(b) &&
mat_traits<A>::template read_element<2,0>(a)==mat_traits<B>::template read_element<2,0>(b) &&
mat_traits<A>::template read_element<2,1>(a)==mat_traits<B>::template read_element<2,1>(b) &&
mat_traits<A>::template read_element<2,2>(a)==mat_traits<B>::template read_element<2,2>(b);
}
namespace
sfinae
{
using ::boost::qvm::operator==;
}
namespace
qvm_detail
{
template <int R,int C>
struct eq_mm_defined;
template <>
struct
eq_mm_defined<3,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==1 && mat_traits<B>::cols==1,
bool>::type
operator==( A const & a, B const & b )
{
return
mat_traits<A>::template read_element<0,0>(a)==mat_traits<B>::template read_element<0,0>(b) &&
mat_traits<A>::template read_element<1,0>(a)==mat_traits<B>::template read_element<1,0>(b) &&
mat_traits<A>::template read_element<2,0>(a)==mat_traits<B>::template read_element<2,0>(b);
}
namespace
sfinae
{
using ::boost::qvm::operator==;
}
namespace
qvm_detail
{
template <int R,int C>
struct eq_mm_defined;
template <>
struct
eq_mm_defined<3,1>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==1 && mat_traits<B>::rows==1 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
bool>::type
operator==( A const & a, B const & b )
{
return
mat_traits<A>::template read_element<0,0>(a)==mat_traits<B>::template read_element<0,0>(b) &&
mat_traits<A>::template read_element<0,1>(a)==mat_traits<B>::template read_element<0,1>(b) &&
mat_traits<A>::template read_element<0,2>(a)==mat_traits<B>::template read_element<0,2>(b);
}
namespace
sfinae
{
using ::boost::qvm::operator==;
}
namespace
qvm_detail
{
template <int R,int C>
struct eq_mm_defined;
template <>
struct
eq_mm_defined<1,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
bool>::type
operator!=( A const & a, B const & b )
{
return
!(mat_traits<A>::template read_element<0,0>(a)==mat_traits<B>::template read_element<0,0>(b)) ||
!(mat_traits<A>::template read_element<0,1>(a)==mat_traits<B>::template read_element<0,1>(b)) ||
!(mat_traits<A>::template read_element<0,2>(a)==mat_traits<B>::template read_element<0,2>(b)) ||
!(mat_traits<A>::template read_element<1,0>(a)==mat_traits<B>::template read_element<1,0>(b)) ||
!(mat_traits<A>::template read_element<1,1>(a)==mat_traits<B>::template read_element<1,1>(b)) ||
!(mat_traits<A>::template read_element<1,2>(a)==mat_traits<B>::template read_element<1,2>(b)) ||
!(mat_traits<A>::template read_element<2,0>(a)==mat_traits<B>::template read_element<2,0>(b)) ||
!(mat_traits<A>::template read_element<2,1>(a)==mat_traits<B>::template read_element<2,1>(b)) ||
!(mat_traits<A>::template read_element<2,2>(a)==mat_traits<B>::template read_element<2,2>(b));
}
namespace
sfinae
{
using ::boost::qvm::operator!=;
}
namespace
qvm_detail
{
template <int R,int C>
struct neq_mm_defined;
template <>
struct
neq_mm_defined<3,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==1 && mat_traits<B>::cols==1,
bool>::type
operator!=( A const & a, B const & b )
{
return
!(mat_traits<A>::template read_element<0,0>(a)==mat_traits<B>::template read_element<0,0>(b)) ||
!(mat_traits<A>::template read_element<1,0>(a)==mat_traits<B>::template read_element<1,0>(b)) ||
!(mat_traits<A>::template read_element<2,0>(a)==mat_traits<B>::template read_element<2,0>(b));
}
namespace
sfinae
{
using ::boost::qvm::operator!=;
}
namespace
qvm_detail
{
template <int R,int C>
struct neq_mm_defined;
template <>
struct
neq_mm_defined<3,1>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==1 && mat_traits<B>::rows==1 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
bool>::type
operator!=( A const & a, B const & b )
{
return
!(mat_traits<A>::template read_element<0,0>(a)==mat_traits<B>::template read_element<0,0>(b)) ||
!(mat_traits<A>::template read_element<0,1>(a)==mat_traits<B>::template read_element<0,1>(b)) ||
!(mat_traits<A>::template read_element<0,2>(a)==mat_traits<B>::template read_element<0,2>(b));
}
namespace
sfinae
{
using ::boost::qvm::operator!=;
}
namespace
qvm_detail
{
template <int R,int C>
struct neq_mm_defined;
template <>
struct
neq_mm_defined<1,3>
{
static bool const value=true;
};
}
template <class A>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==3 && mat_traits<A>::cols==3,
deduce_mat<A> >::type
operator-( A const & a )
{
typedef typename deduce_mat<A>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)=-mat_traits<A>::template read_element<0,0>(a);
mat_traits<R>::template write_element<0,1>(r)=-mat_traits<A>::template read_element<0,1>(a);
mat_traits<R>::template write_element<0,2>(r)=-mat_traits<A>::template read_element<0,2>(a);
mat_traits<R>::template write_element<1,0>(r)=-mat_traits<A>::template read_element<1,0>(a);
mat_traits<R>::template write_element<1,1>(r)=-mat_traits<A>::template read_element<1,1>(a);
mat_traits<R>::template write_element<1,2>(r)=-mat_traits<A>::template read_element<1,2>(a);
mat_traits<R>::template write_element<2,0>(r)=-mat_traits<A>::template read_element<2,0>(a);
mat_traits<R>::template write_element<2,1>(r)=-mat_traits<A>::template read_element<2,1>(a);
mat_traits<R>::template write_element<2,2>(r)=-mat_traits<A>::template read_element<2,2>(a);
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator-;
}
namespace
qvm_detail
{
template <int R,int C>
struct minus_m_defined;
template <>
struct
minus_m_defined<3,3>
{
static bool const value=true;
};
}
template <class A>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==3 && mat_traits<A>::cols==1,
deduce_mat<A> >::type
operator-( A const & a )
{
typedef typename deduce_mat<A>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)=-mat_traits<A>::template read_element<0,0>(a);
mat_traits<R>::template write_element<1,0>(r)=-mat_traits<A>::template read_element<1,0>(a);
mat_traits<R>::template write_element<2,0>(r)=-mat_traits<A>::template read_element<2,0>(a);
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator-;
}
namespace
qvm_detail
{
template <int R,int C>
struct minus_m_defined;
template <>
struct
minus_m_defined<3,1>
{
static bool const value=true;
};
}
template <class A>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==1 && mat_traits<A>::cols==3,
deduce_mat<A> >::type
operator-( A const & a )
{
typedef typename deduce_mat<A>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)=-mat_traits<A>::template read_element<0,0>(a);
mat_traits<R>::template write_element<0,1>(r)=-mat_traits<A>::template read_element<0,1>(a);
mat_traits<R>::template write_element<0,2>(r)=-mat_traits<A>::template read_element<0,2>(a);
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator-;
}
namespace
qvm_detail
{
template <int R,int C>
struct minus_m_defined;
template <>
struct
minus_m_defined<1,3>
{
static bool const value=true;
};
}
template <class A>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==3 && mat_traits<A>::cols==3,
typename mat_traits<A>::scalar_type>::type
determinant( A const & a )
{
typedef typename mat_traits<A>::scalar_type T;
T const a00=mat_traits<A>::template read_element<0,0>(a);
T const a01=mat_traits<A>::template read_element<0,1>(a);
T const a02=mat_traits<A>::template read_element<0,2>(a);
T const a10=mat_traits<A>::template read_element<1,0>(a);
T const a11=mat_traits<A>::template read_element<1,1>(a);
T const a12=mat_traits<A>::template read_element<1,2>(a);
T const a20=mat_traits<A>::template read_element<2,0>(a);
T const a21=mat_traits<A>::template read_element<2,1>(a);
T const a22=mat_traits<A>::template read_element<2,2>(a);
T det=(a00*(a11*a22-a12*a21)-a01*(a10*a22-a12*a20)+a02*(a10*a21-a11*a20));
return det;
}
namespace
sfinae
{
using ::boost::qvm::determinant;
}
namespace
qvm_detail
{
template <int D>
struct determinant_defined;
template <>
struct
determinant_defined<3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==3 && mat_traits<A>::cols==3 && is_scalar<B>::value,
deduce_mat<A> >::type
inverse( A const & a, B det )
{
typedef typename mat_traits<A>::scalar_type T;
BOOST_QVM_ASSERT(det!=scalar_traits<B>::value(0));
T const a00=mat_traits<A>::template read_element<0,0>(a);
T const a01=mat_traits<A>::template read_element<0,1>(a);
T const a02=mat_traits<A>::template read_element<0,2>(a);
T const a10=mat_traits<A>::template read_element<1,0>(a);
T const a11=mat_traits<A>::template read_element<1,1>(a);
T const a12=mat_traits<A>::template read_element<1,2>(a);
T const a20=mat_traits<A>::template read_element<2,0>(a);
T const a21=mat_traits<A>::template read_element<2,1>(a);
T const a22=mat_traits<A>::template read_element<2,2>(a);
T const f=scalar_traits<T>::value(1)/det;
typedef typename deduce_mat<A>::type R;
R r;
mat_traits<R>::template write_element<0,0>(r)= f*(a11*a22-a12*a21);
mat_traits<R>::template write_element<0,1>(r)=-f*(a01*a22-a02*a21);
mat_traits<R>::template write_element<0,2>(r)= f*(a01*a12-a02*a11);
mat_traits<R>::template write_element<1,0>(r)=-f*(a10*a22-a12*a20);
mat_traits<R>::template write_element<1,1>(r)= f*(a00*a22-a02*a20);
mat_traits<R>::template write_element<1,2>(r)=-f*(a00*a12-a02*a10);
mat_traits<R>::template write_element<2,0>(r)= f*(a10*a21-a11*a20);
mat_traits<R>::template write_element<2,1>(r)=-f*(a00*a21-a01*a20);
mat_traits<R>::template write_element<2,2>(r)= f*(a00*a11-a01*a10);
return r;
}
template <class A>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==3 && mat_traits<A>::cols==3,
deduce_mat<A> >::type
inverse( A const & a )
{
typedef typename mat_traits<A>::scalar_type T;
T det=determinant(a);
if( det==scalar_traits<T>::value(0) )
BOOST_QVM_THROW_EXCEPTION(zero_determinant_error());
return inverse(a,det);
}
namespace
sfinae
{
using ::boost::qvm::inverse;
}
namespace
qvm_detail
{
template <int D>
struct inverse_m_defined;
template <>
struct
inverse_m_defined<3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
deduce_mat2<A,B,3,3> >::type
operator*( A const & a, B const & b )
{
typedef typename mat_traits<A>::scalar_type Ta;
typedef typename mat_traits<B>::scalar_type Tb;
Ta const a00 = mat_traits<A>::template read_element<0,0>(a);
Ta const a01 = mat_traits<A>::template read_element<0,1>(a);
Ta const a02 = mat_traits<A>::template read_element<0,2>(a);
Ta const a10 = mat_traits<A>::template read_element<1,0>(a);
Ta const a11 = mat_traits<A>::template read_element<1,1>(a);
Ta const a12 = mat_traits<A>::template read_element<1,2>(a);
Ta const a20 = mat_traits<A>::template read_element<2,0>(a);
Ta const a21 = mat_traits<A>::template read_element<2,1>(a);
Ta const a22 = mat_traits<A>::template read_element<2,2>(a);
Tb const b00 = mat_traits<B>::template read_element<0,0>(b);
Tb const b01 = mat_traits<B>::template read_element<0,1>(b);
Tb const b02 = mat_traits<B>::template read_element<0,2>(b);
Tb const b10 = mat_traits<B>::template read_element<1,0>(b);
Tb const b11 = mat_traits<B>::template read_element<1,1>(b);
Tb const b12 = mat_traits<B>::template read_element<1,2>(b);
Tb const b20 = mat_traits<B>::template read_element<2,0>(b);
Tb const b21 = mat_traits<B>::template read_element<2,1>(b);
Tb const b22 = mat_traits<B>::template read_element<2,2>(b);
typedef typename deduce_mat2<A,B,3,3>::type R;
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==3);
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==3);
R r;
mat_traits<R>::template write_element<0,0>(r)=a00*b00+a01*b10+a02*b20;
mat_traits<R>::template write_element<0,1>(r)=a00*b01+a01*b11+a02*b21;
mat_traits<R>::template write_element<0,2>(r)=a00*b02+a01*b12+a02*b22;
mat_traits<R>::template write_element<1,0>(r)=a10*b00+a11*b10+a12*b20;
mat_traits<R>::template write_element<1,1>(r)=a10*b01+a11*b11+a12*b21;
mat_traits<R>::template write_element<1,2>(r)=a10*b02+a11*b12+a12*b22;
mat_traits<R>::template write_element<2,0>(r)=a20*b00+a21*b10+a22*b20;
mat_traits<R>::template write_element<2,1>(r)=a20*b01+a21*b11+a22*b21;
mat_traits<R>::template write_element<2,2>(r)=a20*b02+a21*b12+a22*b22;
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator*;
}
namespace
qvm_detail
{
template <int R,int CR,int C>
struct mul_mm_defined;
template <>
struct
mul_mm_defined<3,3,3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
A &>::type
operator*=( A & a, B const & b )
{
typedef typename mat_traits<A>::scalar_type Ta;
typedef typename mat_traits<B>::scalar_type Tb;
Ta const a00 = mat_traits<A>::template read_element<0,0>(a);
Ta const a01 = mat_traits<A>::template read_element<0,1>(a);
Ta const a02 = mat_traits<A>::template read_element<0,2>(a);
Ta const a10 = mat_traits<A>::template read_element<1,0>(a);
Ta const a11 = mat_traits<A>::template read_element<1,1>(a);
Ta const a12 = mat_traits<A>::template read_element<1,2>(a);
Ta const a20 = mat_traits<A>::template read_element<2,0>(a);
Ta const a21 = mat_traits<A>::template read_element<2,1>(a);
Ta const a22 = mat_traits<A>::template read_element<2,2>(a);
Tb const b00 = mat_traits<B>::template read_element<0,0>(b);
Tb const b01 = mat_traits<B>::template read_element<0,1>(b);
Tb const b02 = mat_traits<B>::template read_element<0,2>(b);
Tb const b10 = mat_traits<B>::template read_element<1,0>(b);
Tb const b11 = mat_traits<B>::template read_element<1,1>(b);
Tb const b12 = mat_traits<B>::template read_element<1,2>(b);
Tb const b20 = mat_traits<B>::template read_element<2,0>(b);
Tb const b21 = mat_traits<B>::template read_element<2,1>(b);
Tb const b22 = mat_traits<B>::template read_element<2,2>(b);
mat_traits<A>::template write_element<0,0>(a)=a00*b00+a01*b10+a02*b20;
mat_traits<A>::template write_element<0,1>(a)=a00*b01+a01*b11+a02*b21;
mat_traits<A>::template write_element<0,2>(a)=a00*b02+a01*b12+a02*b22;
mat_traits<A>::template write_element<1,0>(a)=a10*b00+a11*b10+a12*b20;
mat_traits<A>::template write_element<1,1>(a)=a10*b01+a11*b11+a12*b21;
mat_traits<A>::template write_element<1,2>(a)=a10*b02+a11*b12+a12*b22;
mat_traits<A>::template write_element<2,0>(a)=a20*b00+a21*b10+a22*b20;
mat_traits<A>::template write_element<2,1>(a)=a20*b01+a21*b11+a22*b21;
mat_traits<A>::template write_element<2,2>(a)=a20*b02+a21*b12+a22*b22;
return a;
}
namespace
sfinae
{
using ::boost::qvm::operator*=;
}
namespace
qvm_detail
{
template <int D>
struct mul_eq_mm_defined;
template <>
struct
mul_eq_mm_defined<3>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==3 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==1,
deduce_mat2<A,B,3,1> >::type
operator*( A const & a, B const & b )
{
typedef typename mat_traits<A>::scalar_type Ta;
typedef typename mat_traits<B>::scalar_type Tb;
Ta const a00 = mat_traits<A>::template read_element<0,0>(a);
Ta const a01 = mat_traits<A>::template read_element<0,1>(a);
Ta const a02 = mat_traits<A>::template read_element<0,2>(a);
Ta const a10 = mat_traits<A>::template read_element<1,0>(a);
Ta const a11 = mat_traits<A>::template read_element<1,1>(a);
Ta const a12 = mat_traits<A>::template read_element<1,2>(a);
Ta const a20 = mat_traits<A>::template read_element<2,0>(a);
Ta const a21 = mat_traits<A>::template read_element<2,1>(a);
Ta const a22 = mat_traits<A>::template read_element<2,2>(a);
Tb const b00 = mat_traits<B>::template read_element<0,0>(b);
Tb const b10 = mat_traits<B>::template read_element<1,0>(b);
Tb const b20 = mat_traits<B>::template read_element<2,0>(b);
typedef typename deduce_mat2<A,B,3,1>::type R;
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==3);
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==1);
R r;
mat_traits<R>::template write_element<0,0>(r)=a00*b00+a01*b10+a02*b20;
mat_traits<R>::template write_element<1,0>(r)=a10*b00+a11*b10+a12*b20;
mat_traits<R>::template write_element<2,0>(r)=a20*b00+a21*b10+a22*b20;
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator*;
}
namespace
qvm_detail
{
template <int R,int CR,int C>
struct mul_mm_defined;
template <>
struct
mul_mm_defined<3,3,1>
{
static bool const value=true;
};
}
template <class A,class B>
BOOST_QVM_INLINE_OPERATIONS
typename lazy_enable_if_c<
mat_traits<A>::rows==1 && mat_traits<B>::rows==3 &&
mat_traits<A>::cols==3 && mat_traits<B>::cols==3,
deduce_mat2<A,B,1,3> >::type
operator*( A const & a, B const & b )
{
typedef typename mat_traits<A>::scalar_type Ta;
typedef typename mat_traits<B>::scalar_type Tb;
Ta const a00 = mat_traits<A>::template read_element<0,0>(a);
Ta const a01 = mat_traits<A>::template read_element<0,1>(a);
Ta const a02 = mat_traits<A>::template read_element<0,2>(a);
Tb const b00 = mat_traits<B>::template read_element<0,0>(b);
Tb const b01 = mat_traits<B>::template read_element<0,1>(b);
Tb const b02 = mat_traits<B>::template read_element<0,2>(b);
Tb const b10 = mat_traits<B>::template read_element<1,0>(b);
Tb const b11 = mat_traits<B>::template read_element<1,1>(b);
Tb const b12 = mat_traits<B>::template read_element<1,2>(b);
Tb const b20 = mat_traits<B>::template read_element<2,0>(b);
Tb const b21 = mat_traits<B>::template read_element<2,1>(b);
Tb const b22 = mat_traits<B>::template read_element<2,2>(b);
typedef typename deduce_mat2<A,B,1,3>::type R;
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::rows==1);
BOOST_QVM_STATIC_ASSERT(mat_traits<R>::cols==3);
R r;
mat_traits<R>::template write_element<0,0>(r)=a00*b00+a01*b10+a02*b20;
mat_traits<R>::template write_element<0,1>(r)=a00*b01+a01*b11+a02*b21;
mat_traits<R>::template write_element<0,2>(r)=a00*b02+a01*b12+a02*b22;
return r;
}
namespace
sfinae
{
using ::boost::qvm::operator*;
}
namespace
qvm_detail
{
template <int R,int CR,int C>
struct mul_mm_defined;
template <>
struct
mul_mm_defined<1,3,3>
{
static bool const value=true;
};
}
}
}
#endif
|
[
"zhaixueqiang@hotmail.com"
] |
zhaixueqiang@hotmail.com
|
cdd442e0125272152fc3d4fe2c842a3ebf7d1983
|
c7ef72740216bec011da20f9b404f845be9b00eb
|
/xic/src/edit/prpedit.cc
|
7e9047342dd968f46f0c1745b45e0ffc07924446
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
Augertron/xictools
|
8e27b842ae8fbcaf05c5329a32f79e6b3486fdc5
|
be58bd6c964f3265ccdc4649c8ba0fabcefd3524
|
refs/heads/master
| 2020-05-16T06:50:04.067760
| 2019-03-15T03:37:26
| 2019-03-15T03:37:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 123,512
|
cc
|
/*========================================================================*
* *
* Distributed by Whiteley Research Inc., Sunnyvale, California, USA *
* http://wrcad.com *
* Copyright (C) 2017 Whiteley Research Inc., all rights reserved. *
* Author: Stephen R. Whiteley, except as indicated. *
* *
* As fully as possible recognizing licensing terms and conditions *
* imposed by earlier work from which this work was derived, if any, *
* this work is released under the Apache License, Version 2.0 (the *
* "License"). You may not use this file except in compliance with *
* the License, and compliance with inherited licenses which are *
* specified in a sub-header below this one if applicable. A copy *
* of the License is provided with this distribution, or you may *
* obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* See the License for the specific language governing permissions *
* and limitations under the License. *
* *
* 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 NON- *
* INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED *
* OR STEPHEN R. WHITELEY 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. *
* *
*========================================================================*
* XicTools Integrated Circuit Design System *
* *
* Xic Integrated Circuit Layout and Schematic Editor *
* *
*========================================================================*
$Id:$
*========================================================================*/
#include "config.h"
#include "main.h"
#include "edit.h"
#include "undolist.h"
#include "pcell.h"
#include "pcell_params.h"
#include "scedif.h"
#include "dsp_tkif.h"
#include "dsp_inlines.h"
#include "cd_propnum.h"
#include "cd_lgen.h"
#include "fio.h"
#include "events.h"
#include "menu.h"
#include "ebtn_menu.h"
#include "promptline.h"
#include "errorlog.h"
#include "select.h"
//----------------------------------------------------------------------
// The prpty command - modify properties of objects using
// PopUpProperties()
//----------------------------------------------------------------------
namespace {
// Add/replace the property specified, do undo list processing.
// Used for physical mode properties only.
//
bool
prpty_replace(CDo *odesc, CDs *sdesc, CDp *pdesc, int value,
const char *string)
{
if (!odesc || !string)
return (true);
if (value == XICP_NOMERGE) {
// This property is restricted to boxes, polys, and wires.
if (odesc->type() != CDBOX && odesc->type() != CDPOLYGON &&
odesc->type() != CDWIRE) {
Log()->ErrorLog(mh::Properties,
"NoMerge applicable to boxes, polygons, and wires only.");
return (false);
}
}
else if (value == XICP_EXT_FLATTEN) {
// Instances only.
if (odesc->type() != CDINSTANCE) {
Log()->ErrorLog(mh::Properties,
"Flatten applicable to instances only.");
return (false);
}
}
CDp *newp = new CDp(string, value);
Ulist()->RecordPrptyChange(sdesc, odesc, pdesc, newp);
return (true);
}
// This is passed to the "long text" editor and to its callback.
//
struct ltobj
{
ltobj(CDs *s, CDo *o, CDp *p, int v)
{ sdesc = s; odesc = o; pdesc = p ? p->dup() : 0; value = v; }
~ltobj() { delete pdesc; }
CDs *sdesc;
CDo *odesc;
CDp *pdesc;
int value;
};
// Doubly linked list of objects to view/process
//
struct sSel
{
sSel(CDo *p) { pointer = p; next = prev = 0; }
CDo *pointer;
sSel *next;
sSel *prev;
};
inline CDo *od_of(sSel *sl) { return (sl ? sl->pointer : 0); }
CDp *prpmatch(CDo*, CDp*, int);
int maskof(int);
// for Vmask
#define NAME_MASK 0x1
#define MODEL_MASK 0x2
#define VALUE_MASK 0x4
#define PARAM_MASK 0x8
#define OTHER_MASK 0x10
#define NOPHYS_MASK 0x20
#define FLATTEN_MASK 0x40
#define NOSYMB_MASK 0x80
#define RANGE_MASK 0x100
#define DEVREF_MASK 0x200
namespace ed_prpedit {
enum { PRPquiescent, PRPadding, PRPdeleting };
typedef unsigned char PRPmodif;
struct PrptyState : public CmdState
{
PrptyState(const char*, const char*);
virtual ~PrptyState();
void setCaller(GRobject c) { Caller = c; }
// Control interface, wrapped into cEdit.
bool pSetup();
bool pCallback(CDo*);
void pRelist();
void pSetGlobal(bool);
void pSetInfoMode(bool b) { InfoMode = b; }
void pUpdateList(CDo*, CDo*);
void pAdd(int);
void pEdit(Ptxt*);
void pRemove(Ptxt*);
void b1down() { cEventHdlr::sel_b1down(); }
void b1up();
void desel();
void esc();
bool key(int, const char*, int);
void undo();
void redo();
static void ltcallback(hyList*, void*);
private:
void prp_showselect(bool);
bool prp_get_prompt(bool, CDo*, char*);
void prp_updtext(sSel*);
void prp_add_elec(Ptxt*, int, bool);
void prp_add_elec_noglob();
void prp_add_elec_glob_all();
void prp_add_elec_glob_seq();
void prp_add_phys(Ptxt*, int, bool);
void prp_add_phys_noglob();
void prp_add_phys_glob_all();
void prp_add_phys_glob_seq();
bool prp_get_add_type(bool);
bool prp_get_string(bool, bool);
void prp_rm(Ptxt*);
bool prp_get_rm_type(bool);
void prp_remove(sSel*, CDp*);
static int btn_callback(Ptxt*);
static void down_callback();
static void up_callback();
void message() { PL()->ShowPrompt(msg1); }
void SetLevel1(bool show) { Level = 1; if (show) message(); }
void SetLevel2() { Level = 2; }
GRobject Caller;
bool GotOne;
PRPmodif Modifying; // set when in adprp or rmprp
bool Global; // global mode add/remove
bool InfoMode; // use info window pop-up
bool ShowAllSel; // show all objects in list as selected
sSel *Shead;
sSel *Scur;
char Types[8];
BBox AOI;
int Value; // current property value for adprp, rmprp
int Vmask; // type vector for rmprp
CDp *SelPrp; // selected property
struct {
char *string;
hyList *hyl;
} Udata; // property string for adprp, rmprp
static const char *msg1;
static const char *nosel;
};
PrptyState *PrptyCmd;
}
}
using namespace ed_prpedit;
const char *PrptyState::msg1 = "Select objects";
const char *PrptyState::nosel = "No objects have been selected.";
namespace {
// While the prpty command is active, this code is called from the
// desel button. It deselects all selected objects.
//
void
prptyDesel(CmdDesc*)
{
// Nothing to do, the work is done in PrptyCmd::desel.
}
// Reset the desel button when active to property specific action.
//
void
switchPropertiesMenu(bool state)
{
if (state)
XM()->RegisterDeselOverride(&prptyDesel);
else
XM()->RegisterDeselOverride(0);
}
}
// Menu function for prpty command. If objects have been selected,
// link them into a new sSel list, and set Level2, where each object
// is highlighted and properties displayed. The arrow keys cycle
// through this list. Otherwise set Level1, which enables selection
// of objects.
//
void
cEdit::propertiesExec(CmdDesc *cmd)
{
if (PrptyCmd) {
PrptyCmd->esc();
return;
}
Deselector ds(cmd);
if (noEditing())
return;
if (!XM()->CheckCurCell(true, false, DSP()->CurMode()))
return;
if (DSP()->CurMode() == Electrical &&
Menu()->MenuButtonStatus("main", MenuSYMBL) == 1) {
PL()->ShowPrompt("Can't show properties in symbolic mode.");
return;
}
switchPropertiesMenu(true);
ED()->PopUpProperties(0, MODE_ON, PRPinactive);
PrptyCmd = new PrptyState("PRPTY", "xic:prpty");
PrptyCmd->setCaller(cmd ? cmd->caller : 0);
if (!PrptyCmd->pSetup()) {
delete PrptyCmd;
return;
}
ds.clear();
}
// For graphics.
//
CmdState*
cEdit::prptyCmd()
{
return (PrptyCmd);
}
bool
cEdit::prptyCallback(CDo *odesc)
{
if (PrptyCmd)
return (PrptyCmd->pCallback(odesc));
return (false);
}
// Update the properties lists.
//
void
cEdit::prptyRelist()
{
if (PrptyCmd)
PrptyCmd->pRelist();
PopUpCellProperties(MODE_UPD);
}
void
cEdit::prptySetGlobal(bool glob)
{
if (PrptyCmd)
PrptyCmd->pSetGlobal(glob);
}
// Set/unset info mode (from the pop-up).
//
void
cEdit::prptySetInfoMode(bool b)
{
if (PrptyCmd)
PrptyCmd->pSetInfoMode(b);
}
void
cEdit::prptyUpdateList(CDo *odesc, CDo *onew)
{
if (PrptyCmd)
PrptyCmd->pUpdateList(odesc, onew);
}
void
cEdit::prptyAdd(int which)
{
if (PrptyCmd)
PrptyCmd->pAdd(which);
}
void
cEdit::prptyEdit(Ptxt *line)
{
if (PrptyCmd)
PrptyCmd->pEdit(line);
}
void
cEdit::prptyRemove(Ptxt *line)
{
if (PrptyCmd)
PrptyCmd->pRemove(line);
}
// End of cEdit functions for PrptyState.
PrptyState::PrptyState(const char *nm, const char *hk) : CmdState(nm, hk)
{
Caller = 0;
if (DSP()->CurMode() == Electrical) {
ScedIf()->connectAll(false);
Types[0] = CDINSTANCE;
Types[1] = CDWIRE;
Types[2] = CDLABEL;
Types[3] = '\0';
}
else
strcpy(Types, Selections.selectTypes());
GotOne = Selections.hasTypes(CurCell(), Types, false);
if (!GotOne)
SetLevel1(false);
else
SetLevel2();
Modifying = PRPquiescent;
Global = false;
InfoMode = false;
ShowAllSel = false;
Shead = Scur = 0;
Value = Vmask = 0;
SelPrp = 0;
Udata.string = 0;
Udata.hyl = 0;
}
PrptyState::~PrptyState()
{
PrptyCmd = 0;
}
bool
PrptyState::pSetup()
{
if (!EV()->PushCallback(this)) {
switchPropertiesMenu(false);
return (false);
}
sSel *sd = 0, *sd0 = 0;
sSelGen sg(Selections, CurCell());
CDo *od;
while ((od = sg.next()) != 0) {
if (!strchr(Types, od->type()))
continue;
if (!sd)
sd = sd0 = new sSel(od);
else {
sd->next = new sSel(od);
sd->next->prev = sd;
sd = sd->next;
}
}
if (!ShowAllSel)
Selections.deselectTypes(CurCell(), 0);
Shead = Scur = sd0;
ED()->PopUpProperties(od_of(Scur), MODE_UPD, PRPactive);
if (!Scur)
message();
return (true);
}
// This function is called by the editor if the user points at an
// object on screen. This pops up a secondary window listing the
// properties of the "alternate" object, allowing cut/paste. A
// true return suppresses hypertext return in editor.
//
bool
PrptyState::pCallback(CDo *odesc)
{
if (InfoMode || (EV()->Cursor().get_downstate() &
(GR_SHIFT_MASK | GR_CONTROL_MASK))) {
if (odesc && XM()->IsBoundaryVisible(CurCell(), odesc))
ED()->PopUpPropertyInfo(odesc, MODE_ON);
return (true);
}
if (Modifying == PRPdeleting)
return (true);
return (false);
}
void
PrptyState::pRelist()
{
CDo *od = Scur ? Scur->pointer : 0;
ED()->PopUpProperties(od, MODE_UPD, PRPnochange);
ED()->PopUpPropertyInfo(0, MODE_UPD);
}
// Set/unset global mode (from the pop-up).
//
void
PrptyState::pSetGlobal(bool glob)
{
Global = glob;
if (!ShowAllSel) {
CDs *cursd = CurCell();
if (glob) {
for (sSel *s = Shead; s; s = s->next) {
// Skip display, then revert to vanilla.
Selections.insertObject(cursd, s->pointer, true);
s->pointer->set_state(CDobjVanilla);
}
}
else
Selections.deselectTypes(cursd, 0);
prp_showselect(true);
}
}
// If an object is being deleted, remove it from the list or replace
// it with onew. This is needed if a device label is updated, and the
// label is in the list, and for objects changing due to applied pseudo-
// properties.
//
void
PrptyState::pUpdateList(CDo *odesc, CDo *onew)
{
for (sSel *sd = Shead; sd; sd = sd->next) {
if (sd->pointer == odesc) {
if (onew)
sd->pointer = onew;
else {
if (sd == Scur) {
if (sd->next)
Scur = sd->next;
else if (sd->prev)
Scur = sd->prev;
else
Scur = 0;
}
if (sd->prev)
sd->prev->next = sd->next;
else
Shead = sd->next;
if (sd->next)
sd->next->prev = sd->prev;
delete sd;
}
break;
}
}
if (Global) {
sSelGen sg(Selections, CurCell());
CDo *od;
while ((od = sg.next()) != 0) {
if (od == odesc) {
if (onew) {
// Keep state, replace sets to selected.
CDobjState st = onew->state();
sg.replace(onew);
onew->set_state(st);
}
else
sg.remove();
break;
}
}
}
ED()->PropertyPurge(odesc, Scur ? Scur->pointer : 0);
ED()->PropertyInfoPurge(odesc, onew);
}
void
PrptyState::pAdd(int which)
{
PL()->RegisterArrowKeyCallbacks(0, 0);
ED()->RegisterPrptyBtnCallback(0);
if (DSP()->CurMode() == Physical)
prp_add_phys(0, which, false);
else
prp_add_elec(0, which, false);
if (PrptyCmd)
pRelist();
}
// Edit the property given in line.
//
void
PrptyState::pEdit(Ptxt *line)
{
PL()->RegisterArrowKeyCallbacks(0, 0);
ED()->RegisterPrptyBtnCallback(0);
if (DSP()->CurMode() == Physical)
prp_add_phys(line, -1, true);
else
prp_add_elec(line, -1, true);
if (PrptyCmd)
pRelist();
}
// Remove the property whose string appears in line, or if in global
// mode remove properties from all objects in the object list.
//
void
PrptyState::pRemove(Ptxt *line)
{
PL()->RegisterArrowKeyCallbacks(0, 0);
ED()->RegisterPrptyBtnCallback(0);
prp_rm(line);
}
void
PrptyState::b1up()
{
if (InfoMode || (EV()->Cursor().get_downstate() &
(GR_SHIFT_MASK | GR_CONTROL_MASK))) {
CDol *sl0;
if (!cEventHdlr::sel_b1up(&AOI, Types, &sl0))
return;
if (!sl0)
return;
CDo *od = 0;
for (CDol *sl = sl0; sl; sl = sl->next) {
if (XM()->IsBoundaryVisible(CurCell(), sl->odesc)) {
od = sl->odesc;
break;
}
}
CDol::destroy(sl0);
if (od)
ED()->PopUpPropertyInfo(od, MODE_ON);
return;
}
sSel *sd = 0, *sd0 = 0;
if (Level == 1) {
if (!Global && !ShowAllSel) {
CDol *sl0;
if (!cEventHdlr::sel_b1up(&AOI, Types, &sl0))
return;
if (!sl0)
return;
for (CDol *sl = sl0; sl; sl = sl->next) {
if (!sd)
sd = sd0 = new sSel(sl->odesc);
else {
sd->next = new sSel(sl->odesc);
sd->next->prev = sd;
sd = sd->next;
}
}
CDol::destroy(sl0);
}
else {
if (!cEventHdlr::sel_b1up(&AOI, Types, 0))
return;
sSelGen sg(Selections, CurCell());
CDo *od;
while ((od = sg.next()) != 0) {
if (!sd)
sd = sd0 = new sSel(od);
else {
sd->next = new sSel(od);
sd->next->prev = sd;
sd = sd->next;
}
}
if (!sd)
return;
}
Shead = Scur = sd0;
ED()->PopUpProperties(od_of(Scur), MODE_UPD, PRPnochange);
SetLevel2();
}
else {
sSel *newsel = 0, *n0 = 0;
CDol *sl0;
if (!cEventHdlr::sel_b1up(&AOI, Types, &sl0))
return;
if (!sl0)
return;
for (CDol *sl = sl0; sl; sl = sl->next) {
// is object already in list?
for (sd = Shead ; sd; sd = sd->next)
if (sd->pointer == sl->odesc)
break;
if (sd) {
// Object is already in list
if (!sl->next && !newsel) {
// This is the last new object, and no other new objects
// were found to not be in the existing list.
//
if (sd == Scur && (sd->prev || sd->next)) {
// This is also the currently marked object,
// deselect and remove from list.
//
Selections.removeObject(CurCell(), sd->pointer);
if (sd->prev)
sd->prev->next = sd->next;
else
Shead = sd->next;
if (sd->next) {
sd->next->prev = sd->prev;
Scur = sd->next;
}
else
Scur = sd->prev;
delete sd;
}
else
// Make the new object the currently marked object
Scur = sd;
CDol::destroy(sl0);
ED()->PopUpProperties(od_of(Scur), MODE_UPD, PRPnochange);
return;
}
continue;
}
else {
// Object not in list. Select it, and add it to the "new"
// list.
//
if (Global || ShowAllSel) {
sl->odesc->set_state(CDobjVanilla);
Selections.insertObject(CurCell(), sl->odesc);
}
if (newsel == 0)
newsel = n0 = new sSel(sl->odesc);
else {
newsel->next = new sSel(sl->odesc);
newsel->next->prev = newsel;
newsel = newsel->next;
}
}
}
//
// If we get here, a new object was found. Link the new list
// into the present list at the present position. Advance the
// present position to the first new object. It is possible that
// Scur/Shead is null, if objects have been merged away through
// pseudo-props
//
CDol::destroy(sl0);
n0->prev = Scur;
if (Scur) {
newsel->next = Scur->next;
Scur->next = n0;
}
if (newsel->next)
newsel->next->prev = newsel;
Scur = n0;
if (!Shead)
Shead = Scur;
ED()->PopUpProperties(od_of(Scur), MODE_UPD, PRPnochange);
}
}
// While the prpty command is active, this code is called from the
// desel button. It deselects all selected objects.
//
void
PrptyState::desel()
{
if (!Scur)
return;
ED()->PopUpProperties(0, MODE_UPD, PRPnochange);
while ((Scur = Shead) != 0) {
Shead = Scur->next;
Selections.removeObject(CurCell(), Scur->pointer);
delete Scur;
}
Scur = Shead = 0;
if (EV()->CurCmd() && EV()->CurCmd() != this)
EV()->CurCmd()->esc();
SetLevel1(true);
}
void
PrptyState::esc()
{
PL()->AbortLongText();
cEventHdlr::sel_esc();
Selections.deselectTypes(CurCell(), 0);
while ((Scur = Shead)) {
Shead = Scur->next;
delete Scur;
}
Scur = Shead = 0;
PL()->ErasePrompt();
EV()->PopCallback(this);
Menu()->Deselect(Caller);
switchPropertiesMenu(false);
ED()->PopUpPropertyInfo(0, MODE_OFF);
ED()->PopUpProperties(0, MODE_UPD, PRPinactive);
delete this;
}
// If the user points at an object, it is selected, added to the sSel
// list if not already there, and becomes the currently marked object.
// If it is already the currently marked object, deselect it and
// remove it from the list.
// Look for arrow keys, which cycle the currently marked object
// through the list. Also respond to accelerators for the button
// commands.
//
bool
PrptyState::key(int code, const char*, int mstate)
{
if (Level == 1)
return (false);
if (code == LEFT_KEY || code == DOWN_KEY) {
if (mstate & (GR_SHIFT_MASK | GR_CONTROL_MASK))
return (false);
if (!Scur)
return (true);
if (Scur->prev)
Scur = Scur->prev;
else {
while (Scur->next)
Scur = Scur->next;
}
ED()->PopUpProperties(od_of(Scur), MODE_UPD, PRPnochange);
return (true);
}
if (code == RIGHT_KEY || code == UP_KEY) {
if (mstate & (GR_SHIFT_MASK | GR_CONTROL_MASK))
return (false);
if (!Scur)
return (true);
if (Scur->next)
Scur = Scur->next;
else {
while (Scur->prev)
Scur = Scur->prev;
}
ED()->PopUpProperties(od_of(Scur), MODE_UPD, PRPnochange);
return (true);
}
return (false);
}
// Undo the last adprp or rmprp, set currently marked object to
// undone object, if not global.
//
void
PrptyState::undo()
{
if (Level == 1)
cEventHdlr::sel_undo();
else {
Oper *cur = Ulist()->UndoList();
if (cur && (!strcmp(cur->cmd(), "adprp") ||
!strcmp(cur->cmd(), "rmprp"))) {
if (cur->prp_list()) {
CDo *odesc = cur->prp_list()->odesc();
bool global = (cur->prp_list()->next_chg() != 0);
if (!cEventHdlr::sel_undo() && !global) {
sSel *sd;
for (sd = Shead; sd; sd = sd->next)
if (sd->pointer == odesc)
break;
if (sd) {
Scur = sd;
ED()->PopUpProperties(od_of(Scur), MODE_UPD,
PRPnochange);
}
}
}
else if (cur->obj_list()) {
if (!cEventHdlr::sel_undo() && Ulist()->HasRedo()) {
Ochg *xc = Ulist()->RedoList()->obj_list();
while (xc) {
for (sSel *sd = Shead; sd; sd = sd->next) {
if (xc->oadd() && xc->odel() &&
sd->pointer == xc->odel()) {
sd->pointer = xc->oadd();
break;
}
}
xc = xc->next_chg();
}
ED()->PopUpProperties(od_of(Scur), MODE_UPD, PRPnochange);
}
}
else
cEventHdlr::sel_undo();
}
else {
// Limit undo to property setting operations
if (cur && (!strcmp(cur->cmd(), "set") ||
!strcmp(cur->cmd(), "ddprp")))
// "set" comes from !set device@param
Ulist()->UndoOperation();
else {
Ulist()->RotateUndo(0);
cEventHdlr::sel_undo();
Ulist()->RotateUndo(cur);
}
}
}
}
// Redo the last adprp or rmprp, set currently marked object to
// object redone, if not global.
//
void
PrptyState::redo()
{
if (Level == 1)
cEventHdlr::sel_redo();
else {
Oper *cur = Ulist()->RedoList();
if (cur && (!strcmp(cur->cmd(), "adprp") ||
!strcmp(cur->cmd(), "rmprp"))) {
if (cur->prp_list()) {
CDo *odesc = cur->prp_list()->odesc();
bool global = (cur->prp_list()->next_chg() != 0);
Ulist()->RedoOperation();
if (!global) {
sSel *sd;
for (sd = Shead; sd; sd = sd->next)
if (sd->pointer == odesc)
break;
if (sd) {
Scur = sd;
ED()->PopUpProperties(od_of(Scur), MODE_UPD,
PRPnochange);
}
}
}
else if (cur->obj_list()) {
Ulist()->RedoOperation();
if (Ulist()->HasUndo()) {
Ochg *xc = Ulist()->UndoList()->obj_list();
while (xc) {
for (sSel *sd = Shead; sd; sd = sd->next) {
if (xc->oadd() && xc->odel() &&
sd->pointer == xc->odel()) {
sd->pointer = xc->oadd();
break;
}
}
xc = xc->next_chg();
}
ED()->PopUpProperties(od_of(Scur), MODE_UPD, PRPnochange);
}
}
else
Ulist()->RedoOperation();
}
else {
// Limit redo to property setting operations
if (cur && (!strcmp(cur->cmd(), "set") ||
!strcmp(cur->cmd(), "ddprp")))
Ulist()->RedoOperation();
else {
Ulist()->RotateRedo(0);
cEventHdlr::sel_redo();
Ulist()->RotateRedo(cur);
}
}
}
}
// Static function.
// Asynchronous property change from text editor for physical
// mode. Since physical cell properties are ascii strings, we
// have to explicitly change the property when done editing.
//
void
PrptyState::ltcallback(hyList *h, void *arg)
{
ltobj *lt = (ltobj*)arg;
if (PrptyCmd)
PrptyCmd->prp_showselect(false);
CDs *cursdp = CurCell(Physical);
if (!cursdp)
return;
Ulist()->ListCheck("adprp", cursdp, false);
char *string;
if (h->ref_type() == HLrefLongText)
string = hyList::string(h, HYcvAscii, true);
else
string = hyList::string(h, HYcvPlain, true);
hyList::destroy(h);
if (PrptyCmd && PrptyCmd->Global) {
for (sSel *sd = PrptyCmd->Shead; sd; sd = sd->next) {
DSP()->ShowOdescPhysProperties(sd->pointer, ERASE);
prpty_replace(sd->pointer, cursdp, prpmatch(sd->pointer,
lt->pdesc, lt->value), lt->value, string);
}
Ulist()->CommitChanges(true);
for (sSel *sd = PrptyCmd->Shead; sd; sd = sd->next)
DSP()->ShowOdescPhysProperties(sd->pointer, DISPLAY);
}
else {
DSP()->ShowOdescPhysProperties(lt->odesc, ERASE);
prpty_replace(lt->odesc, cursdp, prpmatch(lt->odesc, lt->pdesc,
lt->value), lt->value, string);
Ulist()->CommitChanges(true);
DSP()->ShowOdescPhysProperties(lt->odesc, DISPLAY);
}
delete [] string;
delete lt;
if (PrptyCmd)
PrptyCmd->prp_showselect(true);
}
// Turn on/off the display of selected objects other than the currently
// marked object.
//
void
PrptyState::prp_showselect(bool show)
{
if (Global || ShowAllSel) {
if (!show)
for (sSel *s = Shead; s; s = s->next)
Selections.showUnselected(CurCell(), s->pointer);
else
for (sSel *s = Shead; s; s = s->next)
Selections.showSelected(CurCell(), s->pointer);
}
}
// Create the prompt used to solicit the property string.
// Return the existing property, if applicable.
// The prompt is returned in buf.
// The odesc argument is the source of the returned prpty desc.
// If true is returned, don't prompt but use string in buf.
//
bool
PrptyState::prp_get_prompt(bool global, CDo *odesc, char *buf)
{
const char *glmsg = "Global %s? ";
if (DSP()->CurMode() == Electrical) {
// use the existing string as default
switch (Value) {
case P_NAME:
if (global)
sprintf(buf, glmsg, "name");
else
strcpy(buf, "Name? ");
break;
case P_MODEL:
if (global)
sprintf(buf, glmsg, "model");
else
strcpy(buf, "Model name? ");
break;
case P_VALUE:
if (global)
sprintf(buf, glmsg, "value");
else
strcpy(buf, "Value? ");
break;
case P_PARAM:
if (global)
sprintf(buf, glmsg, "parameter string");
else
strcpy(buf, "Parameter string? ");
break;
case P_OTHER:
if (global)
sprintf(buf, glmsg, "string");
else
strcpy(buf, "Property string? ");
break;
case P_NOPHYS:
strcpy(buf, "nophys");
return (true);
case P_FLATTEN:
strcpy(buf, "flatten");
return (true);
case P_SYMBLC:
strcpy(buf, "0");
return (true);
case P_RANGE:
if (global)
sprintf(buf, glmsg, "range");
else
strcpy(buf, "Range? (2 unsigned integers, begin and end) ");
break;
case P_DEVREF:
if (global)
sprintf(buf, glmsg, "reference device string");
else
strcpy(buf, "Reference device String? ");
break;
default:
Value = P_MODEL;
return (prp_get_prompt(global, odesc, buf));
}
}
else {
if (global)
sprintf(buf, "Global property %d string? ", Value);
else
sprintf(buf, "Property %d string? ", Value);
}
return (false);
}
// Push new text into executing input window.
//
void
PrptyState::prp_updtext(sSel *sl)
{
char buf[256];
if (!sl || !sl->pointer)
return;
CDs *cursd = CurCell();
if (!cursd)
return;
prp_get_prompt(false, sl->pointer, buf);
CDp *pdesc = SelPrp;
if (pdesc && pdesc->value() != Value)
// shouldn't happen
Value = pdesc->value();
if (DSP()->CurMode() == Electrical) {
bool use_lt = false;
if (Value == P_VALUE || Value == P_PARAM || Value == P_OTHER)
use_lt = true;
if (pdesc) {
if (Value == P_NAME) {
// don't show default name
if (((CDp_cname*)pdesc)->assigned_name()) {
hyList *h = new hyList(0,
((CDp_cname*)pdesc)->assigned_name(), HYcvPlain);
PL()->EditHypertextPrompt(buf, h, false, PLedUpdate);
hyList::destroy(h);
}
else
PL()->EditHypertextPrompt(buf, 0, false, PLedUpdate);
}
else {
switch (Value) {
case P_MODEL:
case P_VALUE:
case P_PARAM:
case P_OTHER:
case P_DEVREF:
PL()->EditHypertextPrompt(buf, ((CDp_user*)pdesc)->data(),
use_lt, PLedUpdate);
break;
default:
// shouldn't be here
return;
}
}
}
else
PL()->EditHypertextPrompt(buf, 0, use_lt, PLedUpdate);
}
else {
bool use_lt = true;
hyList *hp = 0;
if (!pdesc && Value >= XprpType && Value < XprpEnd) {
char *s = XM()->GetPseudoProp(sl->pointer, Value);
hp = new hyList(cursd, s, HYcvPlain);
delete [] s;
use_lt = false;
}
else if (pdesc && pdesc->string() && *pdesc->string()) {
const char *lttok = HYtokPre HYtokLT HYtokSuf;
if (lstring::prefix(lttok, pdesc->string())) {
if (use_lt)
hp = new hyList(cursd, pdesc->string(), HYcvAscii);
else
hp = new hyList(cursd,
pdesc->string() + strlen(lttok), HYcvPlain);
}
else
hp = new hyList(cursd, pdesc->string(), HYcvPlain);
}
PL()->EditHypertextPrompt(buf, hp, use_lt, PLedUpdate);
hyList::destroy(hp);
}
}
namespace {
// These are the properties cycled through with the arrow keys
// when editing. In physical mode, anything in the list is fine.
//
bool is_prp_editable(const CDp *pd)
{
if (DSP()->CurMode() == Electrical) {
if (!pd)
return (false);
switch (pd->value()) {
case P_NAME:
case P_MODEL:
case P_VALUE:
case P_PARAM:
case P_OTHER:
case P_RANGE:
case P_DEVREF:
return (true);
default:
return (false);
}
}
return (true);
}
}
namespace {
// Return true is the argument is a valid string for a P_NAME
// property. The first character must be alpha, and we can't
// include any SPICE token separators.
//
bool nameprp_ok(const char *str)
{
if (!str)
return (false);
if (!isalpha(*str))
return (false);
str++;
while (*str) {
if (isspace(*str) || *str == '=' || *str == ',')
return (false);
str++;
}
return (true);
}
}
// Add: line = 0, which is always > 0, edit false
// Edit: line 0 or not, which is always -1, edit true
//
void
PrptyState::prp_add_elec(Ptxt *line, int which, bool edit)
{
if (!Shead) {
PL()->ShowPrompt(nosel);
return;
}
if (!CurCell(Electrical) || DSP()->CurMode() != Electrical)
return;
if (!line) {
switch (which) {
case P_NAME:
case P_MODEL:
case P_VALUE:
case P_PARAM:
case P_RANGE:
case P_DEVREF:
line = ED()->PropertySelect(which);
break;
default:
if (which < 0)
line = ED()->PropertyCycle(0, &is_prp_editable, false);
break;
}
}
if (line && !line->prpty())
line = 0;
Value = which;
SelPrp = 0;
if (line) {
SelPrp = line->prpty();
Value = SelPrp->value();
}
if (!SelPrp && edit) {
PL()->ShowPrompt("No editable property found - use Add.");
Value = -1;
return;
}
if (Value < 0)
return;
switch (Value) {
case P_NOPHYS:
case P_FLATTEN:
case P_SYMBLC:
if (!edit)
break;
// fallthrough
default:
PL()->ShowPrompt("This property can not be edited.");
return;
case P_NAME:
case P_MODEL:
case P_VALUE:
case P_PARAM:
case P_OTHER:
case P_RANGE:
case P_DEVREF:
case XICP_PC_PARAMS:
break;
}
if (Scur->pointer->type() != CDINSTANCE) {
PL()->ShowPrompt("Can't modify properties of current object.");
return;
}
CDc *cdesc = OCALL(Scur->pointer);
CDs *msdesc = cdesc->masterCell();
if (!msdesc) {
PL()->ShowPrompt("Internal: instance has no cell pointer!");
return;
}
if (!msdesc->isDevice()) {
switch (Value) {
case P_NAME:
case P_PARAM:
case P_OTHER:
case P_NOPHYS:
case P_FLATTEN:
case P_SYMBLC:
case P_RANGE:
break;
default:
PL()->ShowPrompt("Can't add this property type to subcircuit.");
return;
}
}
else if (Value == P_FLATTEN || Value == P_SYMBLC) {
PL()->ShowPrompt("Can't add this property type to device.");
return;
}
if (Value == P_NAME && Global && !edit) {
PL()->ShowPrompt("You don't want to set all names the same.");
return;
}
Modifying = PRPadding;
prp_showselect(false);
if (edit) {
PL()->RegisterArrowKeyCallbacks(down_callback, up_callback);
ED()->RegisterPrptyBtnCallback(btn_callback);
}
bool ret = prp_get_string(false, edit);
if (edit) {
PL()->RegisterArrowKeyCallbacks(0, 0);
ED()->RegisterPrptyBtnCallback(0);
}
if (!PrptyCmd)
return;
if (ret && Udata.hyl) {
if (Value == P_NAME) {
char *pstr = hyList::string(Udata.hyl, HYcvPlain, false);
if (!nameprp_ok(pstr)) {
delete [] pstr;
PL()->ShowPrompt(
"Bad name, must start with alpha, exclude SPICE token "
"separators space, ',' and '='.");
return;
}
delete [] pstr;
}
if (Global) {
if (edit)
prp_add_elec_glob_seq();
else
prp_add_elec_glob_all();
}
else
prp_add_elec_noglob();
}
if (PrptyCmd) {
if (Scur)
prp_showselect(true);
SelPrp = 0;
Value = -1;
Modifying = PRPquiescent;
}
}
void
PrptyState::prp_add_elec_noglob()
{
CDs *cursde = CurCell(Electrical);
if (!cursde)
return;
Ulist()->ListCheck("adprp", cursde, false);
CDc *cdesc = OCALL(Scur->pointer);
CDp *pdesc = SelPrp;
if (!pdesc && Value != P_OTHER)
pdesc = cdesc->prpty(Value);
ED()->prptyModify(cdesc, pdesc, Value, 0, Udata.hyl);
Ulist()->CommitChanges(true);
// Might have exited during modify.
if (PrptyCmd) {
hyList::destroy(Udata.hyl);
Udata.hyl = 0;
}
}
void
PrptyState::prp_add_elec_glob_all()
{
CDs *cursde = CurCell(Electrical);
if (!cursde)
return;
Ulist()->ListCheck("adprp", cursde, false);
bool changemade = false;
for (sSel *sd = Shead; sd; sd = sd->next) {
if (sd->pointer->type() != CDINSTANCE)
continue;
CDc *cdesc = OCALL(sd->pointer);
CDs *msdesc = cdesc->masterCell();
if (!msdesc)
continue;
if (!msdesc->isDevice() && Value != P_NAME && Value != P_PARAM &&
Value != P_RANGE && Value != P_FLATTEN)
continue;
ED()->prptyModify(cdesc, prpmatch(sd->pointer, 0, Value), Value, 0,
Udata.hyl);
changemade = true;
// Might have exited during modify.
if (!PrptyCmd)
break;
}
if (changemade)
Ulist()->CommitChanges(true);
if (PrptyCmd) {
hyList::destroy(Udata.hyl);
Udata.hyl = 0;
}
}
void
PrptyState::prp_add_elec_glob_seq()
{
CDs *cursde = CurCell(Electrical);
if (!cursde)
return;
// rotate the list so that Scur is head
if (Scur != Shead) {
sSel *s = Scur;
while (s->next)
s = s->next;
s->next = Shead;
Shead->prev = s;
while (s->next != Scur)
s = s->next;
s->next = 0;
Shead = Scur;
Shead->prev = 0;
}
bool changemade = false;
bool first = true;
for (sSel *sd = Shead; sd; sd = sd->next) {
bool ret = true;
CDc *cdesc = OCALL(sd->pointer);
if (!first) {
if (sd->pointer->type() != CDINSTANCE)
continue;
CDs *msdesc = cdesc->masterCell();
if (!msdesc)
continue;
if (!msdesc->isDevice() && Value != P_NAME && Value != P_PARAM &&
Value != P_RANGE && Value != P_FLATTEN)
continue;
Scur = sd;
ED()->PopUpProperties(od_of(Scur), MODE_UPD, PRPnochange);
ret = prp_get_string(false, false);
if (!PrptyCmd)
return;
}
if (!ret || !Udata.hyl)
break;
if (first) {
Ulist()->ListCheck("adprp", cursde, false);
first = false;
}
ED()->prptyModify(cdesc, prpmatch(cdesc, SelPrp, Value), Value, 0,
Udata.hyl);
changemade = true;
// Might have exited during modify.
if (PrptyCmd) {
hyList::destroy(Udata.hyl);
Udata.hyl = 0;
}
else
break;
}
if (changemade)
Ulist()->CommitChanges(true);
if (PrptyCmd)
Scur = Shead;
}
// Add: line = 0, which is always -1, edit false
// Edit: line 0 or not, which is always -1, edit true
//
void
PrptyState::prp_add_phys(Ptxt *line, int which, bool edit)
{
if (!Shead) {
PL()->ShowPrompt(nosel);
return;
}
if (!CurCell(Physical) || DSP()->CurMode() != Physical)
return;
if (!line && edit)
line = ED()->PropertyCycle(0, &is_prp_editable, false);
bool phony_add = false;
if (line && !line->prpty()) {
// If pseudo-property in edit mode, treat as Add...
const char *s = strchr(line->head(), '(');
if (s) {
s++;
Value = atoi(s);
if (prpty_pseudo(Value)) {
SelPrp = 0;
edit = false;
phony_add = true;
}
}
// shouldn't get here
if (!phony_add) {
PL()->ShowPrompt("Property not editable.");
Value = -1;
return;
}
}
if (!phony_add) {
SelPrp = 0;
Value = which;
if (line) {
SelPrp = line->prpty();
Value = SelPrp->value();
}
if (Value == XICP_PC || prpty_reserved(Value) ||
(edit && prpty_pseudo(Value))) {
PL()->ShowPrompt("This property can not be edited.");
SelPrp = 0;
Value = -1;
return;
}
if (!SelPrp && edit) {
PL()->ShowPrompt(
"No editable property selected - select first or use Add.");
Value = -1;
return;
}
}
Modifying = PRPadding;
prp_showselect(false);
bool ret = true;
if (Value < 0) {
ret = prp_get_add_type(false);
if (!PrptyCmd)
return;
}
if (Value == XICP_PC || prpty_reserved(Value)) {
PL()->ShowPrompt("This property can't be set by user.");
SelPrp = 0;
Value = -1;
return;
}
if (ret && Scur && Value >= 0) {
if (Value == XICP_NOMERGE) {
if (edit) {
PL()->ShowPrompt("Property not editable.");
return;
}
delete [] Udata.string;
Udata.string = lstring::copy("nomerge");
if (Global)
prp_add_phys_glob_all();
else
prp_add_phys_noglob();
}
else if (Value == XICP_EXT_FLATTEN) {
if (edit) {
PL()->ShowPrompt("Property not editable.");
return;
}
delete [] Udata.string;
Udata.string = lstring::copy("flatten");
if (Global)
prp_add_phys_glob_all();
else
prp_add_phys_noglob();
}
else {
if (edit) {
PL()->RegisterArrowKeyCallbacks(down_callback, up_callback);
ED()->RegisterPrptyBtnCallback(btn_callback);
}
ret = prp_get_string(false, edit);
if (edit) {
PL()->RegisterArrowKeyCallbacks(0, 0);
ED()->RegisterPrptyBtnCallback(0);
}
if (!PrptyCmd)
return;
if (!ret || !Udata.string) {
delete [] Udata.string;
Udata.string = 0;
}
else {
if (Global) {
if (edit)
prp_add_phys_glob_seq();
else
prp_add_phys_glob_all();
}
else
prp_add_phys_noglob();
}
}
}
if (PrptyCmd) {
if (Scur)
prp_showselect(true);
SelPrp = 0;
Value = -1;
Modifying = PRPquiescent;
}
}
void
PrptyState::prp_add_phys_noglob()
{
CDs *cursdp = CurCell(Physical);
if (!cursdp)
return;
Ulist()->ListCheck("adprp", cursdp, false);
DSP()->ShowOdescPhysProperties(Scur->pointer, ERASE);
prpty_replace(Scur->pointer, cursdp, SelPrp, Value, Udata.string);
// Explicit redraw needed for pseudo-properties.
// Might have exited during modify.
Ulist()->CommitChanges(true);
if (PrptyCmd) {
delete [] Udata.string;
Udata.string = 0;
if (Scur)
DSP()->ShowOdescPhysProperties(Scur->pointer, DISPLAY);
}
}
void
PrptyState::prp_add_phys_glob_all()
{
CDs *cursdp = CurCell(Physical);
if (!cursdp)
return;
Ulist()->ListCheck("adprp", cursdp, false);
sSel *sn;
for (sSel *sd = Shead; sd; sd = sn) {
sn = sd->next;
prpty_replace(sd->pointer, cursdp, 0, Value, Udata.string);
// Might have exited during modify.
if (!PrptyCmd)
break;
}
if (PrptyCmd) {
delete [] Udata.string;
Udata.string = 0;
for (sSel *sd = Shead; sd; sd = sd->next)
DSP()->ShowOdescPhysProperties(sd->pointer, ERASE);
}
// Explicit redraw needed for pseudo-properties
Ulist()->CommitChanges(true);
if (PrptyCmd) {
for (sSel *sd = Shead; sd; sd = sd->next)
DSP()->ShowOdescPhysProperties(sd->pointer, DISPLAY);
}
}
void
PrptyState::prp_add_phys_glob_seq()
{
CDs *cursdp = CurCell(Physical);
if (!cursdp)
return;
// rotate the list so that Scur is head
if (Scur != Shead) {
sSel *s = Scur;
while (s->next)
s = s->next;
s->next = Shead;
Shead->prev = s;
while (s->next != Scur)
s = s->next;
s->next = 0;
Shead = Scur;
Shead->prev = 0;
}
bool changemade = false;
bool first = true;
sSel *sn;
for (sSel *sd = Shead; sd; sd = sn) {
sn = sd->next;
bool ret = true;
if (!first) {
Scur = sd;
ED()->PopUpProperties(od_of(Scur), MODE_UPD, PRPnochange);
ret = prp_get_string(false, false);
if (!PrptyCmd)
return;
}
if (!ret || !Udata.string)
break;
if (first) {
Ulist()->ListCheck("adprp", cursdp, false);
first = false;
}
prpty_replace(sd->pointer, cursdp,
prpmatch(sd->pointer, SelPrp, Value), Value, Udata.string);
changemade = true;
// Might have exited during modify.
if (PrptyCmd) {
delete [] Udata.string;
Udata.string = 0;
}
else
break;
}
if (PrptyCmd)
Scur = Shead;
if (changemade) {
if (PrptyCmd) {
for (sSel *sd = Shead; sd; sd = sd->next)
DSP()->ShowOdescPhysProperties(sd->pointer, ERASE);
}
// Explicit redraw needed for pseudo-properties
Ulist()->CommitChanges(true);
if (PrptyCmd) {
for (sSel *sd = Shead; sd; sd = sd->next)
DSP()->ShowOdescPhysProperties(sd->pointer, DISPLAY);
}
}
}
// Solicit from the user the type or value of a property being added.
// Return false if Esc entered, true otherwise. The value is put into
// Value, which is -1 if no value was recognized.
//
bool
PrptyState::prp_get_add_type(bool global)
{
const char *msg = global ?
"Press Enter, or give property number to add to selected objects? " :
"Property number? ";
char tbuf[64];
*tbuf = '\0';
if (!global && Value >= 0)
sprintf(tbuf, "%d", Value);
Value = -1;
char *in = PL()->EditPrompt(msg, (global || !*tbuf) ? 0 : tbuf);
for (;;) {
PL()->ErasePrompt();
if (!in)
return (false);
int d;
if (sscanf(in, "%d", &d) == 1 && d >= 0) {
if (prpty_reserved(d))
msg = "Given value is for internal use only, try again: ";
else {
Value = d;
break;
}
}
else
msg = "Bad input, try again: ";
Value = -1;
in = PL()->EditPrompt(msg, (global || !*tbuf) ? 0 : tbuf);
}
return (true);
}
// Query the user for the property string to be used in added properties.
// Return false if Esc entered, true otherwise.
// It is assumed here that a null string is a valid return.
//
bool
PrptyState::prp_get_string(bool global, bool allow_switch)
{
CDs *cursd = CurCell();
if (!cursd)
return (false);
if (Value == XICP_PC_PARAMS && Scur->pointer->type() == CDINSTANCE) {
char *pstr;
bool ret = ED()->reparameterize((CDc*)Scur->pointer, &pstr);
if (ret)
Udata.string = pstr;
else {
Log()->ErrorLogV(mh::PCells,
"Error, reparameterize failed:\n%s", Errs()->get_error());
}
return (ret);
}
char buf[256], tbuf[256];
bool immut = prp_get_prompt(global, Scur->pointer, tbuf);
Udata.string = 0;
Udata.hyl = 0;
if (allow_switch && !immut) {
sprintf(buf, "(Up/down arrows to select) %s", tbuf);
strcpy(tbuf, buf);
}
if (DSP()->CurMode() == Electrical) {
hyList *hnew;
if (immut) {
if (Value == P_NOPHYS) {
char *in = PL()->EditPrompt("Device shorted in LVS? ", "n");
in = lstring::strip_space(in);
if (!in) {
PL()->ErasePrompt();
return (false);
}
if (in && (*in == 'y' || *in == 'Y'))
strcpy(tbuf, "shorted");
}
hnew = new hyList(cursd, tbuf, HYcvPlain);
}
else if (Value == P_NAME) {
if (SelPrp && ((CDp_cname*)SelPrp)->assigned_name()) {
hyList *h = new hyList(0, ((CDp_cname*)SelPrp)->assigned_name(),
HYcvPlain);
hnew = PL()->EditHypertextPrompt(tbuf, h, false);
hyList::destroy(h);
}
else
hnew = PL()->EditHypertextPrompt(tbuf, 0, false);
}
else {
bool use_lt = false;
if (Value == P_VALUE || Value == P_PARAM || Value == P_OTHER)
use_lt = true;
if (SelPrp) {
switch (Value) {
case P_MODEL:
case P_VALUE:
case P_PARAM:
case P_OTHER:
case P_DEVREF:
hnew = PL()->EditHypertextPrompt(tbuf,
((CDp_user*)SelPrp)->data(), use_lt);
break;
default:
// shouldn't be here
hnew = PL()->EditHypertextPrompt(tbuf, 0, use_lt);
break;
}
}
else
hnew = PL()->EditHypertextPrompt(tbuf, 0, use_lt);
}
PL()->ErasePrompt();
if (!hnew)
return (false);
hnew->trim_white_space();
if (hnew->ref_type() == HLrefText && !hnew->text()[0]) {
hyList::destroy(hnew);
hnew = 0;
}
Udata.hyl = hnew;
}
else {
if (immut) {
Udata.string = lstring::copy(tbuf);
return (true);
}
bool use_lt = true;
hyList *hp = 0;
if (!SelPrp && (Value >= XprpType && Value < XprpEnd)) {
char *s = XM()->GetPseudoProp(Scur->pointer, Value);
hp = new hyList(cursd, s, HYcvPlain);
delete [] s;
use_lt = false;
}
else if (SelPrp && SelPrp->string() && *SelPrp->string()) {
const char *lttok = HYtokPre HYtokLT HYtokSuf;
if (lstring::prefix(lttok, SelPrp->string())) {
if (use_lt)
hp = new hyList(cursd, SelPrp->string(), HYcvAscii);
else
hp = new hyList(cursd,
SelPrp->string() + strlen(lttok), HYcvPlain);
}
else
hp = new hyList(cursd, SelPrp->string(), HYcvPlain);
}
ltobj *lt = new ltobj(cursd, Scur->pointer, SelPrp, Value);
hyList *hnew = PL()->EditHypertextPrompt(tbuf, hp, use_lt,
PLedStart, PLedNormal, ltcallback, lt);
hyList::destroy(hp);
PL()->ErasePrompt();
if (!hnew) {
delete lt;
return (false);
}
if (hnew->ref_type() == HLrefLongText)
// text editor popped, calls ltcallback when done
return (true);
delete lt;
if (hnew->ref_type() == HLrefText && !hnew->text()[0]) {
hyList::destroy(hnew);
hnew = 0;
}
if (hnew) {
Udata.string = hyList::string(hnew, HYcvPlain, true);
hyList::destroy(hnew);
}
}
return (true);
}
void
PrptyState::prp_rm(Ptxt *line)
{
if (!Shead) {
PL()->ShowPrompt(nosel);
return;
}
if (!line)
return;
CDs *cursd = CurCell();
if (!cursd)
return;
SelPrp = line->prpty();
if (DSP()->CurMode() == Electrical) {
if (SelPrp) {
switch (SelPrp->value()) {
case P_NAME:
case P_MODEL:
case P_VALUE:
case P_PARAM:
case P_OTHER:
case P_NOPHYS:
case P_FLATTEN:
case P_SYMBLC:
case P_RANGE:
case P_DEVREF:
break;
default:
SelPrp = 0;
break;
}
}
}
if (!SelPrp) {
PL()->ShowPrompt("This property can not be deleted.");
return;
}
Modifying = PRPdeleting;
prp_showselect(false);
bool ret = true;
if (SelPrp) {
Value = SelPrp->value();
Vmask = maskof(Value);
}
else {
Value = -1;
Vmask = 0;
ret = prp_get_rm_type(Global);
if (!PrptyCmd)
return;
}
if (ret && Scur) {
if (Global) {
Ulist()->ListCheck("rmprp", cursd, false);
for (sSel *sd = Shead; sd; sd = sd->next) {
if (DSP()->CurMode() == Electrical &&
sd->pointer->type() != CDINSTANCE)
continue;
prp_remove(sd, SelPrp);
}
Ulist()->CommitChanges(true);
}
else {
if (DSP()->CurMode() == Electrical &&
Scur->pointer->type() != CDINSTANCE)
PL()->ShowPrompt("Can't delete properties of this object.");
else {
Ulist()->ListCheck("rmprp", cursd, false);
prp_remove(Scur, SelPrp);
Ulist()->CommitChanges(true);
}
}
}
if (PrptyCmd) {
if (Scur)
prp_showselect(true);
Value = -1;
Vmask = 0;
SelPrp = 0;
Modifying = PRPquiescent;
}
}
// Solicit the type(s) or number of a property to be removed.
// Return false if Esc entered, true otherwise.
//
bool
PrptyState::prp_get_rm_type(bool global)
{
if (DSP()->CurMode() == Electrical) {
const char *glmsg = global ?
"Property types (nmvpoys) to remove from all selected devices? " :
"Property types (nmvpoys) to be removed? ";
Vmask = 0;
for (;;) {
char *in = PL()->EditPrompt(glmsg, 0);
PL()->ErasePrompt();
if (!in)
return (false);
for (char *s = in; *s; s++) {
switch (*s) {
case 'n':
case 'N':
Vmask |= NAME_MASK;
break;
case 'm':
case 'M':
Vmask |= MODEL_MASK;
break;
case 'v':
case 'V':
Vmask |= VALUE_MASK;
break;
case 'i':
case 'I':
case 'p':
case 'P':
Vmask |= PARAM_MASK;
break;
case 'o':
case 'O':
Vmask |= OTHER_MASK;
break;
case 'y':
case 'Y':
Vmask |= NOPHYS_MASK;
break;
case 'f':
case 'F':
Vmask |= FLATTEN_MASK;
break;
case 's':
case 'S':
Vmask |= NOSYMB_MASK;
break;
case 'r':
case 'R':
Vmask |= RANGE_MASK;
break;
case 'd':
case 'D':
Vmask |= DEVREF_MASK;
break;
}
}
if (Vmask)
break;
glmsg =
"Bad input, try again. You must give one or more of n,m,v,p,o. ";
}
}
else {
const char *msg2 = global ?
"Property number to remove from all selected ojbects? " :
"Property number to be removed? ";
for (;;) {
char *in = PL()->EditPrompt(msg2, 0);
PL()->ErasePrompt();
if (!in)
return (false);
int d;
if (sscanf(in, "%d", &d) == 1 && d >= 0) {
if (prpty_reserved(d))
msg2 = "Given value is for internal use only, try again: ";
else {
Value = d;
break;
}
}
else
msg2 = "Bad input, try again: ";
}
}
return (true);
}
// Remove properties from the object in sd. The values to remove
// are in Value or Vmask. Remove all of the properties of the given
// type. If pdesc is given, remove properties that "match" pdesc.
//
void
PrptyState::prp_remove(sSel *sd, CDp *pdesc)
{
CDs *cursd = CurCell();
if (!cursd)
return;
if (DSP()->CurMode() == Electrical) {
if (sd->pointer->type() != CDINSTANCE)
return;
if (pdesc) {
pdesc = prpmatch(sd->pointer, pdesc, pdesc->value());
if (!pdesc)
return;
if (pdesc->value() == P_NAME) {
Udata.hyl = 0;
// replace the property with default
ED()->prptyModify(OCALL(sd->pointer), pdesc, P_NAME, 0, 0);
}
else {
Ulist()->RecordPrptyChange(cursd, sd->pointer, pdesc, 0);
CDla *olabel = pdesc->bound();
if (olabel) {
Ulist()->RecordObjectChange(cursd, olabel, 0);
DSP()->RedisplayArea(&olabel->oBB());
}
}
return;
}
for (int i = 0; ; i++) {
int value;
if (i == 0) {
if (!(Vmask & MODEL_MASK))
continue;
value = P_MODEL;
}
else if (i == 1) {
if (!(Vmask & VALUE_MASK))
continue;
value = P_VALUE;
}
else if (i == 2) {
if (!(Vmask & PARAM_MASK))
continue;
value = P_PARAM;
}
else if (i == 3) {
if (!(Vmask & OTHER_MASK))
continue;
value = P_OTHER;
}
else if (i == 4) {
if (!(Vmask & NOPHYS_MASK))
continue;
value = P_NOPHYS;
}
else if (i == 5) {
if (!(Vmask & FLATTEN_MASK))
continue;
value = P_FLATTEN;
}
else if (i == 6) {
if (!(Vmask & NOSYMB_MASK))
continue;
value = P_SYMBLC;
}
else if (i == 7) {
if (!(Vmask & RANGE_MASK))
continue;
value = P_RANGE;
}
else if (i == 8) {
if (!(Vmask & NAME_MASK))
continue;
value = P_NAME;
}
else if (i == 9) {
if (!(Vmask & DEVREF_MASK))
continue;
value = P_DEVREF;
}
else
break;
while ((pdesc = sd->pointer->prpty(value)) != 0) {
if (value == P_NAME) {
Udata.hyl = 0;
// replace the property with default
ED()->prptyModify(OCALL(sd->pointer), pdesc, P_NAME,
0, 0);
}
else {
Ulist()->RecordPrptyChange(cursd, sd->pointer, pdesc, 0);
CDla *olabel = pdesc->bound();
if (olabel) {
Ulist()->RecordObjectChange(cursd, olabel, 0);
DSP()->RedisplayArea(&olabel->oBB());
}
}
}
}
}
else {
if (pdesc) {
// Remove at most one matching property
pdesc = prpmatch(sd->pointer, pdesc, pdesc->value());
if (pdesc) {
DSP()->ShowOdescPhysProperties(sd->pointer, ERASE);
Ulist()->RecordPrptyChange(cursd, sd->pointer, pdesc, 0);
DSP()->ShowOdescPhysProperties(sd->pointer, DISPLAY);
}
}
else {
// Remove all properties of value Value
DSP()->ShowOdescPhysProperties(sd->pointer, ERASE);
while ((pdesc = sd->pointer->prpty(Value)) != 0)
Ulist()->RecordPrptyChange(cursd, sd->pointer, pdesc, 0);
DSP()->ShowOdescPhysProperties(sd->pointer, DISPLAY);
}
}
}
// Static function.
// Called from the Properties panel, sets the current editing
// property to the one just clicked on.
//
int
PrptyState::btn_callback(Ptxt *pt)
{
if (!pt->prpty())
return (false);
PrptyCmd->SelPrp = pt->prpty();
PrptyCmd->Value = PrptyCmd->SelPrp->value();
PrptyCmd->prp_updtext(PrptyCmd->Scur);
return (true);
}
// Static function.
// Called from the hypertext editor, advances prompt to next
// property.
//
void
PrptyState::down_callback()
{
if (!PrptyCmd || !PrptyCmd->Scur || !PrptyCmd->Scur->pointer->prpty_list())
return;
Ptxt *pt = ED()->PropertyCycle(PrptyCmd->SelPrp, &is_prp_editable, false);
if (!pt)
return;
PrptyCmd->SelPrp = pt->prpty();
PrptyCmd->Value = PrptyCmd->SelPrp->value();
PrptyCmd->prp_updtext(PrptyCmd->Scur);
}
// Static function.
// Called from the hypertext editor, advances prompt to previous
// property.
//
void
PrptyState::up_callback()
{
if (!PrptyCmd || !PrptyCmd->Scur || !PrptyCmd->Scur->pointer->prpty_list())
return;
Ptxt *pt = ED()->PropertyCycle(PrptyCmd->SelPrp, &is_prp_editable, true);
if (!pt)
return;
PrptyCmd->SelPrp = pt->prpty();
PrptyCmd->Value = PrptyCmd->SelPrp->value();
PrptyCmd->prp_updtext(PrptyCmd->Scur);
}
// End of PrptyState functions.
namespace {
// Return a property from odesc that "matches" pdesc, or val if
// pdesc is nil.
//
CDp *
prpmatch(CDo *odesc, CDp *pdesc, int val)
{
if (!odesc)
return (0);
if (DSP()->CurMode() == Electrical) {
if (!pdesc) {
if (val >= 0 && val != P_OTHER)
return (odesc->prpty(val));
}
else {
if (pdesc->value() != P_OTHER)
return (odesc->prpty(pdesc->value()));
// Return a P_OTHER property with matching text
char *s1 = hyList::string(((CDp_user*)pdesc)->data(), HYcvPlain,
false);
for (CDp *pd = odesc->prpty_list(); pd; pd = pd->next_prp()) {
if (pd->value() == P_OTHER) {
char *s2 = hyList::string(((CDp_user*)pd)->data(),
HYcvPlain, false);
int j = strcmp(s1, s2);
delete [] s2;
if (!j) {
delete [] s1;
return (pd);
}
}
}
delete [] s1;
}
}
else if (pdesc && pdesc->string()) {
for (CDp *pd = odesc->prpty_list(); pd; pd = pd->next_prp()) {
if (pd->value() == pdesc->value() && pd->string() &&
!strcmp(pdesc->string(), pd->string()))
return (pd);
}
}
return (0);
}
int
maskof(int prpty)
{
if (DSP()->CurMode() == Physical)
return(0);
switch(prpty) {
case P_NAME:
return (NAME_MASK);
case P_MODEL:
return (MODEL_MASK);
case P_VALUE:
return (VALUE_MASK);
case P_PARAM:
return (PARAM_MASK);
case P_OTHER:
return (OTHER_MASK);
case P_NOPHYS:
return (NOPHYS_MASK);
case P_FLATTEN:
return (FLATTEN_MASK);
case P_SYMBLC:
return (NOSYMB_MASK);
case P_RANGE:
return (RANGE_MASK);
case P_DEVREF:
return (DEVREF_MASK);
default:
return (0);
}
}
}
//----------------------------------------------------------------------
// The props command - show physical properties on-screen, and allow
// editing
//----------------------------------------------------------------------
namespace {
// We don't show internal properties.
//
inline bool is_showable(CDp *pdesc)
{
if (prpty_internal(pdesc->value()))
return (false);
return (true);
}
struct sPrpPointer
{
sPrpPointer() { ctrl_d_entered = false; }
~sPrpPointer() { ctrl_d_entered = false; }
static void ctrl_d_cb();
bool point_at_prpty(WindowDesc*, int, int, CDo**, CDp**);
bool is_ctrl_d() { return (ctrl_d_entered); }
private:
void find_loc(CDo*, int*, int*, int);
static bool ctrl_d_entered;
};
}
bool sPrpPointer::ctrl_d_entered = false;
// If x,y fall on a physical property text area, allow editing of the
// property. Return true if the editor was entered.
//
bool
cEdit::editPhysPrpty()
{
WindowDesc *wdesc = EV()->CurrentWin();
if (!wdesc || wdesc->Mode() != Physical ||
!wdesc->Attrib()->show_phys_props())
return (false);
if (DSP()->CurMode() != Physical)
return (false);
CDs *cursd = CurCell();
if (!cursd)
return (false);
int x, y;
EV()->Cursor().get_raw(&x, &y);
CDo *odesc = 0;
CDp *pdesc = 0;
sPrpPointer PP;
if (PP.point_at_prpty(wdesc, x, y, &odesc, &pdesc)) {
char tbuf[64];
sprintf(tbuf, "%d", pdesc->value());
PL()->RegisterCtrlDCallback(PP.ctrl_d_cb);
char *in = PL()->EditPrompt("Edit number: ", tbuf);
PL()->RegisterCtrlDCallback(0);
if (in) {
int val;
if (sscanf(in, "%d", &val) < 1)
val = pdesc->value();
const char *lttok = HYtokPre HYtokLT HYtokSuf;
hyList *hp;
if (pdesc->string() && lstring::prefix(lttok, pdesc->string()))
hp = new hyList(cursd, pdesc->string(), HYcvAscii);
else
hp = new hyList(cursd, pdesc->string(), HYcvPlain);
ltobj *lt = new ltobj(cursd, odesc, pdesc, val);
PL()->RegisterCtrlDCallback(PP.ctrl_d_cb);
hyList *hnew = PL()->EditHypertextPrompt("Edit string: ", hp,
true, PLedStart, PLedNormal, PrptyState::ltcallback, lt);
PL()->RegisterCtrlDCallback(0);
hyList::destroy(hp);
if (!hnew) {
PL()->ErasePrompt();
return (true);
}
if (hnew->ref_type() == HLrefLongText) {
// text editor popped, calls ltcallback when done
PL()->ErasePrompt();
return (true);
}
if (hnew->ref_type() == HLrefText && !hnew->text()[0]) {
hyList::destroy(hnew);
hnew = 0;
}
if (hnew) {
char *string = hyList::string(hnew, HYcvPlain, true);
hyList::destroy(hnew);
DSP()->ShowOdescPhysProperties(odesc, ERASE);
Ulist()->ListCheck("editpp", cursd, false);
CDp *op = pdesc;
pdesc = new CDp(string, val);
delete [] string;
Ulist()->RecordPrptyChange(cursd, odesc, op, pdesc);
Ulist()->CommitChanges();
DSP()->ShowOdescPhysProperties(odesc, DISPLAY);
PL()->ErasePrompt();
return (true);
}
}
if (PP.is_ctrl_d()) {
DSP()->ShowOdescPhysProperties(odesc, ERASE);
Ulist()->ListCheck("delpp", cursd, false);
Ulist()->RecordPrptyChange(cursd, odesc, pdesc, 0);
Ulist()->CommitChanges();
DSP()->ShowOdescPhysProperties(odesc, DISPLAY);
}
PL()->ErasePrompt();
return (true);
}
return (false);
}
namespace {
void
sPrpPointer::ctrl_d_cb()
{
ctrl_d_entered = true;
}
// If x,y fall on a physical property text area, return true and set the
// pointer args to the object and the property.
//
bool
sPrpPointer::point_at_prpty(WindowDesc *wdesc, int xp, int yp, CDo **oret,
CDp **pret)
{
CDs *cursdp = CurCell(Physical);
if (!cursdp)
return (false);
int delta = wdesc->LogScale(DSP()->PhysPropSize());
BBox BB;
BB.left = xp - delta;
BB.right = xp + delta;
BB.bottom = yp - delta;
BB.top = yp + delta;
CDg gdesc;
gdesc.init_gen(cursdp, CellLayer(), &BB);
CDo *pointer;
while ((pointer = gdesc.next()) != 0) {
if (!pointer->is_normal())
continue;
CDp *pdesc = pointer->prpty_list();
if (!pdesc)
continue;
bool locfound = false;
int x = 0, y = 0;
for ( ; pdesc; pdesc = pdesc->next_prp()) {
if (is_showable(pdesc)) {
if (!locfound) {
find_loc(pointer, &x, &y, delta);
locfound = true;
}
int w, h, nl;
{
char buf[32];
sprintf(buf, "%d ", pdesc->value());
sLstr lstr;
lstr.add(buf);
lstr.add(pdesc->string());
nl = DSP()->DefaultLabelSize(lstr.string(),
Physical, &w, &h);
}
w = (w*delta*nl)/h;
h = delta*nl;
y -= h - delta;
if (xp >= x && xp <= x+w && yp >= y-delta && yp <= y) {
*oret = pointer;
*pret = pdesc;
return (true);
}
y -= delta;
}
}
}
CDsLgen lgen(cursdp);
CDl *ld;
while ((ld = lgen.next()) != 0) {
gdesc.init_gen(cursdp, ld, &BB);
while ((pointer = gdesc.next()) != 0) {
if (!pointer->is_normal())
continue;
CDp *pdesc = pointer->prpty_list();
if (!pdesc)
continue;
bool locfound = false;
int x = 0, y = 0;
for ( ; pdesc; pdesc = pdesc->next_prp()) {
if (is_showable(pdesc)) {
if (!locfound) {
find_loc(pointer, &x, &y, delta);
locfound = true;
}
int w, h, nl;
{
char buf[32];
sprintf(buf, "%d ", pdesc->value());
sLstr lstr;
lstr.add(buf);
lstr.add(pdesc->string());
nl = DSP()->DefaultLabelSize(lstr.string(),
Physical, &w, &h);
}
w = (w*delta*nl)/h;
h = delta*nl;
y -= h - delta;
if (xp >= x && xp <= x+w && yp >= y && yp <= y+h) {
*oret = pointer;
*pret = pdesc;
return (true);
}
y -= delta;
}
}
}
}
return (false);
}
// Return screen coordinates for physical properties of odesc.
// Arg delta is approx. text height.
//
void
sPrpPointer::find_loc(CDo *odesc, int *x, int *y, int delta)
{
if (odesc->type() == CDWIRE) {
// leftmost end
const Point *pts = OWIRE(odesc)->points();
int num = OWIRE(odesc)->numpts();
int wid = OWIRE(odesc)->wire_width()/2;
if (pts[0].x < pts[num-1].x || (pts[0].x == pts[num-1].x &&
pts[0].y > pts[num-1].y)) {
*x = pts[0].x - wid;
*y = pts[0].y + wid - delta;
}
else {
*x = pts[num-1].x - wid;
*y = pts[num-1].y + wid - delta;
}
}
else if (odesc->type() == CDPOLYGON) {
// leftmost vertex with largest y
const Point *pts = OPOLY(odesc)->points();
int num = OPOLY(odesc)->numpts();
int minx = CDinfinity;
int maxy = -CDinfinity;
int iref = 0;
for (int i = 0; i < num; i++) {
if (pts[i].x < minx || (pts[i].x == minx && pts[i].y > maxy)) {
minx = pts[i].x;
maxy = pts[i].y;
iref = i;
}
}
*x = pts[iref].x;
*y = pts[iref].y - delta;
}
else {
// upper left corner
*x = odesc->oBB().left;
*y = odesc->oBB().top - delta;
}
}
// End of sPrpPointer functions.
}
//----------------------------------------------------------------------
// Pseudo-property processing - modify objects according to text.
//----------------------------------------------------------------------
namespace {
Point *scalepts(const BBox*, const BBox*, const Point*, int);
Point *getpts(const char*, int*);
}
// Set attributes for pseudo-prooperty value. If the object is a
// copy, it is modified directly. Otherwise the database object is
// replaced. We don't do merging here, since 1) the new box probably
// has to be moved, such as for XprpMagn, and 2) this confuses the
// Properties Editor.
//
bool
cEdit::acceptPseudoProp(CDo *odesc, CDs *sdesc, int val, const char *string)
{
if (!odesc || !sdesc)
return (false);
if (!string) {
Errs()->add_error("null string encountered");
return (false);
}
if (val == XprpFlags) {
char *tok;
unsigned flags = 0;
while ((tok = lstring::gettok(&string)) != 0) {
if (isdigit(*tok)) {
for (char *t = tok; *t; t++) {
if (!isdigit(*t))
break;
int n = *t - '0';
if (n >= DSP_NUMWINS)
break;
flags |= CDexpand << n;
}
}
else {
for (FlagDef *f = OdescFlags; f->name; f++) {
if (lstring::cieq(tok, f->name))
flags |= f->value;
}
}
delete [] tok;
}
odesc->set_flags(flags);
return (true);
}
if (val == XprpState) {
if (lstring::cieq(string, "normal"))
odesc->set_state(CDobjVanilla);
else if (lstring::cieq(string, "selected"))
odesc->set_state(CDobjSelected);
else if (lstring::cieq(string, "deleted"))
odesc->set_state(CDobjDeleted);
else if (lstring::cieq(string, "incomplete"))
odesc->set_state(CDobjIncomplete);
else if (lstring::cieq(string, "internal"))
odesc->set_state(CDobjInternal);
else {
Errs()->add_error("error, unknown state keyword");
return (false);
}
return (true);
}
if (val == XprpGroup) {
int d;
if (sscanf(string, "%d", &d) != 1) {
Errs()->add_error("syntax error, expecting integer");
return (false);
}
odesc->set_group(d);
return (true);
}
#ifdef HAVE_COMPUTED_GOTO
COMPUTED_JUMP(odesc)
#else
CONDITIONAL_JUMP(odesc)
#endif
box:
return (acceptBoxPseudoProp(odesc, sdesc, val, string));
poly:
return (acceptPolyPseudoProp((CDpo*)odesc, sdesc, val, string));
wire:
return (acceptWirePseudoProp((CDw*)odesc, sdesc, val, string));
label:
return (acceptLabelPseudoProp((CDla*)odesc, sdesc, val, string));
inst:
return (acceptInstPseudoProp((CDc*)odesc, sdesc, val, string));
}
// Handle pseudo-properties applied to boxes.
//
bool
cEdit::acceptBoxPseudoProp(CDo *odesc, CDs *sdesc, int val,
const char *string)
{
// For boxes, accept all (physical or electrical, copy or not).
if (val == XprpBB) {
BBox BB;
if (sscanf(string, "%d,%d %d,%d", &BB.left, &BB.bottom,
&BB.right, &BB.top) != 4) {
Errs()->add_error(
"syntax error, expecting l,b r,t coordinates");
return (false);
}
BB.fix();
if (odesc->is_copy())
odesc->set_oBB(BB);
else {
CDo *newo = sdesc->newBox(odesc, &BB, odesc->ldesc(),
odesc->prpty_list());
if (!newo) {
Errs()->add_error("newBox failed");
return (false);
}
}
return (true);
}
if (val == XprpLayer) {
CDl *ld = CDldb()->findLayer(string, sdesc->displayMode());
if (!ld) {
Errs()->add_error("layer %s not found", string);
return (false);
}
if (odesc->is_copy())
odesc->set_ldesc(ld);
else {
CDo *newo = sdesc->newBox(odesc, &odesc->oBB(), ld,
odesc->prpty_list());
if (!newo) {
Errs()->add_error("newBox failed");
return (false);
}
}
return (true);
}
if (val == XprpCoords) {
Poly poly;
poly.points = getpts(string, &poly.numpts);
if (!poly.points)
return (false);
if (poly.is_rect()) {
BBox BB(poly.points);
delete [] poly.points;
if (odesc->is_copy())
odesc->set_oBB(BB);
else {
CDo *newo = sdesc->newBox(odesc, &BB, odesc->ldesc(),
odesc->prpty_list());
if (!newo) {
Errs()->add_error("newBox failed");
return (false);
}
}
return (true);
}
if (poly.numpts < 4) {
delete [] poly.points;
Errs()->add_error("poly/box has too few points");
return (false);
}
if (odesc->is_copy()) {
delete [] poly.points;
Errs()->add_error("can't change box copy to polygon.");
return (false);
}
else {
CDo *newo = sdesc->newPoly(odesc, &poly, odesc->ldesc(),
odesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newPoly failed");
return (false);
}
}
return (true);
}
if (val == XprpMagn) {
double mag;
if (sscanf(string, "%lf", &mag) != 1) {
Errs()->add_error("syntax error, number expected");
return (false);
}
if (mag < CDMAGMIN || mag > CDMAGMAX) {
Errs()->add_error("error, number %g-%g expected",
CDMAGMIN, CDMAGMAX);
return (false);
}
// The box lower-left corner remains fixed.
BBox BB(odesc->oBB().left, odesc->oBB().bottom,
odesc->oBB().left + mmRnd(mag*odesc->oBB().width()),
odesc->oBB().bottom + mmRnd(mag*odesc->oBB().height()));
if (odesc->is_copy())
odesc->set_oBB(BB);
else {
CDo *newo = sdesc->newBox(odesc, &BB, odesc->ldesc(),
odesc->prpty_list());
if (!newo) {
Errs()->add_error("newBox failed");
return (false);
}
}
return (true);
}
if (val == XprpXY) {
int n;
Point *p = getpts(string, &n);
if (!p)
return (false);
int px = p->x;
int py = p->y;
delete [] p;
if (px != odesc->oBB().left || py != odesc->oBB().bottom) {
BBox BB(px, py, px + odesc->oBB().right - odesc->oBB().left,
py + odesc->oBB().top - odesc->oBB().bottom);
if (odesc->is_copy())
odesc->set_oBB(BB);
else {
CDo *newo = sdesc->newBox(odesc, &BB, odesc->ldesc(),
odesc->prpty_list());
if (!newo) {
delete [] p;
Errs()->add_error("newBox failed");
return (false);
}
}
}
return (true);
}
if (val == XprpWidth) {
int w;
if (sscanf(string, "%d", &w) != 1 || w <= 0) {
Errs()->add_error("error, bad width");
return (false);
}
BBox BB(odesc->oBB());
BB.right = BB.left + w;
if (odesc->is_copy())
odesc->set_oBB(BB);
else {
CDo *newo = sdesc->newBox(odesc, &BB, odesc->ldesc(),
odesc->prpty_list());
if (!newo) {
Errs()->add_error("newBox failed");
return (false);
}
}
return (true);
}
if (val == XprpHeight) {
int h;
if (sscanf(string, "%d", &h) != 1 || h <= 0) {
Errs()->add_error("error, bad height");
return (false);
}
BBox BB(odesc->oBB());
BB.top = BB.bottom + h;
if (odesc->is_copy())
odesc->set_oBB(BB);
else {
CDo *newo = sdesc->newBox(odesc, &BB, odesc->ldesc(),
odesc->prpty_list());
if (!newo) {
Errs()->add_error("newBox failed");
return (false);
}
}
return (true);
}
Errs()->add_error("unknown pseudo-property %d", val);
return (false);
}
// Handle pseudo-properties applied to polygons.
//
bool
cEdit::acceptPolyPseudoProp(CDpo *pdesc, CDs *sdesc, int val,
const char *string)
{
// For polys, accept all (physical or electrical, copy or not).
if (val == XprpBB) {
BBox BB;
if (sscanf(string, "%d,%d %d,%d", &BB.left, &BB.bottom,
&BB.right, &BB.top) != 4) {
Errs()->add_error(
"syntax error, expecting l,b r,t coordinates");
return (false);
}
BB.fix();
int num = pdesc->numpts();
Poly po(num, scalepts(&BB, &pdesc->oBB(), pdesc->points(), num));
if (pdesc->is_copy()) {
pdesc->set_oBB(BB);
delete [] pdesc->points();
pdesc->set_points(po.points);
}
else {
CDo *newo = sdesc->newPoly(pdesc, &po, pdesc->ldesc(),
pdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newPoly failed");
return (false);
}
}
return (true);
}
if (val == XprpLayer) {
CDl *ld = CDldb()->findLayer(string, sdesc->displayMode());
if (!ld) {
Errs()->add_error("layer %s not found", string);
return (false);
}
if (pdesc->is_copy())
pdesc->set_ldesc(ld);
else {
int num = pdesc->numpts();
Poly po(num, Point::dup(pdesc->points(), num));
CDo *newo = sdesc->newPoly(pdesc, &po, ld, pdesc->prpty_list(),
false);
if (!newo) {
Errs()->add_error("newPoly failed");
return (false);
}
}
return (true);
}
if (val == XprpCoords) {
Poly po;
po.points = getpts(string, &po.numpts);
if (!po.points)
return (false);
if (po.is_rect() && !pdesc->is_copy()) {
BBox BB(po.points);
delete [] po.points;
CDo *newo = sdesc->newBox(pdesc, &BB, pdesc->ldesc(),
pdesc->prpty_list());
if (!newo) {
Errs()->add_error("newBox failed");
return (false);
}
return (true);
}
if (po.numpts < 4) {
delete [] po.points;
Errs()->add_error("poly has too few points");
return (false);
}
if (pdesc->is_copy()) {
delete [] pdesc->points();
pdesc->set_points(po.points);
pdesc->set_numpts(po.numpts);
pdesc->computeBB();
}
else {
CDo *newo = sdesc->newPoly(pdesc, &po, pdesc->ldesc(),
pdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newPoly failed");
return (false);
}
}
return (true);
}
if (val == XprpMagn) {
double mag;
if (sscanf(string, "%lf", &mag) != 1) {
Errs()->add_error("syntax error, number expected");
return (false);
}
if (mag < CDMAGMIN || mag > CDMAGMAX) {
Errs()->add_error("error, number %g-%g expected",
CDMAGMIN, CDMAGMAX);
return (false);
}
// The first vertex remains fixed.
int num = pdesc->numpts();
Poly po(num, new Point[num]);
const Point *pts = pdesc->points();
int xr = pts[0].x;
int yr = pts[0].y;
po.points[0].set(xr, yr);
for (int i = 1; i < po.numpts; i++) {
po.points[i].set(xr + mmRnd(mag*(pts[i].x - xr)),
yr + mmRnd(mag*(pts[i].y - yr)));
}
if (pdesc->is_copy()) {
delete [] pdesc->points();
pdesc->set_points(po.points);
pdesc->computeBB();
}
else {
CDo *newo = sdesc->newPoly(pdesc, &po, pdesc->ldesc(),
pdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newPoly failed");
return (false);
}
}
return (true);
}
if (val == XprpXY) {
int n;
Point *p = getpts(string, &n);
if (!p)
return (false);
int px = p->x;
int py = p->y;
delete [] p;
int num = pdesc->numpts();
Poly po(num, 0);
const Point *pts = pdesc->points();
if (px != pts->x || py != pts->y) {
po.points = new Point[num];
int dx = px - pts->x;
int dy = py - pts->y;
for (int i = 0; i < po.numpts; i++) {
po.points[i].x = pts[i].x + dx;
po.points[i].y = pts[i].y + dy;
}
if (pdesc->is_copy()) {
delete [] pdesc->points();
pdesc->set_points(po.points);
pdesc->computeBB();
}
else {
CDo *newo = sdesc->newPoly(pdesc, &po, pdesc->ldesc(),
pdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newPoly failed");
return (false);
}
}
}
return (true);
}
if (val == XprpWidth) {
int w;
if (sscanf(string, "%d", &w) != 1 || w <= 0) {
Errs()->add_error("error, bad width");
return (false);
}
BBox BB(pdesc->oBB());
BB.right = BB.left + w;
int num = pdesc->numpts();
Poly po(num, scalepts(&BB, &pdesc->oBB(), pdesc->points(), num));
if (pdesc->is_copy()) {
pdesc->set_oBB(BB);
delete [] pdesc->points();
pdesc->set_points(po.points);
}
else {
CDo *newo = sdesc->newPoly(pdesc, &po, pdesc->ldesc(),
pdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newPoly failed");
return (false);
}
}
return (true);
}
if (val == XprpHeight) {
int h;
if (sscanf(string, "%d", &h) != 1 || h <= 0) {
Errs()->add_error("error, bad height");
return (false);
}
BBox BB(pdesc->oBB());
BB.top = BB.bottom + h;
int num = pdesc->numpts();
Poly po(num, scalepts(&BB, &pdesc->oBB(), pdesc->points(), num));
if (pdesc->is_copy()) {
pdesc->set_oBB(BB);
delete [] pdesc->points();
pdesc->set_points(po.points);
}
else {
CDo *newo = sdesc->newPoly(pdesc, &po, pdesc->ldesc(),
pdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newPoly failed");
return (false);
}
}
return (true);
}
Errs()->add_error("unknown pseudo-property %d", val);
return (false);
}
// Handle pseudo-properties applied to wires.
//
bool
cEdit::acceptWirePseudoProp(CDw *wdesc, CDs *sdesc, int val,
const char *string)
{
// For wires, electrical wires on the active layer or that
// would be moved to the active layer are rejected, all other
// wires are accepted.
if (sdesc->isElectrical() && wdesc->ldesc()->isWireActive()) {
Errs()->add_error(
"Can't modify wires on an active layer with pseudo-properties.");
return (false);
}
if (val == XprpBB) {
BBox BB;
if (sscanf(string, "%d,%d %d,%d", &BB.left, &BB.bottom,
&BB.right, &BB.top) != 4) {
Errs()->add_error(
"syntax error, expecting l,b r,t coordinates");
return (false);
}
BB.fix();
int num = wdesc->numpts();
Wire wire(num, scalepts(&BB, &wdesc->oBB(), wdesc->points(), num),
wdesc->attributes());
if (wdesc->is_copy()) {
delete [] wdesc->points();
wdesc->set_points(wire.points);
wdesc->computeBB();
}
else {
CDo *newo = sdesc->newWire(wdesc, &wire, wdesc->ldesc(),
wdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newWire failed");
return (false);
}
}
return (true);
}
if (val == XprpLayer) {
CDl *ld = CDldb()->findLayer(string, sdesc->displayMode());
if (!ld) {
Errs()->add_error("layer %s not found", string);
return (false);
}
if (sdesc->isElectrical() && ld->isWireActive()) {
Errs()->add_error(
"Can't move wire to active layer with pseudo-properties");
return (false);
}
if (wdesc->is_copy())
wdesc->set_ldesc(ld);
else {
int num = wdesc->numpts();
Wire wire(num, Point::dup(wdesc->points(), num),
wdesc->attributes());
CDo *newo = sdesc->newWire(wdesc, &wire, ld,
wdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newWire failed");
return (false);
}
}
return (true);
}
if (val == XprpCoords) {
Wire wire(0, 0, wdesc->attributes());
wire.points = getpts(string, &wire.numpts);
if (!wire.points)
return (false);
if (wdesc->is_copy()) {
delete [] wdesc->points();
wdesc->set_points(wire.points);
wdesc->set_numpts(wire.numpts);
wdesc->computeBB();
}
else {
CDo *newo = sdesc->newWire(wdesc, &wire, wdesc->ldesc(),
wdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newWire failed");
return (false);
}
}
return (true);
}
if (val == XprpWwidth) {
int d;
if (sscanf(string, "%d", &d) != 1 || d <= 0) {
Errs()->add_error("error, positive integer expected");
return (false);
}
if (wdesc->is_copy()) {
wdesc->set_wire_width(d);
wdesc->computeBB();
}
else {
int num = wdesc->numpts();
Wire wire(num, Point::dup(wdesc->points(), num),
wdesc->attributes());
wire.set_wire_width(d);
if (wire.wire_width() != wdesc->wire_width()) {
CDo *newo = sdesc->newWire(wdesc, &wire, wdesc->ldesc(),
wdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newWire failed");
return (false);
}
}
}
return (true);
}
if (val == XprpWstyle) {
const char *s = string;
while (isspace(*s))
s++;
int d = -1;
switch (*s) {
case '0':
case 'f':
case 'F':
d = CDWIRE_FLUSH;
break;
case '1':
case 'r':
case 'R':
d = CDWIRE_ROUND;
break;
case '2':
case 'e':
case 'E':
d = CDWIRE_EXTEND;
break;
default:
break;
}
if (d < 0) {
Errs()->add_error("error, integer 0-2 or 'f', 'r', 'e' expected");
return (false);
}
if (wdesc->is_copy()) {
wdesc->set_wire_style((WireStyle)d);
wdesc->computeBB();
}
else {
int num = wdesc->numpts();
Wire wire(num, Point::dup(wdesc->points(), num),
wdesc->attributes());
wire.set_wire_style((WireStyle)d);
if (wire.wire_style() != wdesc->wire_style()) {
CDo *newo = sdesc->newWire(wdesc, &wire, wdesc->ldesc(),
wdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newWire failed");
return (false);
}
}
}
return (true);
}
if (val == XprpMagn) {
double mag;
if (sscanf(string, "%lf", &mag) != 1) {
Errs()->add_error("syntax error, number expected");
return (false);
}
if (mag < CDMAGMIN || mag > CDMAGMAX) {
Errs()->add_error("error, number %g-%g expected",
CDMAGMIN, CDMAGMAX);
return (false);
}
// The first vertex remains fixed.
int num = wdesc->numpts();
Wire wire(num, 0, wdesc->attributes());
const Point *pts = wdesc->points();
wire.points = new Point[wire.numpts];
int xr = pts[0].x;
int yr = pts[0].y;
wire.points[0].set(xr, yr);
for (int i = 1; i < wire.numpts; i++) {
wire.points[i].set(xr + mmRnd(mag*(pts[i].x - xr)),
yr + mmRnd(mag*(pts[i].y - yr)));
}
// Note that the Magn does not change wire width, only the
// point list. Use XprpWwidth.
if (wdesc->is_copy()) {
delete [] wdesc->points();
wdesc->set_points(wire.points);
wdesc->computeBB();
}
else {
CDo *newo = sdesc->newWire(wdesc, &wire, wdesc->ldesc(),
wdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newWire failed");
return (false);
}
}
return (true);
}
if (val == XprpXY) {
int n;
Point *p = getpts(string, &n);
if (!p)
return (false);
int px = p->x;
int py = p->y;
delete [] p;
int num = wdesc->numpts();
Wire wire(num, 0, wdesc->attributes());
const Point *pts = wdesc->points();
if (px != pts->x || py != pts->y) {
wire.points = new Point[wire.numpts];
int dx = px - pts->x;
int dy = py - pts->y;
for (int i = 0; i < wire.numpts; i++) {
wire.points[i].x = pts[i].x + dx;
wire.points[i].y = pts[i].y + dy;
}
if (wdesc->is_copy()) {
delete [] wdesc->points();
wdesc->set_points(wire.points);
wdesc->computeBB();
}
else {
CDo *newo = sdesc->newWire(wdesc, &wire, wdesc->ldesc(),
wdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newWire failed");
return (false);
}
}
}
return (true);
}
if (val == XprpWidth) {
int w;
if (sscanf(string, "%d", &w) != 1 || w <= 0) {
Errs()->add_error("error, bad width");
return (false);
}
BBox BB(wdesc->oBB());
BB.right = BB.left + w;
int num = wdesc->numpts();
Wire wire(num, scalepts(&BB, &wdesc->oBB(), wdesc->points(), num),
wdesc->attributes());
if (wdesc->is_copy()) {
delete [] wdesc->points();
wdesc->set_points(wire.points);
wdesc->computeBB();
}
else {
CDo *newo = sdesc->newWire(wdesc, &wire, wdesc->ldesc(),
wdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newWire failed");
return (false);
}
}
return (true);
}
if (val == XprpHeight) {
int h;
if (sscanf(string, "%d", &h) != 1 || h <= 0) {
Errs()->add_error("error, bad height");
return (false);
}
BBox BB(wdesc->oBB());
BB.top = BB.bottom + h;
int num = wdesc->numpts();
Wire wire(num, scalepts(&BB, &wdesc->oBB(), wdesc->points(), num),
wdesc->attributes());
if (wdesc->is_copy()) {
delete [] wdesc->points();
wdesc->set_points(wire.points);
wdesc->computeBB();
}
else {
CDo *newo = sdesc->newWire(wdesc, &wire, wdesc->ldesc(),
wdesc->prpty_list(), false);
if (!newo) {
Errs()->add_error("newWire failed");
return (false);
}
}
return (true);
}
Errs()->add_error("unknown pseudo-property %d", val);
return (false);
}
// Handle pseudo-properties applied to labels.
//
bool
cEdit::acceptLabelPseudoProp(CDla *ladesc, CDs *sdesc, int val,
const char *string)
{
// For labels, accept all (physical or electrical, copy or not).
// Have to be careful with electrical property labels.
if (val == XprpBB) {
BBox BB;
if (sscanf(string, "%d,%d %d,%d", &BB.left, &BB.bottom,
&BB.right, &BB.top) != 4) {
Errs()->add_error(
"syntax error, expecting l,b r,t coordinates");
return (false);
}
BB.fix();
if (ladesc->is_copy()) {
ladesc->set_xpos(BB.left);
ladesc->set_ypos(BB.bottom);
ladesc->set_width(BB.width());
ladesc->set_height(BB.height());
ladesc->computeBB();
}
else {
Label lab(ladesc->la_label());
lab.x = BB.left;
lab.y = BB.bottom;
lab.width = BB.width();
lab.height = BB.height();
CDla *newo = sdesc->newLabel(ladesc, &lab, ladesc->ldesc(),
ladesc->prpty_list(), true);
if (!newo) {
Errs()->add_error("newLabel failed");
return (false);
}
if (sdesc->isElectrical())
sdesc->prptyLabelUpdate(newo, ladesc);
}
return (true);
}
if (val == XprpLayer) {
CDl *ld = CDldb()->findLayer(string, sdesc->displayMode());
if (!ld) {
Errs()->add_error("layer %s not found", string);
return (false);
}
if (ladesc->is_copy())
ladesc->set_ldesc(ld);
else {
Label ltmp(ladesc->la_label());
CDla *newo = sdesc->newLabel(ladesc, <mp, ld,
ladesc->prpty_list(), true);
if (!newo) {
Errs()->add_error("newLabel failed");
return (false);
}
if (sdesc->isElectrical())
sdesc->prptyLabelUpdate(newo, ladesc);
}
return (true);
}
if (val == XprpCoords) {
int numpts;
Point *p = getpts(string, &numpts);
if (!p)
return (false);
Poly ptmp(numpts, p);
if (ptmp.is_rect()) {
BBox BB(p);
delete [] p;
if (ladesc->is_copy()) {
ladesc->set_xpos(BB.left);
ladesc->set_ypos(BB.bottom);
ladesc->set_width(BB.width());
ladesc->set_height(BB.height());
ladesc->computeBB();
}
else {
Label lab(ladesc->la_label());
lab.x = BB.left;
lab.y = BB.bottom;
lab.width = BB.width();
lab.height = BB.height();
CDla *newo = sdesc->newLabel(ladesc, &lab, ladesc->ldesc(),
ladesc->prpty_list(), true);
if (!newo) {
Errs()->add_error("newLabel failed");
return (false);
}
if (sdesc->isElectrical())
sdesc->prptyLabelUpdate(newo, ladesc);
}
return (true);
}
Errs()->add_error(
"syntax error, expecting rectangular closed path");
delete [] p;
return (false);
}
if (val == XprpText) {
if (!string || !*string) {
Errs()->add_error("empty string not allowed in label");
return (false);
}
hyList *hl = new hyList(sdesc, string, HYcvAscii);
if (!hl) {
Errs()->add_error("internal error: null hyperlist");
return (false);
}
if (ladesc->is_copy()) {
char *oldstr = hyList::string(ladesc->label(), HYcvPlain, false);
if (!oldstr)
oldstr = lstring::copy("X");
double oldwidth, oldheight;
int oldlines = CD()->DefaultLabelSize(oldstr, Physical,
&oldwidth, &oldheight);
int oldlineht = ladesc->height()/oldlines;
delete [] oldstr;
double newwidth, newheight;
int newlines = CD()->DefaultLabelSize(string, Physical,
&newwidth, &newheight);
int newlineht = (int)(newheight/newlines);
hyList::destroy(ladesc->label());
ladesc->set_label(hl);
ladesc->set_height(oldlineht * newlines);
ladesc->set_width((int)((newwidth * oldlineht)/newlineht));
ladesc->computeBB();
}
else {
// This will handle electrical property changes.
CDo *newo = changeLabel(ladesc, sdesc, hl);
hyList::destroy(hl);
if (!newo) {
Errs()->add_error("changeLabel failed");
return (false);
}
}
return (true);
}
if (val == XprpXform) {
// format: [+|-] 0xhex | tok,tok,...
bool had_p = false, had_m = false;
const char *s = string;
while (isspace(*s))
s++;
if (*s == '+') {
had_p = true;
s++;
}
else if (*s == '-') {
had_m = true;
s++;
}
unsigned int xf = string_to_xform(s);
if (ladesc->is_copy()) {
if (had_p)
ladesc->set_xform(ladesc->xform() | xf);
else if (had_m)
ladesc->set_xform(ladesc->xform() & ~xf);
else
ladesc->set_xform(xf);
ladesc->computeBB();
}
else {
Label lab(ladesc->la_label());
if (had_p)
lab.xform |= xf;
else if (had_m)
lab.xform &= ~xf;
else
lab.xform = xf;
CDla *newo = sdesc->newLabel(ladesc, &lab, ladesc->ldesc(),
ladesc->prpty_list(), true);
if (!newo) {
Errs()->add_error("newLabel failed");
return (false);
}
if (sdesc->isElectrical())
sdesc->prptyLabelUpdate(newo, ladesc);
}
return (true);
}
if (val == XprpMagn) {
double mag;
if (sscanf(string, "%lf", &mag) != 1) {
Errs()->add_error("syntax error, number expected");
return (false);
}
if (mag < CDMAGMIN || mag > CDMAGMAX) {
Errs()->add_error("error, number %g-%g expected",
CDMAGMIN, CDMAGMAX);
return (false);
}
if (ladesc->is_copy()) {
ladesc->set_width(mmRnd(mag*ladesc->width()));
ladesc->set_height(mmRnd(mag*ladesc->height()));
ladesc->computeBB();
}
else {
Label lab(ladesc->la_label());
lab.width = mmRnd(mag*ladesc->width());
lab.height = mmRnd(mag*ladesc->height());
CDla *newo = sdesc->newLabel(ladesc, &lab, ladesc->ldesc(),
ladesc->prpty_list(), true);
if (!newo) {
Errs()->add_error("newLabel failed");
return (false);
}
if (sdesc->isElectrical())
sdesc->prptyLabelUpdate(newo, ladesc);
}
return (true);
}
if (val == XprpXY) {
int n;
Point *p = getpts(string, &n);
if (!p)
return (false);
int px = p->x;
int py = p->y;
delete [] p;
if (px != ladesc->xpos() || py != ladesc->ypos()) {
if (ladesc->is_copy()) {
ladesc->set_xpos(px);
ladesc->set_ypos(py);
ladesc->computeBB();
}
else {
Label lab(ladesc->la_label());
lab.x = px;
lab.y = py;
CDla *newo = sdesc->newLabel(ladesc, &lab, ladesc->ldesc(),
ladesc->prpty_list(), true);
if (!newo) {
Errs()->add_error("newLabel failed");
return (false);
}
if (sdesc->isElectrical())
sdesc->prptyLabelUpdate(newo, ladesc);
}
}
return (true);
}
if (val == XprpWidth) {
int w;
if (sscanf(string, "%d", &w) != 1 || w <= 0) {
Errs()->add_error("error, bad width");
return (false);
}
if (ladesc->is_copy()) {
ladesc->set_width(w);
ladesc->computeBB();
}
else {
Label lab(ladesc->la_label());
lab.width = w;
CDla *newo = sdesc->newLabel(ladesc, &lab, ladesc->ldesc(),
ladesc->prpty_list(), true);
if (!newo) {
Errs()->add_error("newLabel failed");
return (false);
}
if (sdesc->isElectrical())
sdesc->prptyLabelUpdate(newo, ladesc);
}
return (true);
}
if (val == XprpHeight) {
int h;
if (sscanf(string, "%d", &h) != 1 || h <= 0) {
Errs()->add_error("error, bad height");
return (false);
}
if (ladesc->is_copy()) {
ladesc->set_height(h);
ladesc->computeBB();
}
else {
Label lab(ladesc->la_label());
lab.height = h;
CDla *newo = sdesc->newLabel(ladesc, &lab, ladesc->ldesc(),
ladesc->prpty_list(), true);
if (!newo) {
Errs()->add_error("newLabel failed");
return (false);
}
if (sdesc->isElectrical())
sdesc->prptyLabelUpdate(newo, ladesc);
}
return (true);
}
Errs()->add_error("unknown pseudo-property %d", val);
return (false);
}
// Handle pseudo-properties applied to instances.
//
bool
cEdit::acceptInstPseudoProp(CDc *cdesc, CDs *sdesc, int val,
const char *string)
{
// For instances, don't accept electrical mode, copies are ok.
if (sdesc->isElectrical()) {
Errs()->add_error(
"Can't change electrical instance with pseudo-properties.");
return (false);
}
if (val == XprpArray) {
int nx, ny, dx, dy;
if (sscanf(string, "%d,%d %d,%d", &nx, &ny, &dx, &dy) != 4) {
Errs()->add_error(
"syntax error, expecting nx,dx ny,dy values");
return (false);
}
if (nx < 1 || ny < 1) {
Errs()->add_error("error, nx or ny less than 1");
return (false);
}
if (cdesc->is_copy()) {
cTfmStack stk;
stk.TPush();
stk.TApplyTransform(cdesc);
CDtx tx;
stk.TCurrent(&tx);
stk.TPop();
CDap ap(nx, ny, dx, dy);
CDattr at(&tx, &ap);
cdesc->setAttr(CD()->RecordAttr(&at));
}
else {
CallDesc calldesc;
cdesc->call(&calldesc);
cTfmStack stk;
stk.TPush();
stk.TApplyTransform(cdesc);
CDtx tx;
stk.TCurrent(&tx);
stk.TPop();
CDap ap(nx, ny, dx, dy);
CDc *newodesc;
if (OIfailed(sdesc->makeCall(&calldesc, &tx, &ap, CDcallNone,
&newodesc))) {
Errs()->add_error("makeCall failed");
return (false);
}
newodesc->prptyAddCopyList(cdesc->prpty_list());
Ulist()->RecordObjectChange(sdesc, cdesc, newodesc);
}
return (true);
}
if (val == XprpTransf) {
cTfmStack stk;
stk.TPush();
for (const char *s = string; *s; s++) {
if (isspace(*s))
continue;
if (*s == 'T') {
s++;
char *tok = lstring::gettok(&s);
if (!tok) {
stk.TPop();
Errs()->add_error(
"syntax error, expecting translation x");
return (false);
}
int x = atoi(tok);
delete [] tok;
tok = lstring::gettok(&s);
if (!tok) {
stk.TPop();
Errs()->add_error(
"syntax error, expecting translation y");
return (false);
}
int y = atoi(tok);
delete [] tok;
stk.TTranslate(x, y);
s--;
}
else if (*s == 'R') {
s++;
char *tok = lstring::gettok(&s);
if (!tok) {
stk.TPop();
Errs()->add_error(
"syntax error, expecting rotation angle");
return (false);
}
s--;
int r = atoi(tok);
delete [] tok;
int x, y;
if (r == 0)
x = 1, y = 0;
else if (r == 45)
x = 1, y = 1;
else if (r == 90)
x = 0, y = 1;
else if (r == 135)
x = -1, y = 1;
else if (r == 180)
x = -1, y = 0;
else if (r == 225)
x = -1, y = -1;
else if (r == 270)
x = 0, y = -1;
else if (r == 315)
x = 1, y = -1;
else {
stk.TPop();
Errs()->add_error("error, bad angle");
return (false);
}
stk.TRotate(x, y);
}
else if (*s == 'M') {
s++;
if (*s == 'X')
stk.TMX();
else if (*s == 'Y')
stk.TMY();
else {
stk.TPop();
Errs()->add_error(
"syntax error, expecting MX or MY");
return (false);
}
}
else {
stk.TPop();
Errs()->add_error(
"syntax error, unknown transformation");
return (false);
}
}
CDtx tx;
stk.TCurrent(&tx);
stk.TPop();
if (cdesc->is_copy()) {
CDap ap(cdesc);
CDattr at(&tx, &ap);
cdesc->setPosX(tx.tx);
cdesc->setPosY(tx.ty);
cdesc->setAttr(CD()->RecordAttr(&at));
}
else {
CallDesc calldesc;
cdesc->call(&calldesc);
CDap ap(cdesc);
CDc *newodesc;
if (OIfailed(sdesc->makeCall(&calldesc, &tx, &ap, CDcallNone,
&newodesc))) {
Errs()->add_error("makeCall failed");
return (false);
}
newodesc->prptyAddCopyList(cdesc->prpty_list());
Ulist()->RecordObjectChange(sdesc, cdesc, newodesc);
}
return (true);
}
if (val == XprpMagn) {
double mag;
if (sscanf(string, "%lf", &mag) != 1) {
Errs()->add_error("syntax error, number expected");
return (false);
}
if (mag < CDMAGMIN || mag > CDMAGMAX) {
Errs()->add_error("error, number %g-%g expected",
CDMAGMIN, CDMAGMAX);
return (false);
}
if (cdesc->is_copy()) {
cTfmStack stk;
stk.TPush();
stk.TApplyTransform(cdesc);
CDtx tx;
stk.TCurrent(&tx);
stk.TPop();
CDap ap(cdesc);
tx.magn = mag;
CDattr at(&tx, &ap);
cdesc->setAttr(CD()->RecordAttr(&at));
}
else {
CallDesc calldesc;
cdesc->call(&calldesc);
cTfmStack stk;
stk.TPush();
stk.TApplyTransform(cdesc);
CDtx tx;
stk.TCurrent(&tx);
stk.TPop();
CDap ap(cdesc);
tx.magn = mag;
CDc *newodesc;
if (OIfailed(sdesc->makeCall(&calldesc, &tx, &ap, CDcallNone,
&newodesc))) {
Errs()->add_error("makeCall failed");
return (false);
}
newodesc->prptyAddCopyList(cdesc->prpty_list());
Ulist()->RecordObjectChange(sdesc, cdesc, newodesc);
}
return (true);
}
if (val == XprpName) {
if (cdesc->is_copy()) {
Errs()->add_error("Can't re-master an instance copy.");
return (false);
}
else {
if (sdesc->cellname() == DSP()->CurCellName()) {
CDcbin cbin;
if (!openCell(string, &cbin, 0)) {
Errs()->add_error("OpenSymbol failed");
return (false);
}
if (!replaceInstance(cdesc, &cbin, true, false)) {
Errs()->add_error("ReplaceCell failed");
return (false);
}
return (true);
}
Errs()->add_error("instance parent not current cell");
}
return (false);
}
if (val == XprpXY) {
int n;
Point *p = getpts(string, &n);
if (!p)
return (false);
int px = p->x;
int py = p->y;
delete [] p;
if (px != cdesc->posX() || py != cdesc->posY()) {
if (cdesc->is_copy()) {
cTfmStack stk;
stk.TPush();
stk.TApplyTransform(cdesc);
CDtx tx;
stk.TCurrent(&tx);
stk.TPop();
CDap ap(cdesc);
tx.tx = px;
tx.ty = py;
CDattr at(&tx, &ap);
cdesc->setPosX(tx.tx);
cdesc->setPosY(tx.ty);
cdesc->setAttr(CD()->RecordAttr(&at));
}
else {
CallDesc calldesc;
cdesc->call(&calldesc);
cTfmStack stk;
stk.TPush();
stk.TApplyTransform(cdesc);
CDtx tx;
stk.TCurrent(&tx);
stk.TPop();
CDap ap(cdesc);
tx.tx = px;
tx.ty = py;
CDc *newodesc;
if (OIfailed(sdesc->makeCall(&calldesc, &tx, &ap,
CDcallNone, &newodesc))) {
Errs()->add_error("makeCall failed");
return (false);
}
newodesc->prptyAddCopyList(cdesc->prpty_list());
Ulist()->RecordObjectChange(sdesc, cdesc, newodesc);
}
}
return (true);
}
Errs()->add_error("unknown pseudo-property %d", val);
return (false);
}
namespace {
// Scale points according to new BB
//
Point *
scalepts(const BBox *BB, const BBox *oBB, const Point *pts, int numpts)
{
Point *npts = new Point[numpts];
double rx = BB->width()/(double)oBB->width();
double ry = BB->height()/(double)oBB->height();
for (int i = 0; i < numpts; i++) {
npts[i].x = mmRnd((pts[i].x - oBB->left)*rx + BB->left);
npts[i].y = mmRnd((pts[i].y - oBB->bottom)*ry + BB->bottom);
}
return (npts);
}
// Parse a list of "%d,%d" coordinates
//
Point *
getpts(const char *string, int *num)
{
const char *s = string;
int cnt = 0;
while (*s) {
lstring::advtok(&s);
cnt++;
}
if (!cnt) {
Errs()->add_error("no coords found!");
return (0);
}
Point *pts = new Point[cnt];
cnt = 0;
while ((s = lstring::gettok(&string)) != 0) {
if (sscanf(s, "%d,%d", &pts[cnt].x, &pts[cnt].y) != 2) {
delete [] s;
delete [] pts;
Errs()->add_error("parse error reading coords!");
return (0);
}
delete [] s;
cnt++;
}
*num = cnt;
return (pts);
}
}
|
[
"stevew@wrcad.com"
] |
stevew@wrcad.com
|
1fdb796c1990d86930e9e811e1992c8084f6c21f
|
6446d917ab76942bb20e1465b6a070ee0686a1c2
|
/chap03/termination.cpp
|
dc862c0f508dd728e3dd8bdefde0b5ec2d672c6d
|
[] |
no_license
|
elect000/C-
|
52dd5aaf549c20e4d4bead74d486c6de8bcddeae
|
0f6096f79be2be39c91cc38a5cc5687659aab4c6
|
refs/heads/master
| 2020-12-30T23:35:06.172463
| 2017-05-26T10:41:12
| 2017-05-26T10:41:12
| 86,602,947
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 504
|
cpp
|
#include <ctime>
#include <iostream>
#include <cstdlib>
using namespace std;
void good_bye () {
cout << "プログラムは正常に終了しました。" << '\n';
}
void put_time () {
time_t current = time(NULL);
struct tm* lct = localtime(¤t);
cout << lct->tm_hour << ":" << lct->tm_min << ":" << lct->tm_sec << '\n';
}
int main()
{
int x;
atexit(good_bye);
atexit(put_time);
cout << "[0]正常終了 [1]異常終了:";
cin >> x;
if (x) {
abort();
}
return 0;
}
|
[
"e.tmailbank@gmail.com"
] |
e.tmailbank@gmail.com
|
5d729401371a44b1c26c8d729de3a995abd97d97
|
7d74a4fab1662506f57be03b165dc7ea03c6ea17
|
/src/core/renderer/sprite_animation.hpp
|
20611e24ed53265890b81ececdd7c9e6c4f7337d
|
[
"MIT"
] |
permissive
|
lowkey42/teamproject
|
2e9a7ec29e41d3b382ea8384a1051ef0f5fd922b
|
41e7dfe27161f319d08d02982443720af55398a3
|
refs/heads/develop
| 2020-04-04T05:55:47.308995
| 2016-10-04T20:34:05
| 2016-10-04T20:34:05
| 49,599,482
| 1
| 0
| null | 2016-07-14T21:10:40
| 2016-01-13T20:22:12
|
C++
|
UTF-8
|
C++
| false
| false
| 3,844
|
hpp
|
/**************************************************************************\
* Animation data for textures and sprites *
* ___ *
* /\/\ __ _ __ _ _ __ _ _ _ __ ___ /___\_ __ _ _ ___ *
* / \ / _` |/ _` | '_ \| | | | '_ ` _ \ // // '_ \| | | / __| *
* / /\/\ \ (_| | (_| | | | | |_| | | | | | | / \_//| |_) | |_| \__ \ *
* \/ \/\__,_|\__, |_| |_|\__,_|_| |_| |_| \___/ | .__/ \__,_|___/ *
* |___/ |_| *
* *
* Copyright (c) 2016 Florian Oetke *
* *
* This file is part of MagnumOpus and distributed under the MIT License *
* See LICENSE file for details. *
\**************************************************************************/
#pragma once
#include "texture.hpp"
#include "sprite_batch.hpp"
#include "material.hpp"
#include "../asset/asset_manager.hpp"
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <string>
#include <vector>
#include <stdexcept>
namespace lux {
namespace util {
class Message_bus;
}
namespace renderer {
using Animation_clip_id = util::Str_id;
class Sprite_animation_state;
struct Animation_event {
util::Str_id name;
void* owner;
};
struct Sprite_animation_Clip;
class Sprite_animation_set {
public:
Sprite_animation_set(asset::istream&);
auto operator=(Sprite_animation_set&&)noexcept -> Sprite_animation_set&;
~Sprite_animation_set();
private:
friend class Sprite_animation_state;
struct PImpl;
std::unique_ptr<PImpl> _impl;
void _register_inst(Sprite_animation_state&)const;
void _unregister_inst(Sprite_animation_state&)const;
};
using Sprite_animation_set_ptr = asset::Ptr<Sprite_animation_set>;
class Sprite_animation_state {
public:
Sprite_animation_state(void* owner=nullptr, Sprite_animation_set_ptr data={},
Animation_clip_id initial_clip=""_strid);
Sprite_animation_state(Sprite_animation_state&&)noexcept;
auto operator=(Sprite_animation_state&&)noexcept -> Sprite_animation_state&;
~Sprite_animation_state();
auto owner()noexcept {return _owner;}
void update(Time dt, util::Message_bus&);
auto uv_rect()const -> glm::vec4;
auto material()const -> const Material&;
auto animation_set()const {return _animation_set;}
void animation_set(Sprite_animation_set_ptr set, Animation_clip_id clip=""_strid);
auto get_clip()const noexcept {return _curr_clip_id;}
void set_clip(Animation_clip_id id);
auto set_clip_if(Animation_clip_id id, Animation_clip_id expected) {
if(_curr_clip_id==expected) {
set_clip(id);
return true;
}
return false;
}
void set_next_clip(Animation_clip_id id) {
_queued_clip_id = id;
}
void speed(float factor) {
_speed_factor = factor;
}
auto playing()const noexcept {return _playing;}
void reset();
private:
void* _owner;
Sprite_animation_set_ptr _animation_set;
Animation_clip_id _curr_clip_id;
util::maybe<Sprite_animation_Clip&> _curr_clip;
util::maybe<Animation_clip_id> _queued_clip_id = util::nothing();
int_fast16_t _frame = 0;
Time _runtime {};
float _speed_factor = 1.f;
bool _playing = true;
};
} /* namespace renderer */
namespace asset {
template<>
struct Loader<renderer::Sprite_animation_set> {
static auto load(istream in) {
return std::make_shared<renderer::Sprite_animation_set>(in);
}
static void store(ostream, const renderer::Sprite_animation_set&) {
FAIL("NOT IMPLEMENTED!");
}
};
}
}
|
[
"mephistopheles@onlinehome.de"
] |
mephistopheles@onlinehome.de
|
e51ee0314e2f4a8feae0a2d70165a4c8fc737ba6
|
520b75c144414d2af5a655e592fa65787ee89aaa
|
/AOJ/Volume20/2035.cpp
|
d99574137c4413ec5f0c1e6cfa0d94a19ad38a74
|
[] |
no_license
|
arrows-1011/CPro
|
4ac069683c672ba685534444412aa2e28026879d
|
2e1a9242b2433851f495468e455ee854a8c4dac7
|
refs/heads/master
| 2020-04-12T09:36:40.846130
| 2017-06-10T08:02:10
| 2017-06-10T08:02:10
| 46,426,455
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 950
|
cpp
|
#include <iostream>
#include <algorithm>
using namespace std;
#define MAX 2001
int dp[MAX][MAX];
int arr[MAX][MAX];
void init(int N){
for(int i = 0 ; i < N ; i++){
for(int j = 0 ; j < N ; j++){
dp[i][j] = 0;
arr[i][j] = MAX;
}
}
}
int main(){
string s;
while(cin >> s){
string t = s;
reverse(t.begin(), t.end());
int len = s.size(); init(len+1);
for(int i = 0 ; i < len ; i++){
for(int j = 0 ; j < len ; j++){
if(s[i] == t[j]){
dp[i+1][j+1] = dp[i][j] + 1;
arr[i+1][j+1] = 0;
}else{
if(dp[i][j+1] < dp[i+1][j]){
dp[i+1][j+1] = dp[i+1][j];
arr[i+1][j+1] = -1;
}else{
dp[i+1][j+1] = dp[i][j+1];
arr[i+1][j+1] = 1;
}
}
}
}
string str;
for(int i = len, j = len ; i > 0 && j > 0 ;){
if(!arr[i][j]){
str += s[i-1];
i--, j--;
}else if(arr[i][j] == 1){
i--;
}else{
j--;
}
}
cout << str << endl;
}
return 0;
}
|
[
"s1210207@gmail.com"
] |
s1210207@gmail.com
|
72776e52a0da51d9738e057e8e17d489959d37e7
|
67aceb910483ef1b11f10a377bd7cc6970bd9b4a
|
/EngineQ/TODO/MathTests/Helpers.hpp
|
a7436d0d96a61f22ae6ed1bea39b8d9ff41e3118
|
[] |
no_license
|
Tsuguri/EngineQ
|
3a408e790a766eb1689a9c0545ddd725f0442ce7
|
805adfacf54e98fd55e93a3d2adc8ce037f9a21c
|
refs/heads/master
| 2020-08-08T00:18:28.580155
| 2019-10-08T12:25:39
| 2019-10-08T12:25:39
| 213,633,437
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 841
|
hpp
|
#pragma once
using namespace EngineQ::Math;
namespace Microsoft {
namespace VisualStudio {
namespace CppUnitTestFramework
{
template<> inline std::wstring ToString<Quaternion>(const Quaternion& t) { RETURN_WIDE_STRING(t.ToString().c_str()); }
template<> inline std::wstring ToString<Matrix3>(const Matrix3& t) { RETURN_WIDE_STRING(t.ToString().c_str()); }
template<> inline std::wstring ToString<Matrix4>(const Matrix4& t) { RETURN_WIDE_STRING(t.ToString().c_str()); }
template<> inline std::wstring ToString<Vector2>(const Vector2& t) { RETURN_WIDE_STRING(t.ToString().c_str()); }
template<> inline std::wstring ToString<Vector3>(const Vector3& t) { RETURN_WIDE_STRING(t.ToString().c_str()); }
template<> inline std::wstring ToString<Vector4>(const Vector4& t) { RETURN_WIDE_STRING(t.ToString().c_str()); }
}
}
}
|
[
"Piotr Pełka"
] |
Piotr Pełka
|
75c1ff6268d0b6ba23056d9892718c6d559220b1
|
a08e005474521e6b10573aed863a3ff8067c9c13
|
/src/crypto/hmac_sha512.cpp
|
cbd32f34e6521c5952e9678a3268e9de2bc5cb9e
|
[
"MIT"
] |
permissive
|
BitcoinClassicDev/BitcoinClassic
|
c18048431dccd4346865f9c5ee3c079831c8adde
|
87f76317eb80c25c54e9104c61bdf570fc7721f3
|
refs/heads/master
| 2020-09-16T00:57:59.563234
| 2019-12-02T19:18:14
| 2019-12-02T19:18:14
| 223,602,827
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 916
|
cpp
|
// Copyright (c) 2014-2018 The BitcoinClassic Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <crypto/hmac_sha512.h>
#include <string.h>
CHMAC_SHA512::CHMAC_SHA512(const unsigned char* key, size_t keylen)
{
unsigned char rkey[128];
if (keylen <= 128) {
memcpy(rkey, key, keylen);
memset(rkey + keylen, 0, 128 - keylen);
} else {
CSHA512().Write(key, keylen).Finalize(rkey);
memset(rkey + 64, 0, 64);
}
for (int n = 0; n < 128; n++)
rkey[n] ^= 0x5c;
outer.Write(rkey, 128);
for (int n = 0; n < 128; n++)
rkey[n] ^= 0x5c ^ 0x36;
inner.Write(rkey, 128);
}
void CHMAC_SHA512::Finalize(unsigned char hash[OUTPUT_SIZE])
{
unsigned char temp[64];
inner.Finalize(temp);
outer.Write(temp, 64).Finalize(hash);
}
|
[
"root@DESKTOP-325AAR8.localdomain"
] |
root@DESKTOP-325AAR8.localdomain
|
37f12bf61166e652202d5c2124304ffdf880af1d
|
1914d1b5f4616fbe246bfd180020556a442e25a7
|
/Hackerrank/infinitum11/subset_gcd.cpp
|
093f370ab74c9aed2ec00135b3ad813301ca8626
|
[] |
no_license
|
dipkakwani/Puzzles
|
0d939f636b03d2c96db83cc05779e9ba29060b8f
|
7ef7d1057d15ba3abd1716ff42b20b5fb276e7d8
|
refs/heads/master
| 2021-01-10T12:04:48.588038
| 2016-05-07T14:02:53
| 2016-05-07T14:02:53
| 52,711,668
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,246
|
cpp
|
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <bits/stdc++.h>
#define MAX 100000
using namespace std;
typedef long long ll;
char memo[1000000001];
ll gcd(ll a, ll b)
{
return (b == 0)?a:gcd(b, a % b);
}
ll GCD(ll a[MAX], int start, int end)
{
ll res = 0;
for (int i = start; i != end; i++)
res = gcd(res, a[i]);
return res;
}
bool subset_gcd(ll a[MAX], ll k, int start, ll res, int size)
{
if (memo[res] != '0')
return (memo[res] == '1')?0:1;
if (res == k)
{
memo[k] = '2';
return 1;
}
if (start >= size)
{
memo[res] = '1';
return 0;
}
ll g = gcd(res, a[start]);
memo[res] = (subset_gcd(a, k, start + 1, res, size) == 1)?'2':'1';
memo[g] = (subset_gcd(a, k, start + 1, g, size) == 1)?'2':'1';
return (memo[res] - '1') || (memo[g] - '1');
}
int main() {
ll a[MAX];
int t;
cin >> t;
while (t--)
{
int n;
ll k;
cin >> n >> k;
for (int i = 0; i < n; i++)
cin >> a[i];
memset(memo, '0', *max_element(a, a + n) + 1);
if (subset_gcd(a, k, 0, 0, n))
cout << "YES\n";
else
cout << "NO\n";
}
return 0;
}
|
[
"dipkakwani@gmail.com"
] |
dipkakwani@gmail.com
|
a8d13b51c1b878df8159eadc0fc113ab11268e05
|
67ba655579bd283ab497a151fa20b7ed3befaf75
|
/cpp_concurrency/blog_code/Threads_2.cpp
|
86e372d07de51cc16405c6d0b13d245b48365a25
|
[] |
no_license
|
JeffYoung17/Course_Learning
|
f8ca46fb57afd879b1bc577cf91c13b6b92b065e
|
d16b0e93df91d6c185341b8825c31b364c194a4c
|
refs/heads/master
| 2020-04-04T03:50:20.752189
| 2019-02-19T11:56:16
| 2019-02-19T11:56:16
| 155,727,976
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 392
|
cpp
|
#include <iostream>
#include <thread>
#include <string>
#include <cstring>
using namespace std;
void func(int i, double d, const std::string& s) // 因为对于s是常引用,所以启动线程的时候std::ref("hello")可有可无
{
cout << i << " " << d << " " << s << endl;
}
int main(int argc, char** argv)
{
std::thread t(func, 1, 3.14, "hello");
t.join();
return 0;
}
|
[
"jeffyoung17@163.com"
] |
jeffyoung17@163.com
|
4cb7a1dcf97644f4f00dbfa35b81b35a1366835d
|
27da6c0a879fc46fa91501b83f9b587b7dede3ce
|
/thirdparty/gtest-1.7.0/test/gtest-port_test.cc
|
1a1ee4a58af35dca49d906319aa09aa1e6794891
|
[
"MIT",
"LicenseRef-scancode-generic-cla",
"BSD-3-Clause"
] |
permissive
|
waqarsqureshi/Restore
|
6b0a0e2d5164442f6355a0c21fa78fd9cc411a60
|
436fcf3eeffd015f5196fd3408aaad758450c290
|
refs/heads/master
| 2020-12-11T09:07:22.877304
| 2016-04-17T20:07:17
| 2016-04-17T20:07:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 39,176
|
cc
|
// Copyright 2008, 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.
//
// Authors: vladl@google.com (Vlad Losev), wan@google.com (Zhanyong Wan)
//
// This file tests the internal cross-platform support utilities.
#include "gtest/internal/gtest-port.h"
#include <stdio.h>
#if GTEST_OS_MAC
# include <time.h>
#endif // GTEST_OS_MAC
#include <list>
#include <utility> // For std::pair and std::make_pair.
#include <vector>
#include "gtest/gtest.h"
#include "gtest/gtest-spi.h"
// Indicates that this translation unit is part of Google Test's
// implementation. It must come before gtest-internal-inl.h is
// included, or there will be a compiler error. This trick is to
// prevent a user from accidentally including gtest-internal-inl.h in
// his code.
#define GTEST_IMPLEMENTATION_ 1
#include "src/gtest-internal-inl.h"
#undef GTEST_IMPLEMENTATION_
using std::make_pair;
using std::pair;
namespace testing {
namespace internal {
TEST(IsXDigitTest, WorksForNarrowAscii) {
EXPECT_TRUE(IsXDigit('0'));
EXPECT_TRUE(IsXDigit('9'));
EXPECT_TRUE(IsXDigit('A'));
EXPECT_TRUE(IsXDigit('F'));
EXPECT_TRUE(IsXDigit('a'));
EXPECT_TRUE(IsXDigit('f'));
EXPECT_FALSE(IsXDigit('-'));
EXPECT_FALSE(IsXDigit('g'));
EXPECT_FALSE(IsXDigit('G'));
}
TEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {
EXPECT_FALSE(IsXDigit(static_cast<char>(0x80)));
EXPECT_FALSE(IsXDigit(static_cast<char>('0' | 0x80)));
}
TEST(IsXDigitTest, WorksForWideAscii) {
EXPECT_TRUE(IsXDigit(L'0'));
EXPECT_TRUE(IsXDigit(L'9'));
EXPECT_TRUE(IsXDigit(L'A'));
EXPECT_TRUE(IsXDigit(L'F'));
EXPECT_TRUE(IsXDigit(L'a'));
EXPECT_TRUE(IsXDigit(L'f'));
EXPECT_FALSE(IsXDigit(L'-'));
EXPECT_FALSE(IsXDigit(L'g'));
EXPECT_FALSE(IsXDigit(L'G'));
}
TEST(IsXDigitTest, ReturnsFalseForWideNonAscii) {
EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(0x80)));
EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x80)));
EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x100)));
}
class Base {
public:
// Copy constructor and assignment operator do exactly what we need, so we
// use them.
Base() : member_(0) {}
explicit Base(int n) : member_(n) {}
virtual ~Base() {}
int member() { return member_; }
private:
int member_;
};
class Derived : public Base {
public:
explicit Derived(int n) : Base(n) {}
};
TEST(ImplicitCastTest, ConvertsPointers) {
Derived derived(0);
EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));
}
TEST(ImplicitCastTest, CanUseInheritance) {
Derived derived(1);
Base base = ::testing::internal::ImplicitCast_<Base>(derived);
EXPECT_EQ(derived.member(), base.member());
}
class Castable {
public:
explicit Castable(bool* converted) : converted_(converted) {}
operator Base() {
*converted_ = true;
return Base();
}
private:
bool* converted_;
};
TEST(ImplicitCastTest, CanUseNonConstCastOperator) {
bool converted = false;
Castable castable(&converted);
Base base = ::testing::internal::ImplicitCast_<Base>(castable);
EXPECT_TRUE(converted);
}
class ConstCastable {
public:
explicit ConstCastable(bool* converted) : converted_(converted) {}
operator Base() const {
*converted_ = true;
return Base();
}
private:
bool* converted_;
};
TEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) {
bool converted = false;
const ConstCastable const_castable(&converted);
Base base = ::testing::internal::ImplicitCast_<Base>(const_castable);
EXPECT_TRUE(converted);
}
class ConstAndNonConstCastable {
public:
ConstAndNonConstCastable(bool* converted, bool* const_converted)
: converted_(converted), const_converted_(const_converted) {}
operator Base() {
*converted_ = true;
return Base();
}
operator Base() const {
*const_converted_ = true;
return Base();
}
private:
bool* converted_;
bool* const_converted_;
};
TEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) {
bool converted = false;
bool const_converted = false;
ConstAndNonConstCastable castable(&converted, &const_converted);
Base base = ::testing::internal::ImplicitCast_<Base>(castable);
EXPECT_TRUE(converted);
EXPECT_FALSE(const_converted);
converted = false;
const_converted = false;
const ConstAndNonConstCastable const_castable(&converted, &const_converted);
base = ::testing::internal::ImplicitCast_<Base>(const_castable);
EXPECT_FALSE(converted);
EXPECT_TRUE(const_converted);
}
class To {
public:
To(bool* converted) { *converted = true; } // NOLINT
};
TEST(ImplicitCastTest, CanUseImplicitConstructor) {
bool converted = false;
To to = ::testing::internal::ImplicitCast_<To>(&converted);
(void)to;
EXPECT_TRUE(converted);
}
TEST(IteratorTraitsTest, WorksForSTLContainerIterators) {
StaticAssertTypeEq<int,
IteratorTraits< ::std::vector<int>::const_iterator>::value_type>();
StaticAssertTypeEq<bool,
IteratorTraits< ::std::list<bool>::iterator>::value_type>();
}
TEST(IteratorTraitsTest, WorksForPointerToNonConst) {
StaticAssertTypeEq<char, IteratorTraits<char*>::value_type>();
StaticAssertTypeEq<const void*, IteratorTraits<const void**>::value_type>();
}
TEST(IteratorTraitsTest, WorksForPointerToConst) {
StaticAssertTypeEq<char, IteratorTraits<const char*>::value_type>();
StaticAssertTypeEq<const void*,
IteratorTraits<const void* const*>::value_type>();
}
// Tests that the element_type typedef is available in scoped_ptr and refers
// to the parameter type.
TEST(ScopedPtrTest, DefinesElementType) {
StaticAssertTypeEq<int, ::testing::internal::scoped_ptr<int>::element_type>();
}
// TODO(vladl@google.com): Implement THE REST of scoped_ptr tests.
TEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {
if (AlwaysFalse())
GTEST_CHECK_(false) << "This should never be executed; "
"It's a compilation test only.";
if (AlwaysTrue())
GTEST_CHECK_(true);
else
; // NOLINT
if (AlwaysFalse())
; // NOLINT
else
GTEST_CHECK_(true) << "";
}
TEST(GtestCheckSyntaxTest, WorksWithSwitch) {
switch (0) {
case 1:
break;
default:
GTEST_CHECK_(true);
}
switch (0)
case 0:
GTEST_CHECK_(true) << "Check failed in switch case";
}
// Verifies behavior of FormatFileLocation.
TEST(FormatFileLocationTest, FormatsFileLocation) {
EXPECT_PRED_FORMAT2(IsSubstring, "foo.cc", FormatFileLocation("foo.cc", 42));
EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation("foo.cc", 42));
}
TEST(FormatFileLocationTest, FormatsUnknownFile) {
EXPECT_PRED_FORMAT2(
IsSubstring, "unknown file", FormatFileLocation(NULL, 42));
EXPECT_PRED_FORMAT2(IsSubstring, "42", FormatFileLocation(NULL, 42));
}
TEST(FormatFileLocationTest, FormatsUknownLine) {
EXPECT_EQ("foo.cc:", FormatFileLocation("foo.cc", -1));
}
TEST(FormatFileLocationTest, FormatsUknownFileAndLine) {
EXPECT_EQ("unknown file:", FormatFileLocation(NULL, -1));
}
// Verifies behavior of FormatCompilerIndependentFileLocation.
TEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {
EXPECT_EQ("foo.cc:42", FormatCompilerIndependentFileLocation("foo.cc", 42));
}
TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {
EXPECT_EQ("unknown file:42",
FormatCompilerIndependentFileLocation(NULL, 42));
}
TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {
EXPECT_EQ("foo.cc", FormatCompilerIndependentFileLocation("foo.cc", -1));
}
TEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {
EXPECT_EQ("unknown file", FormatCompilerIndependentFileLocation(NULL, -1));
}
#if GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_LINUX
void* ThreadFunc(void* data) {
pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(data);
pthread_mutex_lock(mutex);
pthread_mutex_unlock(mutex);
return NULL;
}
TEST(GetThreadCountTest, ReturnsCorrectValue) {
EXPECT_EQ(1U, GetThreadCount());
pthread_mutex_t mutex;
pthread_attr_t attr;
pthread_t thread_id;
// TODO(vladl@google.com): turn mutex into internal::Mutex for automatic
// destruction.
pthread_mutex_init(&mutex, NULL);
pthread_mutex_lock(&mutex);
ASSERT_EQ(0, pthread_attr_init(&attr));
ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));
const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);
ASSERT_EQ(0, pthread_attr_destroy(&attr));
ASSERT_EQ(0, status);
EXPECT_EQ(2U, GetThreadCount());
pthread_mutex_unlock(&mutex);
void* dummy;
ASSERT_EQ(0, pthread_join(thread_id, &dummy));
# if GTEST_OS_MAC || GTEST_OS_LINUX
// MacOS X and Linux may not immediately report the updated thread count after
// joining a thread, causing flakiness in this test. To counter that, we
// wait for up to .5 seconds for the OS to report the correct value.
for (int i = 0; i < 5; ++i) {
if (GetThreadCount() == 1)
break;
SleepMilliseconds(100);
}
# endif // GTEST_OS_MAC || GTEST_OS_LINUX
EXPECT_EQ(1U, GetThreadCount());
pthread_mutex_destroy(&mutex);
}
#else
TEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {
EXPECT_EQ(0U, GetThreadCount());
}
#endif // GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_LINUX
TEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {
const bool a_false_condition = false;
const char regex[] =
#ifdef _MSC_VER
"gtest-port_test\\.cc\\(\\d+\\):"
#elif GTEST_USES_POSIX_RE
"gtest-port_test\\.cc:[0-9]+"
#else
"gtest-port_test\\.cc:\\d+"
#endif // _MSC_VER
".*a_false_condition.*Extra info.*";
EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << "Extra info",
regex);
}
#if GTEST_HAS_DEATH_TEST
TEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {
EXPECT_EXIT({
GTEST_CHECK_(true) << "Extra info";
::std::cerr << "Success\n";
exit(0); },
::testing::ExitedWithCode(0), "Success");
}
#endif // GTEST_HAS_DEATH_TEST
// Verifies that Google Test choose regular expression engine appropriate to
// the platform. The test will produce compiler errors in case of failure.
// For simplicity, we only cover the most important platforms here.
TEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {
#if GTEST_HAS_POSIX_RE
EXPECT_TRUE(GTEST_USES_POSIX_RE);
#else
EXPECT_TRUE(GTEST_USES_SIMPLE_RE);
#endif
}
#if GTEST_USES_POSIX_RE
# if GTEST_HAS_TYPED_TEST
template <typename Str>
class RETest : public ::testing::Test {};
// Defines StringTypes as the list of all string types that class RE
// supports.
typedef testing::Types<
::std::string,
# if GTEST_HAS_GLOBAL_STRING
::string,
# endif // GTEST_HAS_GLOBAL_STRING
const char*> StringTypes;
TYPED_TEST_CASE(RETest, StringTypes);
// Tests RE's implicit constructors.
TYPED_TEST(RETest, ImplicitConstructorWorks) {
const RE empty(TypeParam(""));
EXPECT_STREQ("", empty.pattern());
const RE simple(TypeParam("hello"));
EXPECT_STREQ("hello", simple.pattern());
const RE normal(TypeParam(".*(\\w+)"));
EXPECT_STREQ(".*(\\w+)", normal.pattern());
}
// Tests that RE's constructors reject invalid regular expressions.
TYPED_TEST(RETest, RejectsInvalidRegex) {
EXPECT_NONFATAL_FAILURE({
const RE invalid(TypeParam("?"));
}, "\"?\" is not a valid POSIX Extended regular expression.");
}
// Tests RE::FullMatch().
TYPED_TEST(RETest, FullMatchWorks) {
const RE empty(TypeParam(""));
EXPECT_TRUE(RE::FullMatch(TypeParam(""), empty));
EXPECT_FALSE(RE::FullMatch(TypeParam("a"), empty));
const RE re(TypeParam("a.*z"));
EXPECT_TRUE(RE::FullMatch(TypeParam("az"), re));
EXPECT_TRUE(RE::FullMatch(TypeParam("axyz"), re));
EXPECT_FALSE(RE::FullMatch(TypeParam("baz"), re));
EXPECT_FALSE(RE::FullMatch(TypeParam("azy"), re));
}
// Tests RE::PartialMatch().
TYPED_TEST(RETest, PartialMatchWorks) {
const RE empty(TypeParam(""));
EXPECT_TRUE(RE::PartialMatch(TypeParam(""), empty));
EXPECT_TRUE(RE::PartialMatch(TypeParam("a"), empty));
const RE re(TypeParam("a.*z"));
EXPECT_TRUE(RE::PartialMatch(TypeParam("az"), re));
EXPECT_TRUE(RE::PartialMatch(TypeParam("axyz"), re));
EXPECT_TRUE(RE::PartialMatch(TypeParam("baz"), re));
EXPECT_TRUE(RE::PartialMatch(TypeParam("azy"), re));
EXPECT_FALSE(RE::PartialMatch(TypeParam("zza"), re));
}
# endif // GTEST_HAS_TYPED_TEST
#elif GTEST_USES_SIMPLE_RE
TEST(IsInSetTest, NulCharIsNotInAnySet) {
EXPECT_FALSE(IsInSet('\0', ""));
EXPECT_FALSE(IsInSet('\0', "\0"));
EXPECT_FALSE(IsInSet('\0', "a"));
}
TEST(IsInSetTest, WorksForNonNulChars) {
EXPECT_FALSE(IsInSet('a', "Ab"));
EXPECT_FALSE(IsInSet('c', ""));
EXPECT_TRUE(IsInSet('b', "bcd"));
EXPECT_TRUE(IsInSet('b', "ab"));
}
TEST(IsAsciiDigitTest, IsFalseForNonDigit) {
EXPECT_FALSE(IsAsciiDigit('\0'));
EXPECT_FALSE(IsAsciiDigit(' '));
EXPECT_FALSE(IsAsciiDigit('+'));
EXPECT_FALSE(IsAsciiDigit('-'));
EXPECT_FALSE(IsAsciiDigit('.'));
EXPECT_FALSE(IsAsciiDigit('a'));
}
TEST(IsAsciiDigitTest, IsTrueForDigit) {
EXPECT_TRUE(IsAsciiDigit('0'));
EXPECT_TRUE(IsAsciiDigit('1'));
EXPECT_TRUE(IsAsciiDigit('5'));
EXPECT_TRUE(IsAsciiDigit('9'));
}
TEST(IsAsciiPunctTest, IsFalseForNonPunct) {
EXPECT_FALSE(IsAsciiPunct('\0'));
EXPECT_FALSE(IsAsciiPunct(' '));
EXPECT_FALSE(IsAsciiPunct('\n'));
EXPECT_FALSE(IsAsciiPunct('a'));
EXPECT_FALSE(IsAsciiPunct('0'));
}
TEST(IsAsciiPunctTest, IsTrueForPunct) {
for (const char* p = "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"; *p; p++) {
EXPECT_PRED1(IsAsciiPunct, *p);
}
}
TEST(IsRepeatTest, IsFalseForNonRepeatChar) {
EXPECT_FALSE(IsRepeat('\0'));
EXPECT_FALSE(IsRepeat(' '));
EXPECT_FALSE(IsRepeat('a'));
EXPECT_FALSE(IsRepeat('1'));
EXPECT_FALSE(IsRepeat('-'));
}
TEST(IsRepeatTest, IsTrueForRepeatChar) {
EXPECT_TRUE(IsRepeat('?'));
EXPECT_TRUE(IsRepeat('*'));
EXPECT_TRUE(IsRepeat('+'));
}
TEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) {
EXPECT_FALSE(IsAsciiWhiteSpace('\0'));
EXPECT_FALSE(IsAsciiWhiteSpace('a'));
EXPECT_FALSE(IsAsciiWhiteSpace('1'));
EXPECT_FALSE(IsAsciiWhiteSpace('+'));
EXPECT_FALSE(IsAsciiWhiteSpace('_'));
}
TEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) {
EXPECT_TRUE(IsAsciiWhiteSpace(' '));
EXPECT_TRUE(IsAsciiWhiteSpace('\n'));
EXPECT_TRUE(IsAsciiWhiteSpace('\r'));
EXPECT_TRUE(IsAsciiWhiteSpace('\t'));
EXPECT_TRUE(IsAsciiWhiteSpace('\v'));
EXPECT_TRUE(IsAsciiWhiteSpace('\f'));
}
TEST(IsAsciiWordCharTest, IsFalseForNonWordChar) {
EXPECT_FALSE(IsAsciiWordChar('\0'));
EXPECT_FALSE(IsAsciiWordChar('+'));
EXPECT_FALSE(IsAsciiWordChar('.'));
EXPECT_FALSE(IsAsciiWordChar(' '));
EXPECT_FALSE(IsAsciiWordChar('\n'));
}
TEST(IsAsciiWordCharTest, IsTrueForLetter) {
EXPECT_TRUE(IsAsciiWordChar('a'));
EXPECT_TRUE(IsAsciiWordChar('b'));
EXPECT_TRUE(IsAsciiWordChar('A'));
EXPECT_TRUE(IsAsciiWordChar('Z'));
}
TEST(IsAsciiWordCharTest, IsTrueForDigit) {
EXPECT_TRUE(IsAsciiWordChar('0'));
EXPECT_TRUE(IsAsciiWordChar('1'));
EXPECT_TRUE(IsAsciiWordChar('7'));
EXPECT_TRUE(IsAsciiWordChar('9'));
}
TEST(IsAsciiWordCharTest, IsTrueForUnderscore) {
EXPECT_TRUE(IsAsciiWordChar('_'));
}
TEST(IsValidEscapeTest, IsFalseForNonPrintable) {
EXPECT_FALSE(IsValidEscape('\0'));
EXPECT_FALSE(IsValidEscape('\007'));
}
TEST(IsValidEscapeTest, IsFalseForDigit) {
EXPECT_FALSE(IsValidEscape('0'));
EXPECT_FALSE(IsValidEscape('9'));
}
TEST(IsValidEscapeTest, IsFalseForWhiteSpace) {
EXPECT_FALSE(IsValidEscape(' '));
EXPECT_FALSE(IsValidEscape('\n'));
}
TEST(IsValidEscapeTest, IsFalseForSomeLetter) {
EXPECT_FALSE(IsValidEscape('a'));
EXPECT_FALSE(IsValidEscape('Z'));
}
TEST(IsValidEscapeTest, IsTrueForPunct) {
EXPECT_TRUE(IsValidEscape('.'));
EXPECT_TRUE(IsValidEscape('-'));
EXPECT_TRUE(IsValidEscape('^'));
EXPECT_TRUE(IsValidEscape('$'));
EXPECT_TRUE(IsValidEscape('('));
EXPECT_TRUE(IsValidEscape(']'));
EXPECT_TRUE(IsValidEscape('{'));
EXPECT_TRUE(IsValidEscape('|'));
}
TEST(IsValidEscapeTest, IsTrueForSomeLetter) {
EXPECT_TRUE(IsValidEscape('d'));
EXPECT_TRUE(IsValidEscape('D'));
EXPECT_TRUE(IsValidEscape('s'));
EXPECT_TRUE(IsValidEscape('S'));
EXPECT_TRUE(IsValidEscape('w'));
EXPECT_TRUE(IsValidEscape('W'));
}
TEST(AtomMatchesCharTest, EscapedPunct) {
EXPECT_FALSE(AtomMatchesChar(true, '\\', '\0'));
EXPECT_FALSE(AtomMatchesChar(true, '\\', ' '));
EXPECT_FALSE(AtomMatchesChar(true, '_', '.'));
EXPECT_FALSE(AtomMatchesChar(true, '.', 'a'));
EXPECT_TRUE(AtomMatchesChar(true, '\\', '\\'));
EXPECT_TRUE(AtomMatchesChar(true, '_', '_'));
EXPECT_TRUE(AtomMatchesChar(true, '+', '+'));
EXPECT_TRUE(AtomMatchesChar(true, '.', '.'));
}
TEST(AtomMatchesCharTest, Escaped_d) {
EXPECT_FALSE(AtomMatchesChar(true, 'd', '\0'));
EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a'));
EXPECT_FALSE(AtomMatchesChar(true, 'd', '.'));
EXPECT_TRUE(AtomMatchesChar(true, 'd', '0'));
EXPECT_TRUE(AtomMatchesChar(true, 'd', '9'));
}
TEST(AtomMatchesCharTest, Escaped_D) {
EXPECT_FALSE(AtomMatchesChar(true, 'D', '0'));
EXPECT_FALSE(AtomMatchesChar(true, 'D', '9'));
EXPECT_TRUE(AtomMatchesChar(true, 'D', '\0'));
EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a'));
EXPECT_TRUE(AtomMatchesChar(true, 'D', '-'));
}
TEST(AtomMatchesCharTest, Escaped_s) {
EXPECT_FALSE(AtomMatchesChar(true, 's', '\0'));
EXPECT_FALSE(AtomMatchesChar(true, 's', 'a'));
EXPECT_FALSE(AtomMatchesChar(true, 's', '.'));
EXPECT_FALSE(AtomMatchesChar(true, 's', '9'));
EXPECT_TRUE(AtomMatchesChar(true, 's', ' '));
EXPECT_TRUE(AtomMatchesChar(true, 's', '\n'));
EXPECT_TRUE(AtomMatchesChar(true, 's', '\t'));
}
TEST(AtomMatchesCharTest, Escaped_S) {
EXPECT_FALSE(AtomMatchesChar(true, 'S', ' '));
EXPECT_FALSE(AtomMatchesChar(true, 'S', '\r'));
EXPECT_TRUE(AtomMatchesChar(true, 'S', '\0'));
EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a'));
EXPECT_TRUE(AtomMatchesChar(true, 'S', '9'));
}
TEST(AtomMatchesCharTest, Escaped_w) {
EXPECT_FALSE(AtomMatchesChar(true, 'w', '\0'));
EXPECT_FALSE(AtomMatchesChar(true, 'w', '+'));
EXPECT_FALSE(AtomMatchesChar(true, 'w', ' '));
EXPECT_FALSE(AtomMatchesChar(true, 'w', '\n'));
EXPECT_TRUE(AtomMatchesChar(true, 'w', '0'));
EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b'));
EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C'));
EXPECT_TRUE(AtomMatchesChar(true, 'w', '_'));
}
TEST(AtomMatchesCharTest, Escaped_W) {
EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A'));
EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b'));
EXPECT_FALSE(AtomMatchesChar(true, 'W', '9'));
EXPECT_FALSE(AtomMatchesChar(true, 'W', '_'));
EXPECT_TRUE(AtomMatchesChar(true, 'W', '\0'));
EXPECT_TRUE(AtomMatchesChar(true, 'W', '*'));
EXPECT_TRUE(AtomMatchesChar(true, 'W', '\n'));
}
TEST(AtomMatchesCharTest, EscapedWhiteSpace) {
EXPECT_FALSE(AtomMatchesChar(true, 'f', '\0'));
EXPECT_FALSE(AtomMatchesChar(true, 'f', '\n'));
EXPECT_FALSE(AtomMatchesChar(true, 'n', '\0'));
EXPECT_FALSE(AtomMatchesChar(true, 'n', '\r'));
EXPECT_FALSE(AtomMatchesChar(true, 'r', '\0'));
EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a'));
EXPECT_FALSE(AtomMatchesChar(true, 't', '\0'));
EXPECT_FALSE(AtomMatchesChar(true, 't', 't'));
EXPECT_FALSE(AtomMatchesChar(true, 'v', '\0'));
EXPECT_FALSE(AtomMatchesChar(true, 'v', '\f'));
EXPECT_TRUE(AtomMatchesChar(true, 'f', '\f'));
EXPECT_TRUE(AtomMatchesChar(true, 'n', '\n'));
EXPECT_TRUE(AtomMatchesChar(true, 'r', '\r'));
EXPECT_TRUE(AtomMatchesChar(true, 't', '\t'));
EXPECT_TRUE(AtomMatchesChar(true, 'v', '\v'));
}
TEST(AtomMatchesCharTest, UnescapedDot) {
EXPECT_FALSE(AtomMatchesChar(false, '.', '\n'));
EXPECT_TRUE(AtomMatchesChar(false, '.', '\0'));
EXPECT_TRUE(AtomMatchesChar(false, '.', '.'));
EXPECT_TRUE(AtomMatchesChar(false, '.', 'a'));
EXPECT_TRUE(AtomMatchesChar(false, '.', ' '));
}
TEST(AtomMatchesCharTest, UnescapedChar) {
EXPECT_FALSE(AtomMatchesChar(false, 'a', '\0'));
EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b'));
EXPECT_FALSE(AtomMatchesChar(false, '$', 'a'));
EXPECT_TRUE(AtomMatchesChar(false, '$', '$'));
EXPECT_TRUE(AtomMatchesChar(false, '5', '5'));
EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z'));
}
TEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)),
"NULL is not a valid simple regular expression");
EXPECT_NONFATAL_FAILURE(
ASSERT_FALSE(ValidateRegex("a\\")),
"Syntax error at index 1 in simple regular expression \"a\\\": ");
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a\\")),
"'\\' cannot appear at the end");
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\n\\")),
"'\\' cannot appear at the end");
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("\\s\\hb")),
"invalid escape sequence \"\\h\"");
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^^")),
"'^' can only appear at the beginning");
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(".*^b")),
"'^' can only appear at the beginning");
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("$$")),
"'$' can only appear at the end");
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^$a")),
"'$' can only appear at the end");
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a(b")),
"'(' is unsupported");
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("ab)")),
"')' is unsupported");
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("[ab")),
"'[' is unsupported");
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("a{2")),
"'{' is unsupported");
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("?")),
"'?' can only follow a repeatable token");
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("^*")),
"'*' can only follow a repeatable token");
EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex("5*+")),
"'+' can only follow a repeatable token");
}
TEST(ValidateRegexTest, ReturnsTrueForValid) {
EXPECT_TRUE(ValidateRegex(""));
EXPECT_TRUE(ValidateRegex("a"));
EXPECT_TRUE(ValidateRegex(".*"));
EXPECT_TRUE(ValidateRegex("^a_+"));
EXPECT_TRUE(ValidateRegex("^a\\t\\&?"));
EXPECT_TRUE(ValidateRegex("09*$"));
EXPECT_TRUE(ValidateRegex("^Z$"));
EXPECT_TRUE(ValidateRegex("a\\^Z\\$\\(\\)\\|\\[\\]\\{\\}"));
}
TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) {
EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "a", "ba"));
// Repeating more than once.
EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "aab"));
// Repeating zero times.
EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ba"));
// Repeating once.
EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', "b", "ab"));
EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', ".", "##"));
}
TEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) {
EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', "a$", "baab"));
// Repeating zero times.
EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "bc"));
// Repeating once.
EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', "b", "abc"));
// Repeating more than once.
EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', "-", "ab_1-g"));
}
TEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) {
EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "a$", "baab"));
// Repeating zero times.
EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "bc"));
// Repeating once.
EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', "b", "abc"));
// Repeating more than once.
EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', "-", "ab_1-g"));
}
TEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {
EXPECT_TRUE(MatchRegexAtHead("", ""));
EXPECT_TRUE(MatchRegexAtHead("", "ab"));
}
TEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {
EXPECT_FALSE(MatchRegexAtHead("$", "a"));
EXPECT_TRUE(MatchRegexAtHead("$", ""));
EXPECT_TRUE(MatchRegexAtHead("a$", "a"));
}
TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) {
EXPECT_FALSE(MatchRegexAtHead("\\w", "+"));
EXPECT_FALSE(MatchRegexAtHead("\\W", "ab"));
EXPECT_TRUE(MatchRegexAtHead("\\sa", "\nab"));
EXPECT_TRUE(MatchRegexAtHead("\\d", "1a"));
}
TEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {
EXPECT_FALSE(MatchRegexAtHead(".+a", "abc"));
EXPECT_FALSE(MatchRegexAtHead("a?b", "aab"));
EXPECT_TRUE(MatchRegexAtHead(".*a", "bc12-ab"));
EXPECT_TRUE(MatchRegexAtHead("a?b", "b"));
EXPECT_TRUE(MatchRegexAtHead("a?b", "ab"));
}
TEST(MatchRegexAtHeadTest,
WorksWhenRegexStartsWithRepetionOfEscapeSequence) {
EXPECT_FALSE(MatchRegexAtHead("\\.+a", "abc"));
EXPECT_FALSE(MatchRegexAtHead("\\s?b", " b"));
EXPECT_TRUE(MatchRegexAtHead("\\(*a", "((((ab"));
EXPECT_TRUE(MatchRegexAtHead("\\^?b", "^b"));
EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "b"));
EXPECT_TRUE(MatchRegexAtHead("\\\\?b", "\\b"));
}
TEST(MatchRegexAtHeadTest, MatchesSequentially) {
EXPECT_FALSE(MatchRegexAtHead("ab.*c", "acabc"));
EXPECT_TRUE(MatchRegexAtHead("ab.*c", "ab-fsc"));
}
TEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {
EXPECT_FALSE(MatchRegexAnywhere("", NULL));
}
TEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {
EXPECT_FALSE(MatchRegexAnywhere("^a", "ba"));
EXPECT_FALSE(MatchRegexAnywhere("^$", "a"));
EXPECT_TRUE(MatchRegexAnywhere("^a", "ab"));
EXPECT_TRUE(MatchRegexAnywhere("^", "ab"));
EXPECT_TRUE(MatchRegexAnywhere("^$", ""));
}
TEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {
EXPECT_FALSE(MatchRegexAnywhere("a", "bcde123"));
EXPECT_FALSE(MatchRegexAnywhere("a.+a", "--aa88888888"));
}
TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {
EXPECT_TRUE(MatchRegexAnywhere("\\w+", "ab1_ - 5"));
EXPECT_TRUE(MatchRegexAnywhere(".*=", "="));
EXPECT_TRUE(MatchRegexAnywhere("x.*ab?.*bc", "xaaabc"));
}
TEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {
EXPECT_TRUE(MatchRegexAnywhere("\\w+", "$$$ ab1_ - 5"));
EXPECT_TRUE(MatchRegexAnywhere("\\.+=", "= ...="));
}
// Tests RE's implicit constructors.
TEST(RETest, ImplicitConstructorWorks) {
const RE empty("");
EXPECT_STREQ("", empty.pattern());
const RE simple("hello");
EXPECT_STREQ("hello", simple.pattern());
}
// Tests that RE's constructors reject invalid regular expressions.
TEST(RETest, RejectsInvalidRegex) {
EXPECT_NONFATAL_FAILURE({
const RE normal(NULL);
}, "NULL is not a valid simple regular expression");
EXPECT_NONFATAL_FAILURE({
const RE normal(".*(\\w+");
}, "'(' is unsupported");
EXPECT_NONFATAL_FAILURE({
const RE invalid("^?");
}, "'?' can only follow a repeatable token");
}
// Tests RE::FullMatch().
TEST(RETest, FullMatchWorks) {
const RE empty("");
EXPECT_TRUE(RE::FullMatch("", empty));
EXPECT_FALSE(RE::FullMatch("a", empty));
const RE re1("a");
EXPECT_TRUE(RE::FullMatch("a", re1));
const RE re("a.*z");
EXPECT_TRUE(RE::FullMatch("az", re));
EXPECT_TRUE(RE::FullMatch("axyz", re));
EXPECT_FALSE(RE::FullMatch("baz", re));
EXPECT_FALSE(RE::FullMatch("azy", re));
}
// Tests RE::PartialMatch().
TEST(RETest, PartialMatchWorks) {
const RE empty("");
EXPECT_TRUE(RE::PartialMatch("", empty));
EXPECT_TRUE(RE::PartialMatch("a", empty));
const RE re("a.*z");
EXPECT_TRUE(RE::PartialMatch("az", re));
EXPECT_TRUE(RE::PartialMatch("axyz", re));
EXPECT_TRUE(RE::PartialMatch("baz", re));
EXPECT_TRUE(RE::PartialMatch("azy", re));
EXPECT_FALSE(RE::PartialMatch("zza", re));
}
#endif // GTEST_USES_POSIX_RE
#if !GTEST_OS_WINDOWS_MOBILE
TEST(CaptureTest, CapturesStdout) {
CaptureStdout();
fprintf(stdout, "abc");
EXPECT_STREQ("abc", GetCapturedStdout().c_str());
CaptureStdout();
fprintf(stdout, "def%cghi", '\0');
EXPECT_EQ(::std::string("def\0ghi", 7), ::std::string(GetCapturedStdout()));
}
TEST(CaptureTest, CapturesStderr) {
CaptureStderr();
fprintf(stderr, "jkl");
EXPECT_STREQ("jkl", GetCapturedStderr().c_str());
CaptureStderr();
fprintf(stderr, "jkl%cmno", '\0');
EXPECT_EQ(::std::string("jkl\0mno", 7), ::std::string(GetCapturedStderr()));
}
// Tests that stdout and stderr capture don't interfere with each other.
TEST(CaptureTest, CapturesStdoutAndStderr) {
CaptureStdout();
CaptureStderr();
fprintf(stdout, "pqr");
fprintf(stderr, "stu");
EXPECT_STREQ("pqr", GetCapturedStdout().c_str());
EXPECT_STREQ("stu", GetCapturedStderr().c_str());
}
TEST(CaptureDeathTest, CannotReenterStdoutCapture) {
CaptureStdout();
EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),
"Only one stdout capturer can exist at a time");
GetCapturedStdout();
// We cannot test stderr capturing using death tests as they use it
// themselves.
}
#endif // !GTEST_OS_WINDOWS_MOBILE
TEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {
ThreadLocal<int> t1;
EXPECT_EQ(0, t1.get());
ThreadLocal<void*> t2;
EXPECT_TRUE(t2.get() == NULL);
}
TEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {
ThreadLocal<int> t1(123);
EXPECT_EQ(123, t1.get());
int i = 0;
ThreadLocal<int*> t2(&i);
EXPECT_EQ(&i, t2.get());
}
class NoDefaultContructor {
public:
explicit NoDefaultContructor(const char*) {}
NoDefaultContructor(const NoDefaultContructor&) {}
};
TEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {
ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor("foo"));
bar.pointer();
}
TEST(ThreadLocalTest, GetAndPointerReturnSameValue) {
ThreadLocal<std::string> thread_local_string;
EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
// Verifies the condition still holds after calling set.
thread_local_string.set("foo");
EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));
}
TEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {
ThreadLocal<std::string> thread_local_string;
const ThreadLocal<std::string>& const_thread_local_string =
thread_local_string;
EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
thread_local_string.set("foo");
EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());
}
#if GTEST_IS_THREADSAFE
void AddTwo(int* param) { *param += 2; }
TEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {
int i = 40;
ThreadWithParam<int*> thread(&AddTwo, &i, NULL);
thread.Join();
EXPECT_EQ(42, i);
}
TEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {
// AssertHeld() is flaky only in the presence of multiple threads accessing
// the lock. In this case, the test is robust.
EXPECT_DEATH_IF_SUPPORTED({
Mutex m;
{ MutexLock lock(&m); }
m.AssertHeld();
},
"thread .*hold");
}
TEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {
Mutex m;
MutexLock lock(&m);
m.AssertHeld();
}
class AtomicCounterWithMutex {
public:
explicit AtomicCounterWithMutex(Mutex* mutex) :
value_(0), mutex_(mutex), random_(42) {}
void Increment() {
MutexLock lock(mutex_);
int temp = value_;
{
// Locking a mutex puts up a memory barrier, preventing reads and
// writes to value_ rearranged when observed from other threads.
//
// We cannot use Mutex and MutexLock here or rely on their memory
// barrier functionality as we are testing them here.
pthread_mutex_t memory_barrier_mutex;
GTEST_CHECK_POSIX_SUCCESS_(
pthread_mutex_init(&memory_barrier_mutex, NULL));
GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));
SleepMilliseconds(random_.Generate(30));
GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));
GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));
}
value_ = temp + 1;
}
int value() const { return value_; }
private:
volatile int value_;
Mutex* const mutex_; // Protects value_.
Random random_;
};
void CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {
for (int i = 0; i < param.second; ++i)
param.first->Increment();
}
// Tests that the mutex only lets one thread at a time to lock it.
TEST(MutexTest, OnlyOneThreadCanLockAtATime) {
Mutex mutex;
AtomicCounterWithMutex locked_counter(&mutex);
typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;
const int kCycleCount = 20;
const int kThreadCount = 7;
scoped_ptr<ThreadType> counting_threads[kThreadCount];
Notification threads_can_start;
// Creates and runs kThreadCount threads that increment locked_counter
// kCycleCount times each.
for (int i = 0; i < kThreadCount; ++i) {
counting_threads[i].reset(new ThreadType(&CountingThreadFunc,
make_pair(&locked_counter,
kCycleCount),
&threads_can_start));
}
threads_can_start.Notify();
for (int i = 0; i < kThreadCount; ++i)
counting_threads[i]->Join();
// If the mutex lets more than one thread to increment the counter at a
// time, they are likely to encounter a race condition and have some
// increments overwritten, resulting in the lower then expected counter
// value.
EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());
}
template <typename T>
void RunFromThread(void (func)(T), T param) {
ThreadWithParam<T> thread(func, param, NULL);
thread.Join();
}
void RetrieveThreadLocalValue(
pair<ThreadLocal<std::string>*, std::string*> param) {
*param.second = param.first->get();
}
TEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {
ThreadLocal<std::string> thread_local_string("foo");
EXPECT_STREQ("foo", thread_local_string.get().c_str());
thread_local_string.set("bar");
EXPECT_STREQ("bar", thread_local_string.get().c_str());
std::string result;
RunFromThread(&RetrieveThreadLocalValue,
make_pair(&thread_local_string, &result));
EXPECT_STREQ("foo", result.c_str());
}
// DestructorTracker keeps track of whether its instances have been
// destroyed.
static std::vector<bool> g_destroyed;
class DestructorTracker {
public:
DestructorTracker() : index_(GetNewIndex()) {}
DestructorTracker(const DestructorTracker& /* rhs */)
: index_(GetNewIndex()) {}
~DestructorTracker() {
// We never access g_destroyed concurrently, so we don't need to
// protect the write operation under a mutex.
g_destroyed[index_] = true;
}
private:
static int GetNewIndex() {
g_destroyed.push_back(false);
return g_destroyed.size() - 1;
}
const int index_;
};
typedef ThreadLocal<DestructorTracker>* ThreadParam;
void CallThreadLocalGet(ThreadParam thread_local_param) {
thread_local_param->get();
}
// Tests that when a ThreadLocal object dies in a thread, it destroys
// the managed object for that thread.
TEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {
g_destroyed.clear();
{
// The next line default constructs a DestructorTracker object as
// the default value of objects managed by thread_local_tracker.
ThreadLocal<DestructorTracker> thread_local_tracker;
ASSERT_EQ(1U, g_destroyed.size());
ASSERT_FALSE(g_destroyed[0]);
// This creates another DestructorTracker object for the main thread.
thread_local_tracker.get();
ASSERT_EQ(2U, g_destroyed.size());
ASSERT_FALSE(g_destroyed[0]);
ASSERT_FALSE(g_destroyed[1]);
}
// Now thread_local_tracker has died. It should have destroyed both the
// default value shared by all threads and the value for the main
// thread.
ASSERT_EQ(2U, g_destroyed.size());
EXPECT_TRUE(g_destroyed[0]);
EXPECT_TRUE(g_destroyed[1]);
g_destroyed.clear();
}
// Tests that when a thread exits, the thread-local object for that
// thread is destroyed.
TEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {
g_destroyed.clear();
{
// The next line default constructs a DestructorTracker object as
// the default value of objects managed by thread_local_tracker.
ThreadLocal<DestructorTracker> thread_local_tracker;
ASSERT_EQ(1U, g_destroyed.size());
ASSERT_FALSE(g_destroyed[0]);
// This creates another DestructorTracker object in the new thread.
ThreadWithParam<ThreadParam> thread(
&CallThreadLocalGet, &thread_local_tracker, NULL);
thread.Join();
// Now the new thread has exited. The per-thread object for it
// should have been destroyed.
ASSERT_EQ(2U, g_destroyed.size());
ASSERT_FALSE(g_destroyed[0]);
ASSERT_TRUE(g_destroyed[1]);
}
// Now thread_local_tracker has died. The default value should have been
// destroyed too.
ASSERT_EQ(2U, g_destroyed.size());
EXPECT_TRUE(g_destroyed[0]);
EXPECT_TRUE(g_destroyed[1]);
g_destroyed.clear();
}
TEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {
ThreadLocal<std::string> thread_local_string;
thread_local_string.set("Foo");
EXPECT_STREQ("Foo", thread_local_string.get().c_str());
std::string result;
RunFromThread(&RetrieveThreadLocalValue,
make_pair(&thread_local_string, &result));
EXPECT_TRUE(result.empty());
}
#endif // GTEST_IS_THREADSAFE
} // namespace internal
} // namespace testing
|
[
"kai.wolf@gmail.com"
] |
kai.wolf@gmail.com
|
5fddedf0b6ef257bf775fc8730d514eddcea70c4
|
7597b69c2b1a785d3d622e254c953fc129c9746d
|
/libcryptopp/include/modes.h
|
5a30fd84be77dd56e129073376ea2231f1eb30fc
|
[] |
no_license
|
wonlake/ThirdPartyLib
|
2f38cc806b946c24032e60f053cf370575029d05
|
6b11d060300bb4beb2f8e4cf0fe8af0a85d2de3e
|
refs/heads/master
| 2022-05-09T21:04:13.036440
| 2022-04-18T13:33:14
| 2022-04-18T13:33:14
| 116,561,211
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 21,685
|
h
|
// modes.h - originally written and placed in the public domain by Wei Dai
//! \file modes.h
//! \brief Classes for block cipher modes of operation
#ifndef CRYPTOPP_MODES_H
#define CRYPTOPP_MODES_H
#include "cryptlib.h"
#include "secblock.h"
#include "misc.h"
#include "strciphr.h"
#include "argnames.h"
#include "algparam.h"
// Issue 340
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wsign-conversion"
#endif
#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 4231 4275)
# if (CRYPTOPP_MSC_VERSION >= 1400)
# pragma warning(disable: 6011 6386 28193)
# endif
#endif
NAMESPACE_BEGIN(CryptoPP)
//! \class CipherModeDocumentation
//! \brief Block cipher mode of operation information
//! \details Each class derived from this one defines two types, Encryption and Decryption,
//! both of which implement the SymmetricCipher interface.
//! For each mode there are two classes, one of which is a template class,
//! and the other one has a name that ends in "_ExternalCipher".
//! The "external cipher" mode objects hold a reference to the underlying block cipher,
//! instead of holding an instance of it. The reference must be passed in to the constructor.
//! For the "cipher holder" classes, the CIPHER template parameter should be a class
//! derived from BlockCipherDocumentation, for example DES or AES.
//! \details See NIST SP 800-38A for definitions of these modes. See
//! AuthenticatedSymmetricCipherDocumentation for authenticated encryption modes.
struct CipherModeDocumentation : public SymmetricCipherDocumentation
{
};
//! \class CipherModeBase
//! \brief Block cipher mode of operation information
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CipherModeBase : public SymmetricCipher
{
public:
virtual ~CipherModeBase() {}
size_t MinKeyLength() const {return m_cipher->MinKeyLength();}
size_t MaxKeyLength() const {return m_cipher->MaxKeyLength();}
size_t DefaultKeyLength() const {return m_cipher->DefaultKeyLength();}
size_t GetValidKeyLength(size_t n) const {return m_cipher->GetValidKeyLength(n);}
bool IsValidKeyLength(size_t n) const {return m_cipher->IsValidKeyLength(n);}
unsigned int OptimalDataAlignment() const {return m_cipher->OptimalDataAlignment();}
unsigned int IVSize() const {return BlockSize();}
virtual IV_Requirement IVRequirement() const =0;
void SetCipher(BlockCipher &cipher)
{
this->ThrowIfResynchronizable();
this->m_cipher = &cipher;
this->ResizeBuffers();
}
void SetCipherWithIV(BlockCipher &cipher, const byte *iv, int feedbackSize = 0)
{
this->ThrowIfInvalidIV(iv);
this->m_cipher = &cipher;
this->ResizeBuffers();
this->SetFeedbackSize(feedbackSize);
if (this->IsResynchronizable())
this->Resynchronize(iv);
}
protected:
CipherModeBase() : m_cipher(NULLPTR) {}
inline unsigned int BlockSize() const {CRYPTOPP_ASSERT(m_register.size() > 0); return (unsigned int)m_register.size();}
virtual void SetFeedbackSize(unsigned int feedbackSize)
{
if (!(feedbackSize == 0 || feedbackSize == BlockSize()))
throw InvalidArgument("CipherModeBase: feedback size cannot be specified for this cipher mode");
}
virtual void ResizeBuffers();
BlockCipher *m_cipher;
AlignedSecByteBlock m_register;
};
//! \class ModePolicyCommonTemplate
//! \brief Block cipher mode of operation common operations
//! \tparam POLICY_INTERFACE common operations
template <class POLICY_INTERFACE>
class CRYPTOPP_NO_VTABLE ModePolicyCommonTemplate : public CipherModeBase, public POLICY_INTERFACE
{
unsigned int GetAlignment() const {return m_cipher->OptimalDataAlignment();}
void CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length);
};
template <class POLICY_INTERFACE>
void ModePolicyCommonTemplate<POLICY_INTERFACE>::CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length)
{
m_cipher->SetKey(key, length, params);
ResizeBuffers();
int feedbackSize = params.GetIntValueWithDefault(Name::FeedbackSize(), 0);
SetFeedbackSize(feedbackSize);
}
//! \class CFB_ModePolicy
//! \brief CFB block cipher mode of operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CFB_ModePolicy : public ModePolicyCommonTemplate<CFB_CipherAbstractPolicy>
{
public:
CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "CFB";}
virtual ~CFB_ModePolicy() {}
IV_Requirement IVRequirement() const {return RANDOM_IV;}
protected:
unsigned int GetBytesPerIteration() const {return m_feedbackSize;}
byte * GetRegisterBegin() {return m_register + BlockSize() - m_feedbackSize;}
bool CanIterate() const {return m_feedbackSize == BlockSize();}
void Iterate(byte *output, const byte *input, CipherDir dir, size_t iterationCount);
void TransformRegister();
void CipherResynchronize(const byte *iv, size_t length);
void SetFeedbackSize(unsigned int feedbackSize);
void ResizeBuffers();
SecByteBlock m_temp;
unsigned int m_feedbackSize;
};
inline void CopyOrZero(void *dest, size_t d, const void *src, size_t s)
{
CRYPTOPP_ASSERT(dest);
CRYPTOPP_ASSERT(d >= s);
if (src)
memcpy_s(dest, d, src, s);
else
memset(dest, 0, d);
}
//! \class OFB_ModePolicy
//! \brief OFB block cipher mode of operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE OFB_ModePolicy : public ModePolicyCommonTemplate<AdditiveCipherAbstractPolicy>
{
public:
CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "OFB";}
bool CipherIsRandomAccess() const {return false;}
IV_Requirement IVRequirement() const {return UNIQUE_IV;}
private:
unsigned int GetBytesPerIteration() const {return BlockSize();}
unsigned int GetIterationsToBuffer() const {return m_cipher->OptimalNumberOfParallelBlocks();}
void WriteKeystream(byte *keystreamBuffer, size_t iterationCount);
void CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length);
};
//! \class CTR_ModePolicy
//! \brief CTR block cipher mode of operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CTR_ModePolicy : public ModePolicyCommonTemplate<AdditiveCipherAbstractPolicy>
{
public:
CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "CTR";}
virtual ~CTR_ModePolicy() {}
bool CipherIsRandomAccess() const {return true;}
IV_Requirement IVRequirement() const {return RANDOM_IV;}
protected:
virtual void IncrementCounterBy256();
unsigned int GetAlignment() const {return m_cipher->OptimalDataAlignment();}
unsigned int GetBytesPerIteration() const {return BlockSize();}
unsigned int GetIterationsToBuffer() const {return m_cipher->OptimalNumberOfParallelBlocks();}
void WriteKeystream(byte *buffer, size_t iterationCount)
{OperateKeystream(WRITE_KEYSTREAM, buffer, NULLPTR, iterationCount);}
bool CanOperateKeystream() const {return true;}
void OperateKeystream(KeystreamOperation operation, byte *output, const byte *input, size_t iterationCount);
void CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length);
void SeekToIteration(lword iterationCount);
AlignedSecByteBlock m_counterArray;
};
//! \class BlockOrientedCipherModeBase
//! \brief Block cipher mode of operation default implementation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockOrientedCipherModeBase : public CipherModeBase
{
public:
virtual ~BlockOrientedCipherModeBase() {}
void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms);
unsigned int MandatoryBlockSize() const {return BlockSize();}
bool IsRandomAccess() const {return false;}
bool IsSelfInverting() const {return false;}
bool IsForwardTransformation() const {return m_cipher->IsForwardTransformation();}
void Resynchronize(const byte *iv, int length=-1) {memcpy_s(m_register, m_register.size(), iv, ThrowIfInvalidIVLength(length));}
protected:
bool RequireAlignedInput() const {return true;}
virtual void ResizeBuffers();
SecByteBlock m_buffer;
};
//! \class ECB_OneWay
//! \brief ECB block cipher mode of operation default implementation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ECB_OneWay : public BlockOrientedCipherModeBase
{
public:
CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECB";}
void SetKey(const byte *key, size_t length, const NameValuePairs ¶ms = g_nullNameValuePairs)
{m_cipher->SetKey(key, length, params); BlockOrientedCipherModeBase::ResizeBuffers();}
IV_Requirement IVRequirement() const {return NOT_RESYNCHRONIZABLE;}
unsigned int OptimalBlockSize() const {return BlockSize() * m_cipher->OptimalNumberOfParallelBlocks();}
void ProcessData(byte *outString, const byte *inString, size_t length);
};
//! \class CBC_ModeBase
//! \brief CBC block cipher mode of operation default implementation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_ModeBase : public BlockOrientedCipherModeBase
{
public:
CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "CBC";}
IV_Requirement IVRequirement() const {return UNPREDICTABLE_RANDOM_IV;}
bool RequireAlignedInput() const {return false;}
unsigned int MinLastBlockSize() const {return 0;}
};
//! \class CBC_Encryption
//! \brief CBC block cipher mode of operation encryption operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_Encryption : public CBC_ModeBase
{
public:
void ProcessData(byte *outString, const byte *inString, size_t length);
};
//! \class CBC_CTS_Encryption
//! \brief CBC-CTS block cipher mode of operation encryption operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_CTS_Encryption : public CBC_Encryption
{
public:
CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "CBC/CTS";}
void SetStolenIV(byte *iv) {m_stolenIV = iv;}
unsigned int MinLastBlockSize() const {return BlockSize()+1;}
size_t ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength);
protected:
void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms)
{
CBC_Encryption::UncheckedSetKey(key, length, params);
m_stolenIV = params.GetValueWithDefault(Name::StolenIV(), (byte *)NULLPTR);
}
byte *m_stolenIV;
};
//! \class CBC_Decryption
//! \brief CBC block cipher mode of operation decryption operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_Decryption : public CBC_ModeBase
{
public:
virtual ~CBC_Decryption() {}
void ProcessData(byte *outString, const byte *inString, size_t length);
protected:
virtual void ResizeBuffers();
AlignedSecByteBlock m_temp;
};
//! \class CBC_CTS_Decryption
//! \brief CBC-CTS block cipher mode of operation decryption operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_CTS_Decryption : public CBC_Decryption
{
public:
unsigned int MinLastBlockSize() const {return BlockSize()+1;}
size_t ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength);
};
//! \class CipherModeFinalTemplate_CipherHolder
//! \brief Block cipher mode of operation aggregate
template <class CIPHER, class BASE>
class CipherModeFinalTemplate_CipherHolder : protected ObjectHolder<CIPHER>, public AlgorithmImpl<BASE, CipherModeFinalTemplate_CipherHolder<CIPHER, BASE> >
{
public:
static std::string CRYPTOPP_API StaticAlgorithmName()
{return CIPHER::StaticAlgorithmName() + "/" + BASE::StaticAlgorithmName();}
CipherModeFinalTemplate_CipherHolder()
{
this->m_cipher = &this->m_object;
this->ResizeBuffers();
}
CipherModeFinalTemplate_CipherHolder(const byte *key, size_t length)
{
this->m_cipher = &this->m_object;
this->SetKey(key, length);
}
CipherModeFinalTemplate_CipherHolder(const byte *key, size_t length, const byte *iv)
{
this->m_cipher = &this->m_object;
this->SetKey(key, length, MakeParameters(Name::IV(), ConstByteArrayParameter(iv, this->m_cipher->BlockSize())));
}
CipherModeFinalTemplate_CipherHolder(const byte *key, size_t length, const byte *iv, int feedbackSize)
{
this->m_cipher = &this->m_object;
this->SetKey(key, length, MakeParameters(Name::IV(), ConstByteArrayParameter(iv, this->m_cipher->BlockSize()))(Name::FeedbackSize(), feedbackSize));
}
};
//! \class CipherModeFinalTemplate_ExternalCipher
//! \tparam BASE CipherModeFinalTemplate_CipherHolder base class
//! \details Base class for external mode cipher combinations
template <class BASE>
class CipherModeFinalTemplate_ExternalCipher : public BASE
{
public:
CipherModeFinalTemplate_ExternalCipher() {}
CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher)
{this->SetCipher(cipher);}
CipherModeFinalTemplate_ExternalCipher(BlockCipher &cipher, const byte *iv, int feedbackSize = 0)
{this->SetCipherWithIV(cipher, iv, feedbackSize);}
std::string AlgorithmName() const
{return (this->m_cipher ? this->m_cipher->AlgorithmName() + "/" : std::string("")) + BASE::StaticAlgorithmName();}
};
CRYPTOPP_DLL_TEMPLATE_CLASS CFB_CipherTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >;
CRYPTOPP_DLL_TEMPLATE_CLASS CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >;
CRYPTOPP_DLL_TEMPLATE_CLASS CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >;
//! \class CFB_Mode
//! \brief CFB block cipher mode of operation
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki.
template <class CIPHER>
struct CFB_Mode : public CipherModeDocumentation
{
typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Encryption;
typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Decryption;
};
//! \class CFB_Mode_ExternalCipher
//! \brief CFB mode, external cipher.
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki.
struct CFB_Mode_ExternalCipher : public CipherModeDocumentation
{
typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Encryption;
typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Decryption;
};
//! \class CFB_FIPS_Mode
//! \brief CFB block cipher mode of operation providing FIPS validated cryptography.
//! \details Requires full block plaintext according to FIPS 800-38A
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki.
template <class CIPHER>
struct CFB_FIPS_Mode : public CipherModeDocumentation
{
typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, CFB_RequireFullDataBlocks<CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > > Encryption;
typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, CFB_RequireFullDataBlocks<CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > > Decryption;
};
//! \class CFB_FIPS_Mode_ExternalCipher
//! \brief CFB mode, external cipher, providing FIPS validated cryptography.
//! \details Requires full block plaintext according to FIPS 800-38A
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki.
struct CFB_FIPS_Mode_ExternalCipher : public CipherModeDocumentation
{
typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_RequireFullDataBlocks<CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > > Encryption;
typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_RequireFullDataBlocks<CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > > Decryption;
};
CRYPTOPP_DLL_TEMPLATE_CLASS AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, OFB_ModePolicy> >;
//! \class OFB_Mode
//! \brief OFB block cipher mode of operation
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki.
template <class CIPHER>
struct OFB_Mode : public CipherModeDocumentation
{
typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, OFB_ModePolicy> > > > Encryption;
typedef Encryption Decryption;
};
//! \class OFB_Mode_ExternalCipher
//! \brief OFB mode, external cipher.
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki.
struct OFB_Mode_ExternalCipher : public CipherModeDocumentation
{
typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, OFB_ModePolicy> > > > Encryption;
typedef Encryption Decryption;
};
CRYPTOPP_DLL_TEMPLATE_CLASS AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> >;
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> > > >;
//! \class CTR_Mode
//! \brief CTR block cipher mode of operation
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki.
template <class CIPHER>
struct CTR_Mode : public CipherModeDocumentation
{
typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> > > > Encryption;
typedef Encryption Decryption;
};
//! \class CTR_Mode_ExternalCipher
//! \brief CTR mode, external cipher.
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki.
struct CTR_Mode_ExternalCipher : public CipherModeDocumentation
{
typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> > > > Encryption;
typedef Encryption Decryption;
};
//! \class ECB_Mode
//! \brief ECB block cipher mode of operation
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki.
template <class CIPHER>
struct ECB_Mode : public CipherModeDocumentation
{
typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ECB_OneWay> Encryption;
typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Decryption, ECB_OneWay> Decryption;
};
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<ECB_OneWay>;
//! \class ECB_Mode_ExternalCipher
//! \brief ECB mode, external cipher.
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki.
struct ECB_Mode_ExternalCipher : public CipherModeDocumentation
{
typedef CipherModeFinalTemplate_ExternalCipher<ECB_OneWay> Encryption;
typedef Encryption Decryption;
};
//! \class CBC_Mode
//! \brief CBC block cipher mode of operation
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki.
template <class CIPHER>
struct CBC_Mode : public CipherModeDocumentation
{
typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, CBC_Encryption> Encryption;
typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Decryption, CBC_Decryption> Decryption;
};
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_Encryption>;
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_Decryption>;
//! \class CBC_Mode_ExternalCipher
//! \brief CBC mode, external cipher
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki.
struct CBC_Mode_ExternalCipher : public CipherModeDocumentation
{
typedef CipherModeFinalTemplate_ExternalCipher<CBC_Encryption> Encryption;
typedef CipherModeFinalTemplate_ExternalCipher<CBC_Decryption> Decryption;
};
//! \class CBC_CTS_Mode
//! \brief CBC-CTS block cipher mode of operation
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki.
template <class CIPHER>
struct CBC_CTS_Mode : public CipherModeDocumentation
{
typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, CBC_CTS_Encryption> Encryption;
typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Decryption, CBC_CTS_Decryption> Decryption;
};
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Encryption>;
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Decryption>;
//! \class CBC_CTS_Mode_ExternalCipher
//! \brief CBC mode with ciphertext stealing, external cipher
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki.
struct CBC_CTS_Mode_ExternalCipher : public CipherModeDocumentation
{
typedef CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Encryption> Encryption;
typedef CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Decryption> Decryption;
};
NAMESPACE_END
// Issue 340
#if CRYPTOPP_MSC_VERSION
# pragma warning(pop)
#endif
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic pop
#endif
#endif
|
[
"mei_jun1999@126.com"
] |
mei_jun1999@126.com
|
d91740406ecea008d4fcb209e5ce55363fd5e195
|
08eacc2c591fc45310c8bf697abe9464fb87cd74
|
/atcoder/abc/abc179/d.cpp
|
0a515089398c0725cb28b53d4b45b9aedceb70d6
|
[] |
no_license
|
urashima0429/keipro_practice
|
1074266ee5b0de7002f5c540650a9f8543b0a53c
|
364d28502e53c6679ea81bc40fb80e6a022bbf8d
|
refs/heads/master
| 2021-06-14T23:42:11.242546
| 2021-03-16T06:21:36
| 2021-03-16T06:21:36
| 169,205,471
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,007
|
cpp
|
#include <iostream>
using namespace std;
typedef long long ll;
const ll MOD = 998244353;
const int MAX_N = 200010;
int N, K;
ll bit[MAX_N];
ll sum (int i){
ll s = 0;
while(i > 0){
s = (s + bit[i]) % MOD;
i -= i & -i;
}
return s;
}
void add (int i, ll x){
while(i <= N){
bit[i] = (bit[i] + x) % MOD;
i += i & -i;
}
}
int main(){
int L[12], R[12];
cin >> N >> K;
for (int i = 0; i < K; ++i){
cin >> L[i] >> R[i];
}
for (int i = 1; i < N; ++i){
ll s = 0;
for (int j = 0; j < K; ++j){
s = ( s + sum( max(0, i-L[j]) )) % MOD;
s = ( s - sum( max(0, i-R[j]-1))) % MOD;
if (L[j] <= i && i <= R[j]) {
s = (s + 1) % MOD;
}
}
add(i, (s + MOD) % MOD);
}
ll ans = sum(N-1) - sum(N-2);
ans = ans % MOD;
ans = ans + MOD;
ans = ans % MOD;
cout << ans << endl;
}
|
[
"urashima0429@gmail.com"
] |
urashima0429@gmail.com
|
580b38d9f6501963d0253c8079be95b7ab3d3d43
|
4e1f1eb081d177a607ea6f335978676546f6779e
|
/Exercice5_Liste_Distribuee/ListeDoublementChainee.cpp
|
69b8273917c36af9f3a74f69f8862256b06a988f
|
[] |
no_license
|
BenjaminLaschkar/Devoir1_Structure_de_donnee
|
f3f4e6feefae5ed24a41b2ae9a450bdd583df036
|
8e04321d4660a0bd93f7671e66c6030c541d05e3
|
refs/heads/master
| 2021-09-15T07:26:15.249209
| 2018-05-28T15:11:40
| 2018-05-28T15:11:40
| 133,123,288
| 2
| 0
| null | null | null | null |
WINDOWS-1250
|
C++
| false
| false
| 2,272
|
cpp
|
#include "stdafx.h"
#include "ListeDoublementChainee.h"
#include <iostream>
using namespace std;
ListeDoublementChainee::ListeDoublementChainee(int i) {
debut = new Node(i, NULL, NULL);
debut->suivant = debut->precedent = debut;
taille = 1;
}
ListeDoublementChainee::~ListeDoublementChainee() {
Node *tmp = this->debut;
Node *temp;
while (tmp->precedent) { tmp = tmp->precedent; }
while (tmp) {
temp = tmp->suivant;
delete tmp;
tmp = temp;
}
tmp = temp = NULL;
}
bool ListeDoublementChainee::estVide() { return (this->taille == 0); }
bool ListeDoublementChainee::rechercheID(int cherche) {
int compteur = 0;
Node *tmp = debut;
while (tmp->suivant != debut) {
if (tmp->ID == cherche) compteur++;
tmp = tmp->suivant;
}
if (compteur > 0) {
cout << "'" << cherche << "' a été trouvé " << compteur << " fois." << endl;
return true;
} else {
cout << "'" << cherche << "' n'a pas été trouvé" << endl;
return false;
}
}
void ListeDoublementChainee::afficher(bool dir) {
if (dir) {
Node *tmp = debut;
do {
cout << tmp->ID;
tmp = tmp->precedent;
} while (tmp != debut);
} else {
Node *tmp = debut->suivant;
do {
cout << tmp->ID;
tmp = tmp->suivant;
} while (tmp != debut->suivant);
}
cout << endl;
}
void ListeDoublementChainee::ajouterID(int ID) { this->debut->ID = ID; }
void ListeDoublementChainee::ajouterPrecedent(Node* Precedent) { this->debut->precedent = Precedent; }
void ListeDoublementChainee::ajouterSuivant(Node* Suivant) { this->debut->suivant = Suivant; }
void ListeDoublementChainee::insertNodeApres(int i) {
Node *s = debut->suivant;
Node *p = debut;
Node *temp = new Node(i, p, s);
taille++;
}
void ListeDoublementChainee::insertNodeAvant(int i) {
Node *s = debut;
Node *p = debut->precedent;
Node *temp = new Node(i, p, s);
taille++;
}
void ListeDoublementChainee::supprimerID(int Cherche, bool all) { // si vrai, il supprime tous les noeuds comprenant la recherche
Node *tmp = debut; // si faux, il supprime uniquement le premier noeud
while (tmp) {
if (tmp->ID == Cherche) {
cout << "Suppression " << Cherche << endl;
tmp->precedent->suivant = tmp->suivant;
tmp->suivant->precedent = tmp->precedent;
if (false) return;
}
tmp = tmp->suivant;
}
}
|
[
"rendu.clement@gmail.com"
] |
rendu.clement@gmail.com
|
9ae17fb08ad291d1b43591e60be420e3a425cad1
|
bcf3265a67256c2b6483281232a15621cbfd8574
|
/Server/Src/LogicServer/Guild.h
|
61cb011b8006a2f53b4b618b59ce205c46b8c1e1
|
[] |
no_license
|
bbeyondllove/mmo_game_frame
|
ef7a7d7f68b86f080f5006d85535ad1b17b2ebb5
|
28cd973669f8ff42d35e227c728378817dc7afac
|
refs/heads/main
| 2023-04-07T16:10:45.758435
| 2021-04-06T04:37:12
| 2021-04-06T04:37:12
| 354,854,562
| 4
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 595
|
h
|
#ifndef __GUILD_HEADER_H__
#define __GUILD_HEADER_H__
#include "GuildData.h"
class CGuild
{
public:
CGuild();
~CGuild();
public:
BOOL Init();
BOOL LoadGuildMember(CppMySQLQuery& QueryResult);
CHAR* GetGuildName();
UINT64 GetGuildID();
MemberDataObject* GetGuildMember(UINT64 uID);
MemberDataObject* GetLeader();
MemberDataObject* AddGuildMember(UINT64 uRoleID);
BOOL BroadMessageToAll(UINT32 dwMsgID, const google::protobuf::Message& pdata);
public:
UINT64 m_u64LeaderID;
GuildDataObject* m_pGuildData;
std::map<UINT64, MemberDataObject*> m_mapMemberData;
};
#endif
|
[
"469841047@qq.com"
] |
469841047@qq.com
|
a62a8c79cd240b734108492d70157ee093d8bc2b
|
09a74d737490b78f51533e51e370a55e38692cbd
|
/NBMediaPlayer/src/decoder/NBMediaDecoder.h
|
bfcaddecee6df0907dac7265ef50d848b513b9cb
|
[
"MIT"
] |
permissive
|
zuohouwei/NewBlashPlayer
|
90b57076c9c0b142e338910a6b8d69e376ecf4c8
|
af2104ff143ea885ff7a6808aa12b65c12203c1f
|
refs/heads/master
| 2020-04-07T02:01:16.622611
| 2018-11-05T14:59:49
| 2018-11-05T14:59:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 716
|
h
|
//
// Created by parallels on 9/10/18.
//
#ifndef NBMEDIADECODER_H
#define NBMEDIADECODER_H
#include "NBMediaSource.h"
#include "foundation/NBMetaData.h"
class NBMediaDecoder {
public:
/** the audio decoder only support software
* the video decoder select hardware in auto mode
*/
enum {
NB_DECODER_FLAG_AUTO_SELECT = 0x01,
NB_DECODER_FLAG_FORCE_SOFTWARE = 0x02
};
public:
static NBMediaSource* Create(NBMetaData* metaData, NBMediaSource* mediaTrack, void* window, uint32_t flags = NB_DECODER_FLAG_AUTO_SELECT);
static void Destroy(NBMediaSource* mediaSource);
private:
NBMediaDecoder() {
}
~NBMediaDecoder() {
}
};
#endif //NBMEDIADECODER_H
|
[
"bobmarshall890120@gmail.com"
] |
bobmarshall890120@gmail.com
|
5cd5886998e446ffe7759056abb52355beeba99a
|
8dce1bf646ecd4512ee5725a42af0406b8f3ff87
|
/src/main.h
|
2300354b35e7283ac45cf729d7f30bb6dde31781
|
[
"MIT"
] |
permissive
|
forkee/FootyCash
|
746c2e7fb98a1ba6053e66ae49aac16ef2922723
|
693712e9a196d51020fa2d5a78a0cbc4f823e39a
|
refs/heads/master
| 2021-06-21T12:51:16.191353
| 2017-08-14T08:45:09
| 2017-08-14T08:45:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 38,630
|
h
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_MAIN_H
#define BITCOIN_MAIN_H
#include "core.h"
#include "bignum.h"
#include "sync.h"
#include "txmempool.h"
#include "net.h"
#include "script.h"
#include "scrypt.h"
#include <list>
class CBlock;
class CBlockIndex;
class CInv;
class CKeyItem;
class CNode;
class CReserveKey;
class CWallet;
/** The maximum allowed size for a serialized block, in bytes (network rule) */
static const unsigned int MAX_BLOCK_SIZE = 1000000;
/** The maximum size for mined blocks */
static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
/** The maximum size for transactions we're willing to relay/mine **/
static const unsigned int MAX_STANDARD_TX_SIZE = MAX_BLOCK_SIZE_GEN/5;
/** The maximum allowed number of signature check operations in a block (network rule) */
static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
/** Maxiumum number of signature check operations in an IsStandard() P2SH script */
static const unsigned int MAX_P2SH_SIGOPS = 15;
/** The maximum number of sigops we're willing to relay/mine in a single tx */
static const unsigned int MAX_TX_SIGOPS = MAX_BLOCK_SIGOPS/5;
/** The maximum number of orphan transactions kept in memory */
static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
/** Default for -maxorphanblocks, maximum number of orphan blocks kept in memory */
static const unsigned int DEFAULT_MAX_ORPHAN_BLOCKS = 750;
/** The maximum number of entries in an 'inv' protocol message */
static const unsigned int MAX_INV_SZ = 50000;
/** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */
static const int64_t MIN_TX_FEE = 10000;
/** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */
static const int64_t MIN_RELAY_TX_FEE = MIN_TX_FEE;
inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= Params().MaxMoney()); }
/** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
extern CScript COINBASE_FLAGS;
extern CCriticalSection cs_main;
extern CTxMemPool mempool;
extern std::map<uint256, CBlockIndex*> mapBlockIndex;
extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
extern CBlockIndex* pindexGenesisBlock;
extern unsigned int nNodeLifespan;
extern int nBestHeight;
extern uint256 nBestChainTrust;
extern uint256 nBestInvalidTrust;
extern uint256 hashBestChain;
extern CBlockIndex* pindexBest;
extern uint64_t nLastBlockTx;
extern uint64_t nLastBlockSize;
extern int64_t nLastCoinStakeSearchInterval;
extern const std::string strMessageMagic;
extern int64_t nTimeBestReceived;
extern bool fImporting;
extern bool fReindex;
struct COrphanBlock;
extern std::map<uint256, COrphanBlock*> mapOrphanBlocks;
extern bool fHaveGUI;
// Settings
extern bool fUseFastIndex;
extern unsigned int nDerivationMethodIndex;
extern bool fMinimizeCoinAge;
// Minimum disk space required - used in CheckDiskSpace()
static const uint64_t nMinDiskSpace = 52428800;
class CReserveKey;
class CTxDB;
class CTxIndex;
class CWalletInterface;
/** Register a wallet to receive updates from core */
void RegisterWallet(CWalletInterface* pwalletIn);
/** Unregister a wallet from core */
void UnregisterWallet(CWalletInterface* pwalletIn);
/** Unregister all wallets from core */
void UnregisterAllWallets();
/** Push an updated transaction to all registered wallets */
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fConnect = true);
/** Ask wallets to resend their transactions */
void ResendWalletTransactions(bool fForce = false);
/** Register with a network node to receive its signals */
void RegisterNodeSignals(CNodeSignals& nodeSignals);
/** Unregister a network node */
void UnregisterNodeSignals(CNodeSignals& nodeSignals);
void PushGetBlocks(CNode* pnode, CBlockIndex* pindexBegin, uint256 hashEnd);
bool ProcessBlock(CNode* pfrom, CBlock* pblock);
bool CheckDiskSpace(uint64_t nAdditionalBytes=0);
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
FILE* AppendBlockFile(unsigned int& nFileRet);
bool LoadBlockIndex(bool fAllowNew=true);
void PrintBlockTree();
CBlockIndex* FindBlockByHeight(int nHeight);
bool ProcessMessages(CNode* pfrom);
bool SendMessages(CNode* pto, bool fSendTrickle);
void ThreadImport(std::vector<boost::filesystem::path> vImportFiles);
bool CheckProofOfWork(uint256 hash, unsigned int nBits);
unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
int64_t GetProofOfWorkReward(int64_t nFees, int64_t nHeight);
int64_t GetProofOfStakeReward(const CBlockIndex* pindexPrev, Bignum nCoinAge, int64_t nFees, int64_t nHeight);
bool IsInitialBlockDownload();
bool IsConfirmedInNPrevBlocks(const CTxIndex& txindex, const CBlockIndex* pindexFrom, int nMaxDepth, int& nActualDepth);
std::string GetWarnings(std::string strFor);
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
uint256 WantedByOrphan(const COrphanBlock* pblockOrphan);
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
void ThreadStakeMiner(CWallet *pwallet);
/** (try to) add transaction to memory pool **/
bool AcceptToMemoryPool(CTxMemPool& pool, CTransaction &tx, bool fLimitFree,
bool* pfMissingInputs);
/** Position on disk for a particular transaction. */
class CDiskTxPos
{
public:
unsigned int nFile;
unsigned int nBlockPos;
unsigned int nTxPos;
CDiskTxPos()
{
SetNull();
}
CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
{
nFile = nFileIn;
nBlockPos = nBlockPosIn;
nTxPos = nTxPosIn;
}
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; }
bool IsNull() const { return (nFile == (unsigned int) -1); }
friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
{
return (a.nFile == b.nFile &&
a.nBlockPos == b.nBlockPos &&
a.nTxPos == b.nTxPos);
}
friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
{
return !(a == b);
}
std::string ToString() const
{
if (IsNull())
return "null";
else
return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos);
}
};
enum GetMinFee_mode
{
GMF_BLOCK,
GMF_RELAY,
GMF_SEND,
};
typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
int64_t GetMinFee(const CTransaction& tx, unsigned int nBlockSize = 1, enum GetMinFee_mode mode = GMF_BLOCK, unsigned int nBytes = 0);
/** The basic transaction that is broadcasted on the network and contained in
* blocks. A transaction can contain multiple inputs and outputs.
*/
class CTransaction
{
public:
static const int CURRENT_VERSION=1;
int nVersion;
unsigned int nTime;
std::vector<CTxIn> vin;
std::vector<CTxOut> vout;
unsigned int nLockTime;
// Denial-of-service detection:
mutable int nDoS;
bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
CTransaction()
{
SetNull();
}
CTransaction(int nVersion, unsigned int nTime, const std::vector<CTxIn>& vin, const std::vector<CTxOut>& vout, unsigned int nLockTime)
: nVersion(nVersion), nTime(nTime), vin(vin), vout(vout), nLockTime(nLockTime), nDoS(0)
{
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(nTime);
READWRITE(vin);
READWRITE(vout);
READWRITE(nLockTime);
)
void SetNull()
{
nVersion = CTransaction::CURRENT_VERSION;
nTime = GetAdjustedTime();
vin.clear();
vout.clear();
nLockTime = 0;
nDoS = 0; // Denial-of-service prevention
}
bool IsNull() const
{
return (vin.empty() && vout.empty());
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
}
bool IsCoinStake() const
{
// ppcoin: the coin stake transaction is marked with the first output empty
return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
}
/** Amount of bitcoins spent by this transaction.
@return sum of all outputs (note: does not include fees)
*/
int64_t GetValueOut() const
{
int64_t nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
nValueOut += txout.nValue;
if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
}
return nValueOut;
}
/** Amount of bitcoins coming in to this transaction
Note that lightweight clients may not know anything besides the hash of previous transactions,
so may not be able to calculate this.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return Sum of value of all inputs (scriptSigs)
@see CTransaction::FetchInputs
*/
int64_t GetValueIn(const MapPrevTx& mapInputs) const;
bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
{
CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
// Read transaction
if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
return error("CTransaction::ReadFromDisk() : fseek failed");
try {
filein >> *this;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Return file pointer
if (pfileRet)
{
if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
return error("CTransaction::ReadFromDisk() : second fseek failed");
*pfileRet = filein.release();
}
return true;
}
friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return (a.nVersion == b.nVersion &&
a.nTime == b.nTime &&
a.vin == b.vin &&
a.vout == b.vout &&
a.nLockTime == b.nLockTime);
}
friend bool operator!=(const CTransaction& a, const CTransaction& b)
{
return !(a == b);
}
std::string ToString() const
{
std::string str;
str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%d)\n",
GetHash().ToString(),
nTime,
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
bool ReadFromDisk(COutPoint prevout);
bool DisconnectInputs(CTxDB& txdb);
/** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
@param[in] txdb Transaction database
@param[in] mapTestPool List of pending changes to the transaction index database
@param[in] fBlock True if being called to add a new best-block to the chain
@param[in] fMiner True if being called by CreateNewBlock
@param[out] inputsRet Pointers to this transaction's inputs
@param[out] fInvalid returns true if transaction is invalid
@return Returns true if all inputs are in txdb or mapTestPool
*/
bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
/** Sanity check previous transactions, then, if all checks succeed,
mark them as spent by this transaction.
@param[in] inputs Previous transactions (from FetchInputs)
@param[out] mapTestPool Keeps track of inputs that need to be updated on disk
@param[in] posThisTx Position of this transaction on disk
@param[in] pindexBlock
@param[in] fBlock true if called from ConnectBlock
@param[in] fMiner true if called from CreateNewBlock
@return Returns true if all checks succeed
*/
bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, unsigned int flags = STANDARD_SCRIPT_VERIFY_FLAGS);
bool CheckTransaction() const;
bool GetCoinAge(CTxDB& txdb, const CBlockIndex* pindexPrev, uint64_t& nCoinAge) const;
const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
};
/** wrapper for CTxOut that provides a more compact serialization */
class CTxOutCompressor
{
private:
CTxOut &txout;
public:
CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
IMPLEMENT_SERIALIZE(
READWRITE(VARINT(txout.nValue));
CScriptCompressor cscript(REF(txout.scriptPubKey));
READWRITE(cscript);
)
};
/** Check for standard transaction types
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return True if all inputs (scriptSigs) use only standard transaction forms
@see CTransaction::FetchInputs
*/
bool AreInputsStandard(const CTransaction& tx, const MapPrevTx& mapInputs);
/** Count ECDSA signature operations the old-fashioned (pre-0.6) way
@return number of sigops this transaction's outputs will produce when spent
@see CTransaction::FetchInputs
*/
unsigned int GetLegacySigOpCount(const CTransaction& tx);
/** Count ECDSA signature operations in pay-to-script-hash inputs.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return maximum number of sigops required to validate this transaction's inputs
@see CTransaction::FetchInputs
*/
unsigned int GetP2SHSigOpCount(const CTransaction& tx, const MapPrevTx& mapInputs);
/** Check for standard transaction types
@return True if all outputs (scriptPubKeys) use only standard transaction forms
*/
bool IsStandardTx(const CTransaction& tx, std::string& reason);
bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64_t nBlockTime = 0);
/** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx : public CTransaction
{
private:
int GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const;
public:
uint256 hashBlock;
std::vector<uint256> vMerkleBranch;
int nIndex;
// memory only
mutable bool fMerkleVerified;
CMerkleTx()
{
Init();
}
CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
{
Init();
}
void Init()
{
hashBlock = 0;
nIndex = -1;
fMerkleVerified = false;
}
IMPLEMENT_SERIALIZE
(
nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
nVersion = this->nVersion;
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
)
int SetMerkleBranch(const CBlock* pblock=NULL);
// Return depth of transaction in blockchain:
// -1 : not in blockchain, and not in memory pool (conflicted transaction)
// 0 : in memory pool, waiting to be included in a block
// >=1 : this many blocks deep in the main chain
int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
bool IsInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool(bool fLimitFree=true);
};
/** A txdb record that contains the disk location of a transaction and the
* locations of transactions that spend its outputs. vSpent is really only
* used as a flag, but having the location is very helpful for debugging.
*/
class CTxIndex
{
public:
CDiskTxPos pos;
std::vector<CDiskTxPos> vSpent;
CTxIndex()
{
SetNull();
}
CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
{
pos = posIn;
vSpent.resize(nOutputs);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(pos);
READWRITE(vSpent);
)
void SetNull()
{
pos.SetNull();
vSpent.clear();
}
bool IsNull()
{
return pos.IsNull();
}
friend bool operator==(const CTxIndex& a, const CTxIndex& b)
{
return (a.pos == b.pos &&
a.vSpent == b.vSpent);
}
friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
{
return !(a == b);
}
int GetDepthInMainChain() const;
};
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*
* Blocks are appended to blk0001.dat files on disk. Their location on disk
* is indexed by CBlockIndex objects in memory.
*/
class CBlock
{
public:
// header
static const int CURRENT_VERSION = 7;
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
// network and disk
std::vector<CTransaction> vtx;
// ppcoin: block signature - signed by one of the coin base txout[N]'s owner
std::vector<unsigned char> vchBlockSig;
// memory only
mutable std::vector<uint256> vMerkleTree;
// Denial-of-service detection:
mutable int nDoS;
bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
CBlock()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
// ConnectBlock depends on vtx following header to generate CDiskTxPos
if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
{
READWRITE(vtx);
READWRITE(vchBlockSig);
}
else if (fRead)
{
const_cast<CBlock*>(this)->vtx.clear();
const_cast<CBlock*>(this)->vchBlockSig.clear();
}
)
void SetNull()
{
nVersion = CBlock::CURRENT_VERSION;
hashPrevBlock = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
vtx.clear();
vchBlockSig.clear();
vMerkleTree.clear();
nDoS = 0;
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const
{
if (nVersion > 6)
return Hash(BEGIN(nVersion), END(nNonce));
else
return GetPoWHash();
}
uint256 GetPoWHash() const
{
return scrypt_blockhash(CVOIDBEGIN(nVersion));
}
int64_t GetBlockTime() const
{
return (int64_t)nTime;
}
void UpdateTime(const CBlockIndex* pindexPrev);
// entropy bit for stake modifier if chosen by modifier
unsigned int GetStakeEntropyBit() const
{
// Take last bit of block hash as entropy bit
unsigned int nEntropyBit = ((GetHash().GetLow64()) & 1llu);
LogPrint("stakemodifier", "GetStakeEntropyBit: hashBlock=%s nEntropyBit=%u\n", GetHash().ToString(), nEntropyBit);
return nEntropyBit;
}
// ppcoin: two types of block: proof-of-work or proof-of-stake
bool IsProofOfStake() const
{
return (vtx.size() > 1 && vtx[1].IsCoinStake());
}
bool IsProofOfWork() const
{
return !IsProofOfStake();
}
std::pair<COutPoint, unsigned int> GetProofOfStake() const
{
return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
}
// ppcoin: get max transaction timestamp
int64_t GetMaxTransactionTime() const
{
int64_t maxTransactionTime = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
maxTransactionTime = std::max(maxTransactionTime, (int64_t)tx.nTime);
return maxTransactionTime;
}
uint256 BuildMerkleTree() const
{
vMerkleTree.clear();
BOOST_FOREACH(const CTransaction& tx, vtx)
vMerkleTree.push_back(tx.GetHash());
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
}
j += nSize;
}
return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
}
std::vector<uint256> GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return 0;
BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
{
if (nIndex & 1)
hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
nIndex >>= 1;
}
return hash;
}
bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
{
// Open history file to append
CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("CBlock::WriteToDisk() : AppendBlockFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(Params().MessageStart()) << nSize;
// Write block
long fileOutPos = ftell(fileout);
if (fileOutPos < 0)
return error("CBlock::WriteToDisk() : ftell failed");
nBlockPosRet = fileOutPos;
fileout << *this;
// Flush stdio buffers and commit to disk before returning
fflush(fileout);
if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
FileCommit(fileout);
return true;
}
bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
{
SetNull();
// Open history file to read
CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
if (!fReadTransactions)
filein.nType |= SER_BLOCKHEADERONLY;
// Read block
try {
filein >> *this;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Check the header
if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetPoWHash(), nBits))
return error("CBlock::ReadFromDisk() : errors in block header");
return true;
}
std::string ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u, vchBlockSig=%s)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size(),
HexStr(vchBlockSig.begin(), vchBlockSig.end()));
for (unsigned int i = 0; i < vtx.size(); i++)
{
s << " " << vtx[i].ToString() << "\n";
}
s << " vMerkleTree: ";
for (unsigned int i = 0; i < vMerkleTree.size(); i++)
s << " " << vMerkleTree[i].ToString();
s << "\n";
return s.str();
}
bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos, const uint256& hashProof);
bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
bool AcceptBlock();
bool SignBlock(CWallet& keystore, int64_t nFees);
bool CheckBlockSignature() const;
private:
bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
};
/** The block chain is a tree shaped structure starting with the
* genesis block at the root, with each block potentially having multiple
* candidates to be the next block. pprev and pnext link a path through the
* main/longest chain. A blockindex may have multiple pprev pointing back
* to it, but pnext will only point forward to the longest branch, or will
* be null if the block is not part of the longest chain.
*/
class CBlockIndex
{
public:
const uint256* phashBlock;
CBlockIndex* pprev;
CBlockIndex* pnext;
unsigned int nFile;
unsigned int nBlockPos;
uint256 nChainTrust; // ppcoin: trust score of block chain
int nHeight;
int64_t nMint;
int64_t nMoneySupply;
unsigned int nFlags; // ppcoin: block index flags
enum
{
BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
};
uint64_t nStakeModifier; // hash modifier for proof-of-stake
uint256 bnStakeModifier;
// proof-of-stake specific fields
COutPoint prevoutStake;
unsigned int nStakeTime;
uint256 hashProof;
// block header
int nVersion;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
CBlockIndex()
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nFile = 0;
nBlockPos = 0;
nHeight = 0;
nChainTrust = 0;
nMint = 0;
nMoneySupply = 0;
nFlags = 0;
nStakeModifier = 0;
bnStakeModifier = 0;
hashProof = 0;
prevoutStake.SetNull();
nStakeTime = 0;
nVersion = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
}
CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nFile = nFileIn;
nBlockPos = nBlockPosIn;
nHeight = 0;
nChainTrust = 0;
nMint = 0;
nMoneySupply = 0;
nFlags = 0;
nStakeModifier = 0;
bnStakeModifier = 0;
hashProof = 0;
if (block.IsProofOfStake())
{
SetProofOfStake();
prevoutStake = block.vtx[1].vin[0].prevout;
nStakeTime = block.vtx[1].nTime;
}
else
{
prevoutStake.SetNull();
nStakeTime = 0;
}
nVersion = block.nVersion;
hashMerkleRoot = block.hashMerkleRoot;
nTime = block.nTime;
nBits = block.nBits;
nNonce = block.nNonce;
}
CBlock GetBlockHeader() const
{
CBlock block;
block.nVersion = nVersion;
if (pprev)
block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 GetBlockHash() const
{
return *phashBlock;
}
int64_t GetBlockTime() const
{
return (int64_t)nTime;
}
uint256 GetBlockTrust() const;
bool IsInMainChain() const
{
return (pnext || this == pindexBest);
}
bool CheckIndex() const
{
return true;
}
int64_t GetPastTimeLimit() const
{
return GetBlockTime();
}
enum { nMedianTimeSpan=11 };
int64_t GetMedianTimePast() const
{
int64_t pmedian[nMedianTimeSpan];
int64_t* pbegin = &pmedian[nMedianTimeSpan];
int64_t* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin)/2];
}
/**
* Returns true if there are nRequired or more blocks of minVersion or above
* in the last nToCheck blocks, starting at pstart and going backwards.
*/
static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
unsigned int nRequired, unsigned int nToCheck);
bool IsProofOfWork() const
{
return !(nFlags & BLOCK_PROOF_OF_STAKE);
}
bool IsProofOfStake() const
{
return (nFlags & BLOCK_PROOF_OF_STAKE);
}
void SetProofOfStake()
{
nFlags |= BLOCK_PROOF_OF_STAKE;
}
unsigned int GetStakeEntropyBit() const
{
return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
}
bool SetStakeEntropyBit(unsigned int nEntropyBit)
{
if (nEntropyBit > 1)
return false;
nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
return true;
}
bool GeneratedStakeModifier() const
{
return (nFlags & BLOCK_STAKE_MODIFIER);
}
void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier)
{
nStakeModifier = nModifier;
if (fGeneratedStakeModifier)
nFlags |= BLOCK_STAKE_MODIFIER;
}
std::string ToString() const
{
return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016x, hashProof=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
pprev, pnext, nFile, nBlockPos, nHeight,
FormatMoney(nMint), FormatMoney(nMoneySupply),
GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
nStakeModifier,
hashProof.ToString(),
prevoutStake.ToString(), nStakeTime,
hashMerkleRoot.ToString(),
GetBlockHash().ToString());
}
};
/** Used to marshal pointers into hashes for db storage. */
class CDiskBlockIndex : public CBlockIndex
{
private:
uint256 blockHash;
public:
uint256 hashPrev;
uint256 hashNext;
CDiskBlockIndex()
{
hashPrev = 0;
hashNext = 0;
blockHash = 0;
}
explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
{
hashPrev = (pprev ? pprev->GetBlockHash() : 0);
hashNext = (pnext ? pnext->GetBlockHash() : 0);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(hashNext);
READWRITE(nFile);
READWRITE(nBlockPos);
READWRITE(nHeight);
READWRITE(nMint);
READWRITE(nMoneySupply);
READWRITE(nFlags);
READWRITE(nStakeModifier);
READWRITE(bnStakeModifier);
if (IsProofOfStake())
{
READWRITE(prevoutStake);
READWRITE(nStakeTime);
}
else if (fRead)
{
const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
}
READWRITE(hashProof);
// block header
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
READWRITE(blockHash);
)
uint256 GetBlockHash() const
{
if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0)
return blockHash;
CBlock block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrev;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
return blockHash;
}
std::string ToString() const
{
std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
GetBlockHash().ToString(),
hashPrev.ToString(),
hashNext.ToString());
return str;
}
};
/** Describes a place in the block chain to another node such that if the
* other node doesn't have the same branch, it can find a recent common trunk.
* The further back it is, the further before the fork it may be.
*/
class CBlockLocator
{
protected:
std::vector<uint256> vHave;
public:
CBlockLocator()
{
}
explicit CBlockLocator(const CBlockIndex* pindex)
{
Set(pindex);
}
explicit CBlockLocator(uint256 hashBlock)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end())
Set((*mi).second);
}
CBlockLocator(const std::vector<uint256>& vHaveIn)
{
vHave = vHaveIn;
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
)
void SetNull()
{
vHave.clear();
}
bool IsNull()
{
return vHave.empty();
}
void Set(const CBlockIndex* pindex)
{
vHave.clear();
int nStep = 1;
while (pindex)
{
vHave.push_back(pindex->GetBlockHash());
// Exponentially larger steps back
for (int i = 0; pindex && i < nStep; i++)
pindex = pindex->pprev;
if (vHave.size() > 10)
nStep *= 2;
}
vHave.push_back(Params().HashGenesisBlock());
}
int GetDistanceBack()
{
// Retrace how far back it was in the sender's branch
int nDistance = 0;
int nStep = 1;
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return nDistance;
}
nDistance += nStep;
if (nDistance > 10)
nStep *= 2;
}
return nDistance;
}
CBlockIndex* GetBlockIndex()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return pindex;
}
}
return pindexGenesisBlock;
}
uint256 GetBlockHash()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return hash;
}
}
return Params().HashGenesisBlock();
}
int GetHeight()
{
CBlockIndex* pindex = GetBlockIndex();
if (!pindex)
return 0;
return pindex->nHeight;
}
};
class CWalletInterface {
protected:
virtual void SyncTransaction(const CTransaction &tx, const CBlock *pblock, bool fConnect) =0;
virtual void EraseFromWallet(const uint256 &hash) =0;
virtual void SetBestChain(const CBlockLocator &locator) =0;
virtual void UpdatedTransaction(const uint256 &hash) =0;
virtual void Inventory(const uint256 &hash) =0;
virtual void ResendWalletTransactions(bool fForce) =0;
friend void ::RegisterWallet(CWalletInterface*);
friend void ::UnregisterWallet(CWalletInterface*);
friend void ::UnregisterAllWallets();
};
#endif
|
[
"FootyCash@gmail.com"
] |
FootyCash@gmail.com
|
5587adbeb596df8cb5ac329dc23eebc7542cecc4
|
eeb9de1ca9fbdb7540c5cf361a13e70e1b73293e
|
/1368.cpp
|
66ee4b3516082c15238b656d4782b11d797a5caa
|
[] |
no_license
|
RatanNarayanHegde/CompetitiveProgramming
|
64eee84381e49442615b5ba53359faebb46d717b
|
4c11a3bdf739a9b3ef2ab52ac78b9181c78bb069
|
refs/heads/master
| 2023-04-28T14:37:15.694314
| 2021-05-25T07:44:38
| 2021-05-25T07:44:38
| 347,784,805
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,870
|
cpp
|
#include<bits/stdc++.h>
using namespace std;
#define ff first
#define fo(i,n) for(i=0;i<n;i++)
#define Fo(i,k,n) for(i=k;k<n?i<n:i>n;k<n?i+=1:i-=1)
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl
#define ss second
#define int long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define vi vector<int>
#define mii map<int,int>
#define pqb priority_queue<int>
#define pqs priority_queue<int,vi,greater<int> >
#define setbits(x) __builtin_popcountll(x)
#define zrobits(x) __builtin_ctzll(x)
#define mod 1000000007
#define inf 1e18
#define ps(x,y) fixed<<setprecision(y)<<x
#define w(x) int x; cin>>x; while(x--)
#define FIO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int N = 3e5, M = N;
//=======================
void solve() {
int i, j, n, m;
cin>>n;
int times;
for(int i=1;i<=40;i++){
if(pow(i,10)>=n){
times=i;
break;
}
}
if(times==1){
cout<<"codeforces";return;
}
int count=0;
int curr = pow(times-1,10);
while(curr<n){
count++;
curr*=times;
curr/=(times-1);
}
// cout<<count;
string str="codeforces";
string res;
for(int i=0;i<10;i++){
if(count){
for(int j=0;j<times;j++){
res+=str[i];
}
count--;
}
else{
for(int j=0;j<times-1;j++){
res+=str[i];
}
}
}
// cout<<times;
cout<<res;
}
int32_t main()
{
FIO;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
solve();
return 0;
}
|
[
"ratanhegde@pop-os.localdomain"
] |
ratanhegde@pop-os.localdomain
|
a0b9ab5393537619f5e8a9788fa734a8340b0bf5
|
19d1c24484c1771c0be7cdef45f3342a6889a4cb
|
/nnforge/cuda/maxout_layer_tester_cuda.h
|
80cb5fe4b8b48118718bfd5067def043e5630985
|
[
"Apache-2.0"
] |
permissive
|
dreadlord1984/nnForge
|
06bc261fa9d9d58c45aafdbf3f7026990809c288
|
b4c795ab6ddf3ce9dfe8a628dd1ad33dd19dee9b
|
refs/heads/master
| 2021-01-18T13:40:21.646717
| 2014-08-06T18:23:53
| 2014-08-06T18:23:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,667
|
h
|
/*
* Copyright 2011-2013 Maxim Milakov
*
* 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.
*/
#pragma once
#include "layer_tester_cuda.h"
namespace nnforge
{
namespace cuda
{
class maxout_layer_tester_cuda : public layer_tester_cuda
{
public:
maxout_layer_tester_cuda();
virtual ~maxout_layer_tester_cuda();
virtual void enqueue_test(
cudaStream_t stream_id,
const std::vector<const_cuda_linear_buffer_device_smart_ptr>& schema_data,
const std::vector<const_cuda_linear_buffer_device_smart_ptr>& data,
cuda_linear_buffer_device_smart_ptr input_buffer,
const std::vector<cuda_linear_buffer_device_smart_ptr>& additional_buffers,
unsigned int entry_count);
virtual cuda_linear_buffer_device_smart_ptr get_output_buffer(
cuda_linear_buffer_device_smart_ptr input_buffer,
const std::vector<cuda_linear_buffer_device_smart_ptr>& additional_buffers);
protected:
virtual void tester_configured();
virtual std::vector<size_t> get_sizes_of_additional_buffers_per_entry() const;
private:
int feature_map_subsampling_size;
};
}
}
|
[
"maxim.milakov@gmail.com"
] |
maxim.milakov@gmail.com
|
947104dae24b756d26e65a205d5cd86810e78110
|
66c22ed409b2eee7e1b570749601ccd567a718a4
|
/Src/EntityManager.h
|
42d1d49dd3e686584f28ce09b63d72627ecc96ab
|
[] |
no_license
|
XoDeR/Rio.EntitySystem
|
71e155f0970b88102887db1ba7c808325b2e2c55
|
6a89ad8db1956fea79c213979455a20d05bb8e4c
|
refs/heads/master
| 2021-01-22T05:24:18.493795
| 2015-06-18T15:50:30
| 2015-06-18T15:50:30
| 37,669,192
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 377
|
h
|
#pragma once
#include "Common.h"
#include "Entity.h"
class EntityManager
{
public:
Entity createEntity();
void removeEntity(Entity e);
bool isActive(Entity e);
void registerRemoveComponentCallback(function<void(uint32_t)> removeCallback);
private:
vector<uint8_t> generation;
deque<uint32_t> freeIndices;
vector<function<void(uint32_t)>> removeComponentCallbackList;
};
|
[
"xoder.vs@gmail.com"
] |
xoder.vs@gmail.com
|
6b3af69f4d3ea13d9e119caf66c91087c0a426a1
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/squid/gumtree/squid_repos_function_3485_squid-3.5.27.cpp
|
9d59d3a4ebdb740c55ce0d9ee0f3ce44ed05e693
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,897
|
cpp
|
void
clientReplyContext::purgeDoPurgeHead(StoreEntry *newEntry)
{
if (newEntry && !newEntry->isNull()) {
debugs(88, 4, "clientPurgeRequest: HEAD '" << newEntry->url() << "'" );
#if USE_HTCP
neighborsHtcpClear(newEntry, NULL, http->request, HttpRequestMethod(Http::METHOD_HEAD), HTCP_CLR_PURGE);
#endif
newEntry->release();
purgeStatus = Http::scOkay;
}
/* And for Vary, release the base URI if none of the headers was included in the request */
if (!http->request->vary_headers.isEmpty()
&& http->request->vary_headers.find('=') != SBuf::npos) {
StoreEntry *entry = storeGetPublic(urlCanonical(http->request), Http::METHOD_GET);
if (entry) {
debugs(88, 4, "clientPurgeRequest: Vary GET '" << entry->url() << "'" );
#if USE_HTCP
neighborsHtcpClear(entry, NULL, http->request, HttpRequestMethod(Http::METHOD_GET), HTCP_CLR_PURGE);
#endif
entry->release();
purgeStatus = Http::scOkay;
}
entry = storeGetPublic(urlCanonical(http->request), Http::METHOD_HEAD);
if (entry) {
debugs(88, 4, "clientPurgeRequest: Vary HEAD '" << entry->url() << "'" );
#if USE_HTCP
neighborsHtcpClear(entry, NULL, http->request, HttpRequestMethod(Http::METHOD_HEAD), HTCP_CLR_PURGE);
#endif
entry->release();
purgeStatus = Http::scOkay;
}
}
/*
* Make a new entry to hold the reply to be written
* to the client.
*/
/* FIXME: This doesn't need to go through the store. Simply
* push down the client chain
*/
createStoreEntry(http->request->method, RequestFlags());
triggerInitialStoreRead();
HttpReply *rep = new HttpReply;
rep->setHeaders(purgeStatus, NULL, NULL, 0, 0, -1);
http->storeEntry()->replaceHttpReply(rep);
http->storeEntry()->complete();
}
|
[
"993273596@qq.com"
] |
993273596@qq.com
|
ded7379471bf7632f902c99987a938ef990085c8
|
cc94542e78e38567f9f0f891f8fa31996ea169cb
|
/ITMLib/Utils/ITMSceneParams.h
|
859875ab2de0bf145d714c8eececa14bec4c062a
|
[] |
no_license
|
WSX741405/ITM
|
725700e57ff4d1e7cfe784b85c12f25597df87b2
|
78ad22bc19211d16d1a1db6b9df22b72600ffea1
|
refs/heads/master
| 2021-04-09T16:36:54.226544
| 2018-03-20T13:03:39
| 2018-03-20T13:03:39
| 125,861,673
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,990
|
h
|
// Copyright 2014-2017 Oxford University Innovation Limited and the authors of ITM
#pragma once
namespace ITMLib
{
/** \brief
Stores parameters of a scene like voxel size
*/
class ITMSceneParams
{
public:
/// Size of a voxel, usually given in meters.
float voxelSize;
/** @{ */
/** \brief
Fallback parameters: consider only parts of the
scene from @p viewFrustum_min in front of the camera
to a distance of @p viewFrustum_max. Usually the
actual depth range should be determined
automatically by a ITMLib::Engine::ITMVisualisationEngine.
*/
float viewFrustum_min, viewFrustum_max;
/** @} */
/** \brief
Encodes the width of the band of the truncated
signed distance transform that is actually stored
in the volume. This is again usually specified in
meters. The resulting width in voxels is @ref mu
divided by @ref voxelSize.
*/
float mu;
/** \brief
Up to @ref maxW observations per voxel are averaged.
Beyond that a sliding average is computed.
*/
int maxW;
/** Stop integration once maxW has been reached. */
bool stopIntegratingAtMaxW;
ITMSceneParams(void) {}
ITMSceneParams(float mu, int maxW, float voxelSize,
float viewFrustum_min, float viewFrustum_max, bool stopIntegratingAtMaxW)
{
this->mu = mu;
this->maxW = maxW;
this->voxelSize = voxelSize;
this->viewFrustum_min = viewFrustum_min; this->viewFrustum_max = viewFrustum_max;
this->stopIntegratingAtMaxW = stopIntegratingAtMaxW;
}
explicit ITMSceneParams(const ITMSceneParams *sceneParams) { this->SetFrom(sceneParams); }
void SetFrom(const ITMSceneParams *sceneParams)
{
this->voxelSize = sceneParams->voxelSize;
this->viewFrustum_min = sceneParams->viewFrustum_min;
this->viewFrustum_max = sceneParams->viewFrustum_max;
this->mu = sceneParams->mu;
this->maxW = sceneParams->maxW;
this->stopIntegratingAtMaxW = sceneParams->stopIntegratingAtMaxW;
}
};
}
|
[
"wsx741405@gmail.com"
] |
wsx741405@gmail.com
|
89b522292fc8f3f47675b790242f3a8a018e0c32
|
e5720f95696653b496e5f927eac7492bfb9f132c
|
/0501-1000/0551-Student-Attendance-Record-I/cpp_0551/main.cpp
|
3f48e1624b7b162d695220864db15c4ffb292915
|
[
"MIT"
] |
permissive
|
ooooo-youwillsee/leetcode
|
818cca3dd1fd07caf186ab6d41fb8c44f6cc9bdc
|
2cabb7e3e2465e33e4c96f0ad363cf6ce6976288
|
refs/heads/master
| 2022-05-24T15:37:19.652999
| 2022-05-15T01:25:31
| 2022-05-15T01:25:31
| 218,205,693
| 12
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 225
|
cpp
|
#include <iostream>
#include "Solution1.h"
void test(string s) {
Solution solution;
cout << solution.checkRecord(s) << endl;
}
int main() {
test("PPALLP"); // 1
test("PPALLL"); // 0
test("AA"); // 0
return 0;
}
|
[
"297872913@qq.com"
] |
297872913@qq.com
|
498b5217859fd2d020bba53f50c9776f6795a84a
|
fcd5d7e0fcb55763afd03ea3d72ec441b9a9e2c7
|
/rocky/test/skull/OddTest.cpp
|
23e419108d32aec1836e99712e2f2079478b9b59
|
[] |
no_license
|
ghjang/rocky
|
74f9f36c2a95d527fc0a0e877ff0a8ea36fefbb9
|
07b2de51a8b619d4d682c73023508b5eb5843061
|
refs/heads/master
| 2021-01-10T11:24:03.989558
| 2017-02-03T15:58:43
| 2017-02-03T15:58:43
| 45,999,680
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 351
|
cpp
|
#include "../catch.hpp"
#include "rocky/skull/Odd.h"
TEST_CASE("Odd for std::integral_constant", "[skull]")
{
// expected compile-time error.
//static_assert(Odd<std::tuple<>>());
static_assert(!Odd<int_c_t<0>>());
static_assert(Odd<int_c_t<1>>());
static_assert(!Odd<int_c_t<2>>());
static_assert(Odd<int_c_t<101>>());
}
|
[
"jmxexpert@hotmail.com"
] |
jmxexpert@hotmail.com
|
5cc69ea1dc132d5c0cf2cd6801505f54195e47b2
|
335fb8bfc5f4ff394d0e2abd20205d1670ecd0b1
|
/Beginner Problems/Page 1/1021 - Banknotes and Coins.cpp
|
cd2139e1ba7173b0799cf217f8e7fab51ec9a571
|
[] |
no_license
|
AhmedGharseldin/URI-Online_Judge
|
e6d9120c4190b276bad7b91312a519a61f6db89d
|
adf3e0d92337a0b986818b9ec57d2afcf9709b9e
|
refs/heads/main
| 2023-02-17T09:39:35.270078
| 2021-01-17T11:38:21
| 2021-01-17T11:38:21
| 330,255,688
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 994
|
cpp
|
//https://www.urionlinejudge.com.br/judge/en/problems/view/1021
#include <iostream>
using namespace std;
int main(){
double x;
cin>>x;
int t = x;
int n = (x - t)*100;
int u = 0;
cout<<"NOTAS:"<<endl;
cout<<t/100<<" nota(s) de R$ 100.00"<<endl; //100
u = t%100;
cout<<u/50<<" nota(s) de R$ 50.00"<<endl; //50
u = u%50;
cout<<u/20<<" nota(s) de R$ 20.00"<<endl; //20
u = u%20;
cout<<u/10<<" nota(s) de R$ 10.00"<<endl; //10
u = u%10;
cout<<u/5<<" nota(s) de R$ 5.00"<<endl;
u = u%5;
cout<<u/2<<" nota(s) de R$ 2.00"<<endl;
u = u%2;
cout<<"MOEDAS:"<<endl;
cout<<u/1<<" moeda(s) de R$ 1.00"<<endl;
cout<<n/50<<" moeda(s) de R$ 0.50"<<endl;
n = n%50;
cout<<n/25<<" moeda(s) de R$ 0.25"<<endl;
n = n%25;
cout<<n/10<<" moeda(s) de R$ 0.10"<<endl;
n = n%10;
cout<<n/5<<" moeda(s) de R$ 0.05"<<endl;
n = n%5;
cout<<n/1<<" moeda(s) de R$ 0.01"<<endl;
return 0;
}
|
[
"63879928+AhmedGharseldin@users.noreply.github.com"
] |
63879928+AhmedGharseldin@users.noreply.github.com
|
e779f167f39d2eea0a3a4ee34786f3ff83def902
|
32cbb0a1fc652005198d6ed5ed52e25572612057
|
/core/unit_test/openmptarget/TestOpenMPTarget_TeamScratch.cpp
|
2593609e333cf98b37bf899c483e5b8ed7ce9a33
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
ORNL-CEES/kokkos
|
3874d42a685084f0eb7999939cd9f1da9d42a2a6
|
70d113838b7dade09218a46c1e8aae44b6dbd321
|
refs/heads/hip
| 2020-05-04T03:32:58.012717
| 2020-01-24T20:43:25
| 2020-01-24T20:43:25
| 178,948,568
| 1
| 1
|
NOASSERTION
| 2020-03-01T19:21:45
| 2019-04-01T21:19:04
|
C++
|
UTF-8
|
C++
| false
| false
| 3,225
|
cpp
|
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// 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 of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include <openmptarget/TestOpenMPTarget_Category.hpp>
#include <TestTeam.hpp>
namespace Test {
TEST_F(TEST_CATEGORY, team_shared_request) {
TestSharedTeam<TEST_EXECSPACE, Kokkos::Schedule<Kokkos::Static> >();
TestSharedTeam<TEST_EXECSPACE, Kokkos::Schedule<Kokkos::Dynamic> >();
}
TEST_F(TEST_CATEGORY, team_scratch_request) {
TestScratchTeam<TEST_EXECSPACE, Kokkos::Schedule<Kokkos::Static> >();
TestScratchTeam<TEST_EXECSPACE, Kokkos::Schedule<Kokkos::Dynamic> >();
}
#if defined(KOKKOS_ENABLE_CXX11_DISPATCH_LAMBDA)
#if !defined(KOKKOS_ENABLE_CUDA) || (8000 <= CUDA_VERSION)
TEST_F(TEST_CATEGORY, team_lambda_shared_request) {
TestLambdaSharedTeam<Kokkos::HostSpace, TEST_EXECSPACE,
Kokkos::Schedule<Kokkos::Static> >();
TestLambdaSharedTeam<Kokkos::HostSpace, TEST_EXECSPACE,
Kokkos::Schedule<Kokkos::Dynamic> >();
}
#endif
#endif
TEST_F(TEST_CATEGORY, shmem_size) { TestShmemSize<TEST_EXECSPACE>(); }
TEST_F(TEST_CATEGORY, multi_level_scratch) {
TestMultiLevelScratchTeam<TEST_EXECSPACE,
Kokkos::Schedule<Kokkos::Static> >();
TestMultiLevelScratchTeam<TEST_EXECSPACE,
Kokkos::Schedule<Kokkos::Dynamic> >();
}
} // namespace Test
|
[
"crtrott@sandia.gov"
] |
crtrott@sandia.gov
|
5aac5a697a0348eec5e1c25cfbdf3d0acf326271
|
13b14c9c75143bf2eda87cb4a41006a52dd6f02b
|
/Uva/Uva2008/123/123.cpp
|
33306aed88811f721ab558863eac9eac359f932e
|
[] |
no_license
|
yutaka-watanobe/problem-solving
|
2c311ac856c79c20aef631938140118eb3bc3835
|
f0b92125494fbd3c8d203989ec9fef53f52ad4b4
|
refs/heads/master
| 2021-06-03T12:58:39.881107
| 2020-12-16T14:34:16
| 2020-12-16T14:34:16
| 94,963,754
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,611
|
cpp
|
#include<iostream>
#include<sstream>
#include<string>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
class Line{
public:
int row, col;
vector<string> words;
string title;
Line(){}
void set(int r, int c, vector<string> w){
row = r;
col = c;
words = w;
title = words[col];
}
string getTitle(){
return words[col];
}
bool operator < ( const Line &l ) const{
if ( title == l.title ){
if ( row == l.row ) return col == l.col;
else return row < l.row;
} else return title < l.title;
}
string toUpper(string str){
for ( int i = 0; i < str.size(); i++ ) str[i] = toupper(str[i]);
return str;
}
void print(){
for ( int i = 0; i < words.size(); i++ ){
if ( i ) cout << " ";
if ( i == col ) cout << toUpper(words[i]);
else cout << words[i];
}
cout << endl;
}
};
map<string, bool> IG;
string toLower(string str){
for ( int i = 0; i < str.size(); i++ ) str[i] = tolower(str[i]);
return str;
}
int main(){
string line;
while(1){
getline(cin, line);
if ( line == "::" ) break;
IG[line] = true;
}
string word;
vector<Line> L;
while(1){
getline( cin , line );
if ( cin.eof() ) break;
stringstream sin(line);
vector<string> words;
while( sin >> word) words.push_back(toLower(word));
for ( int i = 0; i < words.size(); i++ ){
if ( IG[words[i]] ) continue;
L.push_back(Line());
L[L.size()-1].set(L.size()-1, i, words);
}
}
sort( L.begin(), L.end() );
for ( int i = 0; i < L.size(); i++ ) L[i].print();
return 0;
}
|
[
"y.watanobe@gmail.com"
] |
y.watanobe@gmail.com
|
f0a91cef27572012fd80398356a730452b80fd62
|
d6e0e7b7597d74bb28f45ca352b40bd66e8bc1b3
|
/sync_tcp_client/sync_tcp_client.cpp
|
5efcbaa5d67c9e616462f283341d258b3db34f5d
|
[] |
no_license
|
benzispawn/network__boost.asio
|
a40fdc371c15636f9faad7e66a15d0f65aa40dc3
|
8635927754ca436ee33c405fbc64ee0c7d96fad4
|
refs/heads/main
| 2023-01-10T14:16:59.293770
| 2020-11-11T03:08:28
| 2020-11-11T03:08:28
| 311,507,968
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 799
|
cpp
|
#include "sync_tcp_client.h"
int main()
{
const std::string raw_ip_address = "127.0.0.1";
const unsigned short port_num = 3333;
try
{
SyncTCPClient client(raw_ip_address, port_num);
client.connect();
std::cout << "Sending request to the server..."
<< std::endl;
std::string response =
client.emulateLongComputationOp(10);
std::cout << "Response received: "
<< response
<< std::endl;
// Close client
client.close();
}
catch(boost::system::system_error &e)
{
std::cout << "Error occured! Error code = "
<< e.code()
<< ". Message: " << e.what();
return e.code().value();
}
return 0;
}
|
[
"spawnbenzi@gmail.com"
] |
spawnbenzi@gmail.com
|
0f3484457a8aea3cf0a2d3e6085acd1a448a8176
|
64d8b83603bb04b9022bf6d1776f3a3593d3ac7d
|
/unit_test/EnTT/Test_EnTT.cpp
|
7aa62e9534ab0bf4023aea3fd3666a53693a7bb5
|
[
"MIT"
] |
permissive
|
nitishingde/yaui
|
a2c7244bce6ec802936ba8d252c38d2db412d09e
|
47698857e026b451bfac1dd0204fa38b2d377540
|
refs/heads/master
| 2021-06-14T04:54:42.594569
| 2020-12-15T14:39:58
| 2020-12-15T14:39:58
| 191,589,819
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 313
|
cpp
|
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "catch2/catch.hpp"
#include "entt/entt.hpp"
#include <iostream>
TEST_CASE("Initialization of EnTT", "[init]") {
entt::registry *reg = new entt::registry();
CHECK(reg != nullptr);
delete reg;
}
|
[
"ngshingde@gmail.com"
] |
ngshingde@gmail.com
|
f7e028dc5f9b42de6e19aa1b4738c876156bc4b8
|
270d448184cbe958e6e6bb17a98b35c381e22d99
|
/objectOriented/lectures/examples/3-5-abstractClass.cpp
|
43ed3e5d82468ad038dd4d3da2d49ee2fbfbf69c
|
[] |
no_license
|
jcjolley/school
|
016ffde715bb07f9ddc09f0c7c0cf4d59a2bd0b3
|
bab28da74b1baba32844ec19278feb11ab65c375
|
refs/heads/master
| 2021-05-01T11:58:47.576569
| 2016-07-20T15:03:10
| 2016-07-20T15:03:10
| 59,164,873
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,004
|
cpp
|
/***********************************************************************
* This demo program is designed to:
* Demonstrate pure Virtual Functions. Note that we cannot
* create an object out of an abstract class so we will
* get a compile error
************************************************************************/
#include <iostream>
using namespace std;
/*****************************
* Base class
* This is an abstract class because
* of the pure virtual function
*****************************/
class Base
{
public:
/**********************************************
* BASE :: METHOD
* This is a pure virtual function (because of the = 0)
* at the end of the method definition Thus the VTable
* has a NULL pointer and the compiler will not allow us
* create an object of type Base
*********************************************/
virtual void method() = 0;
};
/***************************
* Derived class
**************************/
class Derived: public Base
{
public:
/*********************************************
* DERIVED :: METHOD
* This is a derived class. Note that, though
* it is defined in the class definition, it is not
* an inline function. Virtual functions cannot
* be inline
*********************************************/
virtual void method()
{
cout << "Derived!\n";
}
};
/**********************************************************************
* main(): just a drive program to demonstrate the comile error
**********************************************************************/
int main()
{
Base base; // compile error. Because Base is an Abstract Class due to the
// pure virtual function method(), we cannot
// instantiate an object of this type.
// even if we could create an object called base, we would crash
// here due to the NULL pointer in the VTable of Base
base.method();
return 0;
}
|
[
"jolleyboy@gmail.com"
] |
jolleyboy@gmail.com
|
a81bce621612542d5c5992a348d515b98879f9cd
|
dae907db0cf43b427fd1a456b338be3910fc5f90
|
/P84219_en_First_occurrence.cc
|
444eb96b05bec023f97f381e6d62a1ed81c7e5aa
|
[] |
no_license
|
FranciOrtiz/jutge_problems
|
4c5c273ada09f20088b08287356bbb967a642e45
|
a838f6ad8995cf57ae6f11cc6beeb3f13fa7e55d
|
refs/heads/master
| 2022-12-23T20:33:43.775974
| 2020-09-24T09:49:10
| 2020-09-24T09:49:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 543
|
cc
|
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int first_occurrence(double x, const vector<double>& v) {
int L = 0, R = v.size()-1;
while (L<=R) {
int M = (L+R)/2;
if (v[M]==x and v[M-1]!=x) return M;
else if (v[M] < x) L = M+1;
else R = M-1;
}
return -1;
}
int main () {
vector <double> vv;
int s;
cin >> s;
vv.resize(s);
for (int i = 0; i < s; i++) cin >> vv[i];
double xx;
cin >> xx;
cout << first_occurrence(xx,vv) << endl;
}
|
[
"abone9999@gmail.com"
] |
abone9999@gmail.com
|
a4a0ae40973591591299cf83b585a7a854f2bbfd
|
9055c093cd4ba9ab67470fd40d1ef13330f42492
|
/Source/Client/ClientMain.cpp
|
55310769e14daa5cfdd432e26fe95fedf25fbfbb
|
[] |
no_license
|
webdes27/LoongSource
|
379875f51df0c9d9753515f1952d5f11afdc7dec
|
6c248e3340788041714c3006906e704dd5853f71
|
refs/heads/master
| 2022-01-10T18:38:11.764963
| 2019-06-06T12:33:52
| 2019-06-06T12:33:52
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 39,646
|
cpp
|
//-----------------------------------------------------------------------------
//!\file ClientMain.cpp
//!\author Lyp
//!
//!\date 2008-03-27
//! last 2008-03-27
//!
//!\brief 龙客户端
//!
//! Copyright (c) 2008 CTCRST Entertainment All rights reserved.
//-----------------------------------------------------------------------------
#include "stdafx.h"
#include "ClientMain.h"
#include "shellapi.h"
#include "ServerSelectFrame.h"
#include "LoginFrame.h"
#include "HealthyControlFrame.h"
#include "SelectRoleFrame.h"
#include "CreateRoleFrame.h"
#include "WorldFrame.h"
#include "LoadingFrame.h"
#include "Render2D.h"
#include "NetSession.h"
#include "CreatureData.h"
#include "PetProtoData.h"
#include "SceneEffectData.h"
#include "ItemProtoData.h"
#include "SkillProtoData.h"
#include "MapLogicData.h"
#include "ShopProtoData.h"
#include "MallData.h"
#include "LonghunAttData.h"
#include "RoleTitleProtoData.h"
#include "RoleInfoProtoData.h"
#include "GameSet.h"
#include "SysMenuFrame.h"
#include "SysOptionMenuFrame.h"
#include "ExitPromptFrame.h"
#include "GameSettingsFrame.h"
#include "MiniMapStatic.h"
#include "MiniMapFrame.h"
#include "ActiveStatic.h"
#include "ActiveProgress.h"
#include "PlayerStateFrame.h"
#include "TargetStateFrame.h"
#include "TargetSpellStateFrame.h"
#include "TeammatesStateFrame.h"
#include "PlayerViewWindow.h"
#include "PetShowWindow.h"
#include "RoleHeadPicIcon.h"
#include "ZoneMapData.h"
#include "ZoneMapStatic.h"
#include "ZoneMapFrame.h"
#include "TeamSys.h"
#include "TeammatesStateFrame.h"
#include "QuitFrame.h"
#include "StyleActionFrame.h"
#include "FestivalActivityPromptFrame.h"
#include "RoleLevelUpPromptFrame.h"
#include "LoongBenedictionFrame.h"
#include "ChatFrame.h"
#include "MilleSoundFrame.h"
#include "StaticForCast.h"
#include "EmotionFrame.h"
#include "RichEditBoxForChatInput.h"
#include "RichEditBoxForChatShow.h"
#include "ScrollRichEditBox.h"
#include "ShortcutBarFrame.h"
#include "ShortcutButton.h"
#include "WorldPickerFrame.h"
#include "CombatSys.h"
#include "ItemFrame.h"
#include "PocketFrame.h"
#include "PetBagFrame.h"
#include "PetInformationFrame.h"
#include "PetTradeFrame.h"
#include "PetTradeUIFrame.h"
#include "ThroneFrame.h"
#include "StorageFrame.h"
#include "ToolTipFrame.h"
#include "CharacterFrame.h"
#include "TargetCharacterFrame.h"
#include "StateFrame.h"
#include "EquipmentFrame.h"
#include "ReputeFrame.h"
#include "FameHallFrame.h"
#include "ClanTreasureFrame.h"
#include "RoleTitleFrame.h"
#include "InformationFrame.h"
#include "DispRoleInfoFrame.h"
#include "ItemProduceFrame.h"
#include "EquipConsolidateFrame.h"
#include "DeComposeFrame.h"
#include "ConsolidateData.h"
#include "ProduceData.h"
#include "ComposeStatic.h"
#include "TradeFrame.h"
#include "PlayerTradeFrame.h"
#include "LockStatic.h"
#include "PlayerTryDressWnd.h"
#include "MallFrame.h"
#include "MallGiftFrame.h"
#include "YuanbaoFrame.h"
#include "FilterData.h"
#include "PocketEncryptFrame.h"
#include "TreasureChestFrame.h"
#include "GuildFrame.h"
#include "GuildMemberInfoFrame.h"
#include "GuildMemberPosFrame.h"
#include "GuildAffairFrame.h"
#include "GuildUpgradeFrame.h"
#include "GuildPickUpSilverFrame.h"
#include "GuildContributeSilver.h"
#include "GuildBusinessFrame.h"
#include "GuildBusinessRankFrame.h"
#include "GuildStorageFrame.h"
#include "GuildStorePermitFrame.h"
#include "NoticeFrame.h"
#include "GroundItemTipsFrame.h"
#include "InsuranceFrame.h"
#include "GroupBuyFrame.h"
#include "StallVipFrame.h"
#include "SFXData.h"
#include "PlayerActionData.h"
#include "TalentFrame.h"
#include "TalentTreeFrame.h"
#include "SkillBookFrame.h"
#include "QuestMgr.h"
#include "AppliedTree.h"
#include "..\Cool3D\Util\FileUtil.h"
#include "SocialMgr.h"
#include "HttpPicEx.h"
#include "StaticEx.h"
#include "TreeEx.h"
#include "ProgressEx.h"
#include "DungeonSys.h"
#include "QuestTargetWnd.h"
#include "ButtonEx.h"
#include "DragBtn.h"
#include "ItemButton.h"
#include "ItemMenuButton.h"
#include "SkillButton.h"
#include "PetSkillButton.h"
#include "TalentButton.h"
#include "ShopShelfFrame.h"
#include "StallShelfFrame.h"
#include "StallVendFrame.h"
#include "StallSignboardTipsFrame.h"
#include "RichEditWithZ.h"
#include "ChatShowPop.h"
#include "ToolTipStatic.h"
#include "RoleFloatTipsFrame.h"
#include "SkillProgressFrame.h"
#include "IconStatic.h"
#include "SceneCenterInfoFrame.h"
#include "RoleHeadTipsFrame.h"
#include "DakFrame.h"
#include "DakData.h"
#include "LevelUpData.h"
#include "PersonalityActData.h"
#include "StaticNoInput.h"
#include "CountDownFrame.h"
#include "CursorMgr.h"
#include "AudioSys.h"
#include "ItemMgr.h"
#include "EffectMgr.h"
#include "InstanceQuitFrame.h"
#include "ActivityPvPFrame.h"
#include "RemoteRoleStateFrame.h"
#include "ChatChannelSetFrame.h"
#include "MouseIntoTipsFrame.h"
#include "EquipRecencyFrame.h"
#include "SpecialSkillFrame.h"
#include "PetFrame.h"
#include "PetSkillFrame.h"
#include "OnlineTips.h"
#include "GameInputFrame.h"
#include "..\WorldDefine\msg_gm_cmd.h"
#include "..\WorldDefine\svn_revision.h"
#include "ServerTime.h"
#include "OwnerImeMgr.h"
#include "OwnerImeFrame.h"
#include "LocalPlayer.h"
#include "RoleMgr.h"
#include "GmConsole.h"
#include "PerfLogger.h"
#include "SeleRoleMgr.h"
#include "HelpFrame.h"
#include "QuizFrame.h"
#include "ProfessionFrame.h"
#include "GuildBusinessStateWnd.h"
#include "MonsterSayTable.h"
#include "MapMgr.h"
#include "MarriageFrame.h"
#include "DivorceFrame.h"
#include "RenameFrame.h"
#include "IconStaticHL.h"
#include "GemRemovalFrame.h"
#include "GlintPushButton.h"
extern VOID LuaOpenCommonLib(lua_State* l);
//-----------------------------------------------------------------------------
// init
//-----------------------------------------------------------------------------
BOOL Client::Init(HINSTANCE hInst)
{
m_pUtil->Randomize(timeGetTime()*1000);
CreateObj("GameConfig", "VarContainer");
CreateObj("VFS_System", "VirtualFileSys");
CreateObj("VFS_Animation", "VirtualFileSys");
CreateObj("VFS_Model", "VirtualFileSys");
CreateObj("VFS_Map", "VirtualFileSys");
TObjRef<VirtualFileSys>("VFS_System")->SetWorkingPackage(_T("data\\system.cpk"));
TObjRef<VirtualFileSys>("VFS_Animation")->SetWorkingPackage(_T("data\\system.cpk"));
TObjRef<VirtualFileSys>("VFS_Model")->SetWorkingPackage(_T("data\\system.cpk"));
TObjRef<Log>()->Create(NULL);
tstring strPath = g_strLocalPath + _T("\\string_table.xml");
g_StrTable.Init("VFS_System", strPath.c_str());
IFS* pIFS = (IFS*)(VOID*)TObjRef<VirtualFileSys>("VFS_System");
ResMgr::Inst()->SetFS(ResMgr::EFST_System, pIFS);
NavResMgr::Inst()->SetFS(NavResMgr::EFST_System, pIFS);
pIFS = (IFS*)(VOID*)TObjRef<VirtualFileSys>("VFS_Animation");
ResMgr::Inst()->SetFS(ResMgr::EFST_Animation, pIFS);
pIFS = (IFS*)(VOID*)TObjRef<VirtualFileSys>("VFS_Model");
ResMgr::Inst()->SetFS(ResMgr::EFST_Model, pIFS);
NavResMgr::Inst()->SetFS(NavResMgr::EFST_Model, pIFS);
pIFS = (IFS*)(VOID*)TObjRef<VirtualFileSys>("VFS_System");
ResMgr::Inst()->SetFS(ResMgr::EFST_Effect, pIFS);
pIFS = (IFS*)(VOID*)TObjRef<VirtualFileSys>("VFS_Map");
ResMgr::Inst()->SetFS(ResMgr::EFST_Map, pIFS);
NavResMgr::Inst()->SetFS(NavResMgr::EFST_Map, pIFS);
// 初始化渲染系统
this->InitRenderSystem(hInst);
//--初始化NavMap
const int navPoolBytes=8*1024*1024;
NavKernel::Inst()->Init(navPoolBytes);
pIFS = (IFS*)(VOID*)TObjRef<VirtualFileSys>("VFS_System");
Cool3D::AudioSystem::Inst()->SetFS(pIFS);
//--引擎资源管理器打开多线程读盘
ResMgr::Inst()->EnableIOAsync(true);
NavResMgr::Inst()->EnableIOAsync(true);
// 设置程序默认路径
vEngine::SetDefaultDir();
m_pAudioSys->Init();
m_pInput->Init(); // 初始化输入系统
m_pEditor->Init(m_pGUI, TRUE);// 初始化界面编辑器
m_pConsole->Init("VFS_System", 500, FALSE); // 初始化控制台
m_pGameScriptMgr->Init(); // 初始化脚本系统
m_pSession->Init(); // 初始化网络层
m_pFrameMgr->Init(); // 初始化程序框架
this->RegisterControl(); // 注册所有界面控件
this->RegisterFrame(); // 注册所有框架
// 启动选择服务器模块
m_pFrameMgr->CreateFrame(_T("Root"), _T("ServerSelect"), _T("ServerSelectFrame"), 0);
// 启动资源读取线程
m_bTerminateThreadLoad = FALSE;
m_hThreadLoad = (HANDLE)_beginthreadex(NULL, 0, (THREADPROC)m_Trunk.sfp1(&Client::ThreadLoad), NULL, 0, NULL);
if( 0 == m_hThreadLoad || -1 == (INT)m_hThreadLoad )
{
ERR(_T("Create Load thread failed"));
return FALSE;
}
CursorMgr::Inst()->Init(hInst);
if( GameSet::Inst()->Get(EGS_Console) )
{
m_pInputMap->Register(0, g_StrTable[_T("Hotkey_Console")], (INPUTMAPEVENTHANDLE)
m_pConsole->GetTrunk().sfp2(&vEngine::Console::Switch), DIK_F11, TRUE, TRUE, 1);
m_pInputMap->Register(0, g_StrTable[_T("Hotkey_UIEditor")], (INPUTMAPEVENTHANDLE)
m_pEditor->GetTrunk().sfp2(&vEngine::GUIEditor::Switch), DIK_F12, TRUE, TRUE, 1);
}
if( 17173 == GameSet::Inst()->Get(EGS_GmConsle) )
{
// 创建GM console框架
m_pFrameMgr->CreateFrame(_T("Root"), _T("GmConsole"), _T("GmConsoleFrame"), 0);
}
m_pInputMap->Register(0, g_StrTable[_T("Hotkey_ScreenShot0")], (INPUTMAPEVENTHANDLE)
m_Trunk.sfp2(&Client::ScreenShot), DIK_SCROLL, TRUE, TRUE, 1); // BMP格式截图
m_pInputMap->Register(1, g_StrTable[_T("Hotkey_ScreenShot1")], (INPUTMAPEVENTHANDLE)
m_Trunk.sfp2(&Client::ScreenShot), DIK_SYSRQ, TRUE, TRUE, 1); // JPG格式截图
// todo 临时代码 F10显示/隐藏当前所有GUIWnd,同时摄像机进入fly模式
m_pInputMap->Register(0, g_StrTable[_T("Hotkey_UI")], (INPUTMAPEVENTHANDLE)
m_Trunk.sfp2(&Client::SwitchGUIWnd), DIK_F10, TRUE, TRUE, 1);
// 注册控制台命令
m_pConsole->Register(_T("gm"), m_Trunk.sfp1(&Client::GMCommand), _T("gm command"), 1);
m_pConsole->Register(_T("res"), m_Trunk.sfp1(&Client::LogResPool), _T("log res"), 1);
m_pConsole->Register(_T("lrole"), m_Trunk.sfp1(&Client::DisplayLocalRoleAtt), _T("lrole att"), 1);
m_pConsole->Register(_T("headtips"), m_Trunk.sfp1(&Client::HeadTipsCommand), _T("headtips command"), 1);
// 初始化性能LOG生成器
PerfLogger::Inst()->Init();
// 创建tips框架
m_pFrameMgr->CreateFrame(_T("Root"), _T("Tooltip"), _T("ToolTipFrame"), 0);
// 创建自定义输入法
if( OwnerImeMgr::Inst()->IfOwnerIme() )
m_pFrameMgr->CreateFrame(_T("Root"), _T("OwnerIme"), _T("OwnerImeFrame"), 0);
// 建立名贴控件默认使用目录
::CreateDirectory(_T("temp"), NULL);
return TRUE;
}
//-----------------------------------------------------------------------------
// destroy
//-----------------------------------------------------------------------------
VOID Client::Destroy()
{
// 清空temp文件夹
DeleteDirectory(_T("temp"));
// 游戏结束后打开网页
TCHAR szURL[MAX_PATH]={0};
::GetPrivateProfileString(_T("Launcher"), _T("EndURL"), NULL, szURL, MAX_PATH,
_T("launcher\\launcher.ini"));
tstring strURL = szURL;
m_pUtil->CutSpaceOfStringHeadAndTail(strURL);
if( !strURL.empty() )
ShellExecute(NULL, _T("open"), _T("IEXPLORE"), szURL, NULL, SW_MAXIMIZE);
m_pFrameMgr->Destroy();
m_pWindow->Destroy();
m_pEditor->Destroy();
m_pConsole->Destroy();
m_pGUI->Destroy();
SeleRoleMgr::Inst()->Destroy();
CursorMgr::Inst()->Destroy();
OwnerImeMgr::Inst()->Destroy();
m_pAudioSys->Destroy();
ServerTime::Inst()->Destroy();
g_StrTable.Destroy();
KillObj("GUIRender");
Kernel::Inst()->FinalDestroy();
NavKernel::Inst()->Destroy();
}
//-----------------------------------------------------------------------------
// Mainloop
//-----------------------------------------------------------------------------
VOID Client::Mainloop()
{
DWORD dwMsg=0, dwParam1=0, dwParam2=0;
while( FALSE == m_pWindow->MsgLoop() )
{
// update
Cool3D::Kernel::Inst()->Tick();
WorldBase::NavKernel::Inst()->Tick();
Cool3D::IDevice* pDev=Cool3D::Device();
// 监视
m_pConsole->Watch(_T("FPS"), (DWORD)pDev->GetRenderStatus()->FPS);
m_pConsole->Watch(_T("Client Revision"), CLIENT_BUILD_REVISION);
m_pConsole->Watch(_T("vEngine Revision"), VENGINE_BUILD_REVISION);
m_pConsole->Watch(_T("Cool3D Revision"), COOL3D_BUILD_REVISION);
m_pConsole->Watch(_T("WorldBase Revision"), WORLDBASE_BUILD_REVISION);
m_pConsole->Watch(_T("WorldDefine Revision"), WORLDDEFINE_BUILD_REVISION);
m_pConsole->Watch(_T("Primative"), pDev->GetRenderStatus()->numPrim);
m_pConsole->Watch(_T("Draw call"), pDev->GetRenderStatus()->numDrawCall);
m_pConsole->Watch(_T("Texture switch"), pDev->GetRenderStatus()->numTexSwitch);
m_pConsole->Watch(_T("VB switch"), pDev->GetRenderStatus()->numVBSwitch);
m_pConsole->Watch(_T("Texture"), pDev->GetRenderStatus()->texSize);
m_pConsole->Watch(_T("Render target"), pDev->GetRenderStatus()->renderTexSize);
m_pConsole->Watch(_T("UI Render target"), m_pGUIRender->GetRTSize());
m_pConsole->Watch(_T("Static VB"), pDev->GetRenderStatus()->staticVBSize);
m_pConsole->Watch(_T("Dynamic VB"), pDev->GetRenderStatus()->dynamicVBSize);
m_pConsole->Watch(_T("Static IB"), pDev->GetRenderStatus()->staticIBSize);
m_pConsole->Watch(_T("Dynamic IB"), pDev->GetRenderStatus()->dynamicIBSize);
m_pConsole->Watch(_T("UI controls"), m_pGUI->GetControlNum());
m_pConsole->Watch(_T("Connected"), m_pSession->IsConnect());
m_pConsole->Watch(_T("EffectNum"), EffectMgr::Inst()->GetNumEffect());
// 更新性能LOG生成器
PerfLogger::Inst()->Updata();
BeginSpeedTest(_T("Client::Mainloop.msgloop"));
while( m_pWindow->PeekWindowsMsg(dwMsg, dwParam1, dwParam2) )
{
if( FALSE == m_pGUI->OnWindowsMsg(dwMsg, dwParam1, dwParam2) )
{
// 回车,切换输入法,将win32消息投递到聊天系统
if( dwMsg==WM_INPUTLANGCHANGE || (dwMsg==WM_KEYDOWN && dwParam1==VK_RETURN) || dwMsg==WM_KEYDOWN && dwParam1==VK_PRIOR)
{
ChatFrame* pFrame = (ChatFrame*)m_pFrameMgr->GetFrame(_T("Chat"));
if( P_VALID(pFrame) )
pFrame->OnWin32Msg(dwMsg, dwParam1, dwParam2);
}
}
GUIWnd* pWnd = m_pGUI->GetActive();
if( P_VALID(pWnd) && !pWnd->IsEditable() && dwMsg==WM_IME_COMPOSITION )
{
ChatFrame* pFrame = (ChatFrame*)m_pFrameMgr->GetFrame(_T("Chat"));
if( P_VALID(pFrame) )
{
HKL pHkl = pFrame->GetEnglishHKL();
if( pHkl )
ActivateKeyboardLayout( pHkl, KLF_SETFORPROCESS );
}
continue;
}
//全真屏输入法
OwnerImeMgr::Inst()->OnWindowsMsg(dwMsg, dwParam1, dwParam2);
CursorMgr::Inst()->OnWindowsMsg(dwMsg, dwParam1, dwParam2);
if( dwMsg == WM_QUIT )
return;
}
EndSpeedTest(_T("Client::Mainloop.msgloop"));
BeginSpeedTest(_T("Client::Mainloop.update"));
m_pInput->Update();
m_pInputMap->Update();
m_pGUI->Update();
m_pLuaMgr->Update(Kernel::Inst()->GetDeltaTime());
BeginSpeedTest(_T("Client::Mainloop.update.gameframe"));
m_pFrameMgr->Update();
EndSpeedTest(_T("Client::Mainloop.update.gameframe"));
m_pGameScriptMgr->Update(Kernel::Inst()->GetDeltaTime());
m_pSession->Update();
EndSpeedTest(_T("Client::Mainloop.update"));
m_pAudioSys->Update( Kernel::Inst()->GetDeltaTimeDW() );
if( FALSE == m_pWindow->IsWindowActive() )
{
Sleep(100);
}
// render
pDev->Begin();
DWORD dwBackGroundColor = 0xff000000;
SceneGraph* pSG = MapMgr::Inst()->GetSceneGraph();
if( NULL != pSG )
{
const tagDistFog& fog = pSG->GetSceneFog();
dwBackGroundColor = DWORD(fog.color);
}
pDev->Clear(true,true,true,dwBackGroundColor,1.0f,0);
BeginSpeedTest(_T("Client::Mainloop.Render3D"));
m_pFrameMgr->Render3D();
EndSpeedTest(_T("Client::Mainloop.Render3D"));
BeginSpeedTest(_T("Client::Mainloop.Render2D"));
Cool3D::IDraw2D::Inst()->BeginDraw(IDraw2D::EBlend_Alpha, false); // TODO:有些界面不需要Alpha混合
DWORD dwUIRenderTime = timeGetTime();
m_pGUI->Render();
m_pEditor->Render();
m_pConsole->Watch(_T("UI RenderTime"), timeGetTime() - dwUIRenderTime);
Cool3D::IDraw2D::Inst()->EndDraw();
EndSpeedTest(_T("Client::Mainloop.Render2D"));
DrawSpeedTest(0,200);
pDev->End();
// 设备丢失处理,必须在Present之前处理
if( pDev->GetDeviceResetFlag() )
{
m_pGUI->RedrawAllWnd();
m_pFrameMgr->SendEvent( &tagGameEvent( _T("DeviceResetEvent"), NULL ) );
pDev->ClearDeviceResetFlag();
}
BeginSpeedTest(_T("Client::Mainloop.Present"));
pDev->Present();
EndSpeedTest(_T("Client::Mainloop.Present"));
}
}
//-----------------------------------------------------------------------------
// RegisterControl
//-----------------------------------------------------------------------------
VOID Client::RegisterControl()
{
m_pGUI->Register(TWrap<HttpPicEx>(), _T("HttpPicEx"), _T("HttpPicEx"));
m_pGUI->Register(TWrap<StaticEx>(), _T("StaticEx"), _T("StaticEx"));
m_pGUI->Register(TWrap<TreeEx>(), _T("TreeEx"), _T("TreeEx"));
m_pGUI->Register(TWrap<ProgressEx>(), _T("ProgressEx"), _T("ProgressEx"));
m_pGUI->Register(TWrap<ButtonEx>(), _T("ButtonEx"), _T("ButtonEx"));
m_pGUI->Register(TWrap<DragBtn>(), _T("DragBtn"), _T("DragBtn"));
m_pGUI->Register(TWrap<ShortcutButton>(), _T("ShortcutButton"), _T("ShortcutButton"));
m_pGUI->Register(TWrap<RichEditBoxForChatInput>(), _T("RichEditBoxForChatInput"), _T("RichEditBoxForChatInput"));
m_pGUI->Register(TWrap<RichEditBoxForChatShow>(), _T("RichEditBoxForChatShow"), _T("RichEditBoxForChatShow"));
m_pGUI->Register(TWrap<ScrollRichEditBox>(), _T("ScrollRichEditBox"), _T("ScrollRichEditBox"));
m_pGUI->Register(TWrap<ItemButton>(), _T("ItemButton"), _T("ItemButton"));
m_pGUI->Register(TWrap<ItemMenuButton>(), _T("ItemMenuButton"), _T("ItemMenuButton"));
m_pGUI->Register(TWrap<SkillButton>(), _T("SkillButton"), _T("SkillButton"));
m_pGUI->Register(TWrap<PetSkillButton>(), _T("PetSkillButton"), _T("PetSkillButton"));
m_pGUI->Register(TWrap<TalentButton>(), _T("TalentButton"), _T("TalentButton"));
m_pGUI->Register(TWrap<MiniMapStatic>(), _T("MiniMapStatic"), _T("MiniMapStatic"));
m_pGUI->Register(TWrap<ActiveStatic>(), _T("ActiveStatic"), _T("ActiveStatic"));
m_pGUI->Register(TWrap<ActiveProgress>(), _T("ActiveProgress"), _T("ActiveProgress"));
m_pGUI->Register(TWrap<ComposeStatic>(), _T("ComposeStatic"), _T("ComposeStatic"));
m_pGUI->Register(TWrap<PlayerViewWindow>(), _T("PlayerViewWindow"), _T("PlayerViewWindow"));
m_pGUI->Register(TWrap<PetShowWindow>(), _T("PetShowWindow"), _T("PetShowWindow"));
m_pGUI->Register(TWrap<AppliedTree>(), _T("AppliedTree"), _T("AppliedTree"));
m_pGUI->Register(TWrap<ToolTipStatic>(), _T("ToolTipStatic"), _T("ToolTipStatic"));
m_pGUI->Register(TWrap<RichEditWithZ>(), _T("RichEditWithZ"), _T("RichEditWithZ"));
m_pGUI->Register(TWrap<StaticForCast>(), _T("StaticForCast"), _T("StaticForCast"));
m_pGUI->Register(TWrap<RoleHeadPicIcon>(), _T("RoleHeadPicIcon"), _T("RoleHeadPicIcon"));
m_pGUI->Register(TWrap<IconStatic>(), _T("IconStatic"), _T("IconStatic"));
m_pGUI->Register(TWrap<StaticNoInput>(), _T("StaticNoInput"), _T("StaticNoInput"));
m_pGUI->Register(TWrap<ZoneMapStatic>(), _T("ZoneMapStatic"), _T("ZoneMapStatic"));
m_pGUI->Register(TWrap<LockStatic>(), _T("LockStatic"), _T("LockStatic"));
m_pGUI->Register(TWrap<PlayerTryDressWnd>(), _T("PlayerTryDressWnd"), _T("PlayerTryDressWnd"));
m_pGUI->Register(TWrap<GoodsButton>(), _T("GoodsButton"), _T("GoodsButton"));
m_pGUI->Register(TWrap<MallButton>(), _T("MallButton"), _T("MallButton"));
m_pGUI->Register(TWrap<SpecialSkillButton>(), _T("SpecialSkillButton"), _T("SpecialSkillButton"));
m_pGUI->Register(TWrap<GlintPushButton>(), _T("GlintPushButton"), _T("GlintPushButton") );
m_pGUI->Register(TWrap<IconStaticHL>(), _T("IconStaticHL"), _T("IconStaticHL") );
}
//-----------------------------------------------------------------------------
// RegisterFrame
//-----------------------------------------------------------------------------
VOID Client::RegisterFrame()
{
m_pFrameMgr->Register(TWrap<LoginFrame>(), _T("LoginFrame"));
m_pFrameMgr->Register(TWrap<SelectRoleFrame>(), _T("SelectRoleFrame"));
m_pFrameMgr->Register(TWrap<HealthyControlFrame>(), _T("HealthyControlFrame"));
m_pFrameMgr->Register(TWrap<WorldFrame>(), _T("WorldFrame"));
m_pFrameMgr->Register(TWrap<LoadingFrame>(), _T("LoadingFrame"));
m_pFrameMgr->Register(TWrap<SysMenuFrame>(), _T("SysMenuFrame"));
m_pFrameMgr->Register(TWrap<SysOptionMenuFrame>(), _T("SysOptionMenuFrame"));
m_pFrameMgr->Register(TWrap<ExitPromptFrame>(), _T("ExitPromptFrame"));
m_pFrameMgr->Register(TWrap<GameSettingsFrame>(), _T("GameSettingsFrame"));
m_pFrameMgr->Register(TWrap<MiniMapFrame>(), _T("MiniMapFrame"));
m_pFrameMgr->Register(TWrap<PlayerStateFrame>(), _T("PlayerStateFrame"));
m_pFrameMgr->Register(TWrap<TargetStateFrame>(), _T("TargetStateFrame"));
m_pFrameMgr->Register(TWrap<TargetSpellStateFrame>(), _T("TargetSpellStateFrame"));
m_pFrameMgr->Register(TWrap<TeammatesStateFrame>(), _T("TeammatesStateFrame"));
m_pFrameMgr->Register(TWrap<CreateRoleFrame>(), _T("CreateRoleFrame"));
m_pFrameMgr->Register(TWrap<ItemFrame>(), _T("ItemFrame"));
m_pFrameMgr->Register(TWrap<PocketFrame>(), _T("PocketFrame"));
m_pFrameMgr->Register(TWrap<PetBagFrame>(), _T("PetBagFrame"));
m_pFrameMgr->Register(TWrap<ThroneFrame>(), _T("ThroneFrame"));
m_pFrameMgr->Register(TWrap<StorageFrame>(), _T("StorageFrame"));
m_pFrameMgr->Register(TWrap<PocketEncryptFrame>(), _T("PocketEncryptFrame"));
m_pFrameMgr->Register(TWrap<TradeFrame>(), _T("TradeFrame"));
m_pFrameMgr->Register(TWrap<ShopShelfFrame>(), _T("ShopShelfFrame"));
m_pFrameMgr->Register(TWrap<PlayerTradeFrame>(), _T("PlayerTradeFrame"));
m_pFrameMgr->Register(TWrap<ToolTipFrame>(), _T("ToolTipFrame"));
m_pFrameMgr->Register(TWrap<CharacterFrame>(), _T("CharacterFrame"));
m_pFrameMgr->Register(TWrap<TargetCharacterFrame>(), _T("TargetCharacterFrame"));
m_pFrameMgr->Register(TWrap<StateFrame>(), _T("StateFrame"));
m_pFrameMgr->Register(TWrap<EquipmentFrame>(), _T("EquipmentFrame"));
m_pFrameMgr->Register(TWrap<ReputeFrame>(), _T("ReputeFrame"));
m_pFrameMgr->Register(TWrap<FameHallFrame>(), _T("FameHallFrame"));
m_pFrameMgr->Register(TWrap<ClanTreasureFrame>(), _T("ClanTreasureFrame"));
m_pFrameMgr->Register(TWrap<RoleTitleFrame>(), _T("RoleTitleFrame"));
m_pFrameMgr->Register(TWrap<InformationFrame>(), _T("InformationFrame"));
m_pFrameMgr->Register(TWrap<DispRoleInfoFrame>(), _T("DispRoleInfoFrame"));
m_pFrameMgr->Register(TWrap<ItemProduceFrame>(), _T("ItemProduceFrame"));
m_pFrameMgr->Register(TWrap<DeComposeFrame>(), _T("DeComposeFrame"));
m_pFrameMgr->Register(TWrap<EquipConsolidateFrame>(), _T("EquipConsolidateFrame"));
m_pFrameMgr->Register(TWrap<ChatFrame>(), _T("ChatFrame"));
m_pFrameMgr->Register(TWrap<MilleSoundFrame>(), _T("MilleSoundFrame"));
m_pFrameMgr->Register(TWrap<EmotionFrame>(), _T("EmotionFrame"));
m_pFrameMgr->Register(TWrap<ShortcutBarFrame>(), _T("ShortcutBarFrame"));
m_pFrameMgr->Register(TWrap<WorldPickerFrame>(), _T("WorldPickerFrame"));
m_pFrameMgr->Register(TWrap<CombatSys>(), _T("CombatSysFrame"));
m_pFrameMgr->Register(TWrap<TalentFrame>(), _T("TalentFrame"));
m_pFrameMgr->Register(TWrap<TalentTreeFrame>(), _T("TalentTreeFrame"));
m_pFrameMgr->Register(TWrap<SkillBookFrame>(), _T("SkillBookFrame"));
m_pFrameMgr->Register(TWrap<ServerSelectFrame>(), _T("ServerSelectFrame"));
m_pFrameMgr->Register(TWrap<RoleFloatTipsFrame>(), _T("RoleFloatTipsFrame"));
m_pFrameMgr->Register(TWrap<GameInputFrame>(), _T("GameInputFrame"));
m_pFrameMgr->Register(TWrap<SkillProgressFrame>(), _T("SkillProgressFrame"));
m_pFrameMgr->Register(TWrap<SceneCenterInfoFrame>(), _T("SceneCenterInfoFrame"));
m_pFrameMgr->Register(TWrap<RoleHeadTipsFrame>(), _T("RoleHeadTipsFrame"));
m_pFrameMgr->Register(TWrap<DakFrame>(), _T("DakFrame"));
m_pFrameMgr->Register(TWrap<SocialMgr>(), _T("SocialMgrFrame"));
m_pFrameMgr->Register(TWrap<ZoneMapFrame>(), _T("ZoneMapFrame"));
m_pFrameMgr->Register(TWrap<MallFrame>(), _T("MallFrame"));
m_pFrameMgr->Register(TWrap<MallGiftFrame>(), _T("MallGiftFrame"));
m_pFrameMgr->Register(TWrap<YuanbaoFrame>(), _T("YuanbaoFrame"));
m_pFrameMgr->Register(TWrap<TeammatesStateFrame>(), _T("TeammatesState"));
m_pFrameMgr->Register(TWrap<StallShelfFrame>(), _T("StallShelfFrame"));
m_pFrameMgr->Register(TWrap<StallVendFrame>(), _T("StallVendFrame"));
m_pFrameMgr->Register(TWrap<StallSignboardTipsFrame>(), _T("StallSignboardTipsFrame"));
m_pFrameMgr->Register(TWrap<QuitFrame>(), _T("QuitFrame"));
m_pFrameMgr->Register(TWrap<InstanceQuitFrame>(), _T("InstanceQuitFrame"));
m_pFrameMgr->Register(TWrap<DungeonSys>(), _T("DungeonSysFrame"));
m_pFrameMgr->Register(TWrap<CountDownFrame>(), _T("CountDownFrame"));
m_pFrameMgr->Register(TWrap<PetFrame>(), _T("PetFrame"));
m_pFrameMgr->Register(TWrap<PetSkillFrame>(), _T("PetSkillFrame"));
m_pFrameMgr->Register(TWrap<PetInformationFrame>(), _T("PetInformationFrame"));
m_pFrameMgr->Register(TWrap<PetTradeFrame>(), _T("PetTradeFrame"));
m_pFrameMgr->Register(TWrap<PetTradeUIFrame>(), _T("PetTradeUIFrame"));
m_pFrameMgr->Register(TWrap<TreasureChestFrame>(), _T("TreasureChestFrame"));
m_pFrameMgr->Register(TWrap<GuildFrame>(), _T("GuildFrame"));
m_pFrameMgr->Register(TWrap<GuildMemberInfoFrame>(), _T("GuildMemberInfoFrame"));
m_pFrameMgr->Register(TWrap<GuildMemberPosFrame>(), _T("GuildMemberPosFrame"));
m_pFrameMgr->Register(TWrap<GuildAffairFrame>(), _T("GuildAffairFrame"));
m_pFrameMgr->Register(TWrap<GuildUpgradeFrame>(), _T("GuildUpgradeFrame"));
m_pFrameMgr->Register(TWrap<GuildPickUpSilverFrame>(), _T("GuildPickUpSilverFrame"));
m_pFrameMgr->Register(TWrap<GuildContributeSilverFrame>(), _T("GuildContributeSilverFrame"));
m_pFrameMgr->Register(TWrap<GuildBusinessFrame>(), _T("GuildBusinessFrame"));
m_pFrameMgr->Register(TWrap<GuildBusinessRankFrame>(), _T("GuildBusinessRankFrame"));
m_pFrameMgr->Register(TWrap<GuildBusinessStateWnd>(), _T("GuildBusinessStateWnd"));
m_pFrameMgr->Register(TWrap<NoticeFrame>(), _T("NoticeFrame"));
m_pFrameMgr->Register(TWrap<InsuranceFrame>(), _T("InsuranceFrame"));
m_pFrameMgr->Register(TWrap<GroupBuyFrame>(), _T("GroupBuyFrame"));
m_pFrameMgr->Register(TWrap<OnlineTips>(), _T("OnlineTipsFrame"));
m_pFrameMgr->Register(TWrap<GroundItemTipsFrame>(), _T("GroundItemTipsFrame"));
m_pFrameMgr->Register(TWrap<GmConsoleFrame>(), _T("GmConsoleFrame"));
m_pFrameMgr->Register(TWrap<StallVipFrame>(), _T("StallVipFrame"));
m_pFrameMgr->Register(TWrap<OwnerImeFrame>(), _T("OwnerImeFrame"));
m_pFrameMgr->Register(TWrap<RemoteRoleStateFrame>(), _T("RemoteRoleStateFrame"));
m_pFrameMgr->Register(TWrap<ChatChannelSetFrame>(), _T("ChatChannelSetFrame"));
m_pFrameMgr->Register(TWrap<MouseIntoTipsFrame>(), _T("MouseIntoTipsFrame"));
m_pFrameMgr->Register(TWrap<ActivityPvPFrame>(), _T("ActivityPvPFrame"));
m_pFrameMgr->Register(TWrap<EquipRecencyFrame>(), _T("EquipRecencyFrame"));
m_pFrameMgr->Register(TWrap<SpecialSkillFrame>(), _T("SpecialSkillFrame"));
m_pFrameMgr->Register(TWrap<StyleActionFrame>(), _T("StyleActionFrame"));
m_pFrameMgr->Register(TWrap<GuildStorageFrame>(), _T("GuildStorageFrame"));
m_pFrameMgr->Register(TWrap<GuildStorePermitFrame>(), _T("GuildStorePermitFrame"));
m_pFrameMgr->Register(TWrap<HelpFrame>(), _T("HelpFrame"));
m_pFrameMgr->Register(TWrap<QuizFrame>(), _T("QuizFrame"));
m_pFrameMgr->Register(TWrap<ProfessionFrame>(), _T("ProfessionFrame"));
m_pFrameMgr->Register(TWrap<QuestTargetWnd>(), _T("QuestTargetWnd"));
m_pFrameMgr->Register(TWrap<MarriageFrame>(), _T("MarriageFrame"));
m_pFrameMgr->Register(TWrap<DivorceFrame>(), _T("DivorceFrame"));
m_pFrameMgr->Register(TWrap<RenameFrame>(), _T("RenameFrame"));
m_pFrameMgr->Register(TWrap<GemRemovalFrame>(),_T("GemRemovalFrame") );
//注册节日活动上线提示
m_pFrameMgr->Register(TWrap<FestivalActivityPromptFrame>(), _T("FestivalActivityPromptFrame") );
//角色升级到某个级别的提示,寻路
m_pFrameMgr->Register(TWrap<RoleLevelUpPromptFrame>(), _T("RoleLevelUpPromptFrame") );
// 注册神龙赐福模块
m_pFrameMgr->Register(TWrap<LoongBenedictionFrame>(), _T("LoongBenedictionFrame") );
QuestMgr::RegisterFrames(m_pFrameMgr);
CombatSys::RegisterFrames(m_pFrameMgr);
SocialMgr::RegisterFrames(m_pFrameMgr);
}
//-----------------------------------------------------------------------------
// InitRenderSystem
//-----------------------------------------------------------------------------
BOOL Client::InitRenderSystem(HINSTANCE hInst)
{
GameSet::Inst()->Init();
DWORD dwWindow = GameSet::Inst()->Get(EGS_Windowed);
INT nWidth = GameSet::Inst()->Get(EGS_PelsWidth);
INT nHeight = GameSet::Inst()->Get(EGS_PelsHeight);
RECT rc = {0};
// 窗口标题
tstringstream stream;
stream<<g_pAppName<<_T(" ") <<g_pBuildType<<_T(" ")<<g_pVersion;
Kernel::Inst()->CreateEngine(( Cool3D::ConfigFile*)NULL);
switch(dwWindow)
{
case 0: // 全屏
{
m_pWindow->Init(m_pGUIRender, nWidth, nHeight, FALSE, FALSE);
m_pWindow->SetInvisibleIme(TRUE);
OwnerImeMgr::Inst()->Init();
OwnerImeMgr::Inst()->EnableOwnerIme();
}
break;
case 1: // 最佳窗口
m_pWindow->Init(m_pGUIRender, 0, 0, FALSE, TRUE);
break;
case 2: // 标准窗口
m_pWindow->Init(m_pGUIRender, nWidth, nHeight, TRUE, TRUE);
break;
case 3: // 假全屏
m_pWindow->Init(m_pGUIRender, 0, 0, FALSE, FALSE);
break;
}
m_pWindow->CreateWnd(stream.str().c_str(), hInst);
HWND hWnd = (HWND)TObjRef<VarContainer>()->GetDword(_T("HWND"));
// 得到实际客户区大小
::GetClientRect(hWnd, (LPRECT)&rc);
nWidth = rc.right - rc.left;
nHeight = rc.bottom - rc.top;
tagDeviceCfg cfg;
cfg.bWindowed = (dwWindow > 0);
cfg.depthFormat = EDF_D24S8;
cfg.hWnd = hWnd;
cfg.nWidth = nWidth;
cfg.nHeight = nHeight;
cfg.nFullScreenHZ = 0;
cfg.bVerticalSync = TRUE == GameSet::Inst()->Get( EGS_VerSynch );
cfg.multiSampleType = (EMultisampleType)GameSet::Inst()->Get( EGS_MultiSampleType );
if(dwWindow>0)
{
HDC hDC=::GetDC(hWnd);
int screenColorBits=GetDeviceCaps(hDC,BITSPIXEL);
ReleaseDC(hWnd,hDC);
//--自动检测16bit还是32bit窗口模式
cfg.pixelFormat = (screenColorBits==32) ? EPF_X8R8G8B8 : EPF_R5G6B5;
}
else
cfg.pixelFormat=EPF_X8R8G8B8;
Kernel::Inst()->CreateRenderDevice(&cfg);
Kernel::Inst()->GetRenderSys()->EnableFog(true);
// 清空一下后台缓冲
Cool3D::IDevice* pDev=Cool3D::Device();
pDev->Begin();
pDev->Clear(true,true,true,0xff000000,1.0f,0);
pDev->End();
pDev->Present();
pDev->Begin();
pDev->Clear(true,true,true,0xff000000,1.0f,0);
pDev->End();
pDev->Present();
GameSet::Inst()->ApplyAll();
m_pGUIRender->Init();
m_pGUI->Init(nWidth, nHeight, m_pGUIRender, "VFS_System");
// 载入字体
m_pGUI->LoadFont(_T("kaiti.ttf"));
m_pGUI->LoadFont(_T("lishu.ttf"));
m_pGUI->LoadFont(_T("hanyi.ttf"));
m_pGUI->LoadFont(_T("MSYH.TTF"));
m_pGUI->LoadFont(_T("msyhb.ttf"));
return TRUE;
}
//-----------------------------------------------------------------------------
// GUIWnd显示开关
//-----------------------------------------------------------------------------
DWORD Client::SwitchGUIWnd( DWORD dwID, BOOL bDown )
{
if( bDown )
{
WorldFrame* pWolrdFrame = GetWorldFrm();
if( m_pGUI->GetDesktop()->IsInvisible() )
{
m_pGUI->GetDesktop()->SetInvisible(false); // 显示界面
// 摄像机退出fly模式
if( P_VALID(pWolrdFrame) && 17173 == GameSet::Inst()->Get(EGS_GmConsle) )
pWolrdFrame->GetCamera()->EnableFlyMode(false);
}
else
{
m_pGUI->GetDesktop()->SetInvisible(true); // 隐藏界面
// 摄像机进入fly模式
if( P_VALID(pWolrdFrame) && 17173 == GameSet::Inst()->Get(EGS_GmConsle) )
pWolrdFrame->GetCamera()->EnableFlyMode(true);
}
}
return 0;
}
//-----------------------------------------------------------------------------
// 截图
//-----------------------------------------------------------------------------
DWORD Client::ScreenShot(DWORD dwID, BOOL bDown)
{
// INT* p = 0;
// *p = 0;
if( !bDown )
return 0;
// 创建目录,防止玩家将此目录删除之后无法保存图片
CreateDirectory(_T("screenshot"), NULL);
vEngine::SetDefaultDir();
// 如果只使用系统时间作为文件名,那么同一秒内抓的文件会被覆盖
TCHAR szTime[MAX_PATH];
FILETIME CurrentTime;
GetSystemTimeAsFileTime(&CurrentTime);
szTime[0] = _T('\0');
WORD wDate, wTime;
if (FileTimeToLocalFileTime(&CurrentTime, &CurrentTime) &&
FileTimeToDosDateTime(&CurrentTime, &wDate, &wTime))
{
// 年月日以及时分秒和timeGetTime
wsprintf(szTime, _T("[%d-%d-%d %02d%02d%02d]-%d"),
(wDate / 32) & 15, wDate & 31, (wDate / 512) + 1980,
(wTime >> 11), (wTime >> 5) & 0x3F, (wTime & 0x1F) * 2,
timeGetTime());
}
tstringstream streamPath;
if( dwID == 0 )
streamPath << (_T("screenshot\\LoongScreenshot")) << szTime << _T(".bmp");
else
streamPath << (_T("screenshot\\LoongScreenshot")) << szTime << _T(".jpg");
if( Device()->ScreenShot(streamPath.str().c_str(), dwID==1) )
{
ChatFrame* pChatFrame = (ChatFrame*)(m_pFrameMgr->GetFrame(_T("Chat")));
if( P_VALID(pChatFrame) )
{
tstring strMsg = g_StrTable[_T("ScreenShoot_OK")];
strMsg += streamPath.str();
//添加从服务器接受的聊天数据到相应的显示频道
pChatFrame->PushInfo(strMsg.c_str(), ESCC_System);
}
}
return 0;
}
//-----------------------------------------------------------------------------
// GM命令处理
//-----------------------------------------------------------------------------
DWORD Client::GMCommand(LPCTSTR szCommand)
{
if( m_pSession->IsConnect() )
{
tagNC_GMCommand cmd;
lstrcpyn(cmd.szCommand, szCommand, MAX_GM_COMMAND_LEN-1);
m_pSession->Send(&cmd);
return 1;
}
else
{
IMSG(_T("Have not connected to Server yet\r\n"));
return -1;
}
}
//-----------------------------------------------------------------------------
// 将3D引擎资源池状态写入日志文件
//-----------------------------------------------------------------------------
DWORD Client::LogResPool( LPCTSTR szCommand )
{
Cool3D::ResMgr::Inst()->Report();
Cool3D::IDraw2D::Inst()->Report();
WorldBase::NavResMgr::Inst()->Report();
return 0;
}
//-----------------------------------------------------------------------------
// 显示本地角色所有属性
//-----------------------------------------------------------------------------
DWORD Client::DisplayLocalRoleAtt(LPCTSTR szCommand)
{
LocalPlayer* pLP = RoleMgr::Inst()->GetLocalPlayer();
if( P_VALID(pLP))
{
for( int i=ERA_AttA_Start; i<ERA_End; ++i )
{
TCHAR szBuff[X_LONG_NAME] = {0};
_sntprintf( szBuff, X_LONG_NAME, _T("LocalPlayerAtt_%d"), i );
TCHAR szShow[X_LONG_NAME] = {0};
_sntprintf( szShow, X_LONG_NAME, g_StrTable[szBuff], pLP->GetAttribute((ERoleAttribute)i) );
IMSG(_T("%s\n"), szShow);
}
}
return 0;
}
//-----------------------------------------------------------------------------
// 关闭/开起头顶tips
//-----------------------------------------------------------------------------
DWORD Client::HeadTipsCommand(LPCTSTR szCommand)
{
RoleHeadTipsFrame* pFrame = (RoleHeadTipsFrame*)m_pFrameMgr->GetFrame(_T("RoleHeadTips"));
if( P_VALID(pFrame) )
{
tstring strTmp = szCommand;
if( !strTmp.empty() && strTmp.find(_T('0'))!=strTmp.npos )
{
pFrame->SetIsShowHeadTips(FALSE);
}
else if( !strTmp.empty() && strTmp.find(_T('1'))!=strTmp.npos )
{
pFrame->SetIsShowHeadTips(TRUE);
}
}
return 0;
}
//-----------------------------------------------------------------------------
// 资源读取线程
//-----------------------------------------------------------------------------
UINT Client::ThreadLoad( LPVOID )
{
DWORD dwTotalTime = timeGetTime();
try
{
IMSG(_T("CreatureData Loaded.\r\n"));
CreatureData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
IMSG(_T("PetData Loaded.\r\n"));
PetProtoData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
IMSG(_T("ScnSfxData Loaded.\r\n"));
SceneEffectData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
IMSG(_T("ItemProtoData Loaded.\r\n"));
ItemProtoData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
IMSG(_T("SkillProtoData Loaded.\r\n"));
SkillProtoData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
IMSG(_T("ShopProtoData Loaded.\r\n"));
ShopProtoData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
IMSG(_T("ConsolidateData Loaded.\r\n"));
ConsolidateData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
IMSG(_T("ProduceData Loaded.\r\n"));
ProduceData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
RoleInfoProtoData::inst()->LoadFromFile();
if (m_bTerminateThreadLoad)
return 0;
RoleTitleProtoData::Inst()->LoadFromFile();
if (m_bTerminateThreadLoad)
return 0;
MapLogicData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
IMSG(_T("DakData Loaded.\r\n"));
DakData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
IMSG(_T("LevelUpData Loaded.\r\n"));
LevelUpData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
IMSG(_T("PersonalityActData Loaded.\r\n"));
PersonalityActData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
IMSG(_T("ZoneMapData Loaded.\r\n"));
ZoneMapData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
IMSG(_T("QuestMgr Loaded.\r\n"));
QuestMgr::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
MallData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
FilterData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
LonghunAttData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
SFXData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
PlayerActionData::Inst()->LoadFromFile();
if( m_bTerminateThreadLoad )
return 0;
MonsterSayTable::Inst()->Init();
if( m_bTerminateThreadLoad )
return 0;
IMSG(_T("\r\nTotal time = %d\r\n"), timeGetTime()-dwTotalTime);
}
catch(vEngine::Exception)
{
#ifdef _DEBUG
throw; // 方便调试器调试
#endif
}
_endthreadex(0);
return 0;
}
//-----------------------------------------------------------------------------
// 等待资源读取线程完成
//-----------------------------------------------------------------------------
VOID Client::WaitThreadLoad()
{
WaitForSingleObject(m_hThreadLoad, INFINITE);
}
//-----------------------------------------------------------------------------
// 等待资源读取线程强行结束
//-----------------------------------------------------------------------------
VOID Client::ExitThreadLoad()
{
m_bTerminateThreadLoad = TRUE;
WaitForSingleObject(m_hThreadLoad, INFINITE);
}
BOOL Client::DeleteDirectory( LPCTSTR szDirName )
{
TCHAR cFiles[100] = {0};
_tcscpy(cFiles, szDirName);
_tcscat(cFiles, _T("\\*.*"));
WIN32_FIND_DATA wfd;
HANDLE hFind = FindFirstFile(cFiles, &wfd);
TCHAR cTmp[200] = {0};
if(hFind != INVALID_HANDLE_VALUE)
{
BOOL bFind = TRUE;
while(bFind)
{
_tcscpy(cTmp, szDirName);
_tcscat(cTmp, _T("\\"));
_tcscat(cTmp, wfd.cFileName);
SetFileAttributes(cTmp, FILE_ATTRIBUTE_NORMAL);
DeleteFile(cTmp);
bFind=FindNextFile(hFind,&wfd);
}
FindClose(hFind);
}
return TRUE;
}
|
[
"prihodko@dlit.dp.ua"
] |
prihodko@dlit.dp.ua
|
2938c0cd1613028516786a21709d527a58f0c436
|
a6d15c19698025ee007ed6b7b258a4de9eca40d2
|
/softwarecontest/src/GameLobby.h
|
52de347b2d18661bb8e998d37e4a04dae6d7823f
|
[] |
no_license
|
dougreichard/software-contest-2013
|
109910cf837cc9ee46e1f3d8569b2086df49e62a
|
ec4c3ebae22f9530da8ebc4de280d8d3fd5da338
|
refs/heads/master
| 2021-01-13T02:10:37.063244
| 2013-02-28T17:10:37
| 2013-02-28T17:10:37
| 8,271,942
| 0
| 0
| null | 2023-08-29T18:19:55
| 2013-02-18T16:12:57
|
C
|
UTF-8
|
C++
| false
| false
| 408
|
h
|
#pragma once
#include "Socket.h"
#include <list>
using namespace std;
class GameClient;
class GameLobby: public ServerSocket {
public:
void leave(GameClient* client);
GameClient* getPlayerByName(string name);
list<GameClient*>& getClients();
protected:
virtual ClientSocket* AllocClient();
virtual void OnString(string s);
protected:
list<GameClient*> _clients;
list<GameClient*> _goneclients;
};
|
[
"doug.reichard+github@gmail.com"
] |
doug.reichard+github@gmail.com
|
5e847d96a7f6a94f047277bfa05bb2cae1f1f572
|
f8b5a550831d0e7a701be12b991ec037703118d7
|
/include/JoSIM/VoltageSource.hpp
|
6301549c082cdd7cd6b5341db8aec0aed4a204e0
|
[
"MIT"
] |
permissive
|
JoeyDelp/JoSIM
|
37c54aa0c51595d72a472d83878204328cfc412d
|
8818fcef6cd192ac7e0be6dbce89af611b64ad6f
|
refs/heads/master
| 2023-08-31T00:04:42.941902
| 2023-08-10T13:06:34
| 2023-08-10T13:06:34
| 124,359,635
| 56
| 26
|
MIT
| 2023-02-05T16:21:18
| 2018-03-08T08:18:50
|
C++
|
UTF-8
|
C++
| false
| false
| 1,029
|
hpp
|
// Copyright (c) 2021 Johannes Delport
// This code is licensed under MIT license (see LICENSE for details)
#ifndef JOSIM_VOLTAGESOURCE_HPP
#define JOSIM_VOLTAGESOURCE_HPP
#include <optional>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "JoSIM/BasicComponent.hpp"
#include "JoSIM/Function.hpp"
#include "JoSIM/ParameterName.hpp"
#include "JoSIM/Parameters.hpp"
namespace JoSIM {
/*
Vlabel V⁺ V⁻ sourcetype
⎡ 0 0 1⎤ ⎡V⁺⎤ ⎡ 0⎤
⎜ 0 0 -1⎟ ⎜V⁻⎟ = ⎜ 0⎟
⎣ 1 -1 0⎦ ⎣Io⎦ ⎣ 0⎦
*/
class VoltageSource : public BasicComponent {
public:
int64_t sourceIndex_;
double pn1_ = 0.0, pn2_ = pn1_, pn3_ = pn2_, pn4_ = 0.0;
VoltageSource(const std::pair<tokens_t, string_o>& s, const NodeConfig& ncon,
const nodemap& nm, std::unordered_set<std::string>& lm,
nodeconnections& nc, int64_t& bi, const int64_t& ci);
void step_back() override { pn2_ = pn4_; }
}; // class VoltageSource
} // namespace JoSIM
#endif
|
[
"joeydelp@gmail.com"
] |
joeydelp@gmail.com
|
a7543702cd41752d9089994e0ac5d9428da87aeb
|
a44a67ae800e785b9cd2d677668836d8564df0c5
|
/android-jni/jni/boost/variant/variant.hpp
|
b623baae5bfb003324241eb7e8b9349ea9d54a6f
|
[
"MIT"
] |
permissive
|
thanghoang/S3ORAM
|
a6809dfb98fdbf0089e6b1c01eb4a8476852668e
|
ae524107508c03ec45a37b388f069cd8c40242a9
|
refs/heads/master
| 2022-11-02T08:03:28.101304
| 2022-10-24T20:55:08
| 2022-10-24T20:55:08
| 101,727,862
| 20
| 9
|
MIT
| 2022-10-24T20:53:47
| 2017-08-29T06:38:10
|
C++
|
UTF-8
|
C++
| false
| false
| 66,748
|
hpp
|
//-----------------------------------------------------------------------------
// boost variant/variant.hpp header file
// See http://www.boost.org for updates, documentation, and revision history.
//-----------------------------------------------------------------------------
//
// Copyright (c) 2002-2003
// Eric Friedman, Itay Maman
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_VARIANT_VARIANT_HPP
#define BOOST_VARIANT_VARIANT_HPP
#include <cstddef> // for std::size_t
#include <new> // for placement new
#if !defined(BOOST_NO_TYPEID)
#include <typeinfo> // for typeid, std::type_info
#endif // BOOST_NO_TYPEID
#include "boost/variant/detail/config.hpp"
#include "boost/mpl/aux_/config/eti.hpp"
#include "boost/mpl/aux_/value_wknd.hpp"
#include "boost/variant/variant_fwd.hpp"
#include "boost/variant/detail/backup_holder.hpp"
#include "boost/variant/detail/enable_recursive_fwd.hpp"
#include "boost/variant/detail/forced_return.hpp"
#include "boost/variant/detail/initializer.hpp"
#include "boost/variant/detail/make_variant_list.hpp"
#include "boost/variant/detail/over_sequence.hpp"
#include "boost/variant/detail/visitation_impl.hpp"
#include "boost/variant/detail/hash_variant.hpp"
#include "boost/variant/detail/generic_result_type.hpp"
#include "boost/variant/detail/has_nothrow_move.hpp"
#include "boost/variant/detail/move.hpp"
#include "boost/detail/reference_content.hpp"
#include "boost/aligned_storage.hpp"
#include "boost/blank.hpp"
#include "boost/math/common_factor_ct.hpp"
#include "boost/static_assert.hpp"
#include "boost/preprocessor/cat.hpp"
#include "boost/preprocessor/repeat.hpp"
#include "boost/type_traits/alignment_of.hpp"
#include "boost/type_traits/add_const.hpp"
#include "boost/type_traits/has_nothrow_constructor.hpp"
#include "boost/type_traits/has_nothrow_copy.hpp"
#include "boost/type_traits/is_const.hpp"
#include "boost/type_traits/is_same.hpp"
#include "boost/type_traits/is_rvalue_reference.hpp"
#include "boost/utility/enable_if.hpp"
#include "boost/utility/declval.hpp"
#include "boost/variant/recursive_wrapper_fwd.hpp"
#include "boost/variant/static_visitor.hpp"
#include "boost/mpl/assert.hpp"
#include "boost/mpl/begin_end.hpp"
#include "boost/mpl/bool.hpp"
#include "boost/mpl/deref.hpp"
#include "boost/mpl/empty.hpp"
#include "boost/mpl/eval_if.hpp"
#include "boost/mpl/find_if.hpp"
#include "boost/mpl/fold.hpp"
#include "boost/mpl/front.hpp"
#include "boost/mpl/identity.hpp"
#include "boost/mpl/if.hpp"
#include "boost/mpl/int.hpp"
#include "boost/mpl/is_sequence.hpp"
#include "boost/mpl/iterator_range.hpp"
#include "boost/mpl/iter_fold_if.hpp"
#include "boost/mpl/logical.hpp"
#include "boost/mpl/max_element.hpp"
#include "boost/mpl/next.hpp"
#include "boost/mpl/not.hpp"
#include "boost/mpl/pair.hpp"
#include "boost/mpl/protect.hpp"
#include "boost/mpl/push_front.hpp"
#include "boost/mpl/same_as.hpp"
#include "boost/mpl/size_t.hpp"
#include "boost/mpl/sizeof.hpp"
#include "boost/mpl/transform.hpp"
///////////////////////////////////////////////////////////////////////////////
// Implementation Macros:
//
// BOOST_VARIANT_VISITATION_UNROLLING_LIMIT
// Defined in boost/variant/detail/visitation_impl.hpp.
//
// BOOST_VARIANT_MINIMIZE_SIZE
// When #defined, implementation employs all known means to minimize the
// size of variant obje cts. However, often unsuccessful due to alignment
// issues, and potentially harmful to runtime speed, so not enabled by
// default. (TODO: Investigate further.)
#if defined(BOOST_VARIANT_MINIMIZE_SIZE)
# include <climits> // for SCHAR_MAX
# include "boost/mpl/eval_if.hpp"
# include "boost/mpl/equal_to.hpp"
# include "boost/mpl/identity.hpp"
# include "boost/mpl/int.hpp"
# include "boost/mpl/if.hpp"
# include "boost/mpl/less.hpp"
# include "boost/mpl/long.hpp"
# include "boost/mpl/O1_size.hpp"
#endif
namespace boost {
namespace detail { namespace variant {
///////////////////////////////////////////////////////////////////////////////
// (detail) metafunction max_value
//
// Finds the maximum value of the unary metafunction F over Sequence.
//
template <typename Sequence, typename F>
struct max_value
{
private: // helpers, for metafunction result (below)
typedef typename mpl::transform1<Sequence, F>::type transformed_;
typedef typename mpl::max_element<transformed_
>::type max_it;
public: // metafunction result
typedef typename mpl::deref<max_it>::type
type;
};
struct add_alignment
{
template <typename State, typename Item>
struct apply
: mpl::size_t<
::boost::math::static_lcm<
BOOST_MPL_AUX_VALUE_WKND(State)::value
, ::boost::alignment_of<Item>::value
>::value
>
{};
};
///////////////////////////////////////////////////////////////////////////////
// (detail) metafunction find_fallback_type
//
// Provides a fallback (i.e., nothrow default-constructible) type from the
// specified sequence, or no_fallback_type if not found.
//
// This implementation is designed to prefer boost::blank over other potential
// fallback types, regardless of its position in the specified sequence.
//
class no_fallback_type;
struct find_fallback_type_pred
{
template <typename Iterator>
struct apply
{
private:
typedef typename mpl::deref<Iterator>::type t_;
public:
typedef mpl::not_< has_nothrow_constructor<t_> > type;
};
};
template <typename Types>
struct find_fallback_type
{
private: // helpers, for metafunction result (below)
typedef typename mpl::end<Types>::type end_it;
// [Find the first suitable fallback type...]
typedef typename mpl::iter_fold_if<
Types
, mpl::int_<0>, mpl::protect< mpl::next<> >
, mpl::protect< find_fallback_type_pred >
>::type first_result_;
typedef typename first_result_::first first_result_index;
typedef typename first_result_::second first_result_it;
// [...now search the rest of the sequence for boost::blank...]
typedef typename mpl::iter_fold_if<
mpl::iterator_range< first_result_it,end_it >
, first_result_index, mpl::protect< mpl::next<> >
, mpl::protect< mpl::not_same_as<boost::blank> >
>::type second_result_;
typedef typename second_result_::second second_result_it;
public: // metafunction result
// [...and return the results of the search:]
typedef typename mpl::eval_if<
is_same< second_result_it,end_it >
, mpl::if_<
is_same< first_result_it,end_it >
, mpl::pair< no_fallback_type,no_fallback_type >
, first_result_
>
, mpl::identity< second_result_ >
>::type type;
};
#if defined(BOOST_MPL_CFG_MSVC_60_ETI_BUG)
template<>
struct find_fallback_type<int>
{
typedef mpl::pair< no_fallback_type,no_fallback_type > type;
};
#endif // BOOST_MPL_CFG_MSVC_60_ETI_BUG workaround
///////////////////////////////////////////////////////////////////////////////
// (detail) metafunction make_storage
//
// Provides an aligned storage type capable of holding any of the types
// specified in the given type-sequence.
//
template <typename Types, typename NeverUsesBackupFlag>
struct make_storage
{
private: // helpers, for metafunction result (below)
typedef typename mpl::eval_if<
NeverUsesBackupFlag
, mpl::identity< Types >
, mpl::push_front<
Types, backup_holder<void*>
>
>::type types;
typedef typename max_value<
types, mpl::sizeof_<mpl::_1>
>::type max_size;
#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x0551))
typedef typename mpl::fold<
types
, mpl::size_t<1>
, add_alignment
>::type max_alignment;
#else // borland
// temporary workaround -- use maximal alignment
typedef mpl::size_t< -1 > max_alignment;
#endif // borland workaround
public: // metafunction result
#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
typedef ::boost::aligned_storage<
BOOST_MPL_AUX_VALUE_WKND(max_size)::value
, BOOST_MPL_AUX_VALUE_WKND(max_alignment)::value
> type;
#else // MSVC7 and below
BOOST_STATIC_CONSTANT(std::size_t, msvc_max_size_c = max_size::value);
BOOST_STATIC_CONSTANT(std::size_t, msvc_max_alignment_c = max_alignment::value);
typedef ::boost::aligned_storage<
msvc_max_size_c
, msvc_max_alignment_c
> type;
#endif // MSVC workaround
};
#if defined(BOOST_MPL_CFG_MSVC_60_ETI_BUG)
template<>
struct make_storage<int,int>
{
typedef int type;
};
#endif // BOOST_MPL_CFG_MSVC_60_ETI_BUG workaround
///////////////////////////////////////////////////////////////////////////////
// (detail) class destroyer
//
// Internal visitor that destroys the value it visits.
//
struct destroyer
: public static_visitor<>
{
public: // visitor interfaces
template <typename T>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(T& operand, int) const
{
operand.~T();
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x0551)) || \
BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1600))
operand; // suppresses warnings
#endif
BOOST_VARIANT_AUX_RETURN_VOID;
}
};
///////////////////////////////////////////////////////////////////////////////
// (detail) class template known_get
//
// Visitor that returns a reference to content of the specified type.
//
// Precondition: visited variant MUST contain logical content of type T.
//
template <typename T>
class known_get
: public static_visitor<T&>
{
#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)
public: // visitor interface
T& operator()(T& operand) const BOOST_NOEXCEPT
{
return operand;
}
template <typename U>
T& operator()(U&) const
{
// logical error to be here: see precondition above
BOOST_ASSERT(false);
return ::boost::detail::variant::forced_return< T& >();
}
#else // MSVC6
private: // helpers, for visitor interface (below)
T& execute(T& operand, mpl::true_) const
{
return operand;
}
template <typename U>
T& execute(U& operand, mpl::false_) const
{
// logical error to be here: see precondition above
BOOST_ASSERT(false);
return ::boost::detail::variant::forced_return< T& >();
}
public: // visitor interface
template <typename U>
T& operator()(U& operand) const
{
typedef typename is_same< U,T >::type
U_is_T;
return execute(operand, U_is_T());
}
#endif // MSVC6 workaround
};
///////////////////////////////////////////////////////////////////////////////
// (detail) class copy_into
//
// Internal visitor that copies the value it visits into the given buffer.
//
class copy_into
: public static_visitor<>
{
private: // representation
void* storage_;
public: // structors
explicit copy_into(void* storage) BOOST_NOEXCEPT
: storage_(storage)
{
}
public: // internal visitor interface
template <typename T>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(boost::detail::variant::backup_holder<T>& operand, long) const
{
new(storage_) T( operand.get() );
BOOST_VARIANT_AUX_RETURN_VOID;
}
template <typename T>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(const boost::detail::variant::backup_holder<T>& operand, long) const
{
new(storage_) T( operand.get() );
BOOST_VARIANT_AUX_RETURN_VOID;
}
template <typename T>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(const T& operand, int) const
{
new(storage_) T(operand);
BOOST_VARIANT_AUX_RETURN_VOID;
}
};
///////////////////////////////////////////////////////////////////////////////
// (detail) class move_into
//
// Internal visitor that moves the value it visits into the given buffer.
//
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
class move_into
: public static_visitor<>
{
private: // representation
void* storage_;
public: // structors
explicit move_into(void* storage) BOOST_NOEXCEPT
: storage_(storage)
{
}
public: // internal visitor interface
template <typename T>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(boost::detail::variant::backup_holder<T>& operand, long) const
{
new(storage_) T( ::boost::detail::variant::move(operand.get()) );
BOOST_VARIANT_AUX_RETURN_VOID;
}
template <typename T>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(T& operand, int) const BOOST_NOEXCEPT_IF(BOOST_NOEXCEPT_EXPR(T(boost::declval<T>())))
{
new(storage_) T(::boost::detail::variant::move(operand));
BOOST_VARIANT_AUX_RETURN_VOID;
}
};
#endif
///////////////////////////////////////////////////////////////////////////////
// (detail) class assign_storage
//
// Internal visitor that assigns the given storage (which must be a
// constructed value of the same type) to the value it visits.
//
struct assign_storage
: public static_visitor<>
{
private: // representation
const void* rhs_storage_;
public: // structors
explicit assign_storage(const void* rhs_storage) BOOST_NOEXCEPT
: rhs_storage_(rhs_storage)
{
}
public: // internal visitor interfaces
template <typename T>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(backup_holder<T>& lhs_content, long) const
{
lhs_content.get()
= static_cast< const backup_holder<T>* >(rhs_storage_)->get();
BOOST_VARIANT_AUX_RETURN_VOID;
}
template <typename T>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(const backup_holder<T>& lhs_content, long) const
{
lhs_content.get()
= static_cast< const backup_holder<T>* >(rhs_storage_)->get();
BOOST_VARIANT_AUX_RETURN_VOID;
}
template <typename T>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(T& lhs_content, int) const
{
// NOTE TO USER :
// Compile error here indicates one of variant's bounded types does
// not meet the requirements of the Assignable concept. Thus,
// variant is not Assignable.
//
// Hint: Are any of the bounded types const-qualified or references?
//
lhs_content = *static_cast< const T* >(rhs_storage_);
BOOST_VARIANT_AUX_RETURN_VOID;
}
};
///////////////////////////////////////////////////////////////////////////////
// (detail) class move_storage
//
// Internal visitor that moves the given storage (which must be a
// constructed value of the same type) to the value it visits.
//
struct move_storage
: public static_visitor<>
{
private: // representation
void* rhs_storage_;
public: // structors
explicit move_storage(void* rhs_storage) BOOST_NOEXCEPT
: rhs_storage_(rhs_storage)
{
}
public: // internal visitor interfaces
template <typename T>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(backup_holder<T>& lhs_content, long) const
{
lhs_content.get()
= ::boost::detail::variant::move(static_cast<backup_holder<T>* >(rhs_storage_)->get());
BOOST_VARIANT_AUX_RETURN_VOID;
}
template <typename T>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(const backup_holder<T>& lhs_content, long) const
{
lhs_content.get()
= ::boost::detail::variant::move(static_cast<backup_holder<T>* >(rhs_storage_)->get());
BOOST_VARIANT_AUX_RETURN_VOID;
}
template <typename T>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(T& lhs_content, int) const
{
// NOTE TO USER :
// Compile error here indicates one of variant's bounded types does
// not meet the requirements of the Assignable concept. Thus,
// variant is not Assignable.
//
// Hint: Are any of the bounded types const-qualified or references?
//
lhs_content = ::boost::detail::variant::move(*static_cast<T* >(rhs_storage_));
BOOST_VARIANT_AUX_RETURN_VOID;
}
};
///////////////////////////////////////////////////////////////////////////////
// (detail) class direct_assigner
//
// Generic static visitor that: if and only if the visited value is of the
// specified type, assigns the given value to the visited value and returns
// true; else returns false.
//
template <typename T>
class direct_assigner
: public static_visitor<bool>
{
private: // representation
const T& rhs_;
public: // structors
explicit direct_assigner(const T& rhs) BOOST_NOEXCEPT
: rhs_(rhs)
{
}
#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)
public: // visitor interface
bool operator()(T& lhs)
{
lhs = rhs_;
return true;
}
template <typename U>
bool operator()(U&) BOOST_NOEXCEPT
{
return false;
}
#else // MSVC6
private: // helpers, for visitor interface (below)
bool execute(T& lhs, mpl::true_)
{
lhs = rhs_;
return true;
}
template <typename U>
bool execute(U&, mpl::false_)
{
return false;
}
public: // visitor interface
template <typename U>
bool operator()(U& lhs)
{
typedef typename is_same<U,T>::type U_is_T;
return execute(lhs, U_is_T());
}
#endif // MSVC6 workaround
#if BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1600))
private:
// silence MSVC warning C4512: assignment operator could not be generated
direct_assigner& operator= (direct_assigner const&);
#endif
};
///////////////////////////////////////////////////////////////////////////////
// (detail) class direct_mover
//
// Generic static visitor that: if and only if the visited value is of the
// specified type, move assigns the given value to the visited value and returns
// true; else returns false.
//
template <typename T>
class direct_mover
: public static_visitor<bool>
{
private: // representation
T& rhs_;
public: // structors
explicit direct_mover(T& rhs) BOOST_NOEXCEPT
: rhs_(rhs)
{
}
#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)
public: // visitor interface
bool operator()(T& lhs)
{
lhs = ::boost::detail::variant::move(rhs_);
return true;
}
template <typename U>
bool operator()(U&) BOOST_NOEXCEPT
{
return false;
}
#else // MSVC6
public: // visitor interface
template <typename U>
bool operator()(U& lhs)
{
// MSVC6 can not use direct_mover class
return direct_assigner(rhs_)(lhs);
}
#endif // MSVC6 workaround
#if BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1600))
private:
// silence MSVC warning C4512: assignment operator could not be generated
direct_mover& operator= (direct_mover const&);
#endif
};
///////////////////////////////////////////////////////////////////////////////
// (detail) class backup_assigner
//
// Internal visitor that "assigns" the given value to the visited value,
// using backup to recover if the destroy-copy sequence fails.
//
// NOTE: This needs to be a friend of variant, as it needs access to
// indicate_which, indicate_backup_which, etc.
//
template <typename Variant>
class backup_assigner
: public static_visitor<>
{
private: // representation
Variant& lhs_;
int rhs_which_;
const void* rhs_content_;
void (*copy_rhs_content_)(void*, const void*);
public: // structors
template<class RhsT>
backup_assigner(Variant& lhs, int rhs_which, const RhsT& rhs_content)
: lhs_(lhs)
, rhs_which_(rhs_which)
, rhs_content_(&rhs_content)
, copy_rhs_content_(&construct_impl<RhsT>)
{
}
private: // helpers, for visitor interface (below)
template<class RhsT>
static void construct_impl(void* addr, const void* obj)
{
new(addr) RhsT(*static_cast<const RhsT*>(obj));
}
template <typename LhsT>
void backup_assign_impl(
LhsT& lhs_content
, mpl::true_// has_nothrow_move
)
{
// Move lhs content to backup...
LhsT backup_lhs_content(
::boost::detail::variant::move(lhs_content)
); // nothrow
// ...destroy lhs content...
lhs_content.~LhsT(); // nothrow
try
{
// ...and attempt to copy rhs content into lhs storage:
copy_rhs_content_(lhs_.storage_.address(), rhs_content_);
}
catch (...)
{
// In case of failure, restore backup content to lhs storage...
new(lhs_.storage_.address())
LhsT(
::boost::detail::variant::move(backup_lhs_content)
); // nothrow
// ...and rethrow:
throw;
}
// In case of success, indicate new content type:
lhs_.indicate_which(rhs_which_); // nothrow
}
template <typename LhsT>
void backup_assign_impl(
LhsT& lhs_content
, mpl::false_// has_nothrow_move
)
{
// Backup lhs content...
LhsT* backup_lhs_ptr = new LhsT(lhs_content);
// ...destroy lhs content...
lhs_content.~LhsT(); // nothrow
try
{
// ...and attempt to copy rhs content into lhs storage:
copy_rhs_content_(lhs_.storage_.address(), rhs_content_);
}
catch (...)
{
// In case of failure, copy backup pointer to lhs storage...
new(lhs_.storage_.address())
backup_holder<LhsT>( backup_lhs_ptr ); // nothrow
// ...indicate now using backup...
lhs_.indicate_backup_which( lhs_.which() ); // nothrow
// ...and rethrow:
throw;
}
// In case of success, indicate new content type...
lhs_.indicate_which(rhs_which_); // nothrow
// ...and delete backup:
delete backup_lhs_ptr; // nothrow
}
public: // visitor interface
template <typename LhsT>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(LhsT& lhs_content, int)
{
typedef typename has_nothrow_move_constructor<LhsT>::type
nothrow_move;
backup_assign_impl( lhs_content, nothrow_move() );
BOOST_VARIANT_AUX_RETURN_VOID;
}
#if BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1600))
private:
// silence MSVC warning C4512: assignment operator could not be generated
backup_assigner& operator= (backup_assigner const&);
#endif
};
///////////////////////////////////////////////////////////////////////////////
// (detail) class swap_with
//
// Visitor that swaps visited value with content of given variant.
//
// Precondition: Given variant MUST have same logical type as visited value.
//
template <typename Variant>
struct swap_with
: public static_visitor<>
{
private: // representation
Variant& toswap_;
public: // structors
explicit swap_with(Variant& toswap)
: toswap_(toswap)
{
}
public: // internal visitor interfaces
template <typename T>
void operator()(T& operand) const
{
// Since the precondition ensures types are same, get T...
known_get<T> getter;
T& other = toswap_.apply_visitor(getter);
// ...and swap:
::boost::detail::variant::move_swap( operand, other );
}
private:
swap_with& operator=(const swap_with&);
};
///////////////////////////////////////////////////////////////////////////////
// (detail) class reflect
//
// Generic static visitor that performs a typeid on the value it visits.
//
#if !defined(BOOST_NO_TYPEID)
class reflect
: public static_visitor<const std::type_info&>
{
public: // visitor interfaces
template <typename T>
const std::type_info& operator()(const T&) const BOOST_NOEXCEPT
{
return typeid(T);
}
};
#endif // BOOST_NO_TYPEID
///////////////////////////////////////////////////////////////////////////////
// (detail) class comparer
//
// Generic static visitor that compares the content of the given lhs variant
// with the visited rhs content using Comp.
//
// Precondition: lhs.which() == rhs.which()
//
template <typename Variant, typename Comp>
class comparer
: public static_visitor<bool>
{
private: // representation
const Variant& lhs_;
public: // structors
explicit comparer(const Variant& lhs) BOOST_NOEXCEPT
: lhs_(lhs)
{
}
public: // visitor interfaces
template <typename T>
bool operator()(const T& rhs_content) const
{
// Since the precondition ensures lhs and rhs types are same, get T...
known_get<const T> getter;
const T& lhs_content = lhs_.apply_visitor(getter);
// ...and compare lhs and rhs contents:
return Comp()(lhs_content, rhs_content);
}
private:
comparer& operator=(const comparer&);
};
///////////////////////////////////////////////////////////////////////////////
// (detail) class equal_comp
//
// Generic function object compares lhs with rhs using operator==.
//
struct equal_comp
{
template <typename T>
bool operator()(const T& lhs, const T& rhs) const
{
return lhs == rhs;
}
};
///////////////////////////////////////////////////////////////////////////////
// (detail) class less_comp
//
// Generic function object compares lhs with rhs using operator<.
//
struct less_comp
{
template <typename T>
bool operator()(const T& lhs, const T& rhs) const
{
return lhs < rhs;
}
};
///////////////////////////////////////////////////////////////////////////////
// (detail) class template invoke_visitor
//
// Internal visitor that invokes the given visitor using:
// * for wrappers (e.g., recursive_wrapper), the wrapper's held value.
// * for all other values, the value itself.
//
template <typename Visitor>
class invoke_visitor
{
private: // representation
Visitor& visitor_;
public: // visitor typedefs
typedef typename Visitor::result_type
result_type;
public: // structors
explicit invoke_visitor(Visitor& visitor) BOOST_NOEXCEPT
: visitor_(visitor)
{
}
#if !defined(BOOST_NO_VOID_RETURNS)
public: // internal visitor interfaces
template <typename T>
result_type internal_visit(T& operand, int)
{
return visitor_(operand);
}
# if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x0564))
template <typename T>
result_type internal_visit(const T& operand, int)
{
return visitor_(operand);
}
# endif
#else // defined(BOOST_NO_VOID_RETURNS)
private: // helpers, for internal visitor interfaces (below)
template <typename T>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(result_type)
visit_impl(T& operand, mpl::false_)
{
return visitor_(operand);
}
template <typename T>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
visit_impl(T& operand, mpl::true_)
{
visitor_(operand);
BOOST_VARIANT_AUX_RETURN_VOID;
}
public: // internal visitor interfaces
template <typename T>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(result_type)
internal_visit(T& operand, int)
{
typedef typename is_same<result_type, void>::type
has_void_result_type;
return visit_impl(operand, has_void_result_type());
}
#endif // BOOST_NO_VOID_RETURNS) workaround
public: // internal visitor interfaces, cont.
template <typename T>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(result_type)
internal_visit(boost::recursive_wrapper<T>& operand, long)
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(result_type)
internal_visit(const boost::recursive_wrapper<T>& operand, long)
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(result_type)
internal_visit(boost::detail::reference_content<T>& operand, long)
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(result_type)
internal_visit(const boost::detail::reference_content<T>& operand, long)
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(result_type)
internal_visit(boost::detail::variant::backup_holder<T>& operand, long)
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(result_type)
internal_visit(const boost::detail::variant::backup_holder<T>& operand, long)
{
return internal_visit( operand.get(), 1L );
}
#if BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1600))
private:
// silence MSVC warning C4512: assignment operator could not be generated
invoke_visitor& operator= (invoke_visitor const&);
#endif
};
}} // namespace detail::variant
///////////////////////////////////////////////////////////////////////////////
// class template variant (concept inspired by Andrei Alexandrescu)
//
// See docs and boost/variant/variant_fwd.hpp for more information.
//
template <
typename T0_
, BOOST_VARIANT_ENUM_SHIFTED_PARAMS(typename T)
>
class variant
{
private: // helpers, for typedefs (below)
typedef variant wknd_self_t;
struct is_recursive_
: detail::variant::is_recursive_flag<T0_>
{
};
typedef typename mpl::eval_if<
is_recursive_
, T0_
, mpl::identity< T0_ >
>::type unwrapped_T0_;
struct is_sequence_based_
: detail::variant::is_over_sequence<unwrapped_T0_>
{
};
#if !defined(BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT)
private: // helpers, for typedefs (below)
typedef typename mpl::eval_if<
is_sequence_based_
, unwrapped_T0_ // over_sequence<...>::type
, detail::variant::make_variant_list<
unwrapped_T0_
, BOOST_VARIANT_ENUM_SHIFTED_PARAMS(T)
>
>::type specified_types;
BOOST_STATIC_ASSERT((
::boost::mpl::not_< mpl::empty<specified_types> >::value
));
typedef typename mpl::eval_if<
is_recursive_
, mpl::transform<
specified_types
, mpl::protect<
detail::variant::quoted_enable_recursive<wknd_self_t>
>
>
, mpl::identity< specified_types >
>::type recursive_enabled_types;
public: // public typedefs
typedef typename mpl::transform<
recursive_enabled_types
, unwrap_recursive<mpl::_1>
>::type types;
private: // internal typedefs
typedef typename mpl::transform<
recursive_enabled_types
, mpl::protect< detail::make_reference_content<> >
>::type internal_types;
typedef typename mpl::front<
internal_types
>::type internal_T0;
#else // defined(BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT)
private: // helpers, for typedefs (below)
typedef unwrapped_T0_ T0;
#define BOOST_VARIANT_AUX_ENABLE_RECURSIVE_TYPEDEFS(z,N,_) \
typedef typename mpl::eval_if< \
is_recursive_ \
, detail::variant::enable_recursive< \
BOOST_PP_CAT(T,N) \
, wknd_self_t \
> \
, mpl::identity< BOOST_PP_CAT(T,N) > \
>::type BOOST_PP_CAT(recursive_enabled_T,N); \
/**/
BOOST_PP_REPEAT(
BOOST_VARIANT_LIMIT_TYPES
, BOOST_VARIANT_AUX_ENABLE_RECURSIVE_TYPEDEFS
, _
)
#undef BOOST_VARIANT_AUX_ENABLE_RECURSIVE_TYPEDEFS
#define BOOST_VARIANT_AUX_UNWRAP_RECURSIVE_TYPEDEFS(z,N,_) \
typedef typename unwrap_recursive< \
BOOST_PP_CAT(recursive_enabled_T,N) \
>::type BOOST_PP_CAT(public_T,N); \
/**/
BOOST_PP_REPEAT(
BOOST_VARIANT_LIMIT_TYPES
, BOOST_VARIANT_AUX_UNWRAP_RECURSIVE_TYPEDEFS
, _
)
#undef BOOST_VARIANT_AUX_UNWRAP_RECURSIVE_TYPEDEFS
public: // public typedefs
typedef typename detail::variant::make_variant_list<
BOOST_VARIANT_ENUM_PARAMS(public_T)
>::type types;
private: // helpers, for internal typedefs (below)
#define BOOST_VARIANT_AUX_MAKE_REFERENCE_CONTENT_TYPEDEFS(z,N,_) \
typedef detail::make_reference_content< \
BOOST_PP_CAT(recursive_enabled_T,N) \
>::type BOOST_PP_CAT(internal_T,N); \
/**/
BOOST_PP_REPEAT(
BOOST_VARIANT_LIMIT_TYPES
, BOOST_VARIANT_AUX_MAKE_REFERENCE_CONTENT_TYPEDEFS
, _
)
#undef BOOST_VARIANT_AUX_MAKE_REFERENCE_CONTENT_TYPEDEFS
private: // internal typedefs
typedef typename detail::variant::make_variant_list<
BOOST_VARIANT_ENUM_PARAMS(internal_T)
>::type internal_types;
private: // static precondition assertions
// NOTE TO USER :
// variant< type-sequence > syntax is not supported on this compiler!
//
BOOST_MPL_ASSERT_NOT(( is_sequence_based_ ));
#endif // BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT workaround
private: // helpers, for representation (below)
typedef typename detail::variant::find_fallback_type<
internal_types
>::type fallback_type_result_;
typedef typename fallback_type_result_::first
fallback_type_index_;
typedef typename fallback_type_result_::second
fallback_type_;
struct has_fallback_type_
: mpl::not_<
is_same< fallback_type_, detail::variant::no_fallback_type >
>
{
};
typedef has_fallback_type_
never_uses_backup_flag;
typedef typename detail::variant::make_storage<
internal_types, never_uses_backup_flag
>::type storage_t;
private: // helpers, for representation (below)
// which_ on:
// * [0, size<internal_types>) indicates stack content
// * [-size<internal_types>, 0) indicates pointer to heap backup
// if which_ >= 0:
// * then which() -> which_
// * else which() -> -(which_ + 1)
#if !defined(BOOST_VARIANT_MINIMIZE_SIZE)
typedef int which_t;
#else // defined(BOOST_VARIANT_MINIMIZE_SIZE)
// [if O1_size available, then attempt which_t size optimization...]
// [select signed char if fewer than SCHAR_MAX types, else signed int:]
typedef typename mpl::eval_if<
mpl::equal_to< mpl::O1_size<internal_types>, mpl::long_<-1> >
, mpl::identity< int >
, mpl::if_<
mpl::less< mpl::O1_size<internal_types>, mpl::int_<SCHAR_MAX> >
, signed char
, int
>
>::type which_t;
#endif // BOOST_VARIANT_MINIMIZE_SIZE switch
// representation -- private when possible
#if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
private:
#else
public:
#endif
which_t which_;
storage_t storage_;
void indicate_which(int which_arg) BOOST_NOEXCEPT
{
which_ = static_cast<which_t>( which_arg );
}
void indicate_backup_which(int which_arg) BOOST_NOEXCEPT
{
which_ = static_cast<which_t>( -(which_arg + 1) );
}
private: // helpers, for queries (below)
bool using_backup() const BOOST_NOEXCEPT
{
return which_ < 0;
}
public: // queries
int which() const BOOST_NOEXCEPT
{
// If using heap backup...
if (using_backup())
// ...then return adjusted which_:
return -(which_ + 1);
// Otherwise, return which_ directly:
return which_;
}
private: // helpers, for structors (below)
struct initializer
: BOOST_VARIANT_AUX_INITIALIZER_T(
recursive_enabled_types, recursive_enabled_T
)
{
};
void destroy_content()
{
detail::variant::destroyer visitor;
this->internal_apply_visitor(visitor);
}
public: // structors
~variant()
{
destroy_content();
}
variant()
{
// NOTE TO USER :
// Compile error from here indicates that the first bound
// type is not default-constructible, and so variant cannot
// support its own default-construction.
//
new( storage_.address() ) internal_T0();
indicate_which(0); // zero is the index of the first bounded type
}
private: // helpers, for structors, cont. (below)
class convert_copy_into
: public static_visitor<int>
{
private: // representation
void* storage_;
public: // structors
explicit convert_copy_into(void* storage) BOOST_NOEXCEPT
: storage_(storage)
{
}
public: // internal visitor interfaces (below)
template <typename T>
int internal_visit(T& operand, int) const
{
// NOTE TO USER :
// Compile error here indicates one of the source variant's types
// cannot be unambiguously converted to the destination variant's
// types (or that no conversion exists).
//
return initializer::initialize(storage_, operand);
}
# if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x0564))
template <typename T>
result_type internal_visit(const T& operand, int) const
{
return initializer::initialize(storage_, operand);
}
# endif
template <typename T>
int internal_visit(boost::detail::reference_content<T>& operand, long) const
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
int internal_visit(const boost::detail::reference_content<T>& operand, long) const
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
int internal_visit(boost::detail::variant::backup_holder<T>& operand, long) const
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
int internal_visit(const boost::detail::variant::backup_holder<T>& operand, long) const
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
int internal_visit(boost::recursive_wrapper<T>& operand, long) const
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
int internal_visit(const boost::recursive_wrapper<T>& operand, long) const
{
return internal_visit( operand.get(), 1L );
}
};
friend class convert_copy_into;
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
class convert_move_into
: public static_visitor<int>
{
private: // representation
void* storage_;
public: // structors
explicit convert_move_into(void* storage) BOOST_NOEXCEPT
: storage_(storage)
{
}
public: // internal visitor interfaces (below)
template <typename T>
int internal_visit(T& operand, int) const
{
// NOTE TO USER :
// Compile error here indicates one of the source variant's types
// cannot be unambiguously converted to the destination variant's
// types (or that no conversion exists).
//
return initializer::initialize(storage_, detail::variant::move(operand) );
}
template <typename T>
int internal_visit(boost::detail::reference_content<T>& operand, long) const
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
int internal_visit(const boost::detail::reference_content<T>& operand, long) const
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
int internal_visit(boost::detail::variant::backup_holder<T>& operand, long) const
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
int internal_visit(const boost::detail::variant::backup_holder<T>& operand, long) const
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
int internal_visit(boost::recursive_wrapper<T>& operand, long) const
{
return internal_visit( operand.get(), 1L );
}
template <typename T>
int internal_visit(const boost::recursive_wrapper<T>& operand, long) const
{
return internal_visit( operand.get(), 1L );
}
};
friend class convert_move_into;
#endif
private: // helpers, for structors, below
template <typename T>
void convert_construct(
T& operand
, int
, mpl::false_ = mpl::false_() // is_foreign_variant
)
{
// NOTE TO USER :
// Compile error here indicates that the given type is not
// unambiguously convertible to one of the variant's types
// (or that no conversion exists).
//
indicate_which(
initializer::initialize(
storage_.address()
, operand
)
);
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <typename T>
typename boost::enable_if<boost::is_rvalue_reference<T&&> >::type convert_construct(
T&& operand
, int
, mpl::false_ = mpl::false_() // is_foreign_variant
)
{
// NOTE TO USER :
// Compile error here indicates that the given type is not
// unambiguously convertible to one of the variant's types
// (or that no conversion exists).
//
indicate_which(
initializer::initialize(
storage_.address()
, detail::variant::move(operand)
)
);
}
#endif
template <typename Variant>
void convert_construct(
Variant& operand
, long
, mpl::true_// is_foreign_variant
)
{
convert_copy_into visitor(storage_.address());
indicate_which(
operand.internal_apply_visitor(visitor)
);
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <typename Variant>
typename boost::enable_if<boost::is_rvalue_reference<Variant&&> >::type convert_construct(
Variant&& operand
, long
, mpl::true_// is_foreign_variant
)
{
convert_move_into visitor(storage_.address());
indicate_which(
operand.internal_apply_visitor(visitor)
);
}
#endif
template <typename Variant>
void convert_construct_variant(Variant& operand)
{
// [Determine if the given variant is itself a bounded type, or if its
// content needs to be converted (i.e., it is a 'foreign' variant):]
//
typedef typename mpl::find_if<
types
, is_same<
add_const<mpl::_1>
, const Variant
>
>::type found_it;
typedef typename mpl::end<types>::type not_found;
typedef typename is_same<
found_it, not_found
>::type is_foreign_variant;
// Convert construct from operand:
convert_construct(
operand, 1L
, is_foreign_variant()
);
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <typename Variant>
typename boost::enable_if<boost::is_rvalue_reference<Variant&&> >::type convert_construct_variant(Variant&& operand)
{
// [Determine if the given variant is itself a bounded type, or if its
// content needs to be converted (i.e., it is a 'foreign' variant):]
//
typedef typename mpl::find_if<
types
, is_same<
add_const<mpl::_1>
, const Variant
>
>::type found_it;
typedef typename mpl::end<types>::type not_found;
typedef typename is_same<
found_it, not_found
>::type is_foreign_variant;
// Convert move construct from operand:
convert_construct(
detail::variant::move(operand), 1L
, is_foreign_variant()
);
}
#endif
template <BOOST_VARIANT_ENUM_PARAMS(typename U)>
void convert_construct(
boost::variant<BOOST_VARIANT_ENUM_PARAMS(U)>& operand
, long
)
{
convert_construct_variant(operand);
}
template <BOOST_VARIANT_ENUM_PARAMS(typename U)>
void convert_construct(
const boost::variant<BOOST_VARIANT_ENUM_PARAMS(U)>& operand
, long
)
{
convert_construct_variant(operand);
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <BOOST_VARIANT_ENUM_PARAMS(typename U)>
void convert_construct(
boost::variant<BOOST_VARIANT_ENUM_PARAMS(U)>&& operand
, long
)
{
convert_construct_variant( detail::variant::move(operand) );
}
#endif
public: // structors, cont.
#if !defined(BOOST_VARIANT_AUX_BROKEN_CONSTRUCTOR_TEMPLATE_ORDERING)
template <typename T>
variant(const T& operand)
{
convert_construct(operand, 1L);
}
template <typename T>
variant(T& operand)
{
convert_construct(operand, 1L);
}
#elif defined(BOOST_VARIANT_AUX_HAS_CONSTRUCTOR_TEMPLATE_ORDERING_SFINAE_WKND)
// For compilers that cannot distinguish between T& and const T& in
// template constructors, but do fully support SFINAE, we can workaround:
template <typename T>
variant(const T& operand)
{
convert_construct(operand, 1L);
}
template <typename T>
variant(
T& operand
, typename enable_if<
mpl::not_< is_const<T> >
, void
>::type* = 0
)
{
convert_construct(operand, 1L);
}
#else // !defined(BOOST_VARIANT_AUX_HAS_CONSTRUCTOR_TEMPLATE_ORDERING_SFINAE_WKND)
// For compilers that cannot distinguish between T& and const T& in
// template constructors, and do NOT support SFINAE, we can't workaround:
template <typename T>
variant(const T& operand)
{
convert_construct(operand, 1L);
}
#endif // BOOST_VARIANT_AUX_BROKEN_CONSTRUCTOR_TEMPLATE_ORDERING workarounds
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <class T>
variant(T&& operand, typename boost::enable_if<boost::is_rvalue_reference<T&&> >::type* = 0)
{
convert_construct( detail::variant::move(operand), 1L);
}
#endif
public: // structors, cont.
// [MSVC6 requires copy constructor appear after template constructors]
variant(const variant& operand)
{
// Copy the value of operand into *this...
detail::variant::copy_into visitor( storage_.address() );
operand.internal_apply_visitor(visitor);
// ...and activate the *this's primary storage on success:
indicate_which(operand.which());
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
variant(variant&& operand)
{
// Move the value of operand into *this...
detail::variant::move_into visitor( storage_.address() );
operand.internal_apply_visitor(visitor);
// ...and activate the *this's primary storage on success:
indicate_which(operand.which());
}
#endif
private: // helpers, for modifiers (below)
# if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
template <typename Variant>
friend class detail::variant::backup_assigner;
# endif
// class assigner
//
// Internal visitor that "assigns" the visited value to the given variant
// by appropriate destruction and copy-construction.
//
class assigner
: public static_visitor<>
{
private: // representation
variant& lhs_;
int rhs_which_;
public: // structors
assigner(variant& lhs, int rhs_which) BOOST_NOEXCEPT
: lhs_(lhs)
, rhs_which_(rhs_which)
{
}
private: // helpers, for internal visitor interface (below)
template <typename RhsT, typename B1, typename B2>
void assign_impl(
const RhsT& rhs_content
, mpl::true_// has_nothrow_copy
, B1// has_nothrow_move_constructor
, B2// has_fallback_type
)
{
// Destroy lhs's content...
lhs_.destroy_content(); // nothrow
// ...copy rhs content into lhs's storage...
new(lhs_.storage_.address())
RhsT( rhs_content ); // nothrow
// ...and indicate new content type:
lhs_.indicate_which(rhs_which_); // nothrow
}
template <typename RhsT, typename B>
void assign_impl(
const RhsT& rhs_content
, mpl::false_// has_nothrow_copy
, mpl::true_// has_nothrow_move_constructor
, B// has_fallback_type
)
{
// Attempt to make a temporary copy (so as to move it below)...
RhsT temp(rhs_content);
// ...and upon success destroy lhs's content...
lhs_.destroy_content(); // nothrow
// ...move the temporary copy into lhs's storage...
new(lhs_.storage_.address())
RhsT( detail::variant::move(temp) ); // nothrow
// ...and indicate new content type:
lhs_.indicate_which(rhs_which_); // nothrow
}
template <typename RhsT>
void assign_impl(
const RhsT& rhs_content
, mpl::false_// has_nothrow_copy
, mpl::false_// has_nothrow_move_constructor
, mpl::true_// has_fallback_type
)
{
// Destroy lhs's content...
lhs_.destroy_content(); // nothrow
try
{
// ...and attempt to copy rhs's content into lhs's storage:
new(lhs_.storage_.address())
RhsT( rhs_content );
}
catch (...)
{
// In case of failure, default-construct fallback type in lhs's storage...
new (lhs_.storage_.address())
fallback_type_; // nothrow
// ...indicate construction of fallback type...
lhs_.indicate_which(
BOOST_MPL_AUX_VALUE_WKND(fallback_type_index_)::value
); // nothrow
// ...and rethrow:
throw;
}
// In the event of success, indicate new content type:
lhs_.indicate_which(rhs_which_); // nothrow
}
template <typename RhsT>
void assign_impl(
const RhsT& rhs_content
, mpl::false_// has_nothrow_copy
, mpl::false_// has_nothrow_move_constructor
, mpl::false_// has_fallback_type
)
{
detail::variant::backup_assigner<wknd_self_t>
visitor(lhs_, rhs_which_, rhs_content);
lhs_.internal_apply_visitor(visitor);
}
public: // internal visitor interfaces
template <typename RhsT>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(const RhsT& rhs_content, int)
{
typedef typename has_nothrow_copy<RhsT>::type
nothrow_copy;
typedef typename mpl::or_< // reduces compile-time
nothrow_copy
, detail::variant::has_nothrow_move_constructor<RhsT>
>::type nothrow_move_constructor;
assign_impl(
rhs_content
, nothrow_copy()
, nothrow_move_constructor()
, has_fallback_type_()
);
BOOST_VARIANT_AUX_RETURN_VOID;
}
#if BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1600))
private:
// silence MSVC warning C4512: assignment operator could not be generated
assigner& operator= (assigner const&);
#endif
};
friend class assigner;
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
// class move_assigner
//
// Internal visitor that "move assigns" the visited value to the given variant
// by appropriate destruction and move-construction.
//
class move_assigner
: public static_visitor<>
{
private: // representation
variant& lhs_;
int rhs_which_;
public: // structors
move_assigner(variant& lhs, int rhs_which) BOOST_NOEXCEPT
: lhs_(lhs)
, rhs_which_(rhs_which)
{
}
private: // helpers, for internal visitor interface (below)
template <typename RhsT, typename B1, typename B2>
void assign_impl(
RhsT& rhs_content
, mpl::true_// has_nothrow_copy
, mpl::false_// has_nothrow_move_constructor
, B2// has_fallback_type
)
{
// Destroy lhs's content...
lhs_.destroy_content(); // nothrow
// ...copy rhs content into lhs's storage...
new(lhs_.storage_.address())
RhsT( rhs_content ); // nothrow
// ...and indicate new content type:
lhs_.indicate_which(rhs_which_); // nothrow
}
template <typename RhsT, typename B>
void assign_impl(
RhsT& rhs_content
, mpl::true_// has_nothrow_copy
, mpl::true_// has_nothrow_move_constructor
, B// has_fallback_type
)
{
// ...destroy lhs's content...
lhs_.destroy_content(); // nothrow
// ...move the rhs_content into lhs's storage...
new(lhs_.storage_.address())
RhsT( detail::variant::move(rhs_content) ); // nothrow
// ...and indicate new content type:
lhs_.indicate_which(rhs_which_); // nothrow
}
template <typename RhsT>
void assign_impl(
RhsT& rhs_content
, mpl::false_// has_nothrow_copy
, mpl::false_// has_nothrow_move_constructor
, mpl::true_// has_fallback_type
)
{
// Destroy lhs's content...
lhs_.destroy_content(); // nothrow
try
{
// ...and attempt to copy rhs's content into lhs's storage:
new(lhs_.storage_.address())
RhsT( detail::variant::move(rhs_content) );
}
catch (...)
{
// In case of failure, default-construct fallback type in lhs's storage...
new (lhs_.storage_.address())
fallback_type_; // nothrow
// ...indicate construction of fallback type...
lhs_.indicate_which(
BOOST_MPL_AUX_VALUE_WKND(fallback_type_index_)::value
); // nothrow
// ...and rethrow:
throw;
}
// In the event of success, indicate new content type:
lhs_.indicate_which(rhs_which_); // nothrow
}
template <typename RhsT>
void assign_impl(
const RhsT& rhs_content
, mpl::false_// has_nothrow_copy
, mpl::false_// has_nothrow_move_constructor
, mpl::false_// has_fallback_type
)
{
detail::variant::backup_assigner<wknd_self_t>
visitor(lhs_, rhs_which_, rhs_content);
lhs_.internal_apply_visitor(visitor);
}
public: // internal visitor interfaces
template <typename RhsT>
BOOST_VARIANT_AUX_RETURN_VOID_TYPE
internal_visit(RhsT& rhs_content, int)
{
typedef typename detail::variant::has_nothrow_move_constructor<RhsT>::type
nothrow_move_constructor;
typedef typename mpl::or_< // reduces compile-time
nothrow_move_constructor
, has_nothrow_copy<RhsT>
>::type nothrow_copy;
assign_impl(
rhs_content
, nothrow_copy()
, nothrow_move_constructor()
, has_fallback_type_()
);
BOOST_VARIANT_AUX_RETURN_VOID;
}
#if BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1600))
private:
// silence MSVC warning C4512: assignment operator could not be generated
move_assigner& operator= (move_assigner const&);
#endif
};
friend class move_assigner;
#endif // BOOST_NO_CXX11_RVALUE_REFERENCES
void variant_assign(const variant& rhs)
{
// If the contained types are EXACTLY the same...
if (which_ == rhs.which_)
{
// ...then assign rhs's storage to lhs's content:
detail::variant::assign_storage visitor(rhs.storage_.address());
this->internal_apply_visitor(visitor);
}
else
{
// Otherwise, perform general (copy-based) variant assignment:
assigner visitor(*this, rhs.which());
rhs.internal_apply_visitor(visitor);
}
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
void variant_assign(variant&& rhs)
{
// If the contained types are EXACTLY the same...
if (which_ == rhs.which_)
{
// ...then move rhs's storage to lhs's content:
detail::variant::move_storage visitor(rhs.storage_.address());
this->internal_apply_visitor(visitor);
}
else
{
// Otherwise, perform general (move-based) variant assignment:
move_assigner visitor(*this, rhs.which());
rhs.internal_apply_visitor(visitor);
}
}
#endif // BOOST_NO_CXX11_RVALUE_REFERENCES
private: // helpers, for modifiers (below)
template <typename T>
void assign(const T& rhs)
{
// If direct T-to-T assignment is not possible...
detail::variant::direct_assigner<T> direct_assign(rhs);
if (this->apply_visitor(direct_assign) == false)
{
// ...then convert rhs to variant and assign:
//
// While potentially inefficient, the following construction of a
// variant allows T as any type convertible to one of the bounded
// types without excessive code redundancy.
//
variant temp(rhs);
variant_assign( detail::variant::move(temp) );
}
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <typename T>
void move_assign(T&& rhs)
{
// If direct T-to-T move assignment is not possible...
detail::variant::direct_mover<T> direct_move(rhs);
if (this->apply_visitor(direct_move) == false)
{
// ...then convert rhs to variant and assign:
//
// While potentially inefficient, the following construction of a
// variant allows T as any type convertible to one of the bounded
// types without excessive code redundancy.
//
variant temp( detail::variant::move(rhs) );
variant_assign( detail::variant::move(temp) );
}
}
#endif // BOOST_NO_CXX11_RVALUE_REFERENCES
public: // modifiers
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <class T>
typename boost::enable_if<boost::is_rvalue_reference<T&&>, variant& >::type operator=(T&& rhs)
{
move_assign( detail::variant::move(rhs) );
return *this;
}
#endif // BOOST_NO_CXX11_RVALUE_REFERENCES
template <typename T>
variant& operator=(const T& rhs)
{
assign(rhs);
return *this;
}
// [MSVC6 requires copy assign appear after templated operator=]
variant& operator=(const variant& rhs)
{
variant_assign(rhs);
return *this;
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
variant& operator=(variant&& rhs)
{
variant_assign( detail::variant::move(rhs) );
return *this;
}
#endif // BOOST_NO_CXX11_RVALUE_REFERENCES
void swap(variant& rhs)
{
// If the contained types are the same...
if (which() == rhs.which())
{
// ...then swap the values directly:
detail::variant::swap_with<variant> visitor(rhs);
this->apply_visitor(visitor);
}
else
{
// ...otherwise, perform general variant swap:
variant tmp( detail::variant::move(rhs) );
rhs = detail::variant::move(*this);
*this = detail::variant::move(tmp);
}
}
public: // queries
//
// NOTE: member which() defined above.
//
bool empty() const BOOST_NOEXCEPT
{
return false;
}
#if !defined(BOOST_NO_TYPEID)
const std::type_info& type() const
{
detail::variant::reflect visitor;
return this->apply_visitor(visitor);
}
#endif
public: // prevent comparison with foreign types
#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
# define BOOST_VARIANT_AUX_FAIL_COMPARISON_RETURN_TYPE \
void
#else // MSVC7
//
// MSVC7 gives error about return types for above being different than
// the true comparison operator overloads:
//
# define BOOST_VARIANT_AUX_FAIL_COMPARISON_RETURN_TYPE \
bool
#endif // MSVC7 workaround
template <typename U>
BOOST_VARIANT_AUX_FAIL_COMPARISON_RETURN_TYPE
operator==(const U&) const
{
BOOST_STATIC_ASSERT( false && sizeof(U) );
}
template <typename U>
BOOST_VARIANT_AUX_FAIL_COMPARISON_RETURN_TYPE
operator<(const U&) const
{
BOOST_STATIC_ASSERT( false && sizeof(U) );
}
public: // comparison operators
// [MSVC6 requires these operators appear after template operators]
bool operator==(const variant& rhs) const
{
if (this->which() != rhs.which())
return false;
detail::variant::comparer<
variant, detail::variant::equal_comp
> visitor(*this);
return rhs.apply_visitor(visitor);
}
bool operator<(const variant& rhs) const
{
//
// Dirk Schreib suggested this collating order.
//
if (this->which() != rhs.which())
return this->which() < rhs.which();
detail::variant::comparer<
variant, detail::variant::less_comp
> visitor(*this);
return rhs.apply_visitor(visitor);
}
// helpers, for visitation support (below) -- private when possible
#if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
template < BOOST_VARIANT_ENUM_PARAMS(typename U) >
friend class variant;
private:
#else// defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
public:
#endif// !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
template <typename Visitor, typename VoidPtrCV>
static
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(
typename Visitor::result_type
)
internal_apply_visitor_impl(
int internal_which
, int logical_which
, Visitor& visitor
, VoidPtrCV storage
)
{
typedef mpl::int_<0> first_which;
typedef typename mpl::begin<internal_types>::type first_it;
typedef typename mpl::end<internal_types>::type last_it;
typedef detail::variant::visitation_impl_step<
first_it, last_it
> first_step;
return detail::variant::visitation_impl(
internal_which, logical_which
, visitor, storage, mpl::false_()
, never_uses_backup_flag()
, static_cast<first_which*>(0), static_cast<first_step*>(0)
);
}
template <typename Visitor>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(
typename Visitor::result_type
)
internal_apply_visitor(Visitor& visitor)
{
return internal_apply_visitor_impl(
which_, which(), visitor, storage_.address()
);
}
template <typename Visitor>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(
typename Visitor::result_type
)
internal_apply_visitor(Visitor& visitor) const
{
return internal_apply_visitor_impl(
which_, which(), visitor, storage_.address()
);
}
public: // visitation support
template <typename Visitor>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(
typename Visitor::result_type
)
apply_visitor(Visitor& visitor)
{
detail::variant::invoke_visitor<Visitor> invoker(visitor);
return this->internal_apply_visitor(invoker);
}
template <typename Visitor>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(
typename Visitor::result_type
)
apply_visitor(Visitor& visitor) const
{
detail::variant::invoke_visitor<Visitor> invoker(visitor);
return this->internal_apply_visitor(invoker);
}
}; // class variant
///////////////////////////////////////////////////////////////////////////////
// metafunction make_variant_over
//
// See docs and boost/variant/variant_fwd.hpp for more information.
//
template <typename Types>
struct make_variant_over
{
private: // precondition assertions
#if !BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
BOOST_STATIC_ASSERT(( ::boost::mpl::is_sequence<Types>::value ));
#endif
public: // metafunction result
typedef variant<
detail::variant::over_sequence< Types >
> type;
};
///////////////////////////////////////////////////////////////////////////////
// function template swap
//
// Swaps two variants of the same type (i.e., identical specification).
//
template < BOOST_VARIANT_ENUM_PARAMS(typename T) >
inline void swap(
variant< BOOST_VARIANT_ENUM_PARAMS(T) >& lhs
, variant< BOOST_VARIANT_ENUM_PARAMS(T) >& rhs
)
{
lhs.swap(rhs);
}
} // namespace boost
// implementation additions
#if !defined(BOOST_NO_IOSTREAM)
#include "boost/variant/detail/variant_io.hpp"
#endif // BOOST_NO_IOSTREAM
#endif // BOOST_VARIANT_VARIANT_HPP
|
[
"hoangmin@oregonstate.edu"
] |
hoangmin@oregonstate.edu
|
1b0292027478508c23a78592152c180e6d08c8a9
|
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
|
/NT/inetsrv/intlwb/chs2/src/wordlink.cpp
|
023436287d63b36650a338a2e3630feb248d6ef0
|
[] |
no_license
|
jjzhang166/WinNT5_src_20201004
|
712894fcf94fb82c49e5cd09d719da00740e0436
|
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
|
refs/heads/Win2K3
| 2023-08-12T01:31:59.670176
| 2021-10-14T15:14:37
| 2021-10-14T15:14:37
| 586,134,273
| 1
| 0
| null | 2023-01-07T03:47:45
| 2023-01-07T03:47:44
| null |
UTF-8
|
C++
| false
| false
| 25,843
|
cpp
|
/*============================================================================
Microsoft Simplified Chinese Proofreading Engine
Microsoft Confidential.
Copyright 1997-1999 Microsoft Corporation. All Rights Reserved.
Component: Word and WordLink
Purpose: Define the CWord and CWordLink classes
Using CMyPlex to alloc and manage memory for word object in the link
Notes: This module is a fundamental stuff for SCProof'98,
it does NOT depend on any other class.
Owner: donghz@microsoft.com
Platform: Win32
Revise: First created by: donghz 5/26/97
============================================================================*/
#include "myafx.h"
#include "wordlink.h"
#include "myplex.h"
#include "lexicon.h"
/*============================================================================
Implementation of functions in CWord
============================================================================*/
/*============================================================================
CWord constructor
============================================================================*/
CWord::CWord( )
{
m_dwWordID = 0;
m_hLex = 0;
m_dwFlag = 0;
for (int i = 0; i < WORD_ATTRI_SIZE; i++)
m_aAttri[i] = 0;
m_idErr = 0;
m_cwchText = 0;
m_pwchText = NULL;
m_pPrev = NULL;
m_pNext = NULL;
m_pMergedFrom = NULL;
#ifdef DEBUG
m_pMergedTo = NULL;
#endif
}
/*============================================================================
CWord::FillWord():
Fill the word.
============================================================================*/
void CWord::FillWord( LPCWSTR pwchText, USHORT cwchText, CWordInfo* pwinfo )
{
assert(pwchText);
assert(cwchText);
m_pwchText = const_cast<LPWSTR>(pwchText);
m_cwchText = cwchText;
m_dwFlag = 0;
ZeroMemory( (LPVOID)m_aAttri, sizeof(DWORD)*WORD_ATTRI_SIZE);
m_idErr = 0;
if (m_cwchText == 1) {
SetFlag(CWord::WF_CHAR);
}
if (pwinfo != NULL) {
m_dwWordID = pwinfo->GetWordID();
m_hLex = pwinfo->GetLexHandle();
for (USHORT i = 0; i < pwinfo->AttriNum(); i++) {
SetAttri( pwinfo->GetAttri(i) );
}
} else {
m_dwWordID = 0;
m_hLex = 0;
}
}
/*============================================================================
CWord::fIsWordText()
Compare this word's text with given text.
Returns:
TRUE if match
FALSE if not
============================================================================*/
BOOL CWord::fIsWordText(LPCWSTR lpwcText) const
{
assert(m_pwchText && m_cwchText);
assert(lpwcText);
if(m_cwchText != wcslen(lpwcText))
return FALSE;
for(USHORT i = 0; i < m_cwchText; i++) {
if(lpwcText[i] != m_pwchText[i])
return FALSE;
}
return TRUE;
}
/*============================================================================
CWord::fIsTextIdentical(const CWord*)
Compare this word's text with other word's text
Returns:
TRUE if the text of them identical
FALSE if not
============================================================================*/
BOOL CWord::fIsTextIdentical(const CWord* pWord) const
{
assert(m_pwchText);
assert(m_cwchText);
assert(pWord);
assert(pWord->m_pwchText);
if (m_pwchText == NULL || pWord->m_pwchText == NULL
|| m_cwchText != pWord->m_cwchText) {
return FALSE;
}
return (BOOL)(wcsncmp(m_pwchText, pWord->m_pwchText, m_cwchText) == 0);
}
/*============================================================================
Implementation of functions in CWordLink
============================================================================*/
/*============================================================================
CWordLink constructor
============================================================================*/
CWordLink::CWordLink(UINT ciBlockWordCount)
{
// Assert: all blocks are in same size!
m_dwFlag = 0;
m_dwFormat = 0;
m_ciBlockSize = ciBlockWordCount;
m_pwchText = NULL;
m_pWordPool = NULL;
m_pHead = NULL;
m_pTail = NULL;
m_pFree = NULL;
}
/*============================================================================
CWordLink destructor
============================================================================*/
CWordLink::~CWordLink()
{
#ifdef DEBUG
assert(!fDetectLeak()); // Assert: no memory leak detected
#endif
if(m_pWordPool)
m_pWordPool->FreeChain();
}
/*============================================================================
CWordLink::InitLink()
Init word link, set the text buffer pointer and length.
Remarks:
If there are words in the link, free the link at first
dwFormat is a format hint info generate by WinWord,
it's a very important property of the sentence
============================================================================*/
void CWordLink::InitLink(const WCHAR* pwchText, USHORT cwchLen, DWORD dwFormat)
{
FreeLink();
m_dwFlag = 0;
m_pwchText = pwchText;
m_cwchLen = cwchLen;
m_dwFormat = dwFormat;
}
/*============================================================================
CWord::pGetHead()
Get the head Word node of the WordLink.
Remarks:
In debug mode, do a all nodes verify one by one.
============================================================================*/
#ifdef DEBUG
CWord* CWordLink::pGetHead(void)
{
// Verify each node before iterate the WordLink
CWord* pWord = m_pHead;
WCHAR* pwchText;
USHORT cwchText=0;
if (pWord != NULL) {
pwchText = pWord->m_pwchText;
// head node's m_pwchText must match this WordLink's m_pwchText !
assert(pwchText == m_pwchText);
}
while (pWord) {
assert(pWord->cwchLen() > 0);
assert(pWord->fGetFlag(CWord::WF_SBCS) ||
(pWord->cwchLen() == 1 && pWord->fGetFlag(CWord::WF_CHAR)) ||
(pWord->cwchLen() > 1 && !pWord->fGetFlag(CWord::WF_CHAR)) );
assert(pwchText + cwchText == pWord->m_pwchText);
cwchText += pWord->m_cwchText;
pWord->pChildWord(); // do a recursion to childs
pWord = pWord->pNextWord();
}
return (CWord*)m_pHead;
}
#else
CWord* CWordLink::pGetHead(void) { return m_pHead; };
#endif // DEBUG
/*============================================================================
CWordLink::pAllocWord()
Alloc a new word, but do not chain the word into the link.
All public fields in the word object set to 0.
Returns:
a CWord point to the new word.
NULL if alloc failure.
============================================================================*/
CWord* CWordLink::pAllocWord(void)
{
assert(m_pwchText); // Catch uninitialized call
CWord* pWord = pNewWord();
if (pWord != NULL) {
ZeroMemory( pWord, sizeof(CWord) );
/************
pWord->ClearWord();
pWord->m_pwchText = NULL;
pWord->m_cwchText = 0;
pWord->m_pNext = NULL;
pWord->m_pPrev = NULL;
pWord->m_pMergedFrom = NULL;
#ifdef DEBUG
pWord->m_pMergedTo = NULL;
#endif // DEBUG
************/
}
return pWord;
}
/*============================================================================
CWordLink::AppendWord()
Append a word object into the link.
============================================================================*/
void CWordLink::AppendWord(CWord* pWord)
{
#ifdef DEBUG
assert(m_pwchText && m_cwchLen); // Catch uninitialized call
// Word's text pointer must fall in WordLink's text buffer
assert(pWord->m_pwchText >= m_pwchText && pWord->m_cwchText);
assert(pWord->m_pwchText + pWord->m_cwchText <= m_pwchText + m_cwchLen);
assert(!fInLink(pWord)); // pWord must outof current link
assert(!fInChild(pWord));
assert(fInBlocks(pWord)); // pWord must owned by current WordLink
if (m_pTail) {
// No zero-length word allowed
assert(pWord->m_pwchText == m_pTail->m_pwchText + m_pTail->m_cwchText);
} else {
assert(pWord->m_pwchText == m_pwchText);
}
#endif // DEBUG
pWord->m_pNext = NULL;
if (!m_pHead) {
assert(pWord->m_pwchText == m_pwchText);
m_pHead = pWord;
} else {
assert(pWord->m_pwchText > m_pwchText);
m_pTail->m_pNext = pWord;
}
pWord->m_pPrev = m_pTail;
m_pTail = pWord;
}
/*============================================================================
CWordLink::FreeWord()
Free word to the free chain, pWord must out of current WordLink
============================================================================*/
void CWordLink::FreeWord(CWord* pWord)
{
assert(pWord);
assert(m_pwchText); // Catch uninitialized call
#ifdef DEBUG
assert(!fInLink(pWord)); // pWord should not in current link
assert(!fInChild(pWord)); // must not in any of the child links
assert(!fInFree(pWord)); // must not in free link
assert(fInBlocks(pWord)); // pWord must owned by this WordLink instance
#endif // DEBUG
// link the word to the free link
pWord->m_pNext = m_pFree;
m_pFree = pWord;
}
/*============================================================================
CWordLink::FreeLink(CWord*)
Free the word link begin with CWord* (link words to the free chain)
============================================================================*/
void CWordLink::FreeLink( CWord* pWord )
{
assert(pWord);
#ifdef DEBUG
assert(fInBlocks(pWord)); // pWord must owned by this WordLink instance
if (pWord != m_pHead) {
if (m_pwchText) {
assert(!fInLink(pWord)); // pWord should not in current link
assert(!fInChild(pWord));
}
}
#endif // DEBUG
CWord* pNode = pWord;
while (pNode->m_pNext) {
if (pNode->m_pMergedFrom) {
FreeLink(pNode->m_pMergedFrom);
}
pNode = pNode->m_pNext;
#ifdef DEBUG
assert(!fInFree(pWord));
#endif // DEBUG
}
if (pNode->m_pMergedFrom) {
FreeLink(pNode->m_pMergedFrom);
}
pNode->m_pNext = m_pFree;
m_pFree = pWord;
}
/*============================================================================
CWordLink::pSplitWord()
Split a proper word into two words and insert the new word into the link
Returns:
Return the new word pointer if success, return NULL if failed to alloc new word
or invalid cchSplitAt
Remarks:
only Chinese word can be splitted
============================================================================*/
CWord* CWordLink::pSplitWord(CWord* pWord, USHORT cwchSplitAt)
{
assert(m_pwchText); // Catch uninitialized call
assert(pWord);
#ifdef DEBUG
assert(fInLink(pWord)); // pWord must in current link
#endif // DEBUG
assert(cwchSplitAt < pWord->m_cwchText);
assert(!pWord->fGetFlag(CWord::WF_SBCS) && cwchSplitAt > 0);
if (cwchSplitAt == 0 || cwchSplitAt >= pWord->m_cwchText) {
return NULL;
}
if (pWord->m_pMergedFrom != NULL) {
// free the child chains!
CWord* pTemp = pWord->m_pMergedFrom;
pWord->m_pMergedFrom = NULL;
FreeLink(pTemp);
}
CWord* pNew = pNewWord();
if (pNew != NULL) {
// link the new word into the WordLink
pNew->m_pPrev = pWord;
if (pWord->m_pNext == NULL) {
m_pTail = pNew;
pNew->m_pNext = NULL;
} else {
pWord->m_pNext->m_pPrev = pNew;
pNew->m_pNext = pWord->m_pNext;
}
pWord->m_pNext = pNew;
pNew->m_pMergedFrom = NULL;
#ifdef DEBUG
pNew->m_pMergedTo = NULL;
#endif // DEBUG
// Initialize the new word node
pNew->ClearWord();
pNew->m_pwchText = pWord->m_pwchText + cwchSplitAt;
pNew->m_cwchText = pWord->m_cwchText - cwchSplitAt;
if(pNew->m_cwchText == 1) {
pNew->SetFlag(CWord::WF_CHAR);
}
// reset the original word node
pWord->ClearWord();
pWord->m_cwchText = cwchSplitAt;
if(cwchSplitAt == 1) {
pWord->SetFlag(CWord::WF_CHAR);
}
}
return pWord;
}
/*============================================================================
CWordLink::MergeWithNext()
Merge pWord with its next word to a new single word, and chain the old two
word as the new word's child word
Remarks:
pWord should not be the last word in the sentence
============================================================================*/
void CWordLink::MergeWithNext(
CWord* pWord,
BOOL fFree) // TRUE: free the words been merged
// FALSE: chain the words been merged as new word's child
{
assert(m_pwchText);
assert(pWord);
#ifdef DEBUG
assert(fInLink(pWord));
#endif // DEBUG
assert(pWord->m_pNext); // catch the last word in the link
pMerge(pWord, pWord->m_pNext, fFree);
}
/*============================================================================
CWordLink::pLeftMerge()
Merge pWord and it's left ciWords words, the ciWords+1 words chained to
be the new merged word's childs.
Returns:
pointer to the merged word.
if there is not enough left word nodes, words are NOT merged
============================================================================*/
CWord* CWordLink::pLeftMerge(
CWord* pWord, // merge begin from pWord with left ciWords words
UINT ciWords, // 0 - don't merge, 1 - merge one time(merge with prev)
// 2 - merge two time (contain 3 words)
BOOL fFree) // TRUE: free the words been merged
// FALSE: chain the words been merged as new word's child
{
assert(pWord);
#ifdef DEBUG
assert(fInLink(pWord));
#endif
if (ciWords == 0) {
return pWord;
}
assert(ciWords > 0);
CWord* pLeft = pWord;
CWord* pRight = pWord;
for(UINT i = 0; i < ciWords; i++) {
if((pLeft = pLeft->m_pPrev) == NULL) { // Defensive way!
assert(0);
return pWord;
}
}
return pMerge(pLeft, pRight, fFree);
}
/*============================================================================
CWordLink::pRightMerge()
Merge pWord and it's right ciWords words, the ciWords+1 words chained to
be the new merged word's childs.
Returns:
pointer to the merged word.
NULL if there is not enough right word nodes, and words are NOT merged
============================================================================*/
CWord* CWordLink::pRightMerge(
CWord* pWord, // merge begin from pWord with right ciWords words
UINT ciWords, // 0 - don't merge, 1 - merge one time(merge with next)
// 2 - merge two time (contain 3 words)
BOOL fFree) // TRUE: free the words been merged
// FALSE: chain the words been merged as new word's child
{
assert(pWord);
#ifdef DEBUG
assert(fInLink(pWord));
#endif // DEBUG
if (ciWords == 0) {
return pWord;
}
assert(ciWords > 0);
CWord* pLeft = pWord;
CWord* pRight = pWord;
for(UINT i = 0; i < ciWords; i++) {
if ((pRight = pRight->m_pNext) == NULL) { // Defensive way!
assert(0);
return pWord;
}
}
return pMerge(pLeft, pRight, fFree);
}
/*============================================================================
Implementation of private functions in CWordLink
============================================================================*/
// Merge word nodes from pLeft to pRight
// only called by pLeftMerge() and pRightMerge() and MergeWithNext()
// to do the merge work
CWord* CWordLink::pMerge(CWord* pLeft, CWord* pRight, BOOL fFree)
{
assert(pLeft);
assert(pRight);
CWord* pNew;
BOOL fSBCS = (BOOL)(pLeft->fGetFlag(CWord::WF_SBCS));
USHORT cwchText = pLeft->m_cwchText;
pNew = pLeft;
do {
pNew = pNew->m_pNext;
assert(pNew != NULL);
fSBCS = fSBCS && pNew->fGetFlag(CWord::WF_SBCS);
cwchText += pNew->m_cwchText;
} while (pNew != pRight);
// alloc a new word node to save the pLeft and serve as the old pLeft in child
// the pLeft serve as the merged word.
pNew = fFree ? NULL : pAllocWord();
// pNew != NULL
if (pNew != NULL) {
assert(fFree == FALSE);
pNew->CopyWord(pLeft);
#ifdef DEBUG
if (pLeft->fHasChild()) {
CWord* pTemp;
pTemp = pLeft->pChildWord();
while (pTemp) {
pTemp->m_pMergedTo = pNew;
pTemp = pTemp->m_pNext;
}
}
#endif // DEBUG
} else {
// pNew == NULL, low-resource of system, force the words been merged be freed.
fFree = TRUE;
pNew = pLeft->pNextWord();
}
if ( pRight->m_pNext == NULL ) { // tail node
m_pTail = pLeft;
pLeft->m_pNext = NULL;
} else {
pRight->m_pNext->m_pPrev = pLeft;
pLeft->m_pNext = pRight->m_pNext;
}
pLeft->m_cwchText = cwchText;
if (fFree) {
// pNew comes from pLeft->pNextWord()
pNew->m_pPrev = NULL;
pRight->m_pNext = NULL;
FreeLink(pNew);
if (pLeft->fHasChild()) {
pNew = pLeft->pChildWord();
assert(pNew);
pLeft->m_pMergedFrom = NULL;
#ifdef DEBUG
pNew->m_pMergedTo = NULL;
#endif // DEBUG
FreeLink(pNew);
}
} else {
// link the pNew to pWord chain as the pLeft's child
pNew->m_pPrev = NULL;
pNew->m_pNext->m_pPrev = pNew;
pRight->m_pNext = NULL;
pLeft->m_pMergedFrom = pNew;
#ifdef DEBUG
while ( pNew != NULL ) {
pNew->m_pMergedTo = pLeft;
pNew = pNew->m_pNext;
}
assert(pLeft->pChildWord());
#endif //DEBUG
}
// reset the merged node
pLeft->ClearWord();
if(fSBCS) {
pLeft->SetFlag(CWord::WF_SBCS);
}
assert(pLeft->fGetFlag(CWord::WF_SBCS) || pLeft->m_cwchText > 1);
pLeft->SetFlag(CWord::WF_REDUCED); // All merged word node should be reduced
return pLeft;
}
/*============================================================================
CWordLink::pNewWord()
Alloc a new word from the free chain, expand the blocks if free chain empty
============================================================================*/
inline CWord* CWordLink::pNewWord()
{
CWord* pWord;
if (!m_pFree) {
CMyPlex* pNewBlock = CMyPlex::Create(m_pWordPool, m_ciBlockSize,
sizeof(CWord));
if (!pNewBlock)
return NULL; // can not allocate more memory block
// chain them into free list
pWord = (CWord*)pNewBlock->Data();
// free in reverse order to make it easier to debug
pWord += m_ciBlockSize - 1;
for(int i = (m_ciBlockSize - 1); i >= 0; i--, pWord--) {
pWord->m_pNext = m_pFree;
m_pFree = pWord;
}
}
assert(m_pFree != NULL); // we must have nodes in the free list now!
pWord = m_pFree;
m_pFree = m_pFree->m_pNext;
return pWord;
}
/*============================================================================
CWordLink::FreeLink(void)
Free word in the link and reset the link (only link words to the free chain)
Remarks:
This method call FreeLink( CWord *pWord ) recursion to free link and child link
============================================================================*/
void CWordLink::FreeLink(void)
{
#ifdef DEBUG
assert(!fDetectLeak()); // Assert: no memory leak detected
#endif // DEBUG
if (m_pwchText) {
if (m_pHead) {
CWord* pTemp = m_pHead;
m_pwchText = NULL;
m_pHead = NULL;
m_pTail = NULL;
FreeLink(pTemp);
} else {
assert(m_pwchText == NULL);
assert(m_pHead == NULL);
assert(m_pTail == NULL);
}
}
assert(!m_pHead);
}
/*============================================================================
Implementation of private debugging functions
============================================================================*/
#ifdef DEBUG
/*============================================================================
CWordLink::fInLink()
Debugging function to check whether a word pointer is in the link.
Not check whether the pointer is in child chain.
============================================================================*/
BOOL CWordLink::fInLink(CWord* pWord)
{
CWord* pcw = m_pHead;
while (pcw) {
if (pcw == pWord)
return TRUE;
pcw = pcw->m_pNext;
}
return FALSE;
}
/*============================================================================
CWordLink::fInChild()
Debugging function to check whether a word pointer is in one of the
child chains.
============================================================================*/
inline BOOL CWordLink::fInChild(CWord* pWord)
{
CWord* pcw = m_pHead;
while (pcw) {
if (pcw->m_pMergedFrom != NULL && fInChildOf(pWord, pcw)) {
return TRUE;
}
pcw = pcw->pNextWord();
}
return FALSE;
}
/*============================================================================
CWordLink::fInChildOf()
Debugging function to check whether a word pointer is in the child chain
of the pParent.
============================================================================*/
BOOL CWordLink::fInChildOf(CWord* pWord, CWord* pParent)
{
CWord* pcw = pParent->pChildWord();
while (pcw) {
if (pcw == pWord) {
return TRUE;
} else if (pcw->m_pMergedFrom != NULL && fInChildOf(pWord, pcw)) {
return TRUE;
} else {
}
pcw = pcw->m_pNext;
}
return FALSE;
}
/*============================================================================
CWordLink::fInBlocks()
Debugging function to check whether the pWord is in CMyPlex blocks
============================================================================*/
BOOL CWordLink::fInBlocks(CWord* pWord)
{
CWord* pFirstWord;
CMyPlex* pBlock = m_pWordPool;
while(pBlock) {
pFirstWord = (CWord*)(pBlock->Data());
if(pWord >= pFirstWord && pWord < (pFirstWord + m_ciBlockSize)) {
return TRUE;
}
pBlock = pBlock->m_pNext;
}
return FALSE;
}
/*============================================================================
CWordLink::fInFree()
Debugging function to check whether the pWord is in free links
============================================================================*/
BOOL CWordLink::fInFree(CWord* pWord)
{
CWord* pcw = m_pFree;
while (pcw) {
if (pcw == pWord) {
return TRUE;
}
pcw = pcw->m_pNext;
}
return FALSE;
}
/*============================================================================
CWordLink::SetDetectFlag
Debugging function to set the word node leak flg used by fDetectLeak()
============================================================================*/
void CWordLink::SetDetectFlag(CWord* pWord)
{
CWord* pcw = pWord;
while (pcw) {
if (pcw->m_pMergedFrom != NULL) {
SetDetectFlag( pcw->m_pMergedFrom );
}
pcw->SetFlag(CWord::WF_DEBUG);
pcw = pcw->m_pNext;
}
return;
}
/*============================================================================
CWordLink::fDetectLeak()
Debugging function to check whether there are some word node leak to
out of the link and the free chain
Returns:
TRUE if any leak is detected,
FALSE if no leak detected
Remarks:
I hire the most significant bit in CWord::m_bFlag as the debugging use
============================================================================*/
BOOL CWordLink::fDetectLeak(void)
{
CWord* pWord;
CMyPlex* pBlock;
UINT i;
// clear flag bit for all words in all blocks
for(pBlock = m_pWordPool; pBlock; pBlock = pBlock->m_pNext) {
for(i = 0, pWord = (CWord*)(pBlock->Data());
i < m_ciBlockSize; i++, pWord++) {
pWord->ClearFlag(CWord::WF_DEBUG);
}
}
// mark the flag bit for words in current link and in the free chain
SetDetectFlag( m_pHead );
for(pWord = m_pFree; pWord; pWord = pWord->m_pNext) {
pWord->SetFlag(CWord::WF_DEBUG);
}
// Check whether there are any leak words
for(pBlock = m_pWordPool; pBlock; pBlock = pBlock->m_pNext) {
for(i = 0, pWord = (CWord*)(pBlock->Data()); i < m_ciBlockSize; i++, pWord++) {
if(!pWord->fGetFlag(CWord::WF_DEBUG)) {
return TRUE;
}
}
}
return FALSE;
}
#endif // DEBUG
|
[
"seta7D5@protonmail.com"
] |
seta7D5@protonmail.com
|
0de461b0ebd370c5b192af2b7a626a2e7f00d00a
|
9a042e84901ae0f9cfa034964ae6379800ec196d
|
/hydrogenMusic/lyrics.h
|
aefd0025e38cc8085aa0f7ee7217a4fb960c35af
|
[] |
no_license
|
375187588/hydrogenMusic
|
8f57ad918ccc7e5af87440c85c15a7181f13a5bf
|
030d0f0e7c083633ab5fa69d56560cc73e5b0bfd
|
refs/heads/master
| 2022-01-12T17:27:18.131845
| 2019-05-25T22:40:51
| 2019-05-25T22:40:51
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,608
|
h
|
#ifndef LYRICS_H
#define LYRICS_H
#include <QObject>
#include <QQmlListProperty>
#include <string>
#include <QVariant>
const int MAX_LYRCE_REPEAT_NUM = 10;
class Lyric:public QObject
{
Q_OBJECT
Q_PROPERTY(QList<QString> header READ header)
Q_PROPERTY(int lineNum READ lineNum)
Q_PROPERTY(QList<QString> lheader READ lheader WRITE setlheader NOTIFY lheaderChanged)
Q_PROPERTY(QList<QString> lyricContent READ lyricContent WRITE setlyricContent NOTIFY lyricContentChanged)
Q_PROPERTY(QList<int> endTime READ endTime)
Q_PROPERTY(QList<int> startTime READ startTime WRITE setstartTime NOTIFY startTimeChanged)
public:
explicit Lyric(QObject *parent = 0):QObject(parent)
{/*readLyric();*/}
QList<QString> header() const;
int lineNum() const;
QList<QString> lheader() const;
void setlheader(QList<QString> &l);
QList<QString> lyricContent() const;
void setlyricContent(QList<QString> &lc);
QList<int> endTime() const;
QList<int> startTime() const;
void setstartTime(QList<int> &s);
Q_INVOKABLE void readLyric(QString addr);
void analysisOneLine(std::string str);
bool getLyricHeader(std::string str);
Q_INVOKABLE int changeStringToInt(std::string str_time);
void clean();
signals:
void lheaderChanged();
void lyricContentChanged();
void startTimeChanged();
void lAddressChanged();
void ok();
private:
QList<QString> m_header;
int m_lineNum;
QList<QString> m_Lheader;
QList<QString> m_lyricContent;
QList<int> m_endTime;
QList<int> m_startTime;
};
#endif // LYRICS_H
|
[
"root@localhost.localdomain"
] |
root@localhost.localdomain
|
d4af0963b36c3c3f3399f248cade0fb43357c057
|
9e61c2390580b6982cf08a6417e29d69a6acb600
|
/973_K_Closest_Points_To_Origin/heap.cpp
|
2e41ebfbbfc19f9877a77f7e1fdc86529b94b511
|
[] |
no_license
|
acnokego/LeetCode
|
3027e1987cee4d130c9db7e2af4ec4de8a0f43bd
|
3e04e79e05ffcaf423d5a148668e132ee090596f
|
refs/heads/master
| 2021-06-07T02:39:57.956371
| 2019-11-30T03:45:29
| 2019-11-30T03:45:29
| 133,643,518
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 822
|
cpp
|
class Solution {
public:
/*
* Complexity: O(nlgk)
* Space: O(k)
*/
struct compare {
bool operator()(const vector<int>& p1, vector<int>& p2){
long dist1 = p1[0] * p1[0] + p1[1] * p1[1];
long dist2 = p2[0] * p2[0] + p2[1] * p2[1];
return dist1 < dist2;
}
};
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
priority_queue<vector<int>, vector<vector<int>>, compare>max_heap;
for(int i = 0; i < points.size(); ++i){
max_heap.push(points[i]);
while(max_heap.size() > K) {
max_heap.pop();
}
}
vector<vector<int>>ans(max_heap.size());
copy(&(max_heap.top()), &(max_heap.top()) + max_heap.size(), &ans[0]);
return ans;
}
};
|
[
"yuandychen@gmail.com"
] |
yuandychen@gmail.com
|
d18c0a35b2c4d9f6920fcdb7a9ed8f59591b0f49
|
e13580c8245c231f80418a9711c4a1aff15e87b0
|
/Code/sieve.cpp
|
5743cfac88d04ef42966d3379df8e40c96727c23
|
[] |
no_license
|
YsHaNgM/PrimeSieveCXX
|
ddc4046d67ca816ec55c54741369ef7c939272d0
|
8d7c3558db49ef091d523edf0c8963626ab10433
|
refs/heads/master
| 2022-12-31T09:32:48.096246
| 2020-10-21T11:25:17
| 2020-10-21T11:25:17
| 305,846,470
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,803
|
cpp
|
#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <memory>
#ifdef _OPENMP
#include <omp.h>
#endif
//#define NDEBUG
// See README.md for instructions and information.
using ptr = std::shared_ptr<int[]>; // gcc-7 is needed, for shared_ptr [] operand c++17 P0414R2
void filter(int &count, int &p, int *val)
{
*val *= (count % p);
// if (*val == 1)
// {
// auto mod = (count % p);
// switch (mod)
// {
// case 0:
// *val = 0;
// break;
// default:
// break;
// }
// }
};
int main(int argc, char *argv[])
{
#ifdef _OPENMP
std::clock_t c_start = std::clock();
auto t_start = std::chrono::high_resolution_clock::now();
auto n = 1000;
ptr numbers(new int[n + 1]);
std::fill(numbers.get(), numbers.get() + n, 1);
// #pragma omp parallel shared(numbers), firstprivate(n)
{
int bound = std::sqrt(n);
// #pragma omp for
for (auto p = 2; p <= bound; p++)
{
if (numbers[p] != 0)
{
for (int count = p * 2; count <= n; count++)
{
filter(count, p, numbers.get() + count);
}
}
}
}
std::clock_t c_end = std::clock();
auto t_end = std::chrono::high_resolution_clock::now();
std::cout << std::fixed << "CPU time used: "
<< 1000.0 * (c_end - c_start) / CLOCKS_PER_SEC << " ms\n"
<< "Wall clock time passed: "
<< std::chrono::duration<double, std::milli>(t_end - t_start).count()
<< " ms\n";
for (auto i = 2; i <= n; i++)
{
if (numbers[i] != 0)
{
std::cout << i << " ";
}
}
#endif
return 0;
}
|
[
"ysh788@gmail.com"
] |
ysh788@gmail.com
|
845ffc28f988493fbad2093a0bb7897daf840456
|
3f07e0443a505b33f1862c1e30672f72efd932e6
|
/systems/reachnn_benchmark_6_tora_tanh_symbolic_remainder.cpp
|
caa342dbd42fa6e4edea90d8d65ad4d411dac000
|
[] |
no_license
|
ChaoHuang2018/Real-time-Monitoring-for-NNCS
|
332a53e99f9d0288cde10867dd3a242fd010c5db
|
975e0f836440893f7839751f88e815e10f31498b
|
refs/heads/main
| 2023-05-09T13:45:14.953419
| 2021-06-02T13:48:48
| 2021-06-02T13:48:48
| 304,783,341
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,662
|
cpp
|
#include "../flowstar-template/Continuous.h"
#include "../NNTaylor.h"
#include "../domain_computation.h"
#include "../dynamics_linearization.h"
using namespace std;
using namespace flowstar;
int main(int argc, char *argv[])
{
intervalNumPrecision = 600;
// Declaration of the state variables.
unsigned int numVars = 5;
int x0_id = stateVars.declareVar("x0");
int x1_id = stateVars.declareVar("x1");
int x2_id = stateVars.declareVar("x2");
int x3_id = stateVars.declareVar("x3");
int u_id = stateVars.declareVar("u");
int domainDim = numVars + 1;
// Define the continuous dynamics.
Expression_AST<Real> deriv_x0("x1"); // theta_r = 0
Expression_AST<Real> deriv_x1("-x0 + 0.1*sin(x2)"); // theta_r = 0
Expression_AST<Real> deriv_x2("x3"); // theta_r = 0
Expression_AST<Real> deriv_x3("u"); // theta_r = 0
Expression_AST<Real> deriv_u("0");
vector<Expression_AST<Real>> ode_rhs(numVars);
ode_rhs[x0_id] = deriv_x0;
ode_rhs[x1_id] = deriv_x1;
ode_rhs[x2_id] = deriv_x2;
ode_rhs[x3_id] = deriv_x3;
ode_rhs[u_id] = deriv_u;
Deterministic_Continuous_Dynamics dynamics(ode_rhs);
// Specify the parameters for reachability computation.
Computational_Setting setting;
unsigned int order = stoi(argv[4]);
// stepsize and order for reachability analysis
setting.setFixedStepsize(0.005, order);
// time horizon for a single control step
setting.setTime(0.5);
// cutoff threshold
setting.setCutoffThreshold(1e-10);
// queue size for the symbolic remainder
setting.setQueueSize(1000);
// print out the steps
setting.printOff();
// remainder estimation
Interval I(-0.01, 0.01);
vector<Interval> remainder_estimation(numVars, I);
setting.setRemainderEstimation(remainder_estimation);
//setting.printOn();
setting.prepare();
/*
* Initial set can be a box which is represented by a vector of intervals.
* The i-th component denotes the initial set of the i-th state variable.
*/
double w = stod(argv[1]);
int steps = stoi(argv[2]);
Interval init_x0(-0.76 - w, -0.76 + w), init_x1(-0.44 - w, -0.44 + w), init_x2(-0.52 - w, -0.53 + w), init_x3(-0.29 - w, -0.29 + w), init_u(0); //w=0.01
std::vector<Interval> X0;
X0.push_back(init_x0);
X0.push_back(init_x1);
X0.push_back(init_x2);
X0.push_back(init_x3);
X0.push_back(init_u);
// translate the initial set to a flowpipe
Flowpipe initial_set(X0);
// no unsafe set
vector<Constraint> unsafeSet;
// result of the reachability computation
Result_of_Reachability result;
// define the neural network controller
string nn_name = "systems_with_networks/reachnn_benchmark_6_tora/nn_6_tora_tanh";
NeuralNetwork nn(nn_name);
unsigned int maxOrder = 15;
Global_Computation_Setting g_setting;
g_setting.prepareForReachability(maxOrder);
// the order in use
// unsigned int order = 5;
Interval cutoff_threshold(-1e-8, 1e-8);
unsigned int bernstein_order = stoi(argv[3]);
unsigned int partition_num = 4000;
unsigned int if_symbo = stoi(argv[5]);
double err_max = 0;
time_t start_timer;
time_t end_timer;
double seconds;
time(&start_timer);
vector<string> state_vars;
state_vars.push_back("x0");
state_vars.push_back("x1");
state_vars.push_back("x2");
state_vars.push_back("x3");
// perform 35 control steps
for (int iter = 0; iter < steps; ++iter)
{
cout << "Step " << iter << " starts. " << endl;
//vector<Interval> box;
//initial_set.intEval(box, order, setting.tm_setting.cutoff_threshold);
TaylorModelVec<Real> tmv_input;
// tmv_input.tms.push_back(initial_set.tmvPre.tms[0]);
// tmv_input.tms.push_back(initial_set.tmvPre.tms[1]);
TaylorModelVec<Real> tmv_temp;
initial_set.compose(tmv_temp, order, cutoff_threshold);
tmv_input.tms.push_back(tmv_temp.tms[0]);
tmv_input.tms.push_back(tmv_temp.tms[1]);
tmv_input.tms.push_back(tmv_temp.tms[2]);
tmv_input.tms.push_back(tmv_temp.tms[3]);
// taylor propagation
NNTaylor nn_taylor(nn);
TaylorInfo ti(g_setting, order, bernstein_order, partition_num, cutoff_threshold);
TaylorModelVec<Real> tmv_output;
if (if_symbo == 0)
{
nn_taylor.get_output_tmv(tmv_output, tmv_input, ti, initial_set.domain);
}
else
{
cout << "symbolic remainder starts." << endl;
nn_taylor.NN_Reach(tmv_output, tmv_input, ti, initial_set.domain);
}
// cout << "initial_set.domain: " << initial_set.domain[0] << initial_set.domain[1] << endl;
Matrix<Interval> rm1(1, 1);
tmv_output.Remainder(rm1);
cout << rm1 << endl;
cout << "Neural network taylor remainder: " << rm1 << endl;
// taylor
// NNTaylor nn_taylor1(nn);
// vector<Interval> box;
// initial_set.intEval(box, order, setting.tm_setting.cutoff_threshold);
// cout << "initial_set: " << box[0] << box[1] << endl;
// vector<Interval> box_state;
// for (int i = 0; i < state_vars.size(); i++)
// {
// box_state.push_back(box[i]);
// }
// nn_taylor1.set_taylor_linear(state_vars, box_state);
// cout << "11111" << endl;
// vector<double> jcb = nn_taylor1.get_jacobian();
// vector<Real> jcb_real;
// for (int i = 0; i < jcb.size(); i++)
// {
// jcb_real.push_back(Real(jcb[i]));
// }
// Interval rem = nn_taylor1.get_taylor_remainder() + nn_taylor1.get_output();
// cout << "Whole remainder: " << rem << endl;
// Polynomial<Real> tm_coef(jcb_real);
// TaylorModel<Real> tm_output2(jcb_real, rem);
// if (rm1[0][0].width() < rem.width())
if (true)
{
tmv_temp.tms[u_id] = tmv_output.tms[0];
Flowpipe flow_temp(tmv_temp, initial_set.domain, cutoff_threshold);
initial_set = flow_temp;
// initial_set.tmvPre.tms[u_id] = tmv_output.tms[0];
cout << "TM -- Propagation" << endl;
}
else
{
// initial_set.tmvPre.tms[u_id] = tm_output2;
// cout << "TM -- Linear, whole" << endl;
}
dynamics.reach(result, setting, initial_set, unsafeSet);
if (result.status == COMPLETED_SAFE || result.status == COMPLETED_UNSAFE || result.status == COMPLETED_UNKNOWN)
{
initial_set = result.fp_end_of_time;
cout << "Flowpipe taylor remainder: " << initial_set.tmv.tms[0].remainder << " " << initial_set.tmv.tms[1].remainder << endl;
}
else
{
printf("Terminated due to too large overestimation.\n");
return 1;
}
}
vector<Interval> end_box;
string reach_result;
reach_result = "Verification result: Unknown(35)";
result.fp_end_of_time.intEval(end_box, order, setting.tm_setting.cutoff_threshold);
if (end_box[0].inf() >= 0.0 && end_box[0].sup() <= 0.2 && end_box[1].inf() >= 0.05 && end_box[1].sup() <= 0.3)
{
reach_result = "Verification result: Yes(35)";
}
if (end_box[0].inf() >= 0.2 || end_box[0].sup() <= 0.0 || end_box[1].inf() >= 0.3 || end_box[1].sup() <= 0.05)
{
reach_result = "Verification result: No(35)";
}
time(&end_timer);
seconds = difftime(start_timer, end_timer);
// plot the flowpipes in the x-y plane
result.transformToTaylorModels(setting);
Plot_Setting plot_setting;
plot_setting.setOutputDims(x0_id, x1_id);
int mkres = mkdir("./outputs", S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
if (mkres < 0 && errno != EEXIST)
{
printf("Can not create the directory for images.\n");
exit(1);
}
std::string running_time = "Running Time: " + to_string(-seconds) + " seconds";
std::string choice(argv[5]);
ofstream result_output("./outputs/reachnn_benchmark_6_tora_tanh_" + choice + ".txt");
if (result_output.is_open())
{
result_output << reach_result << endl;
result_output << running_time << endl;
}
// you need to create a subdir named outputs
// the file name is example.m and it is put in the subdir outputs
plot_setting.plot_2D_interval_MATLAB("reachnn_benchmark_6_tora_tanh_" + choice, result);
return 0;
}
|
[
"thomashuangchao@gmail.com"
] |
thomashuangchao@gmail.com
|
9326e7c7f1df0cbdb675cb90aa603e656d143fb5
|
e3dbb5424ac55ed2cbdde92be998dee4571ebceb
|
/math/gvec.tpp
|
4b92463a6993934ac6f75df8c3e74805b7691583
|
[] |
no_license
|
ralismark/sd1
|
c027b8ead3465493dbd8c3474025cc0019546337
|
6290604bfa4dabc5d3183af6806b8d2a5ec18967
|
refs/heads/master
| 2021-08-19T11:52:10.966848
| 2017-01-02T11:14:08
| 2017-01-02T11:14:08
| 112,053,737
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,811
|
tpp
|
#pragma once
#include "gvec.hpp"
template <typename T, size_t N>
gvec<T, N>::gvec(T init)
{
for(size_t i = 0; i < N; ++i) {
vals[i] = init;
}
}
template <typename T, size_t N>
gvec<T, N>::gvec(std::initializer_list<T> il)
{
auto it = il.begin();
for(size_t i = 0; i < il.size() && i < N; ++i) {
vals[i] = *it++;
}
}
template <typename T, size_t N>
gvec<T, N> gvec<T, N>::operator+() const
{
return *this;
}
template <typename T, size_t N>
gvec<T, N> gvec<T, N>::operator-() const
{
auto copy = *this;
for(size_t i = 0; i < N; ++i) {
copy.vals[i] = -copy.vals[i];
}
return copy;
}
template <typename T, size_t N>
gvec<T, N>& gvec<T, N>::operator+=(const gvec<T, N>& other)
{
for(size_t i = 0; i < N; ++i) {
vals[i] += other.vals[i];
}
return *this;
}
template <typename T, size_t N>
gvec<T, N>& gvec<T, N>::operator-=(const gvec<T, N>& other)
{
for(size_t i = 0; i < N; ++i) {
vals[i] -= other.vals[i];
}
return *this;
}
template <typename T, size_t N>
gvec<T, N>& gvec<T, N>::operator*=(const gvec<T, N>& other)
{
for(size_t i = 0; i < N; ++i) {
vals[i] *= other.vals[i];
}
return *this;
}
template <typename T, size_t N>
gvec<T, N>& gvec<T, N>::operator/=(const gvec<T, N>& other)
{
for(size_t i = 0; i < N; ++i) {
vals[i] /= other.vals[i];
}
return *this;
}
template <typename T, size_t N>
gvec<T, N> gvec<T, N>::operator+(gvec<T, N> other) const
{
return other += *this;
}
template <typename T, size_t N>
gvec<T, N> gvec<T, N>::operator-(gvec<T, N> other) const
{
other -= *this;
return -other;
}
template <typename T, size_t N>
gvec<T, N> gvec<T, N>::operator*(gvec<T, N> other) const
{
return other *= *this;
}
template <typename T, size_t N>
gvec<T, N> operator/(gvec<T, N> self, const gvec<T, N>& other)
{
return self /= other;
}
template <typename T, size_t N>
gvec<T, N>& gvec<T, N>::operator*=(const T& other)
{
for(size_t i = 0; i < N; ++i) {
vals[i] *= other;
}
return *this;
}
template <typename T, size_t N>
gvec<T, N>& gvec<T, N>::operator/=(const T& other)
{
for(size_t i = 0; i < N; ++i) {
vals[i] /= other;
}
return *this;
}
template <typename T, size_t N>
gvec<T, N> operator*(gvec<T, N> self, const T& other)
{
return self *= other;
}
template <typename T, size_t N>
gvec<T, N> operator/(gvec<T, N> self, const T& other)
{
return self /= other;
}
template <typename T, size_t N>
gvec<T, N> operator*(const T& other, gvec<T, N> self)
{
return self *= other;
}
template <typename T, size_t N>
bool gvec<T, N>::operator==(const gvec<T, N>& other) const
{
for(size_t i = 0; i < N; ++i) {
if(vals[i] != other[i]) {
return false;
}
}
return true;
}
template <typename T, size_t N>
bool gvec<T, N>::operator!=(const gvec<T, N>& other) const
{
return !(*this == other);
}
template <typename T, size_t N>
typename detail::access<T, N>::type* gvec<T, N>::operator->()
{
return &access;
}
template <typename T, size_t N>
const typename detail::access<T, N>::type* gvec<T, N>::operator->() const
{
return &access;
}
template <typename T, size_t N>
const T& gvec<T, N>::operator[](size_t n) const
{
return vals[n];
}
template <typename T, size_t N>
T& gvec<T, N>::operator[](size_t n)
{
return vals[n];
}
template <typename T, size_t N>
std::ostream& operator<<(std::ostream& os, const gvec<T, N>& gv)
{
os << "[ ";
for(size_t i = 0; i < N; ++i) {
if(i != 0) {
os << ", ";
}
os << gv[i];
}
os << " ]";
return os;
}
template <typename T, size_t N>
template <typename C>
gvec<typename std::enable_if<std::is_convertible<T, C>::value, C>::type, N> gvec<T, N>::cast() const
{
gvec<C, N> out;
for(size_t i = 0; i < N; ++i) {
out[i] = vals[i];
}
return out;
}
template <typename O, typename... T>
gvec<O, sizeof...(T)> make_vec(T... vals)
{
gvec<O, sizeof...(T)> gv = {vals...};
return gv;
}
|
[
"timmy.yao@outlook.com.au"
] |
timmy.yao@outlook.com.au
|
06c6ad3183830022793d51e6c12d3d5bfafa41a1
|
c459ada4ee8a006f244757d9b14eaccc2f897c4f
|
/src/demo_apps/server/main.cc
|
b6fdb872bc1e64f5ad2512cf1a2cd0cd2d6d3fb4
|
[
"Apache-2.0"
] |
permissive
|
rrozestw/smf
|
56133b24aab55847d53578dfbb186074c06e538f
|
1dafa1ed529134fd81e504129356cb252694a80f
|
refs/heads/master
| 2021-04-28T11:14:12.385041
| 2018-02-16T04:08:11
| 2018-02-16T23:46:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,939
|
cc
|
// Copyright (c) 2017 Alexander Gallego. All rights reserved.
//
#include <chrono>
#include <iostream>
#include <core/app-template.hh>
#include <core/distributed.hh>
#include "histogram/histogram_seastar_utils.h"
#include "histogram/unique_histogram_adder.h"
#include "platform/log.h"
#include "rpc/filters/zstd_filter.h"
#include "rpc/rpc_filter.h"
#include "rpc/rpc_server.h"
#include "flatbuffers/demo_service.smf.fb.h"
class storage_service : public smf_gen::demo::SmfStorage {
virtual seastar::future<smf::rpc_typed_envelope<smf_gen::demo::Response>>
Get(smf::rpc_recv_typed_context<smf_gen::demo::Request> &&rec) final {
smf::rpc_typed_envelope<smf_gen::demo::Response> data;
// return the same payload
if (rec) { data.data->name = rec->name()->c_str(); }
data.envelope.set_status(200);
return seastar::make_ready_future<
smf::rpc_typed_envelope<smf_gen::demo::Response>>(std::move(data));
}
};
void
cli_opts(boost::program_options::options_description_easy_init o) {
namespace po = boost::program_options;
o("ip", po::value<std::string>()->default_value("127.0.0.1"),
"ip to connect to");
o("port", po::value<uint16_t>()->default_value(20776), "port for service");
o("httpport", po::value<uint16_t>()->default_value(20777),
"port for http stats service");
}
int
main(int args, char **argv, char **env) {
std::setvbuf(stdout, nullptr, _IOLBF, 1024);
seastar::distributed<smf::rpc_server> rpc;
seastar::app_template app;
cli_opts(app.add_options());
return app.run_deprecated(args, argv, [&] {
seastar::engine().at_exit([&] {
return rpc
.map_reduce(smf::unique_histogram_adder(),
&smf::rpc_server::copy_histogram)
.then([](auto h) {
LOG_INFO("Writing server histograms");
return smf::histogram_seastar_utils::write("server_hdr.hgrm",
std::move(h));
})
.then([&rpc] { return rpc.stop(); });
});
auto &cfg = app.configuration();
smf::rpc_server_args args;
args.ip = cfg["ip"].as<std::string>().c_str();
args.rpc_port = cfg["port"].as<uint16_t>();
args.http_port = cfg["httpport"].as<uint16_t>();
// Normal services would either use the defaults or something smarter
// This triggers the memory pressure
args.basic_req_size = 60 /*payload size*/;
args.bloat_mult = 1; // no bloat
args.memory_avail_per_core =
static_cast<uint64_t>(0.9 * seastar::memory::stats().total_memory());
return rpc.start(args)
.then([&rpc] {
LOG_INFO("Registering smf_gen::demo::storage_service");
return rpc.invoke_on_all(
&smf::rpc_server::register_service<storage_service>);
})
.then([&rpc] {
LOG_INFO("Invoking rpc start on all cores");
return rpc.invoke_on_all(&smf::rpc_server::start);
});
});
}
|
[
"gallego.alexx@gmail.com"
] |
gallego.alexx@gmail.com
|
2628725c8e745160e3e3d3c5056655a026406fdb
|
cce2be08daabedee6a6001e371df3f79d754c6d0
|
/virtual function.cpp
|
2c5c970840f982bae281cfd7ec21432b78b5a441
|
[] |
no_license
|
AnshTrehan/old-C-CPP-codes
|
9a9fdac6a5bd3985ee8df900a66f55e2a48f90cd
|
0b8dd8117f4fd8ea2e4184aacdc73fe3ff57d2ae
|
refs/heads/master
| 2022-11-30T13:18:42.708708
| 2020-08-17T05:28:10
| 2020-08-17T05:28:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 491
|
cpp
|
#include<iostream>
#include<conio.h>
using namespace std;
class base
{
public:
int a;
void virtualshow()
{
cout<<"\nHello base class";
cout<<a;
}
};
class derived: public base
{
public:
int b;
void show()
{
cout<<"\nHello derived class";
cout<<b;
}
};
int main()
{
base *ptr;
base b1;
ptr=&b1;
ptr->a=100;
*(ptr).show; //ptr->show()
derived d1;
ptr=&d1;
d1.b=50;
ptr->show();
getch();
}
|
[
"anshtrehan@gmail.com"
] |
anshtrehan@gmail.com
|
ec24f045a4dabd4e7ffd8f7a192bb82b3cd08a56
|
1c317570632645effae4558ea1dcaf05531b997f
|
/HotGain/Source/PluginProcessor.cpp
|
92bada3398ee2df534e0b165dd013d3da9880bf2
|
[] |
no_license
|
ashtonmills/HotGain
|
8695f552e887db9a9c14709804b711415bc63c20
|
d198f3144b4835b583d48b47bdf9a0f49358d048
|
refs/heads/master
| 2020-07-27T13:23:16.375136
| 2019-09-17T16:32:58
| 2019-09-17T16:32:58
| 209,104,394
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,525
|
cpp
|
/*
==============================================================================
This file was auto-generated!
It contains the basic framework code for a JUCE plugin processor.
==============================================================================
*/
#include "PluginProcessor.h"
#include "PluginEditor.h"
//==============================================================================
//This is the initialization list: to initialise (so when the member is created, it is given a value, rather than reating it empty then giving it a value, this is more efficient apparently).
HotGainAudioProcessor::HotGainAudioProcessor()
#ifndef JucePlugin_PreferredChannelConfigurations
: AudioProcessor (BusesProperties()
#if ! JucePlugin_IsMidiEffect
#if ! JucePlugin_IsSynth
.withInput ("Input", AudioChannelSet::stereo(), true)
#endif
.withOutput ("Output", AudioChannelSet::stereo(), true)
#endif
),
//logVolume(-5.0f),
parameters(*this, nullptr)
//this is the constructor
#endif
{
NormalisableRange<float>gainRange(-48.0f, 0.0f);
parameters.createAndAddParameter(GAIN_ID, GAIN_NAME, GAIN_NAME, gainRange,0.5f, nullptr, nullptr);
parameters.state = ValueTree("savedParams");
}
HotGainAudioProcessor::~HotGainAudioProcessor()
{
}
//==============================================================================
const String HotGainAudioProcessor::getName() const
{
return JucePlugin_Name;
}
bool HotGainAudioProcessor::acceptsMidi() const
{
#if JucePlugin_WantsMidiInput
return true;
#else
return false;
#endif
}
bool HotGainAudioProcessor::producesMidi() const
{
#if JucePlugin_ProducesMidiOutput
return true;
#else
return false;
#endif
}
bool HotGainAudioProcessor::isMidiEffect() const
{
#if JucePlugin_IsMidiEffect
return true;
#else
return false;
#endif
}
double HotGainAudioProcessor::getTailLengthSeconds() const
{
return 0.0;
}
int HotGainAudioProcessor::getNumPrograms()
{
return 1; // NB: some hosts don't cope very well if you tell them there are 0 programs,
// so this should be at least 1, even if you're not really implementing programs.
}
int HotGainAudioProcessor::getCurrentProgram()
{
return 0;
}
void HotGainAudioProcessor::setCurrentProgram (int index)
{
}
const String HotGainAudioProcessor::getProgramName (int index)
{
return {};
}
void HotGainAudioProcessor::changeProgramName (int index, const String& newName)
{
}
//==============================================================================
void HotGainAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlock)
{
previousGain = pow(10, *parameters.getRawParameterValue(GAIN_ID));
}
void HotGainAudioProcessor::releaseResources()
{
// When playback stops, you can use this as an opportunity to free up any
// spare memory, etc.
}
#ifndef JucePlugin_PreferredChannelConfigurations
bool HotGainAudioProcessor::isBusesLayoutSupported (const BusesLayout& layouts) const
{
#if JucePlugin_IsMidiEffect
ignoreUnused (layouts);
return true;
#else
// This is the place where you check if the layout is supported.
// In this template code we only support mono or stereo.
if (layouts.getMainOutputChannelSet() != AudioChannelSet::mono()
&& layouts.getMainOutputChannelSet() != AudioChannelSet::stereo())
return false;
// This checks if the input layout matches the output layout
#if ! JucePlugin_IsSynth
if (layouts.getMainOutputChannelSet() != layouts.getMainInputChannelSet())
return false;
#endif
return true;
#endif
}
#endif
void HotGainAudioProcessor::processBlock (AudioBuffer<float>& buffer, MidiBuffer& midiMessages)
{
ScopedNoDenormals noDenormals;
auto totalNumInputChannels = getTotalNumInputChannels();
auto totalNumOutputChannels = getTotalNumOutputChannels();
float currentGain = pow(10, *parameters.getRawParameterValue(GAIN_ID) / 20);
if (currentGain == previousGain)
{
buffer.applyGain(currentGain);
}
else
{
//apply gain ramp gradually increments each sample from the start sample to the last sample in the buffer
//this stops there being a 'click' when you change th values quickly.
buffer.applyGainRamp(0, buffer.getNumSamples(), previousGain, currentGain);
previousGain = currentGain;
}
// In case we have more outputs than inputs, this code clears any output
// channels that didn't contain input data, (because these aren't
// guaranteed to be empty - they may contain garbage).
// This is here to avoid people getting screaming feedback
// when they first compile a plugin, but obviously you don't need to keep
// this code if your algorithm always overwrites all the output channels.
for (auto i = totalNumInputChannels; i < totalNumOutputChannels; ++i)
buffer.clear (i, 0, buffer.getNumSamples());
// This is the place where you'd normally do the guts of your plugin's
// audio processing...
// Make sure to reset the state if your inner loop is processing
// the samples and the outer loop is handling the channels.
// Alternatively, you can process the samples with the channels
// interleaved by keeping the same state.
}
//==============================================================================
bool HotGainAudioProcessor::hasEditor() const
{
return true; // (change this to false if you choose to not supply an editor)
}
AudioProcessorEditor* HotGainAudioProcessor::createEditor()
{
return new HotGainAudioProcessorEditor (*this);
}
//==============================================================================
void HotGainAudioProcessor::getStateInformation (MemoryBlock& destData)
{
std::unique_ptr<XmlElement> xml (parameters.state.createXml());
copyXmlToBinary(*xml, destData);
}
void HotGainAudioProcessor::setStateInformation (const void* data, int sizeInBytes)
{
std::unique_ptr <XmlElement> theParams(getXmlFromBinary(data, sizeInBytes));
if (theParams != nullptr)
{
if (theParams->hasTagName(parameters.state.getType()))
{
parameters.state = ValueTree::fromXml(*theParams);
}
}
}
//==============================================================================
// This creates new instances of the plugin..
AudioProcessor* JUCE_CALLTYPE createPluginFilter()
{
return new HotGainAudioProcessor();
}
|
[
"ashton-mills@outlook.com"
] |
ashton-mills@outlook.com
|
d06b4f02bf9d1e0578cb7fdb10cd8341d137c130
|
f113b7f7695bf2f5c09e5e8afb28cc99ee06c63a
|
/include/DOTk_NonlinearCG/DOTk_LiuStorey.hpp
|
ecebe0aba8fcf8d466cfb6da62021cf5a5141aa0
|
[] |
no_license
|
maguilo11/locus
|
501a074a12e260e2b9f0940a6eb389ad36aefb89
|
cbf926808493c621893cc11f124f813b9e0fcbde
|
refs/heads/master
| 2021-09-24T21:35:27.503003
| 2018-10-15T02:58:38
| 2018-10-15T02:58:38
| 72,475,433
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,153
|
hpp
|
/*
* DOTk_LiuStorey.hpp
*
* Created on: Sep 12, 2014
* Author: Miguel A. Aguilo Valentin
*/
#ifndef DOTK_LIUSTOREY_HPP_
#define DOTK_LIUSTOREY_HPP_
#include "DOTk_DescentDirection.hpp"
namespace dotk
{
class DOTk_OptimizationDataMng;
template<typename ScalarType>
class Vector;
class DOTk_LiuStorey : public dotk::DOTk_DescentDirection
{
public:
DOTk_LiuStorey();
virtual ~DOTk_LiuStorey();
Real computeScaleFactor(const std::shared_ptr<dotk::Vector<Real> > & old_grad_,
const std::shared_ptr<dotk::Vector<Real> > & new_grad_,
const std::shared_ptr<dotk::Vector<Real> > & dir_);
void getDirection(const std::shared_ptr<dotk::Vector<Real> > & old_grad_,
const std::shared_ptr<dotk::Vector<Real> > & new_grad_,
const std::shared_ptr<dotk::Vector<Real> > & dir_);
virtual void direction(const std::shared_ptr<dotk::DOTk_OptimizationDataMng> & mng_);
private:
DOTk_LiuStorey(const dotk::DOTk_LiuStorey &);
dotk::DOTk_LiuStorey & operator=(const dotk::DOTk_LiuStorey &);
};
}
#endif /* DOTK_LIUSTOREY_HPP_ */
|
[
"aguilo.miguel@gmail.com"
] |
aguilo.miguel@gmail.com
|
a57716e8c60118153d20347c8b2e293f49a1e3fe
|
d01dc4b327e33816ac2ce2af40945a721f7b5854
|
/aws-cpp-sdk-imagebuilder/include/aws/imagebuilder/model/ListImageRecipesResult.h
|
02072cc97ea230cd7d664c9b589d793fb45f19a9
|
[
"MIT",
"Apache-2.0",
"JSON"
] |
permissive
|
hpcc-systems/aws-sdk-cpp
|
36f89272e3b140fea596c73234c09fb240f86520
|
9c93f28159e1e01ea3ef789a1b0c2c9643955c96
|
refs/heads/master
| 2022-07-17T05:18:08.190972
| 2020-10-19T20:59:11
| 2020-10-19T20:59:11
| 90,974,127
| 0
| 1
|
Apache-2.0
| 2022-06-30T14:47:34
| 2017-05-11T11:58:14
|
C++
|
UTF-8
|
C++
| false
| false
| 6,310
|
h
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/imagebuilder/Imagebuilder_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/imagebuilder/model/ImageRecipeSummary.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace imagebuilder
{
namespace Model
{
class AWS_IMAGEBUILDER_API ListImageRecipesResult
{
public:
ListImageRecipesResult();
ListImageRecipesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
ListImageRecipesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The request ID that uniquely identifies this request. </p>
*/
inline const Aws::String& GetRequestId() const{ return m_requestId; }
/**
* <p>The request ID that uniquely identifies this request. </p>
*/
inline void SetRequestId(const Aws::String& value) { m_requestId = value; }
/**
* <p>The request ID that uniquely identifies this request. </p>
*/
inline void SetRequestId(Aws::String&& value) { m_requestId = std::move(value); }
/**
* <p>The request ID that uniquely identifies this request. </p>
*/
inline void SetRequestId(const char* value) { m_requestId.assign(value); }
/**
* <p>The request ID that uniquely identifies this request. </p>
*/
inline ListImageRecipesResult& WithRequestId(const Aws::String& value) { SetRequestId(value); return *this;}
/**
* <p>The request ID that uniquely identifies this request. </p>
*/
inline ListImageRecipesResult& WithRequestId(Aws::String&& value) { SetRequestId(std::move(value)); return *this;}
/**
* <p>The request ID that uniquely identifies this request. </p>
*/
inline ListImageRecipesResult& WithRequestId(const char* value) { SetRequestId(value); return *this;}
/**
* <p>The list of image pipelines. </p>
*/
inline const Aws::Vector<ImageRecipeSummary>& GetImageRecipeSummaryList() const{ return m_imageRecipeSummaryList; }
/**
* <p>The list of image pipelines. </p>
*/
inline void SetImageRecipeSummaryList(const Aws::Vector<ImageRecipeSummary>& value) { m_imageRecipeSummaryList = value; }
/**
* <p>The list of image pipelines. </p>
*/
inline void SetImageRecipeSummaryList(Aws::Vector<ImageRecipeSummary>&& value) { m_imageRecipeSummaryList = std::move(value); }
/**
* <p>The list of image pipelines. </p>
*/
inline ListImageRecipesResult& WithImageRecipeSummaryList(const Aws::Vector<ImageRecipeSummary>& value) { SetImageRecipeSummaryList(value); return *this;}
/**
* <p>The list of image pipelines. </p>
*/
inline ListImageRecipesResult& WithImageRecipeSummaryList(Aws::Vector<ImageRecipeSummary>&& value) { SetImageRecipeSummaryList(std::move(value)); return *this;}
/**
* <p>The list of image pipelines. </p>
*/
inline ListImageRecipesResult& AddImageRecipeSummaryList(const ImageRecipeSummary& value) { m_imageRecipeSummaryList.push_back(value); return *this; }
/**
* <p>The list of image pipelines. </p>
*/
inline ListImageRecipesResult& AddImageRecipeSummaryList(ImageRecipeSummary&& value) { m_imageRecipeSummaryList.push_back(std::move(value)); return *this; }
/**
* <p>The next token used for paginated responses. When this is not empty, there
* are additional elements that the service has not included in this request. Use
* this token with the next request to retrieve additional objects. </p>
*/
inline const Aws::String& GetNextToken() const{ return m_nextToken; }
/**
* <p>The next token used for paginated responses. When this is not empty, there
* are additional elements that the service has not included in this request. Use
* this token with the next request to retrieve additional objects. </p>
*/
inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }
/**
* <p>The next token used for paginated responses. When this is not empty, there
* are additional elements that the service has not included in this request. Use
* this token with the next request to retrieve additional objects. </p>
*/
inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }
/**
* <p>The next token used for paginated responses. When this is not empty, there
* are additional elements that the service has not included in this request. Use
* this token with the next request to retrieve additional objects. </p>
*/
inline void SetNextToken(const char* value) { m_nextToken.assign(value); }
/**
* <p>The next token used for paginated responses. When this is not empty, there
* are additional elements that the service has not included in this request. Use
* this token with the next request to retrieve additional objects. </p>
*/
inline ListImageRecipesResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}
/**
* <p>The next token used for paginated responses. When this is not empty, there
* are additional elements that the service has not included in this request. Use
* this token with the next request to retrieve additional objects. </p>
*/
inline ListImageRecipesResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}
/**
* <p>The next token used for paginated responses. When this is not empty, there
* are additional elements that the service has not included in this request. Use
* this token with the next request to retrieve additional objects. </p>
*/
inline ListImageRecipesResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}
private:
Aws::String m_requestId;
Aws::Vector<ImageRecipeSummary> m_imageRecipeSummaryList;
Aws::String m_nextToken;
};
} // namespace Model
} // namespace imagebuilder
} // namespace Aws
|
[
"aws-sdk-cpp-automation@github.com"
] |
aws-sdk-cpp-automation@github.com
|
60206d4a638ea746cdbcad325bd4dce25a74dfc8
|
ef5c199ad0b4d2bb6da40005c2babf84fe29fd60
|
/DatabaseConnector.h
|
09c5ec29f0f32d489c3250cde81e0d80c8652f5f
|
[] |
no_license
|
SkyZoThreaD/Organizer
|
bd54b5a7367f016b1cbed4e3f50771b0f64e06a3
|
d22bf4d24fdb2c22143f257e5d3094332d0fae04
|
refs/heads/master
| 2021-04-12T01:58:05.686980
| 2018-03-26T15:30:32
| 2018-03-26T15:30:32
| 125,854,685
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 986
|
h
|
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include "ModelColumns.h"
#include <sstream>
#include <gtkmm.h>
std::string StateNumberToString(int nb);
std::string UrgencyNumberToString(int nb);
class DatabaseConnector
{
private:
std::string m_ServerIpPort;
std::string m_User;
std::string m_Password;
std::string m_Database;
public:
DatabaseConnector(std::string ServerIpPort, std::string User, std::string Password, std::string Database);
void AddTask(std::string TaskTitle, std::string TaskContent, int TaskUrgency, int TaskState);
void FillTreeModel(Glib::RefPtr<Gtk::ListStore> List, ModelColumns *m_Columns);
};
|
[
"skyzothread@gmail.com"
] |
skyzothread@gmail.com
|
a3a708fc5dc4686a629f4f99cb755b07f5d564c6
|
dc7b248286b79ebd7787208d4357b1a4a18aa45c
|
/PWGGA/PHOSTasks/PHOS_Run2/AliAnalysisTaskPHOSEmbedding.cxx
|
5f6c52e004e53984e3d82ba87b2715cb71fb93d8
|
[] |
no_license
|
mfloris/AliPhysics
|
d73cb4fa1fd136b84abf96e5d53a6147864b40ac
|
20c8b26f77b8f2f42c17e71f07230bb89fb8d505
|
refs/heads/master
| 2021-01-23T02:04:47.991147
| 2017-12-08T10:46:20
| 2017-12-08T10:46:20
| 85,959,803
| 0
| 0
| null | 2017-03-23T14:32:47
| 2017-03-23T14:32:47
| null |
UTF-8
|
C++
| false
| false
| 33,912
|
cxx
|
#include <stdio.h>
#include <iostream>
#include "TChain.h"
#include "TTree.h"
#include "TObjArray.h"
#include "TClonesArray.h"
#include "TRandom3.h"
#include "TGrid.h"
#include "TROOT.h"
#include "AliInputEventHandler.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisTaskSE.h"
#include "AliAnalysisTaskESDfilter.h"
#include "AliLog.h"
#include "AliESDtrackCuts.h"
#include "AliESDHeader.h"
#include "AliESDEvent.h"
#include "AliESDVZERO.h"
#include "AliESDTZERO.h"
#include "AliESDCaloCells.h"
#include "AliESDCaloCluster.h"
#include "AliESDVertex.h"
#include "AliESDtrack.h"
#include "AliVEvent.h"
#include "AliVHeader.h"
#include "AliVTrack.h"
#include "AliVCluster.h"
#include "AliVCaloCells.h"
#include "AliMultSelection.h"
#include "AliEventplane.h"
#include "AliPDG.h"
#include "AliAODMCHeader.h"
#include "AliAODHeader.h"
#include "AliAODEvent.h"
#include "AliAODCaloCells.h"
#include "AliAODCaloCluster.h"
#include "AliAODVertex.h"
#include "AliAODTrack.h"
#include "AliAODMCParticle.h"
#include "AliAODInputHandler.h"
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"
#include "AliStack.h"
#include "TGeoManager.h"
#include "TGeoGlobalMagField.h"
#include "AliGeomManager.h"
#include "AliGRPObject.h"
#include "AliMagF.h"
#include "AliPHOSGeometry.h"
#include "AliPHOSDigit.h"
#include "AliPHOSReconstructor.h"
#include "AliPHOSClusterizerv1.h"
#include "AliPHOSCalibData.h"
#include "AliCDBManager.h"
#include "AliCDBPath.h"
#include "AliCDBEntry.h"
#include "AliCDBMetaData.h"
#include "AliPHOSAodCluster.h"
#include "AliPHOSEsdCluster.h"
#include "AliOADBContainer.h"
#include "AliAnalysisTaskPHOSEmbedding.h"
using namespace std;
// Author: Daiki Sekihata (Hiroshima University)
ClassImp(AliAnalysisTaskPHOSEmbedding)
//____________________________________________________________________________________________________________________________________
AliAnalysisTaskPHOSEmbedding::AliAnalysisTaskPHOSEmbedding(const char *name):
AliAnalysisTaskSE(name),
//AliAnalysisTaskESDfilter(name),
fParticle(""),
fEvent(0x0),
fRandom3(0x0),
fAODPathArray(0x0),
fAODPath(""),
fAODInput(0x0),
fAODTree(0x0),
fAODEvent(0x0),
fNEvents(0),
fEventCounter(0),
fEventLoopMin(0),
fEventLoopMax(0),
fCellsPHOS(0x0),
fDigitsTree(0x0),
fClustersTree(0x0),
fDigitsArr(0x0),
fPHOSReconstructor(0x0),
fClusterizer(0x0),
fInitialized(kFALSE),
fRunNumber(0),
fESDEvent(0x0),
fMCArray(0x0),
fEmbeddedClusterArray(0x0),
fEmbeddedCells(0x0),
fSignalECorrection(1.),
fSignalCalibData(0x0),
fUserNonLin(0x0)
{
// Constructor
//fRandom3 = new TRandom3(1);//0 is not preferable.
AliCDBManager *cdb = AliCDBManager::Instance();
cdb->SetDefaultStorage("raw://");
cdb->SetRun(246982);//dummy run number//necessary run number is set in Init()
fUserNonLin = new TF1("fUserNonLin","1.",0,100);
//fEventCuts = new AliEventCuts(kFALSE);
// Define input and output slots here
// Input slot #0 works with a TChain
DefineInput(0, TChain::Class());
// Output slot #0 id reserved by the base class for AOD
// Output slot #1 writes into a TH1 container
//DefineOutput(1, THashList::Class());
}
//____________________________________________________________________________________________________________________________________
AliAnalysisTaskPHOSEmbedding::~AliAnalysisTaskPHOSEmbedding()
{
delete fRandom3;
fRandom3 = 0x0;
delete fUserNonLin;
fUserNonLin = 0x0;
if(fPHOSReconstructor){
delete fPHOSReconstructor;
fPHOSReconstructor = 0x0;
}
if(fMCArray){
delete fMCArray;
fMCArray = 0x0;
}
if(fEmbeddedClusterArray){
delete fEmbeddedClusterArray;
fEmbeddedClusterArray = 0x0;
}
if(fEmbeddedCells){
delete fEmbeddedCells;
fEmbeddedCells = 0x0;
}
}
//____________________________________________________________________________________________________________________________________
void AliAnalysisTaskPHOSEmbedding::UserCreateOutputObjects()
{
// Create histograms
// Called once
//fOutputContainer = new THashList();
//fOutputContainer->SetOwner(kTRUE);
fMCArray = new TClonesArray("AliAODMCParticle",0);
fEmbeddedClusterArray = new TClonesArray("AliAODCaloCluster",0);
//fEmbeddedClusterArray->SetName(Form("Embedded%sCaloClusters",fParticle.Data()));
fEmbeddedCells = new AliAODCaloCells();
//fEmbeddedCells->SetName(Form("Embedded%sPHOScells",fParticle.Data()));
//PostData(1,fOutputContainer);
}
//____________________________________________________________________________________________________________________________________
void AliAnalysisTaskPHOSEmbedding::UserExec(Option_t *option)
{
// Main loop
// Called for each event
fEvent = dynamic_cast<AliVEvent*>(InputEvent());
if(!fEvent){
AliError("event is not available.");
return;
}
if(fRunNumber != fEvent->GetRunNumber()){
fRunNumber = fEvent->GetRunNumber();
Init();
}
if(fEventLoopMax > fEventCounter + fEventLoopMin){
fEventCounter++;
}
else{//fEventCounter reaches Nevent in input AOD MC tree. go to next file.
AliInfo("fEventCounter reaches at fEventLoopMax. Go to next external MC file.");
Bool_t IsFileOK = OpenAODFile();//fNEvents are set here. //fEventCounter is reset here.
if(!IsFileOK){
AliError(Form("external file (%s) could not be opened. return.",fAODPath.Data()));
return;
}
}
AliInfo(Form("fEventCounter = %d in current MC AOD input.",fEventCounter));
fAODTree->GetEvent(fEventCounter + fEventLoopMin);
ConvertAODtoESD();
//To do
//SetPHOSCells
//SetClusters
//start embedding
CopyRecalibrateDigits();
if(fDigitsArr){
delete fDigitsArr;
fDigitsArr = 0x0;
}
fDigitsArr = new TClonesArray("AliPHOSDigit",4*56*64);
fDigitsArr->Clear();
gROOT->cd(); //make sure that the digits and RecPoints Trees are memory resident
if(fDigitsTree){
delete fDigitsTree;
fDigitsTree = 0x0;
}
fDigitsTree = new TTree("digitstree","digitstree");
fDigitsTree->Branch("PHOS","TClonesArray", &fDigitsArr, 32000);
if(fClustersTree){
delete fClustersTree;
fClustersTree = 0x0;
}
fClustersTree = new TTree("clustertree","clustertree");
//Remember number of Clusters before we added new ones...
Int_t fNCaloClustersOld = fEvent->GetNumberOfCaloClusters();
Int_t nPHOSBefore=0;
Int_t nCPVBefore=0;
Int_t nEMCALBefore=0;
for(Int_t iClust=0; iClust<fEvent->GetNumberOfCaloClusters(); iClust++){
AliVCluster *cluster = (AliVCluster*)fEvent->GetCaloCluster(iClust);
if(cluster->GetType() == AliVCluster::kPHOSNeutral) nPHOSBefore++;
else if(cluster->GetType() == AliVCluster::kPHOSCharged) nCPVBefore++;
else nEMCALBefore++;
}
AliInfo(Form("Before embedding: Nall = %d , nPHOS = %d , nCPV = %d , nEMCAL = %d.",fNCaloClustersOld, nPHOSBefore, nCPVBefore, nEMCALBefore));
AliInfo(Form("Ncluster in sigle simulation = %d",fAODEvent->GetNumberOfCaloClusters()));
AliAODCaloCells *cellsEmb = (AliAODCaloCells*)fAODEvent->GetPHOSCells();
Int_t NcellEmb = cellsEmb->GetNumberOfCells();
AliInfo(Form("Before embedding: N PHOS cells in simulation = %d",NcellEmb));
//-------------------------------------------------------------------------------------
//Transform CaloCells into Digits which can be used for standard reconstruction
//Add signal digits to the event
//-------------------------------------------------------------------------------------
//First copy data digits
Int_t ndigit=0 ;
for (Short_t icell = 0; icell < fCellsPHOS->GetNumberOfCells(); icell++) {
Short_t id=0;
Double_t time=0., amp=0. ;
Int_t mclabel;
Double_t efrac =0. ;
if(fCellsPHOS->GetCell(icell, id, amp, time,mclabel, efrac) != kTRUE) break;
Int_t idLong=id ;
if(id<0)idLong= -id+56*64*5 ; //CPV digits
new((*fDigitsArr)[ndigit]) AliPHOSDigit(-1,idLong,float(amp),float(time),ndigit);
ndigit++;
}
//Add Digits from Signal
TClonesArray sdigits("AliPHOSDigit",0) ;
Int_t isdigit=0 ;
if(fAODEvent){
AliAODCaloCells* cellsS = fAODEvent->GetPHOSCells();
Int_t cellLabels[1000]={0} ; //1000 should be enough for simulated
Int_t cellSecondLabels[1000]={0} ; //low-statistics event.
for(Int_t i=0;i<cellsS->GetNumberOfCells();i++){
cellLabels[i]=-1 ;
cellSecondLabels[i]=-1;
}
//------------------------------------------------------------------------------------
//Ancestry information
//Celect digits contributing to fAODEvent clusters and add primary information
//(it is not stored in CaloCells)
//------------------------------------------------------------------------------------
sdigits.Expand(cellsS->GetNumberOfCells());
for(Int_t i=0; i<fAODEvent->GetNumberOfCaloClusters(); i++) {
//cluster from embedded signal
AliAODCluster *clus = (AliAODCaloCluster*)fAODEvent->GetCaloCluster(i);
if(!clus->IsPHOS()) continue;
AliInfo(Form("Ecluster in M.C. = %e GeV",clus->E()));
Int_t label = clus->GetLabel();
Int_t label2 = -1 ;
if (clus->GetNLabels()>=2) label2 = clus->GetLabelAt(1) ;
UShort_t * index = clus->GetCellsAbsId() ;
for(Int_t ic=0; ic < clus->GetNCells(); ic++ ){
for (Int_t icell = 0; icell < cellsS->GetNumberOfCells(); icell++){
Short_t cellNumber;
Double_t cellAmplitude=0., cellTime=0. ;
Int_t mclabel;
Double_t efrac =0. ;
cellsS->GetCell(icell, cellNumber, cellAmplitude, cellTime,mclabel,efrac) ;
Int_t longCellNumber=cellNumber ;
if(cellNumber<0)longCellNumber= -cellNumber+56*64*5 ; //CPV digits
if(longCellNumber==index[ic]){
cellLabels[icell]=label;
cellSecondLabels[icell]=label2;
break ;
}
}
}
}
for (Int_t icell = 0; icell < cellsS->GetNumberOfCells(); icell++) {
Short_t cellNumber;
Double_t cellAmplitude=0., cellTime=0. ;
Int_t mclabel;
Double_t efrac =0. ;
if (cellsS->GetCell(icell, cellNumber, cellAmplitude, cellTime,mclabel,efrac) != kTRUE) break;
//Add only digits related to the cluster, no noisy digits...
if(cellLabels[icell]==-1){
continue ;
}
cellAmplitude = DecalibrateSignal(cellAmplitude,cellNumber);//decalibration from Dmitri, Daiki added this line on 21.December.2016
Int_t longCellNumber=cellNumber ;
if(cellNumber<0)longCellNumber= -cellNumber+56*64*5 ; //CPV digits
new(sdigits[isdigit]) AliPHOSDigit(cellLabels[icell],longCellNumber,float(cellAmplitude),float(cellTime),isdigit);
isdigit++;
}
}
//Merge digits
Int_t icurrent = 0 ; //index of the last used digit in underlying event
fDigitsArr->Expand(ndigit+isdigit) ;
for(Int_t i=0; i<isdigit;i++){
AliPHOSDigit * sdigit=static_cast<AliPHOSDigit*>(sdigits.At(i)) ;
Bool_t added=kFALSE ;
for(Int_t id=icurrent;id<ndigit;id++){
AliPHOSDigit * digit=static_cast<AliPHOSDigit*>(fDigitsArr->At(id)) ;
if(sdigit->GetId() == digit->GetId() ){
*digit += *sdigit ; //add energies
icurrent=id+1 ;
added=kTRUE ;
break ; //no more digits with same ID in the list
}
if(sdigit->GetId() < digit->GetId() ){
icurrent=id ;
break ; //no more digits with same ID in the list
}
}
if(!added){
new((*fDigitsArr)[ndigit]) AliPHOSDigit(*sdigit) ;
ndigit++ ;
}
}
//Change Amp back from Energy to ADC counts
//Note that Reconstructor uses best ("new") calibration
for(Int_t i=0; i<ndigit;i++){
AliPHOSDigit * digit=static_cast<AliPHOSDigit*>(fDigitsArr->At(i)) ;
Float_t calib =fPHOSReconstructor->Calibrate(1.,digit->GetId()) ;
if(calib>0.)
digit->SetEnergy(digit->GetEnergy()/calib) ;
}
fDigitsArr->Sort() ;
for (Int_t i = 0 ; i < ndigit ; i++) {
AliPHOSDigit *digit = static_cast<AliPHOSDigit*>( fDigitsArr->At(i) ) ;
digit->SetIndexInList(i) ;
}
fDigitsTree->Fill();
//clusterize and make tracking//no track matching here!
fPHOSReconstructor->Reconstruct(fDigitsTree,fClustersTree) ;
//Note that the current ESDEvent will be modified!
fPHOSReconstructor->FillESD(fDigitsTree, fClustersTree, fESDEvent);
//this modified event should go to ConvertEmbeddedClusters
Int_t nPHOSAfter=0;
Int_t nCPVAfter=0;
Int_t nEMCALAfter=0;
for(Int_t iClust=0; iClust<fESDEvent->GetNumberOfCaloClusters(); iClust++) {
AliESDCaloCluster * cluster = (AliESDCaloCluster*)fESDEvent->GetCaloCluster(iClust);
if(cluster->IsPHOS()){
if(cluster->GetType() == AliVCluster::kPHOSNeutral) nPHOSAfter++;
if(cluster->GetType() == AliVCluster::kPHOSCharged) nCPVAfter++;
}
else{
nEMCALAfter++;
}
}
AliInfo(Form("After embedding: Nall = %d , nPHOSAfter = %d , nCPVAfter = %d , nEMCALAfter = %d.", fESDEvent->GetNumberOfCaloClusters(), nPHOSAfter, nCPVAfter, nEMCALAfter));
const Int_t Ncell = fESDEvent->GetPHOSCells()->GetNumberOfCells();
AliInfo(Form("%d PHOS cells after embedding.",Ncell));
ConvertESDtoAOD();
//convert AliAODMCParticle
TClonesArray *mcarray_org = dynamic_cast<TClonesArray*>(fAODEvent->FindListObject(AliAODMCParticle::StdBranchName()));
const Int_t Npart = mcarray_org->GetEntries();
fMCArray->Clear();
fMCArray->Expand(Npart);
for(Int_t i=0;i<Npart;i++){
AliAODMCParticle* aodpart = (AliAODMCParticle*)mcarray_org->At(i);
//printf("PDG = %d , X = %e , Y = %e , Z = %e\n",aodpart->GetPdgCode(), aodpart->Xv(),aodpart->Yv(),aodpart->Zv());
new ((*fMCArray)[i]) AliAODMCParticle(*aodpart);
}
AliVEvent* input = InputEvent();
const TString brname = Form("%s_%s",AliAODMCParticle::StdBranchName(),fParticle.Data());
TObject* outMC = input->FindListObject(brname);
AliInfo(Form("MC array name = %s , entry = %d.",brname.Data(),Npart));
if(!outMC){
AliInfo(Form("%s object is not found in input event. Add it.",brname.Data()));
fMCArray->SetName(brname);
input->AddObject(fMCArray);
}
const TString brname_cluster = Form("Embedded%sCaloClusters",fParticle.Data());
AliInfo(Form("name of embedded cluster array = %s",brname_cluster.Data()));
TObject* outClusters = input->FindListObject(brname_cluster);
if(!outClusters){
AliInfo(Form("%s object is not found in input event. Add it.",brname_cluster.Data()));
fEmbeddedClusterArray->SetName(brname_cluster);
input->AddObject(fEmbeddedClusterArray);
}
const TString brname_cell = Form("Embedded%sPHOScells",fParticle.Data());
AliInfo(Form("name of embedded cells = %s",brname_cell.Data()));
TObject* outCells = input->FindListObject(brname_cell);
if(!outCells){
AliInfo(Form("%s object is not found in input event. Add it.",brname_cell.Data()));
fEmbeddedCells->SetName(brname_cell);
input->AddObject(fEmbeddedCells);
}
//PostData(1, fOutputContainer);
}
//____________________________________________________________________________________________________________________________________
void AliAnalysisTaskPHOSEmbedding::Terminate(Option_t *option)
{
//Called once at the end of the query
//In principle, this function is not needed...
AliInfo(Form("%s is done.",GetName()));
}
//____________________________________________________________________________________________________________________________________
Bool_t AliAnalysisTaskPHOSEmbedding::UserNotify()
{
AliAODInputHandler *aodH = dynamic_cast<AliAODInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler());
TTree* tr = aodH->GetTree();
TDirectory* dr = tr->GetDirectory();
TString DataPath = dr->GetPath();
TObjArray *tx = DataPath.Tokenize("/");
//tx->Print();
Int_t Nt = tx->GetEntries();
//for (Int_t i = 0; i < Nt; i++) std::cout << "i = " << i << " , " << ((TObjString *)(tx->At(i)))->String() << std::endl;
TString filestr = ((TObjString *)(tx->At(Nt-2)))->String();
Int_t fileID = filestr.Atoi();
TString runstr = ((TObjString *)(tx->At(5)))->String();
Int_t runNum = runstr.Atoi();
UInt_t seed = UInt_t(runNum * 1e+4) + UInt_t(fileID);
AliInfo(Form("seed is %u",seed));
fRandom3 = new TRandom3(seed);
return kTRUE;
}
//____________________________________________________________________________________________________________________________________
Int_t AliAnalysisTaskPHOSEmbedding::SelectAODFile()
{
Int_t Nfile = fAODPathArray->GetEntries();
Int_t ientry = (Int_t)(Nfile * fRandom3->Rndm());
TObjString *objStr = (TObjString*) fAODPathArray->At(ientry);
if(!objStr){
AliError("Could not get path of AOD MC file.");
return -1;
}
fAODPath = objStr->GetString();
AliInfo(Form("External MC file is %s.",fAODPath.Data()));
return Nfile;
}
//____________________________________________________________________________________________________________________________________
Bool_t AliAnalysisTaskPHOSEmbedding::OpenAODFile()
{
AliInfo("Open a new file.");
if(!gGrid){
AliInfo("Trying to connect to AliEn ...");
TGrid::Connect("alien://");
}
if(fAODInput && fAODInput->IsOpen()) fAODInput->Close();
Int_t Nfile = SelectAODFile();//1st trial
fAODInput = TFile::Open(fAODPath,"TIMEOUT=180");
if(!fAODInput){
AliError(Form("1/3 trial failed : An external AOD MC input (%s) could not be opened.",fAODPath.Data()));
Nfile = SelectAODFile();//2nd trial
fAODInput = TFile::Open(fAODPath,"TIMEOUT=180");
if(!fAODInput){
AliError(Form("2/3 trial failed : An external AOD MC input (%s) could not be opened.",fAODPath.Data()));
Nfile = SelectAODFile();//3rd trial
fAODInput = TFile::Open(fAODPath,"TIMEOUT=180");
if(!fAODInput){
AliError(Form("3/3 trial failed : An external AOD MC input (%s) could not be opened.",fAODPath.Data()));
return kFALSE;
}//end of 3rd trial
}//end of 2nd trial
}//end of 1st trial
fAODTree = (TTree*)fAODInput->Get("aodTree");
if(!fAODTree){
AliError(Form("aodTree from an external AOD MC input (%s) is not found.",fAODPath.Data()));
return kFALSE;
}
if(fAODEvent){
//remove previous input MC event
delete fAODEvent;
fAODEvent = 0x0;
}
fAODEvent = new AliAODEvent();
fAODEvent->ReadFromTree(fAODTree);
fNEvents = fAODTree->GetEntries();
AliInfo(Form("%d events are stored in %s.",fNEvents,fAODPath.Data()));
fEventCounter = 0;//reset counter.
Int_t index1 = Int_t(fNEvents * fRandom3->Rndm());
Int_t index2 = Int_t(fNEvents * fRandom3->Rndm());
fEventLoopMin = TMath::Min(index1,index2);
fEventLoopMax = TMath::Max(index1,index2);
AliInfo(Form("Event loop in external MC file will run over %d - %d.",fEventLoopMin,fEventLoopMax));
return kTRUE;
}
//____________________________________________________________________________________________________________________________________
void AliAnalysisTaskPHOSEmbedding::CopyRecalibrateDigits()
{
//Recalibrate digits if there is better calibration ("new")
//exists than one used in reconstruction ("ESD")
AliAODEvent *event = dynamic_cast<AliAODEvent*>(fEvent);
if(fCellsPHOS){
delete fCellsPHOS;
fCellsPHOS = 0x0;
}
fCellsPHOS = new AliAODCaloCells();
fCellsPHOS->CreateContainer(event->GetPHOSCells()->GetNumberOfCells());
AliInfo(Form("%d PHOS cells in real data.",event->GetPHOSCells()->GetNumberOfCells()));
for (Short_t icell=0;icell<event->GetPHOSCells()->GetNumberOfCells();icell++){
Short_t id=0;
Double_t time=0., amp=0.;
Int_t mclabel = -1;
Double_t efrac =0.;
if(event->GetPHOSCells()->GetCell(icell, id, amp, time, mclabel, efrac) != kTRUE) break;
fCellsPHOS->SetCell(icell, id, amp, time, mclabel, efrac);
}
}
//____________________________________________________________________________________________________________________________________
void AliAnalysisTaskPHOSEmbedding::Init()
{
AliAODEvent *event = dynamic_cast<AliAODEvent*>(InputEvent());
if(!event){
AliError("Can not obtain InputEvent!") ;
return;
}
Int_t runNum = event->GetRunNumber();
AliCDBManager::Instance()->SetRun(runNum);
//AliCDBManager::Instance()->SetDefaultStorage("raw://");
fPHOSReconstructor = new AliPHOSReconstructor("Run2");
AliCDBPath path("PHOS","Calib","RecoParam");
AliCDBEntry *entry = AliCDBManager::Instance()->Get(path.GetPath());
if(!entry){
AliError(Form("Can not get OCDB entry %s",path.GetPath().Data())) ;
return ;
}
TObjArray* recoParamArray = (TObjArray*)entry->GetObject();
AliPHOSRecoParam* recoParam = (AliPHOSRecoParam*)recoParamArray->At(2);
fPHOSReconstructor->SetRecoParam(recoParam) ;
InitMF() ;
InitGeometry() ;
//Get OADB calibration for this run for de-calibration of signal
AliOADBContainer calibContainer("phosRecalibration");
calibContainer.InitFromFile("$ALICE_PHYSICS/OADB/PHOS/PHOSCalibrations.root","phosRecalibration");
TObjArray *recalib = (TObjArray*)calibContainer.GetObject(runNum,"PHOSRecalibration");
if(!recalib){
AliWarning(Form("Can not read calibrations for run %d, do not apply OADB de-calibration\n",runNum)) ;
}
else{
const Int_t recoPass=1;
fSignalCalibData = (AliPHOSCalibData*)recalib->At(recoPass-1) ;
}
}
//____________________________________________________________________________________________________________________________________
void AliAnalysisTaskPHOSEmbedding::InitMF()
{
//------------------------------------
// Initialization of the Mag.Fiels from GRP entry
// Copied from AliReconstruction::InitGRP()
//------------------------------------
AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/Data");
AliGRPObject * aGRPData=0 ;
if (entry) {
TMap* m = dynamic_cast<TMap*>(entry->GetObject()); // old GRP entry
if (m) {
AliInfo("Found a TMap in GRP/GRP/Data, converting it into an AliGRPObject");
m->Print();
aGRPData = new AliGRPObject();
aGRPData->ReadValuesFromMap(m);
}
else {
AliInfo("Found an AliGRPObject in GRP/GRP/Data, reading it");
aGRPData = dynamic_cast<AliGRPObject*>(entry->GetObject()); // new GRP entry
entry->SetOwner(0);
}
}
if (!aGRPData) {
AliError("No GRP entry found in OCDB!");
return ;
}
//*** Dealing with the magnetic field map
TString lhcState = aGRPData->GetLHCState();
if (lhcState==AliGRPObject::GetInvalidString()) {
AliError("GRP/GRP/Data entry: missing value for the LHC state ! Using UNKNOWN");
lhcState = "UNKNOWN";
}
TString beamType = aGRPData->GetBeamType();
if (beamType==AliGRPObject::GetInvalidString()) {
AliError("GRP/GRP/Data entry: missing value for the beam type ! Using UNKNOWN");
beamType = "UNKNOWN";
}
Float_t beamEnergy = aGRPData->GetBeamEnergy();
if (beamEnergy==AliGRPObject::GetInvalidFloat()) {
AliError("GRP/GRP/Data entry: missing value for the beam energy ! Using 0");
beamEnergy = 0;
}
TString runType = aGRPData->GetRunType();
if (runType==AliGRPObject::GetInvalidString()) {
AliError("GRP/GRP/Data entry: missing value for the run type ! Using UNKNOWN");
runType = "UNKNOWN";
}
if ( TGeoGlobalMagField::Instance()->IsLocked() ) {
if (TGeoGlobalMagField::Instance()->GetField()->TestBit(AliMagF::kOverrideGRP)) {
AliInfo("PHOSEmbedding: MF is locked - GRP information will be ignored !");
AliInfo("Running with the externally locked B field !");
}
else {
AliInfo("Destroying existing B field instance!");
delete TGeoGlobalMagField::Instance();
}
}
if ( !TGeoGlobalMagField::Instance()->IsLocked() ) {
// Construct the field map out of the information retrieved from GRP.
Bool_t ok = kTRUE;
// L3
Float_t l3Current = aGRPData->GetL3Current((AliGRPObject::Stats)0);
if (l3Current == AliGRPObject::GetInvalidFloat()) {
AliError("GRP/GRP/Data entry: missing value for the L3 current !");
ok = kFALSE;
}
Char_t l3Polarity = aGRPData->GetL3Polarity();
if (l3Polarity == AliGRPObject::GetInvalidChar()) {
AliError("GRP/GRP/Data entry: missing value for the L3 polarity !");
ok = kFALSE;
}
// Dipole
Float_t diCurrent = aGRPData->GetDipoleCurrent((AliGRPObject::Stats)0);
if (diCurrent == AliGRPObject::GetInvalidFloat()) {
AliError("GRP/GRP/Data entry: missing value for the dipole current !");
ok = kFALSE;
}
Char_t diPolarity = aGRPData->GetDipolePolarity();
if (diPolarity == AliGRPObject::GetInvalidChar()) {
AliError("GRP/GRP/Data entry: missing value for the dipole polarity !");
ok = kFALSE;
}
// read special bits for the polarity convention and map type
Int_t polConvention = aGRPData->IsPolarityConventionLHC() ? AliMagF::kConvLHC : AliMagF::kConvDCS2008;
Bool_t uniformB = aGRPData->IsUniformBMap();
if (ok) {
AliMagF* fld = AliMagF::CreateFieldMap(TMath::Abs(l3Current) * (l3Polarity ? -1:1),
TMath::Abs(diCurrent) * (diPolarity ? -1:1),
polConvention,uniformB,beamEnergy, beamType.Data());
if (fld) {
TGeoGlobalMagField::Instance()->SetField( fld );
TGeoGlobalMagField::Instance()->Lock();
AliInfo("Running with the B field constructed out of GRP !");
}
else AliFatal("Failed to create a B field map !");
}
else AliFatal("B field is neither set nor constructed from GRP ! Exitig...");
}
}
//____________________________________________________________________________________________________________________________________
void AliAnalysisTaskPHOSEmbedding::InitGeometry()
{
// Import ideal TGeo geometry and apply misalignment
if (!gGeoManager) {
AliGeomManager::LoadGeometry("geometry.root");
if (!gGeoManager) {
AliFatal("Can not load geometry");
}
if(!AliGeomManager::CheckSymNamesLUT("PHOS")) {
AliFatal("CheckSymNamesLUT");
}
}
TString detStr = "PHOS";
TString loadAlObjsListOfDets = "PHOS";
if(AliGeomManager::GetNalignable("GRP") != 0) loadAlObjsListOfDets.Prepend("GRP "); //add alignment objects for non-sensitive modules
AliGeomManager::ApplyAlignObjsFromCDB(loadAlObjsListOfDets.Data());
AliCDBManager::Instance()->UnloadFromCache("*/Align/*");
AliCDBManager::Instance()->UnloadFromCache("GRP/Geometry/Data");
}
//____________________________________________________________________________________________________________________________________
void AliAnalysisTaskPHOSEmbedding::ConvertAODtoESD()
{
//this ESD event is necessary for AliPHOSReconstructor::FillESD.
if(fESDEvent){
delete fESDEvent;
fESDEvent = 0x0;
}
const AliVVertex *vVertex = fEvent->GetPrimaryVertex();
Double_t vtx_data[3] = {-999,-999,-999};
vtx_data[0] = vVertex->GetX();
vtx_data[1] = vVertex->GetY();
vtx_data[2] = vVertex->GetZ();
AliInfo(Form("vetex position in AOD | X = %f cm , Y = %f cm , Z = %f cm.",vtx_data[0],vtx_data[1],vtx_data[2]));
//create AliESDEvent and set vertex position from AOD.
//only vertex position is necessary for AliPHOSPID/AliPHOSTrackSegmentsMaker
//think again AliPHOSReconstructor::FillESD should be called or I should write them here manually.
//at least, track maching is re-done in PHOSTender.
fESDEvent = new AliESDEvent();
fESDEvent->CreateStdContent();//this is important to set PHOSCells in AliESDEvent.
AliESDVertex *vertex = new AliESDVertex();
vertex->SetXYZ(vtx_data);
fESDEvent->SetPrimaryVertexTracks(vertex);
fESDEvent->SetPrimaryVertexSPD(vertex);
fESDEvent->SetPrimaryVertexTPC(vertex);
delete vertex;
vertex = 0x0;
const Int_t Ncell = fEvent->GetPHOSCells()->GetNumberOfCells();
AliESDCaloCells *phoscells = dynamic_cast<AliESDCaloCells*>(fESDEvent->GetPHOSCells());
phoscells->CreateContainer(Ncell);
AliInfo(Form("%d PHOS cells in real data before embedding.",Ncell));
for (Short_t icell=0;icell<Ncell;icell++){
Short_t id=0;
Double_t time=0., amp=0.;
Int_t mclabel = -1;
Double_t efrac =0.;
if(fEvent->GetPHOSCells()->GetCell(icell, id, amp, time, mclabel, efrac) != kTRUE) break;
phoscells->SetCell(icell, id, amp, time, mclabel, efrac);
}
const AliESDVertex *esdVertexBest = fESDEvent->GetPrimaryVertex();
Double_t vtxBest[3] = {};
vtxBest[0] = esdVertexBest->GetX();
vtxBest[1] = esdVertexBest->GetY();
vtxBest[2] = esdVertexBest->GetZ();
AliInfo(Form("vetex position in ESD | X = %f cm , Y = %f cm , Z = %f cm.",vtxBest[0],vtxBest[1],vtxBest[2]));
}
//____________________________________________________________________________________________________________________________________
void AliAnalysisTaskPHOSEmbedding::ConvertESDtoAOD()
{
fEmbeddedClusterArray->Clear();
fEmbeddedCells->Clear("");
// Access to the AOD container of clusters
Int_t jClusters = 0;
const Int_t Ncluster = fESDEvent->GetNumberOfCaloClusters();
fEmbeddedClusterArray->Expand(Ncluster);
//PHOS + CPV clusters are stored.
for (Int_t iClust=0; iClust<Ncluster; iClust++) {
AliESDCaloCluster * cluster = (AliESDCaloCluster*)fESDEvent->GetCaloCluster(iClust);
Int_t id = cluster->GetID();
Int_t nLabel = cluster->GetNLabels();
Int_t *labels = cluster->GetLabels();
Float_t energy = cluster->E();
Float_t posF[3] = {0.};
cluster->GetPosition(posF);
AliAODCaloCluster *caloCluster = new((*fEmbeddedClusterArray)[jClusters++]) AliAODCaloCluster(id,
nLabel,
labels,
energy,
posF,
NULL,
cluster->GetType(),0);
Double_t dx=cluster->GetTrackDx() ;
Double_t dz=cluster->GetTrackDz() ;
Float_t cpv=99. ; //No track matched by default
//no track matching
// TArrayI * itracks = cluster->GetTracksMatched() ;
// if(itracks->GetSize()>0){
// Int_t iTr = itracks->At(0);
// if(iTr>=0 && iTr<fESDEvent->GetNumberOfTracks()){
// AliESDtrack *track = fESDEvent->GetTrack(iTr) ;
// Double_t pt = track->Pt() ;
// Short_t charge = track->Charge() ;
// cpv=TestCPVRun2(dx, dz, pt,charge) ;
// }
// }
caloCluster->SetCaloCluster(cluster->GetDistanceToBadChannel(),
cluster->GetDispersion(),
cluster->GetM20(), cluster->GetM02(),
cpv,
cluster->GetNExMax(),cluster->GetTOF()) ;
caloCluster->SetPIDFromESD(cluster->GetPID());
caloCluster->SetNCells(cluster->GetNCells());
caloCluster->SetCellsAbsId(cluster->GetCellsAbsId());
caloCluster->SetCellsAmplitudeFraction(cluster->GetCellsAmplitudeFraction());
}
//for(Int_t i=0;i<fEmbeddedClusterArray->GetEntriesFast();i++){
// AliAODCaloCluster *caloCluster =(AliAODCaloCluster *)fEmbeddedClusterArray->At(i) ;
// caloCluster->GetID();
//}
//Now cells
if(fESDEvent->GetPHOSCells()){ // protection against missing ESD information
AliESDCaloCells &fESDEventPHcells = *(fESDEvent->GetPHOSCells());
Int_t nPHcell = fESDEventPHcells.GetNumberOfCells() ;
fEmbeddedCells->CreateContainer(nPHcell);
fEmbeddedCells->SetType(AliAODCaloCells::kPHOSCell);
for (Int_t iCell = 0; iCell < nPHcell; iCell++) {
//fEmbeddedCells->SetCell(iCell,fESDEventPHcells.GetCellNumber(iCell),fESDEventPHcells.GetAmplitude(iCell),fESDEventPHcells.GetTime(iCell));
fEmbeddedCells->SetCell(iCell,fESDEventPHcells.GetCellNumber(iCell),fESDEventPHcells.GetAmplitude(iCell),fESDEventPHcells.GetTime(iCell),fESDEventPHcells.GetMCLabel(iCell),fESDEventPHcells.GetEFraction(iCell),fESDEventPHcells.GetHighGain(iCell));
}
fEmbeddedCells->Sort();
}
AliInfo(Form("entry of fEmbeddedClusterArray = %d (PHOS+CPV) and Ncell = %d (PHOS+CPV) after embedding.",fEmbeddedClusterArray->GetEntriesFast(),fEmbeddedCells->GetNumberOfCells()));
}
//____________________________________________________________________________________________________________________________________
Double_t AliAnalysisTaskPHOSEmbedding::DecalibrateSignal(Double_t cellAmplitude,Int_t cellNumber)
{
//Apply de-calibration inverse to the calibration, stored in OADB
AliInfo(Form("before correction : cellAmplitude = %e (GeV), fSignalECorrection = %e.",cellAmplitude,fSignalECorrection));
//Apply overall energy correction
cellAmplitude *= fSignalECorrection;
if(!fSignalCalibData){
AliInfo("fSignalCalibData is not applied.");
return cellAmplitude;
}
Int_t relId[4];
AliPHOSGeometry * phosgeom = AliPHOSGeometry::GetInstance();
phosgeom->AbsToRelNumbering(cellNumber,relId);
if(relId[1]!=0) //CPV
return cellAmplitude ;
Int_t module = relId[0];
Int_t column = relId[3];
Int_t row = relId[2];
Double_t c = fSignalCalibData->GetADCchannelEmc(module,column,row);
AliInfo(Form("calibration co-efficient at M%d : X%d : Z%d in OADB is %e",module,row,column,c));
if(c>0){
cellAmplitude *= 1./c;
cellAmplitude *= fUserNonLin->Eval(cellAmplitude);
AliInfo(Form("after correction : cellAmplitude = %e (GeV)",cellAmplitude));
return cellAmplitude;
}
else{
cellAmplitude *= fUserNonLin->Eval(cellAmplitude);
AliInfo(Form("after correction : cellAmplitude = %e (GeV)",cellAmplitude));
return cellAmplitude;
}
}
//____________________________________________________________________________________________________________________________________
//____________________________________________________________________________________________________________________________________
//____________________________________________________________________________________________________________________________________
//____________________________________________________________________________________________________________________________________
|
[
"daiki.sekihata@cern.ch"
] |
daiki.sekihata@cern.ch
|
aa04f826af9d3780f4623c24ac2e1f6b1f1e3710
|
4b62193204d4e2694fa52a8edae6c0542503e2c7
|
/abserv/abserv/InteractionComp.cpp
|
87c988a1bdd1d96a8eebaf50d0b46cb9ba7d8963
|
[
"MIT",
"CC-BY-4.0"
] |
permissive
|
blockspacer/ABx
|
67a216772cc5cf235a50e149969c6d668641bb4d
|
39b5f3be0406b7c2957c0496e41f902478dc2cb0
|
refs/heads/master
| 2023-01-03T04:12:28.223454
| 2020-10-26T08:34:53
| 2020-10-26T08:34:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,074
|
cpp
|
/**
* Copyright 2020 Stefan Ascher
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "InteractionComp.h"
#include "Player.h"
#include "SelectionComp.h"
#include "Npc.h"
#include "ItemDrop.h"
namespace Game {
namespace Components {
InteractionComp::InteractionComp(Player& owner) :
owner_(owner)
{
owner_.SubscribeEvent<void(void)>(EVENT_ON_CANCELALL, std::bind(&InteractionComp::OnCancelAll, this));
}
void InteractionComp::OnCancelAll()
{
type_ = Type::None;
}
void InteractionComp::UpdateGeneric()
{
auto interactingWith = target_.lock();
if (!interactingWith)
return;
if (Is<Npc>(*interactingWith))
{
auto& npc = To<Npc>(*interactingWith);
Ranges range = npc.GetInteractionRange();
if (npc.IsInRange(range, &owner_))
{
npc.CallEvent<void(Actor*)>(EVENT_ON_INTERACT, &owner_);
type_ = Type::None;
}
return;
}
if (Is<ItemDrop>(*interactingWith))
{
if (interactingWith->IsInRange(Ranges::Adjecent, &owner_))
{
To<ItemDrop>(*interactingWith).PickUp(&owner_);
type_ = Type::None;
}
return;
}
if (Is<Player>(*interactingWith))
{
if (interactingWith->IsInRange(Ranges::Adjecent, &owner_))
{
type_ = Type::None;
}
return;
}
}
void InteractionComp::UpdateSkill()
{
auto interactingWith = target_.lock();
if (!interactingWith)
return;
if (interactingWith->IsInRange(skillRange_, &owner_))
{
owner_.UseSkill(skillIndex_, false);
type_ = Type::None;
}
}
void InteractionComp::Update(uint32_t)
{
if (type_ == Type::None)
return;
if (type_ == Type::Generic)
return UpdateGeneric();
return UpdateSkill();
}
void InteractionComp::Interact(bool suppress, bool ping)
{
auto* interactingWith = owner_.selectionComp_->GetSelectedObject();
if (!interactingWith)
return;
auto interactingWithSp = interactingWith->GetPtr<GameObject>();
if (owner_.IsImmobilized() || owner_.IsDead())
return;
target_ = interactingWithSp;
type_ = Type::None;
if (AB::Entities::IsOutpost(owner_.GetGame()->data_.type))
{
if (Is<Player>(interactingWith))
{
if (!suppress)
{
owner_.FollowObject(interactingWith, ping, RANGE_TOUCH);
type_ = Type::Generic;
return;
}
if (ping)
owner_.CallEvent<void(uint32_t, AB::GameProtocol::ObjectCallType, int)>(EVENT_ON_PINGOBJECT, interactingWith->id_,
AB::GameProtocol::ObjectCallType::Follow, 0);
return;
}
if (Is<Npc>(interactingWith))
{
if (!suppress)
{
auto& npc = To<Npc>(*interactingWith);
Ranges range = npc.GetInteractionRange();
if (!owner_.IsInRange(range, interactingWith))
{
if (owner_.FollowObject(interactingWith, false, RANGE_TOUCH))
{
type_ = Type::Generic;
if (ping)
owner_.CallEvent<void(uint32_t, AB::GameProtocol::ObjectCallType, int)>(EVENT_ON_PINGOBJECT,
interactingWith->id_, AB::GameProtocol::ObjectCallType::TalkingTo, 0);
}
return;
}
type_ = Type::Generic;
if (ping)
owner_.CallEvent<void(uint32_t, AB::GameProtocol::ObjectCallType, int)>(EVENT_ON_PINGOBJECT,
interactingWith->id_, AB::GameProtocol::ObjectCallType::TalkingTo, 0);
return;
}
if (ping)
owner_.CallEvent<void(uint32_t, AB::GameProtocol::ObjectCallType, int)>(EVENT_ON_PINGOBJECT,
interactingWith->id_, AB::GameProtocol::ObjectCallType::TalkingTo, 0);
}
return;
}
if (Is<ItemDrop>(interactingWith))
{
if (suppress)
{
if (ping)
owner_.CallEvent<void(uint32_t, AB::GameProtocol::ObjectCallType, int)>(EVENT_ON_PINGOBJECT,
interactingWith->id_, AB::GameProtocol::ObjectCallType::PickingUp, 0);
return;
}
if (!owner_.IsInRange(Ranges::Adjecent, interactingWith))
{
if (owner_.FollowObject(interactingWith, false, RANGE_TOUCH))
{
type_ = Type::Generic;
if (ping)
owner_.CallEvent<void(uint32_t, AB::GameProtocol::ObjectCallType, int)>(EVENT_ON_PINGOBJECT,
interactingWith->id_, AB::GameProtocol::ObjectCallType::PickingUp, 0);
}
return;
}
type_ = Type::Generic;
if (ping)
owner_.CallEvent<void(uint32_t, AB::GameProtocol::ObjectCallType, int)>(EVENT_ON_PINGOBJECT,
interactingWith->id_, AB::GameProtocol::ObjectCallType::PickingUp, 0);
return;
}
if (Is<Actor>(interactingWith))
{
if (owner_.IsAlly(To<Actor>(interactingWith)))
{
if (!suppress)
{
owner_.FollowObject(interactingWith, ping);
type_ = Type::Generic;
}
else
{
if (ping)
owner_.CallEvent<void(uint32_t, AB::GameProtocol::ObjectCallType, int)>(EVENT_ON_PINGOBJECT,
interactingWith->id_, AB::GameProtocol::ObjectCallType::Follow, 0);
}
return;
}
if (owner_.IsEnemy(To<Actor>(interactingWith)))
{
if (!suppress)
{
owner_.Attack(To<Actor>(interactingWith), ping);
type_ = Type::Generic;
}
else
{
if (ping)
owner_.CallEvent<void(uint32_t, AB::GameProtocol::ObjectCallType, int)>(EVENT_ON_PINGOBJECT,
interactingWith->id_, AB::GameProtocol::ObjectCallType::Target, 0);
}
return;
}
}
}
void InteractionComp::UseSkill(bool suppress, int skillIndex, bool ping)
{
if (skillIndex < 0 || skillIndex >= PLAYER_MAX_SKILLS)
return;
if (owner_.IsImmobilized() || owner_.IsDead())
return;
auto* interactingWith = owner_.selectionComp_->GetSelectedObject();
if (interactingWith)
target_ = interactingWith->GetPtr<GameObject>();
else
target_.reset();
skillIndex_ = skillIndex;
SkillBar* sb = owner_.GetSkillBar();
auto skill = sb->GetSkill(skillIndex);
if (!skill)
{
// Will send an error to the player
owner_.UseSkill(skillIndex, ping);
return;
}
if (suppress)
{
owner_.CallEvent<void(uint32_t, AB::GameProtocol::ObjectCallType, int)>(EVENT_ON_PINGOBJECT,
interactingWith ? interactingWith->id_ : 0,
AB::GameProtocol::ObjectCallType::UseSkill, skillIndex + 1);
return;
}
skillRange_ = skill->GetRange();
if (!skill->NeedsTarget())
{
// Can use it right away
owner_.UseSkill(skillIndex, ping);
return;
}
if (!interactingWith)
{
// Needs a target but we don't have one -> send an error to the player
owner_.UseSkill(skillIndex, ping);
return;
}
if (interactingWith->IsInRange(skillRange_, &owner_))
{
owner_.UseSkill(skillIndex_, ping);
return;
}
if (ping)
owner_.CallEvent<void(uint32_t, AB::GameProtocol::ObjectCallType, int)>(EVENT_ON_PINGOBJECT,
interactingWith ? interactingWith->id_ : 0,
AB::GameProtocol::ObjectCallType::UseSkill, skillIndex + 1);
owner_.FollowObject(interactingWith, false, RangeDistances[static_cast<size_t>(skillRange_)]);
type_ = Type::Skill;
}
}
}
|
[
"sa@0x2a.wtf"
] |
sa@0x2a.wtf
|
f5f2b19b623ecda00a3c5695eba37543a2b186a1
|
b5a9d42f7ea5e26cd82b3be2b26c324d5da79ba1
|
/tensorflow/stream_executor/gpu/gpu_diagnostics.h
|
5b786b9c85a516ddcc85f4f08c81fa65aba92256
|
[
"Apache-2.0"
] |
permissive
|
uve/tensorflow
|
e48cb29f39ed24ee27e81afd1687960682e1fbef
|
e08079463bf43e5963acc41da1f57e95603f8080
|
refs/heads/master
| 2020-11-29T11:30:40.391232
| 2020-01-11T13:43:10
| 2020-01-11T13:43:10
| 230,088,347
| 0
| 0
|
Apache-2.0
| 2019-12-25T10:49:15
| 2019-12-25T10:49:14
| null |
UTF-8
|
C++
| false
| false
| 3,995
|
h
|
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_STREAM_EXECUTOR_GPU_GPU_DIAGNOSTICS_H_
#define TENSORFLOW_STREAM_EXECUTOR_GPU_GPU_DIAGNOSTICS_H_
#include <tuple>
#include "tensorflow/stream_executor/platform/port.h"
#include "tensorflow/stream_executor/lib/statusor.h"
#include "tensorflow/stream_executor/platform/port.h"
namespace stream_executor {
namespace gpu {
// e.g. DriverVersion{346, 3, 4}
using DriverVersion = std::tuple<int, int, int>;
// FIXME: These functions are in stream_executor::cuda namespaces for now
// Will move to stream_executor::gpu namespace in the near future
//
//// Converts a parsed driver version to string form.
// string DriverVersionToString(DriverVersion version);
//
//// Converts a parsed driver version or status value to natural string form.
// string DriverVersionStatusToString(port::StatusOr<DriverVersion> version);
//
//// Converts a string of a form like "331.79" to a DriverVersion{331, 79}.
// port::StatusOr<DriverVersion> StringToDriverVersion(const string& value);
class Diagnostician {
public:
// Logs diagnostic information when CUDA appears to be misconfigured (e.g. is
// not initializing).
//
// Note: if we're running on a machine that has no GPUs, we don't want to
// produce very much log spew beyond saying, "looks like there's no CUDA
// kernel
// module running".
//
// Note: we use non-Google-File:: API here because we may be called before
// InitGoogle has completed.
static void LogDiagnosticInformation();
// Given the driver version file contents, finds the kernel module version and
// returns it as a string.
//
// This is solely used for more informative log messages when the user is
// running on a machine that happens to have a libcuda/kernel driver mismatch.
static port::StatusOr<DriverVersion> FindKernelModuleVersion(
const string& driver_version_file_contents);
// Extracts the kernel driver version from the current host.
static port::StatusOr<DriverVersion> FindKernelDriverVersion();
// Iterates through loaded DSOs with DlIteratePhdrCallback to find the
// driver-interfacing DSO version number. Returns it as a string.
static port::StatusOr<DriverVersion> FindDsoVersion();
// Logs information about the kernel driver version and userspace driver
// library version.
static void LogDriverVersionInformation();
private:
// Given the DSO version number and the driver version file contents, extracts
// the driver version and compares, warning the user in the case of
// incompatibility.
//
// This is solely used for more informative log messages when the user is
// running on a machine that happens to have a libcuda/kernel driver mismatch.
static void WarnOnDsoKernelMismatch(
port::StatusOr<DriverVersion> dso_version,
port::StatusOr<DriverVersion> kernel_version);
// Logs information about the dev nodes present on this machine: their
// existence, permissions, accessibility from this uid/gid.
static void LogDevNodeDiagnosticInformation();
static string GetDevNodePath(int dev_node_ordinal);
SE_DISALLOW_COPY_AND_ASSIGN(Diagnostician);
};
} // namespace gpu
} // namespace stream_executor
#endif // TENSORFLOW_STREAM_EXECUTOR_GPU_GPU_DIAGNOSTICS_H_
|
[
"v-grniki@microsoft.com"
] |
v-grniki@microsoft.com
|
f301fb9996382476128ec41dd645c2f3f477a75c
|
1f1cc05377786cc2aa480cbdfde3736dd3930f73
|
/xulrunner-sdk-26/xulrunner-sdk/include/nsISerializable.h
|
bb9f9b6d98852432c046961d5bef48281445c01c
|
[
"Apache-2.0"
] |
permissive
|
julianpistorius/gp-revolution-gaia
|
84c3ec5e2f3b9e76f19f45badc18d5544bb76e0d
|
6e27b83efb0d4fa4222eaf25fb58b062e6d9d49e
|
refs/heads/master
| 2021-01-21T02:49:54.000389
| 2014-03-27T09:58:17
| 2014-03-27T09:58:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,124
|
h
|
/*
* DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/m-cen-l64-xr-ntly-000000000000/build/xpcom/ds/nsISerializable.idl
*/
#ifndef __gen_nsISerializable_h__
#define __gen_nsISerializable_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIObjectInputStream; /* forward declaration */
class nsIObjectOutputStream; /* forward declaration */
/* starting interface: nsISerializable */
#define NS_ISERIALIZABLE_IID_STR "91cca981-c26d-44a8-bebe-d9ed4891503a"
#define NS_ISERIALIZABLE_IID \
{0x91cca981, 0xc26d, 0x44a8, \
{ 0xbe, 0xbe, 0xd9, 0xed, 0x48, 0x91, 0x50, 0x3a }}
class NS_NO_VTABLE nsISerializable : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISERIALIZABLE_IID)
/* void read (in nsIObjectInputStream aInputStream); */
NS_IMETHOD Read(nsIObjectInputStream *aInputStream) = 0;
/* void write (in nsIObjectOutputStream aOutputStream); */
NS_IMETHOD Write(nsIObjectOutputStream *aOutputStream) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsISerializable, NS_ISERIALIZABLE_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSISERIALIZABLE \
NS_IMETHOD Read(nsIObjectInputStream *aInputStream); \
NS_IMETHOD Write(nsIObjectOutputStream *aOutputStream);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSISERIALIZABLE(_to) \
NS_IMETHOD Read(nsIObjectInputStream *aInputStream) { return _to Read(aInputStream); } \
NS_IMETHOD Write(nsIObjectOutputStream *aOutputStream) { return _to Write(aOutputStream); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSISERIALIZABLE(_to) \
NS_IMETHOD Read(nsIObjectInputStream *aInputStream) { return !_to ? NS_ERROR_NULL_POINTER : _to->Read(aInputStream); } \
NS_IMETHOD Write(nsIObjectOutputStream *aOutputStream) { return !_to ? NS_ERROR_NULL_POINTER : _to->Write(aOutputStream); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsSerializable : public nsISerializable
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISERIALIZABLE
nsSerializable();
private:
~nsSerializable();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsSerializable, nsISerializable)
nsSerializable::nsSerializable()
{
/* member initializers and constructor code */
}
nsSerializable::~nsSerializable()
{
/* destructor code */
}
/* void read (in nsIObjectInputStream aInputStream); */
NS_IMETHODIMP nsSerializable::Read(nsIObjectInputStream *aInputStream)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void write (in nsIObjectOutputStream aOutputStream); */
NS_IMETHODIMP nsSerializable::Write(nsIObjectOutputStream *aOutputStream)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsISerializable_h__ */
|
[
"luis@geeksphone.com"
] |
luis@geeksphone.com
|
27e829b521be49a518d3851f090e485a1034b8e1
|
cdd45cad8525c94b8beb1b3e75c76b3c870ab084
|
/chapter2/splitting_num.cpp
|
0519b4b0011381435361939a09212a1d77bf85b7
|
[] |
no_license
|
kyro1202/Competitive-Programming-3
|
4fcf4e5516c83ce7dbfcb9084a6fa8e23b7d9dfe
|
1e1e784fac3f3db9117ebabca0486b0edffe149d
|
refs/heads/master
| 2021-03-22T00:16:20.365660
| 2018-06-06T05:02:07
| 2018-06-06T05:02:07
| 101,572,720
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 577
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
bitset<31> a,b;
int count; long int n;
while(true)
{
count = 0;
cin >> n;
if(!n)
break;
bitset<31> inp(n);
a.reset(); b.reset();
for(int i = 0 ; i < inp.size() ; i++)
{
if(inp.test(i))
{
count++;
if(count%2)
a[i] = 1;
else
b[i] = 1;
}
}
cout << a.to_ulong() << " " << b.to_ulong() << endl;
}
}
|
[
"shivishiva2012@gmail.com"
] |
shivishiva2012@gmail.com
|
14f71bbf1f000a76b5e92c4b20a4ad45845f4240
|
1ede0ec505f59698f44ec45119d9af72187e4ffa
|
/Header/Game.h
|
14d26ba945eaf928637811c212046cbcccaa6e2a
|
[] |
no_license
|
terepaii/Graverted
|
81cb1dc26b459edc66b19b071a43252342e5a015
|
111cacca03beec60c7e76652d62967df3371657a
|
refs/heads/master
| 2021-01-23T06:54:23.541665
| 2013-05-18T14:38:12
| 2013-05-18T14:38:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 768
|
h
|
#ifndef GAME_H_
#define GAME_H_
#include "ScreenManager.h"
#include "SplashScreen.h"
#include "CreditsMenu.h"
#include "InputHandler.h"
class Game
{
public:
Game();
~Game();
static const enum GameState{SPLASH,
MAINMENU,
LEVEL1,
LEVEL2,
LEVEL3,
CREDITS,
GAME_OVER,
EXIT};
void Start();
private:
void Load();
void showSplashScreen(sf::RenderWindow& window, std::string& filepath);
void showMainMenu(sf::RenderWindow& window);
void showCreditsMenu(sf::RenderWindow& window);
void mainGameLoop();
bool exitGame();
sf::RenderWindow window;
GameState gameState;
std::string menuSelection;
SplashScreen splashScreen;
InputHandler input;
CreditsMenu credits;
ScreenManager mainMenu;
};
#endif
|
[
"danielkeohane4823@gmail.com"
] |
danielkeohane4823@gmail.com
|
e83863de74916659186770d163df3f85dce7ea9c
|
bfdfcb02edd4d792ab9888bcf0809036d919fc4e
|
/include/scenes/createAccountScene.h
|
03af274395e191dcd27bcca3f51f0688bf0ac4fe
|
[] |
no_license
|
Krosser22/MultiplayerClient
|
67c6f3f4b76c803d393e993e2f8f8203c2336955
|
da12c323abf27efbe98c0ecdfe39b71662e0f477
|
refs/heads/master
| 2021-01-09T05:25:40.708269
| 2017-01-12T23:56:42
| 2017-01-12T23:56:42
| 80,764,872
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 568
|
h
|
/**
*** ////////////////////////////////////////////
*** /////Autor: Juan Daniel Laserna Condado/////
*** /////Email: S6106112@live.tees.ac.uk /////
*** ///// 2016-2017 /////
*** ////////////////////////////////////////////
**/
#ifndef __CREATE_ACCOUNT_SCENE_H__
#define __CREATE_ACCOUNT_SCENE_H__
#include "scenes/scene.h"
class CreateAccountScene : public Scene {
public:
CreateAccountScene() {};
~CreateAccountScene() {};
void start();
void input();
void update();
void finish();
};
#endif //__CREATE_ACCOUNT_SCENE_H__
|
[
"condadodaniel@hotmail.com"
] |
condadodaniel@hotmail.com
|
d97eaa94404f0339316e46074772b9f1654abf3c
|
b71556aee4654b48e91ba8124a3a8ded26de273e
|
/contest/ICPC/The 2019 Asia Yinchuan First Round Online Programming/F.cpp
|
f58df17363548d51da30abf67d231785e5243b44
|
[] |
no_license
|
young-zy/algorithm
|
0255a327390c6b149870b34fbd34816dc002e82e
|
536eddd9a6bc03e81c566afa05c53f555eb14a86
|
refs/heads/master
| 2021-07-23T07:23:29.929221
| 2020-04-23T16:33:28
| 2020-04-23T16:33:28
| 149,439,464
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,015
|
cpp
|
#include<bits/stdc++.h>
#define endl "\n"
#define INF 0x3f3f3f3f
using namespace std;
int a[205];
int d[205][205];
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
for(int te = 0; te < t ; te++){
int n,q;
cin>>n>>q;
for(int i = 1; i<=n ; i ++){
cin>>a[i];
}
for(int i = 1; i<=n ; i++){
for(int j = 0; j<=n;j++){
cin>>d[i][j];
}
}
for(int qe = 0 ;qe < q; qe++){
int u,v,w;
cin>>u>>v>>w;
int temp[205][205];
for(int i = 1; i<=n ; i++){
for(int j = 1; j<=n;j++){
if(i == j){
d[i][j] = 0;
}else if(a[i] >w || a[j]>w ){
temp[i][j] = INF;
}else{
temp[i][j] = d[i][j];
}
}
}
}
}
return 0;
}
|
[
"youngzhaozhou@gmail.com"
] |
youngzhaozhou@gmail.com
|
da660e68ea0fe1b62a0f4953e5708caa08a64422
|
ce99b399bead6c9a285f07d386d04a4a1c5f6bb7
|
/Cookbook/4569OS_CodeBundle/Chapter04/Chapter04/Shadows/Shadows/ShadowsDoc.h
|
36db4264eeead9962f03d519c6e3f8a697662009
|
[] |
no_license
|
codediy/OgreDemo
|
13e97c984499330bbd733f5c7c64212324e428b4
|
6fb0ad2edde881feda040f5eb8bdf134f6ca9495
|
refs/heads/master
| 2020-12-05T21:44:51.348401
| 2020-01-07T06:13:00
| 2020-01-07T06:13:00
| 232,255,494
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,462
|
h
|
// This MFC Samples source code demonstrates using MFC Microsoft Office Fluent User Interface
// (the "Fluent UI") and is provided only as referential material to supplement the
// Microsoft Foundation Classes Reference and related electronic documentation
// included with the MFC C++ library software.
// License terms to copy, use or distribute the Fluent UI are available separately.
// To learn more about our Fluent UI licensing program, please visit
// http://msdn.microsoft.com/officeui.
//
// Copyright (C) Microsoft Corporation
// All rights reserved.
// ShadowsDoc.h : interface of the CShadowsDoc class
//
#pragma once
class CShadowsDoc : public CDocument
{
protected: // create from serialization only
CShadowsDoc();
DECLARE_DYNCREATE(CShadowsDoc)
// Attributes
public:
// Operations
public:
// Overrides
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
#ifdef SHARED_HANDLERS
virtual void InitializeSearchContent();
virtual void OnDrawThumbnail(CDC& dc, LPRECT lprcBounds);
#endif // SHARED_HANDLERS
// Implementation
public:
virtual ~CShadowsDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
DECLARE_MESSAGE_MAP()
#ifdef SHARED_HANDLERS
// Helper function that sets search content for a Search Handler
void SetSearchContent(const CString& value);
#endif // SHARED_HANDLERS
};
|
[
"zmwwork@163.com"
] |
zmwwork@163.com
|
019e5d90b98cf0044c34dc583a4eac6a72aabe88
|
78a483c9c75aef625bcc78bb1e9cc1edfce56127
|
/sci/LinearOT/linear-uniform.h
|
748d9ac458c17781b0c500e69eeb3c20d987da3f
|
[] |
no_license
|
smog70151/SCI
|
4cf3255e998602738ef6ca8e0a44adbfbaca8bd8
|
d8819900793be5d2a95ba91a1e23be7136bc7316
|
refs/heads/master
| 2023-04-26T22:37:40.739371
| 2021-05-14T12:30:40
| 2021-05-14T12:30:40
| 346,612,600
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 32,980
|
h
|
/*
Authors: Nishant Kumar
Copyright:
Copyright (c) 2020 Microsoft Research
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef LINEAR_UNIFORM_H__
#define LINEAR_UNIFORM_H__
#include <iostream>
#ifdef USE_EIGEN
#include <Eigen/Dense>
#endif
#include "sci/OT/iknp.h"
// Special case of LinearOT which works only for uniform bitwidth multiplication
// Faster than LinearOT for uniform bitwidth matrix multiplication
template <typename IO, typename intType, typename otType>
class MatMulUniform
{
public:
IO *io = nullptr;
sci::OT<otType> *otImpl = nullptr;
sci::OT<otType> *otImplRoleReversed = nullptr;
int SCI_party;
int bitlength;
const uint32_t batchSizeOTs =
1ULL << 18; // This is the default size of the batch of OTs that will be
// done in one go for matmul
// This will be scaled appropriately to manage memory if the
// matmul dimensions are too large.
const uint64_t MaxMemToUseInBytes = 2.5 * (1 << 30); // 2.5 GiB
intType moduloMask;
MatMulUniform(int SCI_party, int bitlength, IO *io, sci::OT<otType> *otImpl,
sci::OT<otType> *otImplRoleReversed)
{
this->SCI_party = SCI_party;
assert(((SCI_party == 1) || (SCI_party == 2)) && "PartyNum should be 1 or 2.");
this->bitlength = bitlength;
this->io = io;
assert(io != nullptr && "IO can't be nullptr.");
assert(otImpl != nullptr && "otImpl can't be nullptr.");
this->otImpl = otImpl;
this->otImplRoleReversed = otImplRoleReversed;
if (bitlength == 64)
moduloMask = -1;
else
moduloMask = (1ULL << bitlength) - 1;
}
~MatMulUniform() {}
#ifdef USE_EIGEN
void ideal_func_eigen(int s1, int s2, int s3, const intType *A,
const intType *B, intType *C)
{
Eigen::Matrix<intType, Eigen::Dynamic, Eigen::Dynamic> eigen_a(s1, s2);
Eigen::Matrix<intType, Eigen::Dynamic, Eigen::Dynamic> eigen_b(s2, s3);
Eigen::Matrix<intType, Eigen::Dynamic, Eigen::Dynamic> eigen_c(s1, s3);
for (int i = 0; i < s1; i++)
{
for (int j = 0; j < s2; j++)
{
eigen_a(i, j) = Arr2DIdxRowM(A, s1, s2, i, j);
}
}
for (int i = 0; i < s2; i++)
{
for (int j = 0; j < s3; j++)
{
eigen_b(i, j) = Arr2DIdxRowM(B, s2, s3, i, j);
}
}
eigen_c = eigen_a * eigen_b;
for (int i = 0; i < s1; i++)
{
for (int j = 0; j < s3; j++)
{
Arr2DIdxRowM(C, s1, s3, i, j) = eigen_c(i, j);
}
}
}
#endif
void ideal_func(int s1, int s2, int s3, const intType *A, const intType *B,
intType *C)
{
#ifndef USE_EIGEN
for (int i = 0; i < s1; i++)
{
for (int j = 0; j < s3; j++)
{
Arr2DIdxRowM(C, s1, s3, i, j) = 0;
for (int k = 0; k < s2; k++)
{
Arr2DIdxRowM(C, s1, s3, i, j) +=
(Arr2DIdxRowM(A, s1, s2, i, k) * Arr2DIdxRowM(B, s2, s3, k, j));
}
}
}
#else
ideal_func_eigen(s1, s2, s3, A, B, C);
#endif
for (int i = 0; i < s1 * s3; i++)
{
C[i] = C[i] & moduloMask;
}
}
void verifyMatmulShares(int s1, int s2, int s3, const intType *A_share,
const intType *B_share, const intType *C_share)
{
if (SCI_party == sci::ALICE)
{
intType *A_temp_share = new intType[s1 * s2];
intType *B_temp_share = new intType[s2 * s3];
intType *C_temp_share = new intType[s1 * s3];
intType *C_clear = new intType[s1 * s3];
io->recv_data(A_temp_share, sizeof(intType) * s1 * s2);
io->recv_data(B_temp_share, sizeof(intType) * s2 * s3);
io->recv_data(C_temp_share, sizeof(intType) * s1 * s3);
sci::elemWiseAdd<intType>(s1 * s2, A_share, A_temp_share, A_temp_share);
sci::elemWiseAdd<intType>(s2 * s3, B_share, B_temp_share, B_temp_share);
sci::elemWiseAdd<intType>(s1 * s3, C_share, C_temp_share, C_temp_share);
ideal_func(s1, s2, s3, A_temp_share, B_temp_share, C_clear);
for (int i = 0; i < s1; i++)
{
for (int j = 0; j < s3; j++)
{
assert(Arr2DIdxRowM(C_clear, s1, s3, i, j) ==
(Arr2DIdxRowM(C_temp_share, s1, s3, i, j) & moduloMask));
}
}
delete[] A_temp_share;
delete[] B_temp_share;
delete[] C_temp_share;
delete[] C_clear;
}
else if (SCI_party == sci::BOB)
{
io->send_data(A_share, sizeof(intType) * s1 * s2);
io->send_data(B_share, sizeof(intType) * s2 * s3);
io->send_data(C_share, sizeof(intType) * s1 * s3);
}
else
{
assert(false);
}
}
void fillInSimpleValues(int s1, int s2, intType *arr)
{
if (SCI_party == sci::ALICE)
{
for (int i = 0; i < s1; i++)
{
for (int j = 0; j < s2; j++)
{
Arr2DIdxRowM(arr, s1, s2, i, j) = i + j + 1;
}
}
}
else if (SCI_party == sci::BOB)
{
for (int i = 0; i < s1; i++)
{
for (int j = 0; j < s2; j++)
{
Arr2DIdxRowM(arr, s1, s2, i, j) = 0;
}
}
}
}
/*
This function is not being used anywhere right now
- matmul where dimensions of matrices are (s1,s2) and (s2,s3)
- inp is input of the sender of size (s1,s2)
- outp is the share of the result of size (s1,s3)
*/
void funcOTSenderNonBatched(int s1, int s2, int s3, const intType *inp,
intType *outp, sci::OT<otType> *otInstance)
{
uint64_t *corrData = new uint64_t[s1 * s2 * bitlength * s3];
uint64_t *rData = new uint64_t[s1 * s2 * bitlength * s3];
uint64_t *chunkSizes = new uint64_t[s2 * bitlength * s3];
uint64_t *numChunks = new uint64_t[s2 * bitlength * s3];
intType *inpColumnMajor = new intType[s1 * s2];
intType *outpColumnMajor = new intType[s1 * s3];
sci::convertRowToColMajor<intType>(s1, s2, inp, inpColumnMajor);
for (int i = 0; i < s1 * s3; i++)
{
outpColumnMajor[i] = 0;
}
for (int col = 0; col < s3; col++)
{
for (int j = 0; j < s2; j++)
{
for (int k = 0; k < bitlength; k++)
{
for (int i = 0; i < s1; i++)
{
intType curElem = Arr2DIdxColM(inpColumnMajor, s1, s2, i, j);
Arr4DIdxRowM(corrData, s3, s2, bitlength, s1, col, j, k, i) =
((intType)(((intType)curElem) << k)) >> k;
// casting is imp to make sure that
// right shift happens in apt bitwidth
}
chunkSizes[col * s2 * bitlength + j * bitlength + k] = bitlength - k;
numChunks[col * s2 * bitlength + j * bitlength + k] = s1;
}
}
}
otInstance->template send_cot_matmul<intType>(
rData, corrData, chunkSizes, numChunks, s2 * bitlength * s3);
for (int col = 0; col < s3; col++)
{
for (int i = 0; i < s2; i++)
{
for (int j = 0; j < bitlength; j++)
{
for (int k = 0; k < s1; k++)
{
// Arr3DIdxRowM(rData,s2,bitlength,s1,i,j,k) should be of
// bitlength-j bits -- top j bits should be 0.
uint64_t curElem =
Arr4DIdxRowM(rData, s3, s2, bitlength, s1, col, i, j, k);
assert(((((1ULL << j) - 1) << (bitlength - j)) & curElem) == 0 &&
"assertion failed");
Arr2DIdxColM(outpColumnMajor, s1, s3, k, col) -=
(((intType)curElem) << j);
}
}
}
}
sci::convertColToRowMajor<intType>(s1, s3, outpColumnMajor, outp);
for (int i = 0; i < s1 * s3; i++)
{
outp[i] = outp[i] & moduloMask;
}
delete[] corrData;
delete[] rData;
delete[] chunkSizes;
delete[] numChunks;
}
/*
This function is not being used anywhere right now
- The matrix multiplication being performed is (s1, s2) * (s2, s3).
- inp is the receiver's array to be multiplied of size (s2, s3)
- outp is the share of the receiver after multiplication of size
(s1,s3)
*/
void funcOTReceiverNonBatched(int s1, int s2, int s3, const intType *inp,
intType *outp, sci::OT<otType> *otInstance)
{
// copy inp from row to column and outp from column to row major
uint8_t *choiceBitArr = new uint8_t[s2 * bitlength * s3];
uint64_t *recv_data = new uint64_t[s1 * s2 * bitlength * s3];
uint64_t *chunkSizes = new uint64_t[s2 * bitlength * s3];
uint64_t *numChunks = new uint64_t[s2 * bitlength * s3];
intType *inpColumnMajor = new intType[s2 * s3];
intType *outpColumnMajor = new intType[s1 * s3];
sci::convertRowToColMajor<intType>(s2, s3, inp, inpColumnMajor);
for (int j = 0; j < s3; j++)
{
for (int i = 0; i < s2; i++)
{
for (int k = 0; k < bitlength; k++)
{
choiceBitArr[j * s2 * bitlength + i * bitlength + k] =
(Arr2DIdxColM(inpColumnMajor, s2, s3, i, j) & (1ULL << k)) >>
k; // Unsigned right shift
chunkSizes[j * s2 * bitlength + i * bitlength + k] = (bitlength - k);
numChunks[j * s2 * bitlength + i * bitlength + k] = s1;
}
}
}
otInstance->template recv_cot_matmul<intType>(
recv_data, choiceBitArr, chunkSizes, numChunks, s2 * s3 * bitlength);
// recv_data can be interpreted as a 4d array of size(s3,s2,bitlength,s1)
for (int i = 0; i < s1 * s3; i++)
{
outpColumnMajor[i] = 0;
}
for (int i = 0; i < s3; i++)
{
for (int j = 0; j < s2; j++)
{
for (int k = 0; k < bitlength; k++)
{
for (int w = 0; w < s1; w++)
{
Arr2DIdxColM(outpColumnMajor, s1, s3, w, i) +=
(((intType)Arr4DIdxRowM(recv_data, s3, s2, bitlength, s1, i, j,
k, w))
<< k);
}
}
}
}
sci::convertColToRowMajor<intType>(s1, s3, outpColumnMajor, outp);
for (int i = 0; i < s1 * s3; i++)
{
outp[i] = outp[i] & moduloMask;
}
delete[] choiceBitArr;
delete[] recv_data;
delete[] chunkSizes;
delete[] numChunks;
}
int chooseOptimalBatchSize(int senderMatmulDims)
{
uint64_t temp =
MaxMemToUseInBytes / ((uint64_t)senderMatmulDims * sizeof(intType));
if (temp > batchSizeOTs)
{
temp = batchSizeOTs;
}
return temp;
}
/*
- matmul where dimensions of matrices are (s1,s2) and (s2,s3)
- inp is input of the sender of size (s1,s2)
- outp is the share of the result of size (s1,s3)
*/
void funcOTSenderInputA(int s1, int s2, int s3, const intType *inp,
intType *outp, sci::OT<otType> *otInstance,
bool inpAlreadyColumnMajor = false)
{
intType *inpColumnMajor = const_cast<intType *>(inp);
if (!inpAlreadyColumnMajor)
{
inpColumnMajor = new intType[s1 * s2];
sci::convertRowToColMajor<intType>(s1, s2, inp, inpColumnMajor);
}
intType *outpColumnMajor = new intType[s1 * s3];
int curBatchSizeOTs = chooseOptimalBatchSize(s1);
intType *corrData = new intType[curBatchSizeOTs * s1];
intType *data = new intType[curBatchSizeOTs * s1];
uint32_t *chunkSizes = new uint32_t[curBatchSizeOTs];
uint32_t *numChunks = new uint32_t[curBatchSizeOTs];
for (int i = 0; i < s1 * s3; i++)
{
outpColumnMajor[i] = 0;
}
int numOTs = s2 * s3 * bitlength;
int bitIdxRecv = 0, rowIdxRecv = 0, colIdxRecv = 0;
for (int i = 0; i < numOTs; i += curBatchSizeOTs)
{
int j;
for (j = i; (j < numOTs) && (j < i + curBatchSizeOTs); j++)
{
// current OT# is j
sci::linIdxRowMInverseMapping(j, s3, s2, bitlength, colIdxRecv,
rowIdxRecv, bitIdxRecv);
for (int k = 0; k < s1; k++)
{
corrData[(j - i) * s1 + k] =
(((intType)Arr2DIdxColM(inpColumnMajor, s1, s2, k, rowIdxRecv))
<< bitIdxRecv) >>
bitIdxRecv;
}
chunkSizes[j - i] = bitlength - bitIdxRecv;
numChunks[j - i] = s1;
}
otInstance->template send_cot_matmul<intType>(data, corrData, chunkSizes,
numChunks, j - i, s1);
for (int j = i; (j < numOTs) && (j < i + curBatchSizeOTs); j++)
{
// current OT# is j
sci::linIdxRowMInverseMapping(j, s3, s2, bitlength, colIdxRecv,
rowIdxRecv, bitIdxRecv);
for (int k = 0; k < s1; k++)
{
Arr2DIdxColM(outpColumnMajor, s1, s3, k, colIdxRecv) -=
(((intType)Arr2DIdxRowM(data, curBatchSizeOTs, s1, (j - i), k))
<< bitIdxRecv);
}
}
}
sci::convertColToRowMajor<intType>(s1, s3, outpColumnMajor, outp);
for (int i = 0; i < s1 * s3; i++)
{
outp[i] = outp[i] & moduloMask;
}
if (!inpAlreadyColumnMajor)
delete[] inpColumnMajor;
delete[] outpColumnMajor;
delete[] corrData;
delete[] data;
delete[] chunkSizes;
delete[] numChunks;
}
/*
- The matrix multiplication being performed is (s1, s2) * (s2, s3).
- inp is the receiver's array to be multiplied of size (s2, s3)
- outp is the share of the receiver after multiplication of size
(s1,s3)
*/
void funcOTReceiverInputB(int s1, int s2, int s3, const intType *inp,
intType *outp, sci::OT<otType> *otInstance,
bool inpAlreadyColumnMajor = false)
{
// copy inp from row to column and outp from column to row major
intType *inpColumnMajor = const_cast<intType *>(inp);
intType *outpColumnMajor = new intType[s1 * s3];
if (!inpAlreadyColumnMajor)
{
inpColumnMajor = new intType[s2 * s3];
sci::convertRowToColMajor<intType>(s2, s3, inp, inpColumnMajor);
}
uint64_t masks[64];
for (int i = 0; i < 64; i++)
{
masks[i] = 1ULL << i;
}
int curBatchSizeOTs = chooseOptimalBatchSize(s1);
intType *data = new intType[curBatchSizeOTs * s1];
uint8_t *choiceBitArr = new uint8_t[curBatchSizeOTs];
uint32_t *chunkSizes = new uint32_t[curBatchSizeOTs];
uint32_t *numChunks = new uint32_t[curBatchSizeOTs];
for (int i = 0; i < s1 * s3; i++)
{
outpColumnMajor[i] = 0;
}
int numOTs = s2 * s3 * bitlength;
int bitIdxRecv = 0, rowIdxRecv = 0, colIdxRecv = 0;
for (int i = 0; i < numOTs; i += curBatchSizeOTs)
{
int j;
for (j = i; (j < numOTs) && (j < i + curBatchSizeOTs); j++)
{
// current OT# is j
sci::linIdxRowMInverseMapping(j, s3, s2, bitlength, colIdxRecv,
rowIdxRecv, bitIdxRecv);
choiceBitArr[j - i] =
(Arr2DIdxColM(inpColumnMajor, s2, s3, rowIdxRecv, colIdxRecv) &
masks[bitIdxRecv]) >>
bitIdxRecv;
chunkSizes[j - i] = bitlength - bitIdxRecv;
numChunks[j - i] = s1;
}
otInstance->template recv_cot_matmul<intType>(
data, choiceBitArr, chunkSizes, numChunks, j - i, s1);
for (int j = i; (j < numOTs) && (j < i + curBatchSizeOTs); j++)
{
// current OT# is j
sci::linIdxRowMInverseMapping(j, s3, s2, bitlength, colIdxRecv,
rowIdxRecv, bitIdxRecv);
for (int k = 0; k < s1; k++)
{
Arr2DIdxColM(outpColumnMajor, s1, s3, k, colIdxRecv) +=
(((intType)Arr2DIdxRowM(data, curBatchSizeOTs, s1, (j - i), k))
<< bitIdxRecv);
}
}
}
sci::convertColToRowMajor<intType>(s1, s3, outpColumnMajor, outp);
for (int i = 0; i < s1 * s3; i++)
{
outp[i] = outp[i] & moduloMask;
}
if (!inpAlreadyColumnMajor)
delete[] inpColumnMajor;
delete[] outpColumnMajor;
delete[] data;
delete[] choiceBitArr;
delete[] chunkSizes;
delete[] numChunks;
}
/*
- matmul where dimensions of matrices are (s1,s2) and (s2,s3)
- inp is input of the sender of size (s2,s3)
- outp is the share of the result of size (s1,s3)
*/
void funcOTSenderInputB(int s1, int s2, int s3, const intType *inp,
intType *outp, sci::OT<otType> *otInstance)
{
int curBatchSizeOTs = chooseOptimalBatchSize(s3);
intType *corrData = new intType[curBatchSizeOTs * s3];
intType *data = new intType[curBatchSizeOTs * s3];
uint32_t *chunkSizes = new uint32_t[curBatchSizeOTs];
uint32_t *numChunks = new uint32_t[curBatchSizeOTs];
for (int i = 0; i < s1 * s3; i++)
{
outp[i] = 0;
}
int numOTs = s1 * s2 * bitlength;
int bitIdxRecv = 0, rowIdxRecv = 0, colIdxRecv = 0;
for (int i = 0; i < numOTs; i += curBatchSizeOTs)
{
int j;
for (j = i; (j < numOTs) && (j < i + curBatchSizeOTs); j++)
{
// current OT# is j
sci::linIdxRowMInverseMapping(j, s1, s2, bitlength, rowIdxRecv,
colIdxRecv, bitIdxRecv);
for (int k = 0; k < s3; k++)
{
corrData[(j - i) * s3 + k] =
(((intType)Arr2DIdxRowM(inp, s2, s3, colIdxRecv, k))
<< bitIdxRecv) >>
bitIdxRecv;
}
chunkSizes[j - i] = bitlength - bitIdxRecv;
numChunks[j - i] = s3;
}
otInstance->template send_cot_matmul<intType>(data, corrData, chunkSizes,
numChunks, j - i, s3);
for (int j = i; (j < numOTs) && (j < i + curBatchSizeOTs); j++)
{
// current OT# is j
sci::linIdxRowMInverseMapping(j, s1, s2, bitlength, rowIdxRecv,
colIdxRecv, bitIdxRecv);
for (int k = 0; k < s3; k++)
{
Arr2DIdxRowM(outp, s1, s3, rowIdxRecv, k) -=
(((intType)Arr2DIdxRowM(data, curBatchSizeOTs, s3, (j - i), k))
<< bitIdxRecv);
}
}
}
for (int i = 0; i < s1 * s3; i++)
{
outp[i] = outp[i] & moduloMask;
}
delete[] corrData;
delete[] data;
delete[] chunkSizes;
delete[] numChunks;
}
/*
- The matrix multiplication being performed is (s1, s2) * (s2, s3).
- inp is the receiver's array to be multiplied of size (s1, s2)
- outp is the share of the receiver after multiplication of size
(s1,s3)
*/
void funcOTReceiverInputA(int s1, int s2, int s3, const intType *inp,
intType *outp, sci::OT<otType> *otInstance)
{
uint64_t masks[64];
for (int i = 0; i < 64; i++)
{
masks[i] = 1ULL << i;
}
int curBatchSizeOTs = chooseOptimalBatchSize(s3);
intType *data = new intType[curBatchSizeOTs * s3];
uint8_t *choiceBitArr = new uint8_t[curBatchSizeOTs];
uint32_t *chunkSizes = new uint32_t[curBatchSizeOTs];
uint32_t *numChunks = new uint32_t[curBatchSizeOTs];
for (int i = 0; i < s1 * s3; i++)
{
outp[i] = 0;
}
int numOTs = s1 * s2 * bitlength;
int bitIdxRecv = 0, rowIdxRecv = 0, colIdxRecv = 0;
for (int i = 0; i < numOTs; i += curBatchSizeOTs)
{
int j;
for (j = i; (j < numOTs) && (j < i + curBatchSizeOTs); j++)
{
// current OT# is j
sci::linIdxRowMInverseMapping(j, s1, s2, bitlength, rowIdxRecv,
colIdxRecv, bitIdxRecv);
choiceBitArr[j - i] =
(Arr2DIdxRowM(inp, s1, s2, rowIdxRecv, colIdxRecv) &
masks[bitIdxRecv]) >>
bitIdxRecv;
chunkSizes[j - i] = bitlength - bitIdxRecv;
numChunks[j - i] = s3;
}
otInstance->template recv_cot_matmul<intType>(
data, choiceBitArr, chunkSizes, numChunks, j - i, s3);
for (int j = i; (j < numOTs) && (j < i + curBatchSizeOTs); j++)
{
// current OT# is j
sci::linIdxRowMInverseMapping(j, s1, s2, bitlength, rowIdxRecv,
colIdxRecv, bitIdxRecv);
for (int k = 0; k < s3; k++)
{
Arr2DIdxRowM(outp, s1, s3, rowIdxRecv, k) +=
(((intType)Arr2DIdxRowM(data, curBatchSizeOTs, s3, (j - i), k))
<< bitIdxRecv);
}
}
}
for (int i = 0; i < s1 * s3; i++)
{
outp[i] = outp[i] & moduloMask;
}
delete[] data;
delete[] choiceBitArr;
delete[] chunkSizes;
delete[] numChunks;
}
/*
- Dot product functionality
- Sender has input 'inp' of size 'size'
*/
void funcDotProdOTSender(int size, const intType *inp, intType *outp,
sci::OT<otType> *otInstance)
{
for (int i = 0; i < size; i++)
{
outp[i] = 0;
}
int curBatchSizeOTs = batchSizeOTs;
int numOTs = size * bitlength;
intType *curCorrData = new intType[curBatchSizeOTs];
uint32_t *curChunkSizes = new uint32_t[curBatchSizeOTs];
uint32_t *curNumChunks = new uint32_t[curBatchSizeOTs];
intType *curData = new intType[curBatchSizeOTs];
int bitIdxRecv = 0, cellIdxRecv = 0;
for (int i = 0; i < numOTs; i += curBatchSizeOTs)
{
int j;
for (j = i; (j < numOTs) && (j < i + curBatchSizeOTs); j++)
{
// current OT# is j
sci::linIdxRowMInverseMapping(j, size, bitlength, cellIdxRecv,
bitIdxRecv);
curCorrData[j - i] =
(((intType)inp[cellIdxRecv]) << bitIdxRecv) >> bitIdxRecv;
curChunkSizes[j - i] = bitlength - bitIdxRecv;
curNumChunks[j - i] = 1;
}
otInstance->template send_cot_matmul<intType>(
curData, curCorrData, curChunkSizes, curNumChunks, j - i, size);
for (int j = i; (j < numOTs) && (j < i + curBatchSizeOTs); j++)
{
// current OT# is j
sci::linIdxRowMInverseMapping(j, size, bitlength, cellIdxRecv,
bitIdxRecv);
outp[cellIdxRecv] -= (((intType)curData[j - i]) << bitIdxRecv);
}
}
for (int i = 0; i < size; i++)
{
outp[i] = outp[i] & moduloMask;
}
delete[] curCorrData;
delete[] curChunkSizes;
delete[] curNumChunks;
delete[] curData;
}
/*
- Dot product functionality
- Receiver has input 'inp' of size 'size'
*/
void funcDotProdOTReceiver(int size, const intType *inp, intType *outp,
sci::OT<otType> *otInstance)
{
uint64_t masks[64];
for (int i = 0; i < 64; i++)
{
masks[i] = 1ULL << i;
}
for (int i = 0; i < size; i++)
{
outp[i] = 0;
}
int curBatchSizeOTs = batchSizeOTs;
int numOTs = size * bitlength;
uint8_t *curChoiceBits = new uint8_t[curBatchSizeOTs];
uint32_t *curNumChunks = new uint32_t[curBatchSizeOTs];
uint32_t *curChunkSizes = new uint32_t[curBatchSizeOTs];
intType *curData = new intType[curBatchSizeOTs];
int bitIdxRecv = 0, cellIdxRecv = 0;
for (int i = 0; i < numOTs; i += curBatchSizeOTs)
{
int j;
for (j = i; (j < numOTs) && (j < i + curBatchSizeOTs); j++)
{
// current OT# is j
sci::linIdxRowMInverseMapping(j, size, bitlength, cellIdxRecv,
bitIdxRecv);
curChoiceBits[j - i] =
(inp[cellIdxRecv] & masks[bitIdxRecv]) >> bitIdxRecv;
curChunkSizes[j - i] = bitlength - bitIdxRecv;
curNumChunks[j - i] = 1;
}
otInstance->template recv_cot_matmul<intType>(
curData, curChoiceBits, curChunkSizes, curNumChunks, j - i, size);
for (int j = i; (j < numOTs) && (j < i + curBatchSizeOTs); j++)
{
// current OT# is j
sci::linIdxRowMInverseMapping(j, size, bitlength, cellIdxRecv,
bitIdxRecv);
outp[cellIdxRecv] += (curData[j - i] << bitIdxRecv);
}
}
for (int i = 0; i < size; i++)
{
outp[i] = outp[i] & moduloMask;
}
delete[] curChoiceBits;
delete[] curNumChunks;
delete[] curChunkSizes;
delete[] curData;
}
/*
This code is unoptimized and not being used anywhere currently.
- Matrix triplet of size (s1,s2)*(s2,s3)
- A_share, B_share, C_share are shares of A,B,C
- shape(A_share) = (s1,s2)
- shape(B_share) = (s2,s3)
- shape(C_share) = (s1,s3)
*/
void generateBeaverMatrixTriplet(int s1, int s2, int s3, sci::PRG128 prg,
intType *A_share, intType *B_share,
intType *C_share)
{
assert(otImplRoleReversed != nullptr);
prg.random_data(A_share, s1 * s2 * sizeof(intType));
prg.random_data(B_share, s2 * s3 * sizeof(intType));
intType *temp = new intType[s1 * s3];
if (SCI_party == sci::ALICE)
{
// The OTs can be done in parallel
funcOTSenderInputA(s1, s2, s3, A_share, C_share, otImpl);
funcOTReceiverInputB(s1, s2, s3, B_share, temp, otImplRoleReversed);
}
else if (SCI_party == sci::BOB)
{
funcOTReceiverInputB(s1, s2, s3, B_share, C_share, otImpl);
funcOTSenderInputA(s1, s2, s3, A_share, temp, otImplRoleReversed);
}
else
{
assert(false);
}
sci::elemWiseAdd<intType>(s1 * s3, C_share, temp, C_share);
ideal_func(s1, s2, s3, A_share, B_share, temp);
sci::elemWiseAdd<intType>(s1 * s3, C_share, temp, C_share);
}
/*
This code is unoptimized and not being used anywhere currently.
- Run the online phase of beaver
- Matrices to be multiplied are of size (s1,s2) and (s2,s3).
- X_share => size = (s1,s2), share of X
- Y_share => size = (s2,s3), share of Y
- Z_share => size = (s1,s3), share of output Z=X*Y
- A_share, B_share, C_share are shares of the beaver triplet (A,B,C)
*/
void runBeaverOnlinePhase(int s1, int s2, int s3, const intType *X_share,
const intType *Y_share, intType *Z_share,
const intType *A_share, const intType *B_share,
const intType *C_share)
{
intType *E_share = new intType[s1 * s2];
intType *F_share = new intType[s2 * s3];
intType *E_temp_share = new intType[s1 * s2];
intType *F_temp_share = new intType[s2 * s3];
intType *Z_temp_share = new intType[s1 * s3];
sci::elemWiseSub<intType>(s1 * s2, X_share, A_share, E_share);
sci::elemWiseSub<intType>(s2 * s3, Y_share, B_share, F_share);
if (SCI_party == sci::ALICE)
{
io->send_data(E_share, sizeof(intType) * s1 * s2);
io->send_data(F_share, sizeof(intType) * s2 * s3);
io->recv_data(E_temp_share, sizeof(intType) * s1 * s2);
io->recv_data(F_temp_share, sizeof(intType) * s2 * s3);
}
else if (SCI_party == sci::BOB)
{
io->recv_data(E_temp_share, sizeof(intType) * s1 * s2);
io->recv_data(F_temp_share, sizeof(intType) * s2 * s3);
io->send_data(E_share, sizeof(intType) * s1 * s2);
io->send_data(F_share, sizeof(intType) * s2 * s3);
}
else
{
assert(false);
}
// Add the shares of E and F to get E and F in the clear
sci::elemWiseAdd<intType>(s1 * s2, E_share, E_temp_share, E_share);
sci::elemWiseAdd<intType>(s2 * s3, F_share, F_temp_share, F_share);
// Now E_share and F_share hold the clear values of E & F
ideal_func(s1, s2, s3, E_share, Y_share, Z_temp_share);
if (SCI_party == sci::ALICE)
{
ideal_func(s1, s2, s3, X_share, F_share, Z_share);
}
else if (SCI_party == sci::BOB)
{
sci::elemWiseSub<intType>(s1 * s2, X_share, E_share, E_temp_share);
ideal_func(s1, s2, s3, E_temp_share, F_share, Z_share);
}
sci::elemWiseAdd<intType>(s1 * s3, Z_share, Z_temp_share, Z_share);
sci::elemWiseAdd<intType>(s1 * s3, C_share, Z_share, Z_share);
delete[] E_share;
delete[] F_share;
delete[] E_temp_share;
delete[] F_temp_share;
delete[] Z_temp_share;
}
};
#endif // LINEAR_UNIFORM_H__
|
[
"smog70151@gmail.com"
] |
smog70151@gmail.com
|
1194ac0326682b90ad1fea35b43cdc3e69f9905e
|
f31c0986ebc80731362a136f99bb6be461690440
|
/src/WorkLayer/ClientCredits.h
|
6bfb7cc24807bb34c24182144b38ce318dc72e2c
|
[] |
no_license
|
witeyou/easyMule
|
9c3e0af72c49f754704f029a6c3c609f7300811a
|
ac91abd9cdf35dd5bb697e175e8d07a89c496944
|
refs/heads/master
| 2023-03-30T16:19:27.200126
| 2021-03-26T12:22:52
| 2021-03-26T12:22:52
| 351,774,027
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,093
|
h
|
/*
* $Id: ClientCredits.h 5577 2008-05-20 09:20:25Z huby $
*
* this file is part of eMule
* Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#pragma once
#include "MapKey.h"
#pragma warning(disable:4516) // access-declarations are deprecated; member using-declarations provide a better alternative
#pragma warning(disable:4244) // conversion from 'type1' to 'type2', possible loss of data
#pragma warning(disable:4100) // unreferenced formal parameter
#pragma warning(disable:4702) // unreachable code
#include <crypto/rsa.h>
#pragma warning(default:4702) // unreachable code
#pragma warning(default:4100) // unreferenced formal parameter
#pragma warning(default:4244) // conversion from 'type1' to 'type2', possible loss of data
#pragma warning(default:4516) // access-declarations are deprecated; member using-declarations provide a better alternative
#define MAXPUBKEYSIZE 80
#define CRYPT_CIP_REMOTECLIENT 10
#define CRYPT_CIP_LOCALCLIENT 20
#define CRYPT_CIP_NONECLIENT 30
#pragma pack(1)
struct CreditStruct_29a{
uchar abyKey[16];
uint32 nUploadedLo; // uploaded TO him
uint32 nDownloadedLo; // downloaded from him
uint32 nLastSeen;
uint32 nUploadedHi; // upload high 32
uint32 nDownloadedHi; // download high 32
uint16 nReserved3;
};
struct CreditStruct{
uchar abyKey[16];
uint32 nUploadedLo; // uploaded TO him
uint32 nDownloadedLo; // downloaded from him
uint32 nLastSeen;
uint32 nUploadedHi; // upload high 32
uint32 nDownloadedHi; // download high 32
uint16 nReserved3;
uint8 nKeySize;
uchar abySecureIdent[MAXPUBKEYSIZE];
};
#pragma pack()
enum EIdentState{
IS_NOTAVAILABLE,
IS_IDNEEDED,
IS_IDENTIFIED,
IS_IDFAILED,
IS_IDBADGUY,
};
class CClientCredits
{
friend class CClientCreditsList;
public:
CClientCredits(CreditStruct* in_credits);
CClientCredits(const uchar* key);
~CClientCredits();
const uchar* GetKey() const {return m_pCredits->abyKey;}
uchar* GetSecureIdent() {return m_abyPublicKey;}
uint8 GetSecIDKeyLen() const {return m_nPublicKeyLen;}
CreditStruct* GetDataStruct() const {return m_pCredits;}
void ClearWaitStartTime();
void AddDownloaded(uint32 bytes, uint32 dwForIP);
void AddUploaded(uint32 bytes, uint32 dwForIP);
uint64 GetUploadedTotal() const;
uint64 GetDownloadedTotal() const;
float GetScoreRatio(uint32 dwForIP) const;
void SetLastSeen() {m_pCredits->nLastSeen = time(NULL);}
bool SetSecureIdent(const uchar* pachIdent, uint8 nIdentLen); // Public key cannot change, use only if there is not public key yet
uint32 m_dwCryptRndChallengeFor;
uint32 m_dwCryptRndChallengeFrom;
EIdentState GetCurrentIdentState(uint32 dwForIP) const; // can be != IdentState
uint32 GetSecureWaitStartTime(uint32 dwForIP);
void SetSecWaitStartTime(uint32 dwForIP);
protected:
void Verified(uint32 dwForIP);
EIdentState IdentState;
private:
void InitalizeIdent();
CreditStruct* m_pCredits;
byte m_abyPublicKey[80]; // even keys which are not verified will be stored here, and - if verified - copied into the struct
uint8 m_nPublicKeyLen;
uint32 m_dwIdentIP;
uint32 m_dwSecureWaitTime;
uint32 m_dwUnSecureWaitTime;
uint32 m_dwWaitTimeIP; // client IP assigned to the waittime
};
class CClientCreditsList
{
public:
CClientCreditsList();
~CClientCreditsList();
// return signature size, 0 = Failed | use sigkey param for debug only
uint8 CreateSignature(CClientCredits* pTarget, uchar* pachOutput, uint8 nMaxSize, uint32 ChallengeIP, uint8 byChaIPKind, CryptoPP::RSASSA_PKCS1v15_SHA_Signer* sigkey = NULL);
bool VerifyIdent(CClientCredits* pTarget, const uchar* pachSignature, uint8 nInputSize, uint32 dwForIP, uint8 byChaIPKind);
CClientCredits* GetCredit(const uchar* key) ;
void Process();
uint8 GetPubKeyLen() const {return m_nMyPublicKeyLen;}
byte* GetPublicKey() {return m_abyMyPublicKey;}
bool CryptoAvailable();
protected:
void LoadList( bool bFromBakFile=false );
void SaveList();
void InitalizeCrypting();
bool CreateKeyPair();
void OnCorruptedFile(LPCTSTR lpszPathFile);
#ifdef _DEBUG
bool Debug_CheckCrypting();
#endif
private:
CMap<CCKey, const CCKey&, CClientCredits*, CClientCredits*> m_mapClients;
uint32 m_nLastSaved;
CryptoPP::RSASSA_PKCS1v15_SHA_Signer* m_pSignkey;
byte m_abyMyPublicKey[80];
uint8 m_nMyPublicKeyLen;
};
|
[
"1171838741@qq.com"
] |
1171838741@qq.com
|
b26b93ed73ef5357c27c8991e4fa248a2e95afff
|
08b8cf38e1936e8cec27f84af0d3727321cec9c4
|
/data/crawl/wget/old_hunk_2623.cpp
|
899afdc074d208f97946109ac0e41162ab371a6a
|
[] |
no_license
|
ccdxc/logSurvey
|
eaf28e9c2d6307140b17986d5c05106d1fd8e943
|
6b80226e1667c1e0760ab39160893ee19b0e9fb1
|
refs/heads/master
| 2022-01-07T21:31:55.446839
| 2018-04-21T14:12:43
| 2018-04-21T14:12:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 137
|
cpp
|
file);
if (unlink (file))
logprintf (LOG_NOTQUIET, "unlink: %s\n", strerror (errno));
register_delete_file (file);
}
|
[
"993273596@qq.com"
] |
993273596@qq.com
|
d48d6d859f34eef2fa3610d21d1c699df534b8c8
|
92235f47acfb1b2258d4627f92d7f87a8cd70fb9
|
/viennacl/linalg/host_based/gemm_sse_micro_kernel.hpp
|
0ebf03a29ec267d141af82f41f3083e4f9afeaaa
|
[
"MIT"
] |
permissive
|
Fritzkefit/viennacl-dev
|
2c61eda4d226f8343ff5d3c449d9fbfc4932aa58
|
c1d44d77e9d6b6bac139a94def43902d10668229
|
refs/heads/master
| 2021-01-16T18:42:44.325976
| 2015-11-15T23:01:29
| 2015-11-15T23:01:29
| 40,937,663
| 0
| 0
| null | 2015-08-17T23:43:38
| 2015-08-17T23:43:38
| null |
UTF-8
|
C++
| false
| false
| 8,653
|
hpp
|
#ifndef VIENNACL_LINALG_HOST_BASED_GEMM_SSE_MICRO_KERNEL_HPP_
#define VIENNACL_LINALG_HOST_BASED_GEMM_SSE_MICRO_KERNEL_HPP_
#include "viennacl/linalg/host_based/common.hpp"
#include "immintrin.h"
/* register-block sizes:
* D := double, F := float */
#define MR_D (6)
#define NR_D (4)
#define MR_F (8)
#define NR_F (8)
/* addresses for buffer_C */
#define C0_ROW_D(a) (a*NR_D)
#define C1_ROW_D(a) (a*NR_D + NR_D/2)
#define C0_ROW_F(a) (a*NR_F)
#define C1_ROW_F(a) (a*NR_F + NR_F/2)
namespace viennacl
{
/**
* @brief general "dummy" template, fully specialized for supported types (double/float)
*/
template<typename NumericT>
inline void sse_micro_kernel(NumericT const *buffer_A, NumericT const *buffer_B, NumericT *buffer_C,
vcl_size_t num_micro_slivers, vcl_size_t mr, vcl_size_t nr)
{
assert(false && bool("called with unsupported numeric type!"));
}
/**
* @brief SSE micro-kernel for floats, calculates a 8x8 block of matrix C from slivers of A and B
*/
template<>
inline void sse_micro_kernel<float>(float const *buffer_A, float const *buffer_B, float *buffer_C,
vcl_size_t num_micro_slivers, vcl_size_t mr, vcl_size_t nr)
{
assert( (mr == MR_F) && (nr == NR_F) && bool("mr and nr obtained by 'get_block_sizes()' in 'matrix_operations.hpp' and given to 'avx_micro_kernel()' do not match with MR_F/NR_F defined in 'gemm_avx_micro_kernel.hpp' ") );
__m128 xmm0 , xmm1 , xmm2 , xmm3 ;
__m128 xmm4 , xmm5 , xmm6 , xmm7 ;
__m128 xmm8 , xmm9 , xmm10, xmm11;
__m128 xmm12, xmm13, xmm14, xmm15;
for (vcl_size_t l=0; l<num_micro_slivers; ++l)
{
xmm0 = _mm_load_ps(buffer_B+l*NR_F);
xmm1 = _mm_load_ps(buffer_B+l*NR_F+4);
xmm2 = _mm_load_ps1(buffer_A+l*MR_F);
xmm3 = _mm_mul_ps(xmm0, xmm2);
xmm4 = _mm_mul_ps(xmm1, xmm2);
xmm2 = _mm_load_ps1(buffer_A+l*MR_F+1);
xmm5 = _mm_mul_ps(xmm0, xmm2);
xmm6 = _mm_mul_ps(xmm1, xmm2);
xmm2 = _mm_load_ps1(buffer_A+l*MR_F+2);
xmm7 = _mm_mul_ps(xmm0, xmm2);
xmm8 = _mm_mul_ps(xmm1, xmm2);
xmm2 = _mm_load_ps1(buffer_A+l*MR_F+3);
xmm9 = _mm_mul_ps(xmm0, xmm2);
xmm10 = _mm_mul_ps(xmm1, xmm2);
xmm2 = _mm_load_ps1(buffer_A+l*MR_F+4);
xmm11 = _mm_mul_ps(xmm0, xmm2);
xmm12 = _mm_mul_ps(xmm1, xmm2);
xmm2 = _mm_load_ps1(buffer_A+l*MR_F+5);
xmm13 = _mm_mul_ps(xmm0, xmm2);
xmm14 = _mm_mul_ps(xmm1, xmm2);
/* free registers by storing their results */
xmm15 = _mm_load_ps(buffer_C+C0_ROW_F(0));
xmm15 = _mm_add_ps(xmm15, xmm3);
_mm_store_ps(buffer_C+C0_ROW_F(0), xmm15);
xmm15 = _mm_load_ps(buffer_C+C1_ROW_F(0));
xmm15 = _mm_add_ps(xmm15, xmm4);
_mm_store_ps(buffer_C+C1_ROW_F(0), xmm15);
/* continue calculating */
xmm2 = _mm_load_ps1(buffer_A+l*MR_F+6);
xmm3 = _mm_mul_ps(xmm0, xmm2);
xmm4 = _mm_mul_ps(xmm1, xmm2);
/* free registers by storing their results */
xmm15 = _mm_load_ps(buffer_C+C0_ROW_F(1));
xmm15 = _mm_add_ps(xmm15, xmm5);
_mm_store_ps(buffer_C+C0_ROW_F(1), xmm15);
xmm15 = _mm_load_ps(buffer_C+C1_ROW_F(1));
xmm15 = _mm_add_ps(xmm15, xmm6);
_mm_store_ps(buffer_C+C1_ROW_F(1), xmm15);
/* continue calculating */
xmm2 = _mm_load_ps1(buffer_A+l*MR_F+7);
xmm5 = _mm_mul_ps(xmm0, xmm2);
xmm6 = _mm_mul_ps(xmm1, xmm2);
/* store the rest of the results */
xmm15 = _mm_load_ps(buffer_C+C0_ROW_F(2));
xmm15 = _mm_add_ps(xmm15, xmm7);
_mm_store_ps(buffer_C+C0_ROW_F(2), xmm15);
xmm15 = _mm_load_ps(buffer_C+C1_ROW_F(2));
xmm15 = _mm_add_ps(xmm15, xmm8);
_mm_store_ps(buffer_C+C1_ROW_F(2), xmm15);
xmm15 = _mm_load_ps(buffer_C+C0_ROW_F(3));
xmm15 = _mm_add_ps(xmm15, xmm9);
_mm_store_ps(buffer_C+C0_ROW_F(3), xmm15);
xmm15 = _mm_load_ps(buffer_C+C1_ROW_F(3));
xmm15 = _mm_add_ps(xmm15, xmm10);
_mm_store_ps(buffer_C+C1_ROW_F(3), xmm15);
xmm15 = _mm_load_ps(buffer_C+C0_ROW_F(4));
xmm15 = _mm_add_ps(xmm15, xmm11);
_mm_store_ps(buffer_C+C0_ROW_F(4), xmm15);
xmm15 = _mm_load_ps(buffer_C+C1_ROW_F(4));
xmm15 = _mm_add_ps(xmm15, xmm12);
_mm_store_ps(buffer_C+C1_ROW_F(4), xmm15);
xmm15 = _mm_load_ps(buffer_C+C0_ROW_F(5));
xmm15 = _mm_add_ps(xmm15, xmm13);
_mm_store_ps(buffer_C+C0_ROW_F(5), xmm15);
xmm15 = _mm_load_ps(buffer_C+C1_ROW_F(5));
xmm15 = _mm_add_ps(xmm15, xmm14);
_mm_store_ps(buffer_C+C1_ROW_F(5), xmm15);
xmm15 = _mm_load_ps(buffer_C+C0_ROW_F(6));
xmm15 = _mm_add_ps(xmm15, xmm3);
_mm_store_ps(buffer_C+C0_ROW_F(6), xmm15);
xmm15 = _mm_load_ps(buffer_C+C1_ROW_F(6));
xmm15 = _mm_add_ps(xmm15, xmm4);
_mm_store_ps(buffer_C+C1_ROW_F(6), xmm15);
xmm15 = _mm_load_ps(buffer_C+C0_ROW_F(7));
xmm15 = _mm_add_ps(xmm15, xmm5);
_mm_store_ps(buffer_C+C0_ROW_F(7), xmm15);
xmm15 = _mm_load_ps(buffer_C+C1_ROW_F(7));
xmm15 = _mm_add_ps(xmm15, xmm6);
_mm_store_ps(buffer_C+C1_ROW_F(7), xmm15);
}//for
}//sse_micro_kernel()
/**
* @brief SSE micro-kernel for doubles, calculates a 6x4 block of matrix C from slivers of A and B
*/
template<>
inline void sse_micro_kernel<double>(double const *buffer_A, double const *buffer_B, double *buffer_C,
vcl_size_t num_micro_slivers, vcl_size_t mr, vcl_size_t nr)
{
assert( (mr == MR_D) && (nr == NR_D) && bool("mr and nr obtained by 'get_block_sizes()' in 'matrix_operations.hpp' and given to 'avx_micro_kernel()' do not match with MR_D/NR_D defined in 'gemm_avx_micro_kernel.hpp' ") );
__m128d xmm0 , xmm1 , xmm2 , xmm3 ;
__m128d xmm4 , xmm5 , xmm6 , xmm7 ;
__m128d xmm8 , xmm9 , xmm10, xmm11;
__m128d xmm12, xmm13, xmm14, xmm15;
vcl_size_t l;
for (l=0; l<num_micro_slivers; ++l)
{
xmm0 = _mm_load_pd(buffer_B+l*NR_D);
xmm1 = _mm_load_pd(buffer_B+l*NR_D+2);
xmm2 = _mm_load_pd1(buffer_A+l*MR_D);
xmm3 = _mm_mul_pd(xmm0, xmm2);
xmm4 = _mm_mul_pd(xmm1, xmm2);
xmm2 = _mm_load_pd1(buffer_A+l*MR_D+1);
xmm5 = _mm_mul_pd(xmm0, xmm2);
xmm6 = _mm_mul_pd(xmm1, xmm2);
xmm2 = _mm_load_pd1(buffer_A+l*MR_D+2);
xmm7 = _mm_mul_pd(xmm0, xmm2);
xmm8 = _mm_mul_pd(xmm1, xmm2);
xmm2 = _mm_load_pd1(buffer_A+l*MR_D+3);
xmm9 = _mm_mul_pd(xmm0, xmm2);
xmm10 = _mm_mul_pd(xmm1, xmm2);
xmm2 = _mm_load_pd1(buffer_A+l*MR_D+4);
xmm11 = _mm_mul_pd(xmm0, xmm2);
xmm12 = _mm_mul_pd(xmm1, xmm2);
xmm2 = _mm_load_pd1(buffer_A+l*MR_D+5);
xmm13 = _mm_mul_pd(xmm0, xmm2);
xmm14 = _mm_mul_pd(xmm1, xmm2);
/* store new entries */
xmm15 = _mm_load_pd(buffer_C+C0_ROW_D(0));
xmm15 = _mm_add_pd(xmm15, xmm3);
_mm_store_pd(buffer_C+C0_ROW_D(0), xmm15);
xmm15 = _mm_load_pd(buffer_C+C1_ROW_D(0));
xmm15 = _mm_add_pd(xmm15, xmm4);
_mm_store_pd(buffer_C+C1_ROW_D(0), xmm15);
xmm15 = _mm_load_pd(buffer_C+C0_ROW_D(1));
xmm15 = _mm_add_pd(xmm15, xmm5);
_mm_store_pd(buffer_C+C0_ROW_D(1), xmm15);
xmm15 = _mm_load_pd(buffer_C+C1_ROW_D(1));
xmm15 = _mm_add_pd(xmm15, xmm6);
_mm_store_pd(buffer_C+C1_ROW_D(1), xmm15);
xmm15 = _mm_load_pd(buffer_C+C0_ROW_D(2));
xmm15 = _mm_add_pd(xmm15, xmm7);
_mm_store_pd(buffer_C+C0_ROW_D(2), xmm15);
xmm15 = _mm_load_pd(buffer_C+C1_ROW_D(2));
xmm15 = _mm_add_pd(xmm15, xmm8);
_mm_store_pd(buffer_C+C1_ROW_D(2), xmm15);
xmm15 = _mm_load_pd(buffer_C+C0_ROW_D(3));
xmm15 = _mm_add_pd(xmm15, xmm9);
_mm_store_pd(buffer_C+C0_ROW_D(3), xmm15);
xmm15 = _mm_load_pd(buffer_C+C1_ROW_D(3));
xmm15 = _mm_add_pd(xmm15, xmm10);
_mm_store_pd(buffer_C+C1_ROW_D(3), xmm15);
xmm15 = _mm_load_pd(buffer_C+C0_ROW_D(4));
xmm15 = _mm_add_pd(xmm15, xmm11);
_mm_store_pd(buffer_C+C0_ROW_D(4), xmm15);
xmm15 = _mm_load_pd(buffer_C+C1_ROW_D(4));
xmm15 = _mm_add_pd(xmm15, xmm12);
_mm_store_pd(buffer_C+C1_ROW_D(4), xmm15);
xmm15 = _mm_load_pd(buffer_C+C0_ROW_D(5));
xmm15 = _mm_add_pd(xmm15, xmm13);
_mm_store_pd(buffer_C+C0_ROW_D(5), xmm15);
xmm15 = _mm_load_pd(buffer_C+C1_ROW_D(5));
xmm15 = _mm_add_pd(xmm15, xmm14);
_mm_store_pd(buffer_C+C1_ROW_D(5), xmm15);
}//for
}//sse_micro_kernel<double>
}//viennacl
#endif
|
[
"e1125349@student.tuwien.ac.at"
] |
e1125349@student.tuwien.ac.at
|
36bc8de279ea2fd248a02cc85a5ff4c5fa4d5645
|
25edf5af35ca5f7d7b12846ded53a59739c1cce2
|
/lab/5/testzoolist_partial/utility.h
|
d459a3d54449c2ff45be1950b866981827d93673
|
[] |
no_license
|
whanata/dsa-activities
|
14ebb0b920a51bc23db74df9780b64eeaa2a964e
|
97c4ee19f3749fd283eb5f184d680803ab1d1ba7
|
refs/heads/master
| 2021-01-21T12:59:36.185071
| 2016-05-03T05:39:31
| 2016-05-03T05:39:31
| 53,576,131
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 819
|
h
|
#ifndef _UTILITY_H
#define _UTILITY_H
#include <fstream>
#include <string.h>
using namespace std;
bool readline(ifstream &fin, char *line, int linesize, char delim)
{
// the problem
// Unix ends text lines with \n
// Mac ends with \r
// Windows ends with \r\n
// getline does not include the final delimiter
// BUT, it will leave the \r from a windows file.
// This means a line read with getline from a windows text file
// will have an additional \r tacked to the end of the line.
// This is very annoying!!!!
if (fin.eof()) return false;
fin.getline(line, linesize, delim);
// check for \r and get rid of it
if (!fin.good()) return false;
int last = strlen(line) - 1;
if (line >= 0 && line[last] == '\r') line[last] = '\0';
return true;
}
#endif
|
[
"whanata@gmail.com"
] |
whanata@gmail.com
|
fbeabfbdbee69edc15f390c466d42586702c42ff
|
7fc9d6c59c6a40d7bb3fa40a7d89f896753d25ee
|
/bzoj/2746.cpp
|
feca2b023da45ec0d7487606bc1dc60d089299b8
|
[] |
no_license
|
yzcmf/oicode
|
902116f8d50c870e1a251083c6421c4563bab4fa
|
69d687e267a54ca64fc957595ef5327de37c005a
|
refs/heads/master
| 2020-07-25T14:17:00.186895
| 2016-08-08T03:07:15
| 2016-08-08T03:07:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,121
|
cpp
|
/* BZOJ-2746: [HEOI2012]旅行问题
* AC自动机+倍增LCA */
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <algorithm>
const int mod_v = 1000000007;
const int MaxN = 1000010, MaxAlpha = 26, MaxL = 20;
typedef std::vector<int> describe_t;
struct node_t
{
int hash;
int fail, ch[MaxAlpha];
} node[MaxN];
int used = 1;
int dist[MaxL][MaxN], depth[MaxN];
char str[MaxN];
describe_t *describe;
void add_string(const char* str, describe_t* desc)
{
int now = 1;
for(int i = 0; str[i]; ++i)
{
int x = str[i] - 'a';
if(!node[now].ch[x])
{
node[now].ch[x] = ++used;
node[used].hash = (1ll * node[now].hash * MaxAlpha + x) % mod_v;
}
now = node[now].ch[x];
desc->push_back(now);
}
}
void make_fail()
{
int *que = new int[used];
int qhead = 0, qtail = 0;
que[qtail++] = 1;
while(qhead != qtail)
{
int now = que[qhead++];
dist[0][now] = node[now].fail;
depth[now] = depth[node[now].fail] + 1;
for(int l = 1; l != MaxL; ++l)
dist[l][now] = dist[l - 1][dist[l - 1][now]];
for(int i = 0; i != MaxAlpha; ++i)
{
int u = node[now].ch[i];
if(!u) continue;
int z = node[now].fail;
for(; z && !node[z].ch[i]; z = node[z].fail);
if(!z) node[u].fail = 1;
else node[u].fail = node[z].ch[i];
que[qtail++] = u;
}
}
delete[] que;
}
int get_lca(int u, int v)
{
if(depth[u] < depth[v])
std::swap(u, v);
int diff = depth[u] - depth[v];
for(int i = 0; diff; ++i, diff >>= 1)
if(diff & 1) u = dist[i][u];
for(int p = MaxL - 1; u != v; p ? --p : 0)
{
if(!p || dist[p][u] != dist[p][v])
{
u = dist[p][u];
v = dist[p][v];
}
}
return u;
}
int main()
{
int n, m;
std::scanf("%d", &n);
describe = new describe_t[n];
for(int i = 0; i != n; ++i)
{
std::scanf("%s", str);
add_string(str, describe + i);
}
make_fail();
std::scanf("%d", &m);
for(int i = 0; i != m; ++i)
{
int a, b, c, d;
std::scanf("%d %d %d %d", &a, &b, &c, &d);
int u = describe[a - 1][b - 1];
int v = describe[c - 1][d - 1];
int lca = get_lca(u, v);
std::printf("%d\n", node[lca].hash);
}
delete[] describe;
return 0;
}
|
[
"miskcoo@gmail.com"
] |
miskcoo@gmail.com
|
e0f34b28e8c173e98ca5e4c7e8af9d468fc9b04f
|
ad48248020176912cb6190c85db85bcb47201cd1
|
/Loong/LoongCore/include/LoongCore/scene/components/LoongCCamera.h
|
4dce3366b02d0d4d92460d5cccd2b7d0d7bf3c33
|
[
"Apache-2.0"
] |
permissive
|
carlcc/Loong
|
f2d77c3fa465f4e9c99c113d0c0fee35ca11d6e4
|
577e89b436eb0e5899295c95ee4587c0270cea94
|
refs/heads/master
| 2023-02-01T21:56:49.343306
| 2020-12-20T09:08:07
| 2020-12-20T09:08:07
| 268,041,564
| 9
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,213
|
h
|
//
// Copyright (c) 2020 Carl Chen. All rights reserved.
//
#pragma once
#include "LoongCore/scene/LoongComponent.h"
#include "LoongRenderer/LoongCamera.h"
namespace Loong::Core {
class LoongCCamera final : public LoongComponent {
public:
explicit LoongCCamera(LoongActor* owner);
~LoongCCamera() override;
const std::string& GetName() override
{
static const std::string kName("Camera");
return kName;
}
void SetFov(float value)
{
camera_.SetFov(Math::Clamp(value, 0.0F, float(Math::Pi)));
}
void SetNear(float value)
{
camera_.SetNear(Math::Clamp(value, 0.01F, GetFar()));
}
void SetFar(float value)
{
camera_.SetFar(Math::Max(value, GetNear()));
}
void SetClearColor(const Math::Vector3& clearColor) { camera_.SetClearColor(clearColor); }
float GetFov() const { return camera_.GetFov(); }
float GetNear() const { return camera_.GetNear(); }
float GetFar() const { return camera_.GetFar(); }
const Math::Vector3& GetClearColor() const { return camera_.GetClearColor(); }
Renderer::LoongCamera& GetCamera() { return camera_; }
private:
Renderer::LoongCamera camera_;
};
}
|
[
"carlmarxchen@foxmail.com"
] |
carlmarxchen@foxmail.com
|
0868122d064a8947679e49bfb1eeaed467fa8281
|
7d2f5e2795493e3d69eeebcd9f3d462b0ad491be
|
/GenXIntrinsics/include/llvmVCWrapper/IR/GlobalValue.h
|
98a88f3a0834f52f616ba047e063f55ba77439db
|
[
"MIT"
] |
permissive
|
zuban32/vc-intrinsics
|
bdfc163617de68da5c578d2c8ed5d2f3d9e57c3c
|
c05825063e4e0e41a8cefa8bb79f17204c2be3a5
|
refs/heads/master
| 2023-03-26T21:54:52.210419
| 2021-03-11T12:16:28
| 2021-03-17T15:33:21
| 274,940,100
| 0
| 0
|
MIT
| 2020-06-25T14:39:20
| 2020-06-25T14:39:20
| null |
UTF-8
|
C++
| false
| false
| 1,666
|
h
|
/*===================== begin_copyright_notice ==================================
Copyright (c) 2020, Intel Corporation
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.
======================= end_copyright_notice ==================================*/
#ifndef VCINTR_IR_GLOBALVALUE_H
#define VCINTR_IR_GLOBALVALUE_H
#include <llvm/IR/GlobalValue.h>
namespace VCINTR {
namespace GlobalValue {
inline unsigned getAddressSpace(const llvm::GlobalValue &GV) {
#if VC_INTR_LLVM_VERSION_MAJOR <= 7
return GV.getType()->getAddressSpace();
#else
return GV.getAddressSpace();
#endif
}
} // namespace GlobalValue
} // namespace VCINTR
#endif // VCINTR_IR_GLOBALVARIABLE_H
|
[
"konstantin.vladimirov@intel.com"
] |
konstantin.vladimirov@intel.com
|
2310f86450914767af4505ae6e2bea4256315c07
|
5954dd2e2efa1b7da4165136fa56b286fd9d5638
|
/17_Console/Function.h
|
82f5478f6a2ecccc6f64e07c97c8a598a83f22d5
|
[] |
no_license
|
zhmmmm/Public
|
466b4519dafcf2b2d1c82a039006928b344248c0
|
f8b895c28c7cc7b75de5492aed4da9b0702225f7
|
refs/heads/master
| 2020-03-30T23:58:40.450316
| 2018-10-22T14:19:43
| 2018-10-22T14:19:43
| 151,713,632
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,135
|
h
|
#pragma once
#include <list>
//功能性
//struct Bullet
//{
// int X;
// int Y;
//};
////链表型的子弹
//std::list<Bullet> mBullet;
//if (true)//某键按下
//{
// Bullet Temp;//新建一个子弹
// Temp.X = 0;//子弹的当前位置
// Temp.Y = 0;
// mBullet.push_back(Temp);//把新建好的子弹存入链表
//}
////逻辑更新
//for (std::list<Bullet>::iterator i = mBullet.begin(); i != mBullet.end(); i++)//遍历链表中的所有的子弹
//{
// if (true)
// {
// i = mBullet.erase(i);//越界的子弹释放
// }
// else//未越界的子弹继续移动
// {
// i->Y++;
// }
//}
////绘制
//for (std::list<Bullet>::iterator i = mBullet.begin(); i != mBullet.end(); i++)//遍历链表中的所有的子弹
//{
// //通过i->Y,i->X 作为左边来绘制
//}
void ___Number(int *Num,int *Number)
{
int Add_10 = 10;
int i = 0;
int Arr[256] = { 0 };
int Arr_10 = 1;
while (true)
{
int Temp = (*Num) % Add_10;
Arr[i] = Temp / Arr_10;
(*Num) -= Temp;
Add_10 *= 10;
i++;
if ((*Num) == 0) { break; }
Arr_10 *= 10;
}
for (int j = 0; j < i; j++)
{
(*Number) += (Arr[j] * Arr_10);
Arr_10 /= 10;
}
}
|
[
"15982683979@163.com"
] |
15982683979@163.com
|
a7b08f8b17266bf8e1fdda69106beb085b437b49
|
5a07933eda39f8463cc0b06087e5b875bb9293d3
|
/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.h
|
9b6b259decaef1af61f151ff43301b6b2477109b
|
[
"Apache-2.0"
] |
permissive
|
codeblooded/grpc
|
4bd818c02b74e119dd75c4681bf9359cc696c5e2
|
e11c486c6a6d6f24bc1cc4cd0cb76bce57404ca5
|
refs/heads/master
| 2021-06-27T20:29:38.995197
| 2020-05-11T23:26:16
| 2020-05-11T23:26:16
| 236,610,890
| 3
| 0
|
Apache-2.0
| 2020-10-22T06:43:42
| 2020-01-27T22:36:20
|
C++
|
UTF-8
|
C++
| false
| false
| 1,493
|
h
|
//
// Copyright 2019 gRPC authors.
//
// 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 GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_BALANCER_ADDRESSES_H
#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_BALANCER_ADDRESSES_H
#include <grpc/support/port_platform.h>
#include <grpc/impl/codegen/grpc_types.h>
#include "src/core/ext/filters/client_channel/server_address.h"
namespace grpc_core {
grpc_arg CreateGrpclbBalancerAddressesArg(
const ServerAddressList* address_list);
const ServerAddressList* FindGrpclbBalancerAddressesInChannelArgs(
const grpc_channel_args& args);
grpc_arg CreateGrpclbBalancerNameArg(const char* balancer_name);
const char* FindGrpclbBalancerNameInChannelArgs(const grpc_channel_args& args);
} // namespace grpc_core
#endif /* \
GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_BALANCER_ADDRESSES_H \
*/
|
[
"roth@google.com"
] |
roth@google.com
|
56d6c4f91b0d3e1fce5c41df394692114f1067db
|
8ca7e4b6a56a0a969e3ff56226ae632193b98017
|
/main.cpp
|
27b65e5f02fd8bfe6f254e34e7df76f487044fd3
|
[] |
no_license
|
YunkeXiao/CP-Template
|
af1f80618c3fc6ac43469ab8dee40bb6de765ab9
|
9d6fbf3f9b33c6fa3b2a23b68af0845a2eea1b10
|
refs/heads/master
| 2020-07-27T14:51:32.438272
| 2019-09-26T19:45:22
| 2019-09-26T19:45:22
| 209,131,090
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,438
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
#define vi vector<int>
#define ii pair<int,int>
#define iii pair<int,pair<int,int>>
#define vii vector<pair<int,int>>
#define vvi vector<vector<int>>
typedef long long ll;
typedef unsigned long long ull;
typedef unordered_map<ll, ll> ump;
typedef map<ll, ll> mp;
typedef unordered_set<ll> uset;
#define pb push_back
#define mp make_pair
#define fi first
#define se second
//**************************************** GRAPH ******************************************
//**********DSU**********
ll findp(ll v, ll plist[], ll slist[]) {
if (plist[v] == v) {
return v;
} else {
plist[v] = findp(plist[v], plist, slist);
return plist[v];
}
}
bool unionp(ll a, ll b, ll plist[], ll slist[]) {
ll ap = findp(a, plist, slist), bp = findp(b, plist, slist);
if (ap == bp) {
return false;
}
plist[bp] = ap;
slist[ap] += slist[bp];
return true;
}
//**********dijkstra*********
//adj is start->end->value
vector<ll> dijkstra(int start, vector<vector<pair<ll, ll>>> adj
// ,vector<int> & p
) {
const int INF = 1000000000;
ll n = (ll) adj.size();
vector<ll> d;
d.assign((unsigned long) n, INF);
// p.assign(n, -1);
d[start] = 0;
set<pair<ll, ll>> q;
q.insert({0, start});
while (!q.empty()) {
ll v = q.begin()->second;
q.erase(q.begin());
for (auto edge : adj[v]) {
ll to = edge.first;
ll len = edge.second;
if (d[v] + len < d[to]) {
q.erase({d[to], to});
d[to] = d[v] + len;
// p[to] = v;
q.insert({d[to], to});
}
}
}
return d;
}
//**************************************** MATH ******************************************
//**********Powerset**********
vvi powerSet(int set[], int set_size) {
ll pow_set_size = (ll) pow(2, set_size);
int counter, j;
vvi output;
for (ll count = 0; count < pow_set_size; count++) {
vi comb;
for (j = 0; j < set_size; j++) {
if ((count >> j) & 1) {
comb.pb(set[j]);
}
}
output.pb(comb);
}
return output;
}
//**********N choose K**********
ll nck(ll n, ll k) {
ll out = n;
if (k > n) return 0;
if (k * 2 > n) k = n - k;
if (k == 0) return 1;
for (int i = 2; i <= k; i++) {
out *= (n - i + 1);
out /= i;
}
return out;
}
//**********sieve**********
//If prime factor, if case is prime, endloop != 1, add endloop value to list
vi sieve(ll n) {
ll size = n + 10;
bitset<10000010> p;
vi primes;
p.set();
p[0] = p[1] = false;
for (ll i = 2; i <= size; i++) {
if (p[i]) {
for (ll j = i * 2; j <= size; j += i) { p[j] = false; }
primes.pb((int) i);
}
}
return primes;
}
//**********isPrime**********
bool isPrime(ll n) {
// Sieve (Modify size for max)
ll size = n + 10;
bitset<10000010> bs;
vi primes;
bs.set();
bs[0] = bs[1] = false;
for (ll i = 2; i <= size; i++) {
if (bs[i]) {
for (ll j = i * i; j <= size; j *= i) { bs[j] = false; }
primes.pb((int) i);
}
}
if (n <= 10000010) { return bs[n]; }
for (int i = 0; i < (int) primes.size(); i++) { if (n % primes[i] == 0) { return false; }}
return true;
};
//**********modpow***********
ll modpow(ll n, ll e, ll mod) {
ll output = 1, x = n % mod, y = e;
while (y > 0) {
if (y & 1) { output = (output * x) % mod; }
y = y >> 1;
x = (x * x) % mod;
}
return output;
}
//**********GCD/LCM**********
// GCD(a, b, c) = GCD(a, GCD(b, c))
ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); }
ll lcm(ll a, ll b) { return a * (b / gcd(a, b)); }
//*********************************************************************************************************************
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
return 0;
}
/*
⠶⣿⣭⡧⡤⣤⣻⣛⣹⣿⣿⣿⣶⣄
⣼⣊⣤⣶⣷⣶⣧⣤⣽⣿⣿⣿⣿⣿⣿⣷
⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇
⢀⣠⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧
⠸⠿⣿⣿⠿⣿⣿⣿⣿⣿⣿⣿⡿⣿⣻⣿⣿⣿⣿⣿⡆
⢸⣿⣿⡀⠘⣿⡿⢿⣿⣿⡟⣾⣿⣯⣽⣼⣿⣿⣿⣿⡀
⢀⡠⠚⢛⣛⣃⢄⡁⢀⢀⢀⠈⠁⠛⠛⠛⠛⠚⠻⣿⣿⣿⣷
⣴⣶⣶⣶⣷⡄⠊⠉⢻⣟⠃⢀⢀⢀⢀⡠⠔⠒⢀ ⢀ ⢀ ⢀⢹⣿⣿⣿⣄
⢠⣾⣿⣿⣿⣿⣿⣿⣿⣶⣄⣙⠻⠿⠶⠒⠁⢀⢀⣀⣤⣰⣶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄
⢿⠟⠛⠋⣿⣿⣿⣿⣿⣿⣿⣟⡿⠷⣶⣶⣶⢶⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡄
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠉⠙⠻⠿⣿⣿⡿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⢸⣿⣿⣿⣿⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿
⢸⣿⣿⣿⣿⣄⠈⠛⠿⣿⣿⣿⣿⣿⣿⣿⡿⠟⣹⣿⣿⣿⣿⣿⣿⣿⣿⠇
⢻⣿⣿⣿⣿⣧⣀⢀⢀⠉⠛⠛⠋⠉⢀⣠⣾⣿⣿⣿⣿⣿⣿⣿⣿⠏
⢻⣿⣿⣿⣿⣿⣷⣤⣄⣀⣀⣤⣴⣾⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋
⠙⠿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛
⢹⣿⡿⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠁
⢸⣿⡇ ⠈⠙⠛⠛⠛⠛⠛⠛⠻⣿⣿⣿⠇
⣸⣿⡇ ⢨⣿⣿
⣾⣿⡿⠃ ⢸⣿⡏
⠻⠿ ⢠⣿⣿⡇
*/
|
[
"yunke0123@hotmail.com"
] |
yunke0123@hotmail.com
|
91e9b3a887291fa4a79ec1346fa9d2f3bfd71a11
|
232767d21db4e52a9f76c6023f7e0cbec739b5d7
|
/can/src/ServiceRequest.cc
|
819a62985c9efc29cb3440d5a605f0d8b53b855f
|
[
"Zlib"
] |
permissive
|
Sourabh-Pandit/cc
|
27a73f1d565c5cd7149fe1eeaef9e814a2e3a79c
|
73a2eef31c21c624f1c77340b05cec0ac44793c4
|
refs/heads/master
| 2021-02-16T02:50:44.365556
| 2020-02-16T23:27:42
| 2020-02-16T23:27:42
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,065
|
cc
|
/*
* Copyright (C) 2019 Frank Mertens.
*
* Distribution and use is allowed under the terms of the zlib license
* (see cc/LICENSE-zlib).
*
*/
#include <cc/can/ServiceRequest>
#include <cc/can/ReadRequest>
#include <cc/can/WriteRequest>
#include <cc/can/ReadSegmentRequest>
#include <cc/can/WriteSegmentRequest>
#include <cc/can/AbortRequest>
#include <cc/can/BlockRequest>
namespace cc {
namespace can {
String ServiceRequest::Instance::toString() const
{
if (!isValid()) return String{};
String s;
switch (specifier()) {
case Specifier::Read: s = ReadRequest{frame_}; break;
case Specifier::Write: s = WriteRequest{frame_}; break;
case Specifier::ReadSegment: s = ReadSegmentRequest{frame_}; break;
case Specifier::WriteSegment: s = WriteSegmentRequest{frame_}; break;
case Specifier::Abort: s = AbortRequest{frame_}; break;
case Specifier::BlockRead:
case Specifier::BlockWrite: s = BlockRequest{frame_}; break;
};
return s;
}
}} // namespace cc::can
|
[
"frank@cyblogic.de"
] |
frank@cyblogic.de
|
e31b1051cb8025101b392068dd7f6b40faec2b8b
|
e0bf5836e4f0d75b28b1f787446e655cdeeb8b03
|
/files/459e.cpp
|
58ca311f7641c2e736e5ab9245d255541dac15b3
|
[] |
no_license
|
arunnsit/allcodes
|
3f0b73facdee06e802455c6c3fb5de7baae702c2
|
5e6a8bf3883d0c5f67dfa7cc3dc026dbb4c63a71
|
refs/heads/master
| 2021-01-10T13:58:24.900593
| 2017-10-03T18:11:34
| 2017-10-03T18:11:34
| 50,598,937
| 0
| 2
| null | 2019-09-30T20:16:32
| 2016-01-28T17:06:03
|
C++
|
UTF-8
|
C++
| false
| false
| 843
|
cpp
|
#include<stdio.h>
#include<algorithm>
struct node{
int u;
int v;
int w;
};
using namespace std;
bool cmp(node a,node b){
return a.w<b.w;
}
int dp[400000][3]={0};
node a[400000];
int main(){
int n,m,x,y,i,j,s=-1;
scanf("%d %d",&n,&m);
for (int i = 0; i < m; ++i)
{
scanf("%d %d %d",&a[i].u,&a[i].v,&a[i].w);
/* code */
}
sort(a,a+m,cmp);
for (int i = 0; i < m; ++i){
if(dp[a[i].u][0]+1>dp[a[i].v][0]&&a[i].w>dp[a[i].u][1]){
dp[a[i].v][2]=dp[a[i].v][0];
dp[a[i].v][0]=dp[a[i].u][0]+1;
dp[a[i].v][1]=a[i].w;
s=max(dp[a[i].v][0],s);
}
else if(dp[a[i].u][2]+1>dp[a[i].v][0]&&a[i].w==dp[a[i].u][1]){
dp[a[i].v][2]=dp[a[i].v][0];
dp[a[i].v][0]=dp[a[i].u][2]+1;
dp[a[i].v][1]=a[i].w;
s=max(dp[a[i].v][0],s);
}}
printf("%d\n",s);
}
|
[
"arun.yad96@gmail.com"
] |
arun.yad96@gmail.com
|
1a8d75470e79bb69732a98508cb3ec579f00d1d7
|
fc13a625638bd671c9384f6abd4b67190a766dc9
|
/sources/dc-motor-state-control/src/main.cpp
|
491bc7ac5d21fe5ba5f0830fa09a0e89e3b72250
|
[] |
no_license
|
Martinsoyyo/inverted-pendulum
|
04ed6c271d2b376c44d74e4d9f53a99b2d32f17b
|
114e5881d5d42f897228091013fced8d26882c59
|
refs/heads/master
| 2023-08-21T16:32:50.692889
| 2021-09-23T15:39:58
| 2021-09-23T15:39:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,319
|
cpp
|
/**
* == Stabilizing DC motor with state control ==
*
* Cart is being controlled by state controller (x, v) based on params found by fitting the model
*
* == Hardware specification ==
* OMRON E6B2-CWZ6C pinout
* - Brown - Vcc
* - Black - Phase A
* - White - Phase B
* - Orange - Phaze Z
* - Blue - GND
*
* LPD3806-600BM-G5-24C pinout
* - Green - Phase A
* - White - Phase B
* - Red - Vcc
* - Black - GND
*/
#include <Arduino.h>
// motor encoder pins
#define OUTPUT_A 3 // PE5
#define OUTPUT_B 2 // PE4
// pulses per revolution
#define PPR 2400
#define SHAFT_R 0.00573
#define PWM_PIN 10
#define DIR_PIN 8
#define MAX_STALL_U 45.0
#define POSITION_LIMIT 0.2
#define X0 0.065
#define A 35.98
#define B 2.22
#define C -2.79
#define Kx 285.4
#define Kv 37.1
volatile long encoderValue = 0L;
volatile long lastEncoded = 0L;
unsigned long now = 0L;
unsigned long lastTimeMicros = 0L;
float x, last_x, v, dt;
unsigned long log_prescaler = 0;
void encoderHandler();
void setup() {
// setting PWD frequency on pin 10 to 31kHz
TCCR2B = (TCCR2B & 0b11111000) | 0x01;
pinMode(OUTPUT_A, INPUT_PULLUP);
pinMode(OUTPUT_B, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(OUTPUT_A), encoderHandler, CHANGE);
attachInterrupt(digitalPinToInterrupt(OUTPUT_B), encoderHandler, CHANGE);
pinMode(PWM_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
digitalWrite(DIR_PIN, LOW);
Serial.begin(9600);
lastTimeMicros = 0L;
}
float sign(float v) {
if (fabs(v) < 1e-8) {
return 0.0;
} else if (v > 0) {
return 1.0;
} else {
return -1.0;
}
}
float avoidStall(float u) {
if (fabs(u) < MAX_STALL_U) {
return u > 0 ? u + MAX_STALL_U : u - MAX_STALL_U;
}
return u;
}
float saturate(float v, float maxValue) {
if (fabs(v) > maxValue) {
return (v > 0) ? maxValue : -maxValue;
} else {
return v;
}
}
float getCartDistance(long pulses, long ppr) {
return 2.0 * PI * pulses / PPR * SHAFT_R;
}
void driveMotor(float u) {
digitalWrite(DIR_PIN, u > 0.0 ? LOW : HIGH);
analogWrite(PWM_PIN, fabs(u));
}
void log_state(float control, float u) {
if (log_prescaler % 50 == 0) {
Serial.print(x, 4);Serial.print("\t");
Serial.print(v, 4);Serial.print("\t");
Serial.print(control, 4);Serial.print("\t");
Serial.println(u, 4);
}
log_prescaler++;
}
void loop() {
now = micros();
dt = 1.0 * (now - lastTimeMicros) / 1000000;
x = getCartDistance(encoderValue, PPR);
v = (x - last_x) / dt;
float control = - (Kx * (x - X0) + Kv * v);
float u = (control + A * v - C * sign(v)) / B;
u = 255.0 * u / 12.0;
last_x = x;
lastTimeMicros = now;
driveMotor(saturate(u, 250));
log_state(control, u);
delay(5);
}
void encoderHandler() {
int MSB = (PINE & (1 << PE5)) >> PE5; //MSB = most significant bit
int LSB = (PINE & (1 << PE4)) >> PE4; //LSB = least significant bit
int encoded = (MSB << 1) | LSB; //converting the 2 pin value to single number
int sum = (lastEncoded << 2) | encoded; //adding it to the previous encoded value
if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) {
encoderValue++; //CW
}
if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) {
encoderValue--; //CCW
}
lastEncoded = encoded; //store this value for next time
}
|
[
"zjor.se@gmail.com"
] |
zjor.se@gmail.com
|
aa07e0158a20af2e8b95e10247a5b473e5283305
|
510959a396e2e72eaec632c5c5f7b32f01adbdb4
|
/elenasrc2/ide/historylist.h
|
2694521a421d12ac936381a4fbc2fc4ac1a81307
|
[
"Apache-2.0"
] |
permissive
|
sanyaade-teachings/elena-lang
|
a6c700ccf0cc8186d271f2226205cdf76bf19f5d
|
5b9871e654fe2e57e88931bbebcfbb5155a52247
|
refs/heads/master
| 2020-05-29T11:35:21.276914
| 2014-01-25T08:52:14
| 2014-01-25T08:52:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 711
|
h
|
//---------------------------------------------------------------------------
// E L E N A P r o j e c t: ELENA IDE
// MenuHistoryList class header
// (C)2005-2011, by Alexei Rakov
//---------------------------------------------------------------------------
#ifndef historylistH
#define historylistH
#include "ide.h"
#include "menulist.h"
namespace _GUI_
{
// --- MenuHistoryList ---
class RecentList : public MenuHistoryList
{
public:
void load(_ELENA_::IniConfigFile& file, const char* section);
void save(_ELENA_::IniConfigFile& file, const char* section);
RecentList(int maxCount, int menuBaseId);
};
} // _GUI_
#endif // historylistH
|
[
"arakov@yandex.ru"
] |
arakov@yandex.ru
|
1818f18b558e66d09f8be62d025b0cb87f6d9f44
|
c83031e047a315807f5bfbd33d93ee3f3b07b860
|
/src/Swarm.cpp
|
cb42d635f452876ae840699a03eb17a173963bad
|
[] |
no_license
|
kdloney/PriestFinalData_PhaedrasLove
|
ce036703901483a4c93d8bc4becdbbfa184b01ca
|
3d6839a4045bd361bec91501a0ef1f3a067148a1
|
refs/heads/master
| 2020-03-30T18:24:05.725365
| 2014-03-04T12:26:46
| 2014-03-04T12:26:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,743
|
cpp
|
#include "Swarm.h"
// This 'swarm' object demonstrates a simple particle system
// with 'simple harmonic motion'
swarm::swarm(){
light.setAmbientColor(ofColor(0, 0, 0));
}
void swarm::init(int nParticles, float xDis, float yDis, float zDis, float velocityDispersion, float rVal, float gVal, float bVal, float aVal){
// Check if we've already initialised
if(particles.size() != 0){
// clear out old data
ofLogWarning("swarm") << "Swarm: Already initialised";
particles.clear();
}
ofSeedRandom();
//
ofVec3f position, velocity;
ofColor color;
for(int i = 0; i < nParticles; i++){
position.x = (ofRandom(1.0f) - 0.5f) * xDis;
position.y = (ofRandom(1.0f) - 0.5f) * yDis;
position.z = (ofRandom(1.0f) - 0.5f) * zDis;
velocity.x = (ofRandom(1.0f) - 0.5f) * velocityDispersion;
velocity.y = (ofRandom(1.0f) - 0.5f) * velocityDispersion;
velocity.z = (ofRandom(1.0f) - 0.5f) * velocityDispersion;
color.r = rVal;
color.g = gVal;
color.b = bVal;
color.a = aVal;
particle newParticle;
newParticle.position = position;
newParticle.velocity = velocity;
newParticle.color = color;
// add our new particle to the vector
particles.push_back(newParticle);
}
}
void swarm::customDraw(){
// We run the update ourselves manually. ofNode does
// not do this for us.
update();
//--
// Draw particles
// We use the position of the first
// particle as the position of the
// light.
/*
ofPushStyle();
light.enable();
light.setPosition(particles[0].position*.02);
for(int i = 0; i < particles.size(); i++){
ofPushStyle();
ofSetColor(particles[i].color);
ofSphere(particles[i].position, .7);
ofPopStyle();
}
light.disable();
ofDisableLighting();
*/
for(int i = 0; i < particles.size(); i++){
ofPushStyle();
ofSetColor(particles[i].color);
ofSphere(particles[i].position, .7);
ofPopStyle();
}
//
//--
//______________________LOOK HERE__________________________________
// Render light as white sphere
//ofSetColor(255, 255, 255);
//ofSphere(light.getPosition(), 2.0);
//ofSetDrawBitmapMode(OF_BITMAPMODE_MODEL);
//ofDrawBitmapString(" light", particles[0].position);
//ofPopStyle();
}
void swarm::update(){
// Calculate time past per frame
float dt = ofGetLastFrameTime();
// Update positions, velocities
for(int i = 0; i < particles.size(); i++){
// -----------
//
// MOTION MATHS
//
// 'Simple Harmonic Motion' + a little extra
// ----
//
// [1] apply velocity to postion
// (i.e. integrate velocity)
//
// v = dx / dt (*)
// x = x + dx [every frame]
//
// therefore
// x = x + v * dt (*)
//
// (velcotity is taken from previous frame)
particles[i].position += particles[i].velocity * dt;
// [2] apply spring force to velocity
// (i.e. integrate acceleration)
//
// a = -k * x (this is the shm restoring force, aka spring force)
// a = dv / dt
//
// therefore from (*)s above
// (v = v + dv)
//
// v = v + (dt * a)
// v = v + (dt * -k * x)
//
//particles[i].velocity += -SPRING_CONSTANT * particles[i].position * dt;
particles[i].velocity += -SPRING_CONSTANT / particles[i].position;
// [3] to get a super simple kind of 'flocking' behaviour
// we add a second spring force to velocity relative
// to the position of the light
// NOTICE: THIS ISN'T REAL FLOCKING!
particles[i].velocity += -SPRING_CONSTANT * (particles[i].position - light.getPosition()) * dt;
// [4] Force a maximum velocity
if(particles[i].velocity.length() > MAX_VELOCITY){
particles[i].velocity /= particles[i].velocity.length() * MAX_VELOCITY;
}
//
// -----------
}
}
|
[
"kdloney@gmail.com"
] |
kdloney@gmail.com
|
17ebc2f4048cadefcab532ec4bb3f12b195b8e91
|
88137561a97490e0f9b453ee476430810bb65b46
|
/LightSource.cpp
|
41f6f24f325f16dce32bc0f2b4a0f1826d9d3737
|
[] |
no_license
|
Euronia/LancerDeRayons
|
fc3f7819b832eef6e241e4918f6a2cfe532c7c0a
|
e0a259d43212fd8becda8469377c7a2379feb1ef
|
refs/heads/master
| 2021-01-01T17:22:41.260041
| 2014-06-04T12:50:31
| 2014-06-04T12:50:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 310
|
cpp
|
#include "LightSource.h"
LightSource::LightSource(const Point& originPoint ,const Color& lightColor)
:
origin(originPoint) ,
color(lightColor)
{
}
Point LightSource::getOrigin () const
{
return origin;
}
Color LightSource::getColor () const
{
return color;
}
|
[
"mouton.thibault@gmail.com"
] |
mouton.thibault@gmail.com
|
17f77c042acd044e8bb4cc924e65a8ea33e89715
|
3b38e11bd517ba7825bc23ad890fe0150cfd2bf2
|
/src/vartypes/primitives/VarQWidget.cpp
|
64037538471f0771ec4140e72e2bf0acbddac2e5
|
[] |
no_license
|
eschneeweiss/Umass_RoboCup_Logger
|
a1b9a7f265f8dce139e92ebb1a0c8964803ceb1c
|
cc2ced98c75f4c44e96754d619be5e17810c6f88
|
refs/heads/master
| 2020-09-21T05:42:59.737244
| 2016-10-12T19:48:53
| 2016-10-12T19:48:53
| 67,076,577
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 953
|
cpp
|
//========================================================================
// This software is free: you can redistribute it and/or modify
// it under the terms of the GNU General Public License Version 3,
// as published by the Free Software Foundation.
//
// This software 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
// Version 3 in the file COPYING that came with this distribution.
// If not, see <http://www.gnu.org/licenses/>.
//========================================================================
/*!
\file VarQWidget.cpp
\brief C++ Implementation: VarQWidget
\author Stefan Zickler, (C) 2008
*/
#include "vartypes/primitives/VarQWidget.h"
|
[
"eschneeweiss@umass.edu"
] |
eschneeweiss@umass.edu
|
b6c9ec35c92977dc7f37ece852dcadb83b43a37a
|
6ced41da926682548df646099662e79d7a6022c5
|
/aws-cpp-sdk-eks/include/aws/eks/model/UpdateNodegroupConfigRequest.h
|
19b88ee5ed133de7d9b8cdd0c6bdab4bb1a7364a
|
[
"Apache-2.0",
"MIT",
"JSON"
] |
permissive
|
irods/aws-sdk-cpp
|
139104843de529f615defa4f6b8e20bc95a6be05
|
2c7fb1a048c96713a28b730e1f48096bd231e932
|
refs/heads/main
| 2023-07-25T12:12:04.363757
| 2022-08-26T15:33:31
| 2022-08-26T15:33:31
| 141,315,346
| 0
| 1
|
Apache-2.0
| 2022-08-26T17:45:09
| 2018-07-17T16:24:06
|
C++
|
UTF-8
|
C++
| false
| false
| 13,481
|
h
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/eks/EKS_EXPORTS.h>
#include <aws/eks/EKSRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/eks/model/UpdateLabelsPayload.h>
#include <aws/eks/model/UpdateTaintsPayload.h>
#include <aws/eks/model/NodegroupScalingConfig.h>
#include <aws/eks/model/NodegroupUpdateConfig.h>
#include <utility>
#include <aws/core/utils/UUID.h>
namespace Aws
{
namespace EKS
{
namespace Model
{
/**
*/
class AWS_EKS_API UpdateNodegroupConfigRequest : public EKSRequest
{
public:
UpdateNodegroupConfigRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "UpdateNodegroupConfig"; }
Aws::String SerializePayload() const override;
/**
* <p>The name of the Amazon EKS cluster that the managed node group resides
* in.</p>
*/
inline const Aws::String& GetClusterName() const{ return m_clusterName; }
/**
* <p>The name of the Amazon EKS cluster that the managed node group resides
* in.</p>
*/
inline bool ClusterNameHasBeenSet() const { return m_clusterNameHasBeenSet; }
/**
* <p>The name of the Amazon EKS cluster that the managed node group resides
* in.</p>
*/
inline void SetClusterName(const Aws::String& value) { m_clusterNameHasBeenSet = true; m_clusterName = value; }
/**
* <p>The name of the Amazon EKS cluster that the managed node group resides
* in.</p>
*/
inline void SetClusterName(Aws::String&& value) { m_clusterNameHasBeenSet = true; m_clusterName = std::move(value); }
/**
* <p>The name of the Amazon EKS cluster that the managed node group resides
* in.</p>
*/
inline void SetClusterName(const char* value) { m_clusterNameHasBeenSet = true; m_clusterName.assign(value); }
/**
* <p>The name of the Amazon EKS cluster that the managed node group resides
* in.</p>
*/
inline UpdateNodegroupConfigRequest& WithClusterName(const Aws::String& value) { SetClusterName(value); return *this;}
/**
* <p>The name of the Amazon EKS cluster that the managed node group resides
* in.</p>
*/
inline UpdateNodegroupConfigRequest& WithClusterName(Aws::String&& value) { SetClusterName(std::move(value)); return *this;}
/**
* <p>The name of the Amazon EKS cluster that the managed node group resides
* in.</p>
*/
inline UpdateNodegroupConfigRequest& WithClusterName(const char* value) { SetClusterName(value); return *this;}
/**
* <p>The name of the managed node group to update.</p>
*/
inline const Aws::String& GetNodegroupName() const{ return m_nodegroupName; }
/**
* <p>The name of the managed node group to update.</p>
*/
inline bool NodegroupNameHasBeenSet() const { return m_nodegroupNameHasBeenSet; }
/**
* <p>The name of the managed node group to update.</p>
*/
inline void SetNodegroupName(const Aws::String& value) { m_nodegroupNameHasBeenSet = true; m_nodegroupName = value; }
/**
* <p>The name of the managed node group to update.</p>
*/
inline void SetNodegroupName(Aws::String&& value) { m_nodegroupNameHasBeenSet = true; m_nodegroupName = std::move(value); }
/**
* <p>The name of the managed node group to update.</p>
*/
inline void SetNodegroupName(const char* value) { m_nodegroupNameHasBeenSet = true; m_nodegroupName.assign(value); }
/**
* <p>The name of the managed node group to update.</p>
*/
inline UpdateNodegroupConfigRequest& WithNodegroupName(const Aws::String& value) { SetNodegroupName(value); return *this;}
/**
* <p>The name of the managed node group to update.</p>
*/
inline UpdateNodegroupConfigRequest& WithNodegroupName(Aws::String&& value) { SetNodegroupName(std::move(value)); return *this;}
/**
* <p>The name of the managed node group to update.</p>
*/
inline UpdateNodegroupConfigRequest& WithNodegroupName(const char* value) { SetNodegroupName(value); return *this;}
/**
* <p>The Kubernetes labels to be applied to the nodes in the node group after the
* update.</p>
*/
inline const UpdateLabelsPayload& GetLabels() const{ return m_labels; }
/**
* <p>The Kubernetes labels to be applied to the nodes in the node group after the
* update.</p>
*/
inline bool LabelsHasBeenSet() const { return m_labelsHasBeenSet; }
/**
* <p>The Kubernetes labels to be applied to the nodes in the node group after the
* update.</p>
*/
inline void SetLabels(const UpdateLabelsPayload& value) { m_labelsHasBeenSet = true; m_labels = value; }
/**
* <p>The Kubernetes labels to be applied to the nodes in the node group after the
* update.</p>
*/
inline void SetLabels(UpdateLabelsPayload&& value) { m_labelsHasBeenSet = true; m_labels = std::move(value); }
/**
* <p>The Kubernetes labels to be applied to the nodes in the node group after the
* update.</p>
*/
inline UpdateNodegroupConfigRequest& WithLabels(const UpdateLabelsPayload& value) { SetLabels(value); return *this;}
/**
* <p>The Kubernetes labels to be applied to the nodes in the node group after the
* update.</p>
*/
inline UpdateNodegroupConfigRequest& WithLabels(UpdateLabelsPayload&& value) { SetLabels(std::move(value)); return *this;}
/**
* <p>The Kubernetes taints to be applied to the nodes in the node group after the
* update. For more information, see <a
* href="https://docs.aws.amazon.com/eks/latest/userguide/node-taints-managed-node-groups.html">Node
* taints on managed node groups</a>.</p>
*/
inline const UpdateTaintsPayload& GetTaints() const{ return m_taints; }
/**
* <p>The Kubernetes taints to be applied to the nodes in the node group after the
* update. For more information, see <a
* href="https://docs.aws.amazon.com/eks/latest/userguide/node-taints-managed-node-groups.html">Node
* taints on managed node groups</a>.</p>
*/
inline bool TaintsHasBeenSet() const { return m_taintsHasBeenSet; }
/**
* <p>The Kubernetes taints to be applied to the nodes in the node group after the
* update. For more information, see <a
* href="https://docs.aws.amazon.com/eks/latest/userguide/node-taints-managed-node-groups.html">Node
* taints on managed node groups</a>.</p>
*/
inline void SetTaints(const UpdateTaintsPayload& value) { m_taintsHasBeenSet = true; m_taints = value; }
/**
* <p>The Kubernetes taints to be applied to the nodes in the node group after the
* update. For more information, see <a
* href="https://docs.aws.amazon.com/eks/latest/userguide/node-taints-managed-node-groups.html">Node
* taints on managed node groups</a>.</p>
*/
inline void SetTaints(UpdateTaintsPayload&& value) { m_taintsHasBeenSet = true; m_taints = std::move(value); }
/**
* <p>The Kubernetes taints to be applied to the nodes in the node group after the
* update. For more information, see <a
* href="https://docs.aws.amazon.com/eks/latest/userguide/node-taints-managed-node-groups.html">Node
* taints on managed node groups</a>.</p>
*/
inline UpdateNodegroupConfigRequest& WithTaints(const UpdateTaintsPayload& value) { SetTaints(value); return *this;}
/**
* <p>The Kubernetes taints to be applied to the nodes in the node group after the
* update. For more information, see <a
* href="https://docs.aws.amazon.com/eks/latest/userguide/node-taints-managed-node-groups.html">Node
* taints on managed node groups</a>.</p>
*/
inline UpdateNodegroupConfigRequest& WithTaints(UpdateTaintsPayload&& value) { SetTaints(std::move(value)); return *this;}
/**
* <p>The scaling configuration details for the Auto Scaling group after the
* update.</p>
*/
inline const NodegroupScalingConfig& GetScalingConfig() const{ return m_scalingConfig; }
/**
* <p>The scaling configuration details for the Auto Scaling group after the
* update.</p>
*/
inline bool ScalingConfigHasBeenSet() const { return m_scalingConfigHasBeenSet; }
/**
* <p>The scaling configuration details for the Auto Scaling group after the
* update.</p>
*/
inline void SetScalingConfig(const NodegroupScalingConfig& value) { m_scalingConfigHasBeenSet = true; m_scalingConfig = value; }
/**
* <p>The scaling configuration details for the Auto Scaling group after the
* update.</p>
*/
inline void SetScalingConfig(NodegroupScalingConfig&& value) { m_scalingConfigHasBeenSet = true; m_scalingConfig = std::move(value); }
/**
* <p>The scaling configuration details for the Auto Scaling group after the
* update.</p>
*/
inline UpdateNodegroupConfigRequest& WithScalingConfig(const NodegroupScalingConfig& value) { SetScalingConfig(value); return *this;}
/**
* <p>The scaling configuration details for the Auto Scaling group after the
* update.</p>
*/
inline UpdateNodegroupConfigRequest& WithScalingConfig(NodegroupScalingConfig&& value) { SetScalingConfig(std::move(value)); return *this;}
/**
* <p>The node group update configuration.</p>
*/
inline const NodegroupUpdateConfig& GetUpdateConfig() const{ return m_updateConfig; }
/**
* <p>The node group update configuration.</p>
*/
inline bool UpdateConfigHasBeenSet() const { return m_updateConfigHasBeenSet; }
/**
* <p>The node group update configuration.</p>
*/
inline void SetUpdateConfig(const NodegroupUpdateConfig& value) { m_updateConfigHasBeenSet = true; m_updateConfig = value; }
/**
* <p>The node group update configuration.</p>
*/
inline void SetUpdateConfig(NodegroupUpdateConfig&& value) { m_updateConfigHasBeenSet = true; m_updateConfig = std::move(value); }
/**
* <p>The node group update configuration.</p>
*/
inline UpdateNodegroupConfigRequest& WithUpdateConfig(const NodegroupUpdateConfig& value) { SetUpdateConfig(value); return *this;}
/**
* <p>The node group update configuration.</p>
*/
inline UpdateNodegroupConfigRequest& WithUpdateConfig(NodegroupUpdateConfig&& value) { SetUpdateConfig(std::move(value)); return *this;}
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request.</p>
*/
inline const Aws::String& GetClientRequestToken() const{ return m_clientRequestToken; }
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request.</p>
*/
inline bool ClientRequestTokenHasBeenSet() const { return m_clientRequestTokenHasBeenSet; }
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request.</p>
*/
inline void SetClientRequestToken(const Aws::String& value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken = value; }
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request.</p>
*/
inline void SetClientRequestToken(Aws::String&& value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken = std::move(value); }
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request.</p>
*/
inline void SetClientRequestToken(const char* value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken.assign(value); }
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request.</p>
*/
inline UpdateNodegroupConfigRequest& WithClientRequestToken(const Aws::String& value) { SetClientRequestToken(value); return *this;}
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request.</p>
*/
inline UpdateNodegroupConfigRequest& WithClientRequestToken(Aws::String&& value) { SetClientRequestToken(std::move(value)); return *this;}
/**
* <p>Unique, case-sensitive identifier that you provide to ensure the idempotency
* of the request.</p>
*/
inline UpdateNodegroupConfigRequest& WithClientRequestToken(const char* value) { SetClientRequestToken(value); return *this;}
private:
Aws::String m_clusterName;
bool m_clusterNameHasBeenSet;
Aws::String m_nodegroupName;
bool m_nodegroupNameHasBeenSet;
UpdateLabelsPayload m_labels;
bool m_labelsHasBeenSet;
UpdateTaintsPayload m_taints;
bool m_taintsHasBeenSet;
NodegroupScalingConfig m_scalingConfig;
bool m_scalingConfigHasBeenSet;
NodegroupUpdateConfig m_updateConfig;
bool m_updateConfigHasBeenSet;
Aws::String m_clientRequestToken;
bool m_clientRequestTokenHasBeenSet;
};
} // namespace Model
} // namespace EKS
} // namespace Aws
|
[
"aws-sdk-cpp-automation@github.com"
] |
aws-sdk-cpp-automation@github.com
|
5e7accd26d336867e70d445869db815288a3397c
|
98b6001550c19fad60975e5dac262dde561e887b
|
/WinAPI/lessons/lesson7_slider progress bar/main2.cpp
|
945745a9a0a37d85959c17c3d5ad525a57f0a43e
|
[] |
no_license
|
ArBond/ITStep
|
eee3998d7292ea110ee5f6fd39723cc5d7a095d8
|
8d013e349648e52c8753f94331dfe611086e57b5
|
refs/heads/master
| 2020-04-05T11:44:03.579526
| 2018-02-23T09:08:03
| 2018-02-23T09:08:03
| 81,499,847
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,782
|
cpp
|
#include <Windows.h>
#include "commctrl.h"
#pragma comment(lib, "comctl32")
#include "resource.h"
#define ID_TIMER1 123
#define ID_TIMER2 124
#define ID_STATUSBAR 234
BOOL CALLBACK DlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
static HWND hPrBar;
static HWND hStatusBar;
static HWND hSlider;
static HWND hTimerInSec;
static int seconds = 0;
static int parts[3] = { 150, 250, -1 };
switch (uMsg)
{
case WM_INITDIALOG:
hPrBar = GetDlgItem(hWnd, IDC_PROGRESS1);
hSlider = GetDlgItem(hWnd, IDC_SLIDER1);
hStatusBar = CreateWindowEx(NULL, STATUSCLASSNAME, NULL, WS_CHILD | WS_VISIBLE | SBARS_TOOLTIPS | SBARS_SIZEGRIP, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hWnd, (HMENU)ID_STATUSBAR, GetModuleHandle(NULL), NULL);
SendMessage(hStatusBar, SB_SIMPLE, false, 0);
SendMessage(hStatusBar, SB_SETPARTS, 3, (LPARAM)parts);
SendMessage(hStatusBar, SB_SETTEXT, 0, LPARAM(L" User: Bondarenko Artemi"));
SendMessage(hStatusBar, SB_SETTEXT, 2, LPARAM(L" Time: 0 sec"));
SendMessage(hPrBar, PBM_SETBKCOLOR, 0, LPARAM(RGB(100, 200, 100)));
SendMessage(hPrBar, PBM_SETBARCOLOR, 0, LPARAM(RGB(55, 50, 200)));
SendMessage(hPrBar, PBM_SETRANGE, 0, MAKELPARAM(0, 100));
SendMessage(hSlider, TBM_SETRANGE, true, MAKELPARAM(0, 255));
SendMessage(hSlider, TBM_SETPOS, true, 200);
SetTimer(hWnd, ID_TIMER1, 100, NULL);
SetTimer(hWnd, ID_TIMER2, 1000, NULL);
hTimerInSec = GetDlgItem(hWnd, ID_TIMER2);
return true;
case WM_TIMER:
SendMessage(hPrBar, PBM_DELTAPOS, 1, 0);
wchar_t buff[50];
memset(buff, 0, 50);
wsprintf(buff, L" Progress: %i %%", (LPCWSTR)SendMessage(hPrBar, PBM_GETPOS, 1, 0));
SendMessage(hStatusBar, SB_SETTEXT, 1, LPARAM(buff));
if (LOWORD(wParam) == ID_TIMER2)
{
seconds++;
memset(buff, 0, 50);
wsprintf(buff, L" Time: %i sec", seconds);
SendMessage(hStatusBar, SB_SETTEXT, 2, LPARAM(buff));
}
if (SendMessage(hPrBar, PBM_GETPOS, 0, 0) == 100)
{
SendMessage(hWnd, WM_CLOSE, 0, 0);
}
return true;
case WM_HSCROLL:
SendMessage(hPrBar, PBM_SETBARCOLOR, 0, LPARAM(RGB(255 - SendMessage(hSlider, TBM_GETPOS, 0, 0), 50, SendMessage(hSlider, TBM_GETPOS, 0, 0))));
return true;
case WM_CLOSE:
KillTimer(hWnd, ID_TIMER1);
DestroyWindow(hWnd);
PostQuitMessage(0);
return true;
default:
return false;
}
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int)
{
INITCOMMONCONTROLSEX cc;
cc.dwSize = sizeof(cc);
cc.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&cc);
HWND hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, DlgProc);
ShowWindow(hWnd, SW_NORMAL);
UpdateWindow(hWnd);
MSG msg;
while (GetMessage(&msg, 0, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
|
[
"bonartembon@gmail.com"
] |
bonartembon@gmail.com
|
882f535e71b4e6e6c6f70219651481f04fcd29c1
|
fbbc663c607c9687452fa3192b02933b9eb3656d
|
/tags/1.22.02.00/unarchiver/unzip.cpp
|
a74bec4f2054fa517a87470d11f53c8e6749790e
|
[
"BSD-3-Clause"
] |
permissive
|
svn2github/OpenMPT
|
594837f3adcb28ba92a324e51c6172a8c1e8ea9c
|
a2943f028d334a8751b9f16b0512a5e0b905596a
|
refs/heads/master
| 2021-07-10T05:07:18.298407
| 2019-01-19T10:27:21
| 2019-01-19T10:27:21
| 106,434,952
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,469
|
cpp
|
/*
* unzip.cpp
* ---------
* Purpose: Implementation file for extracting modules from .zip archives, making use of MiniZip (from the zlib contrib package)
* Notes : (currently none)
* Authors: OpenMPT Devs
* The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
*/
#include "../soundlib/FileReader.h"
#include <vector>
#include "unzip.h"
#include "../common/misc_util.h"
#include <algorithm>
#ifndef ZLIB_WINAPI
#define ZLIB_WINAPI
#endif // ZLIB_WINAPI
#include <contrib/minizip/unzip.h>
// Low-level file abstractions for in-memory file handling
struct ZipFileAbstraction
{
static voidpf ZCALLBACK fopen_mem(voidpf opaque, const char *, int mode)
{
FileReader &file = *static_cast<FileReader *>(opaque);
if((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == ZLIB_FILEFUNC_MODE_WRITE)
{
return nullptr;
} else
{
file.Rewind();
return opaque;
}
}
static uLong ZCALLBACK fread_mem(voidpf opaque, voidpf, void *buf, uLong size)
{
FileReader &file = *static_cast<FileReader *>(opaque);
if(size > file.BytesLeft())
{
size = file.BytesLeft();
}
memcpy(buf, file.GetRawData(), size);
file.Skip(size);
return size;
}
static uLong ZCALLBACK fwrite_mem(voidpf, voidpf, const void *, uLong)
{
return 0;
}
static long ZCALLBACK ftell_mem(voidpf opaque, voidpf)
{
FileReader &file = *static_cast<FileReader *>(opaque);
return file.GetPosition();
}
static long ZCALLBACK fseek_mem(voidpf opaque, voidpf, uLong offset, int origin)
{
FileReader &file = *static_cast<FileReader *>(opaque);
switch(origin)
{
case ZLIB_FILEFUNC_SEEK_CUR:
offset += file.GetPosition();
break;
case ZLIB_FILEFUNC_SEEK_END:
offset += file.GetLength();
break;
case ZLIB_FILEFUNC_SEEK_SET:
break;
default:
return -1;
}
return (file.Seek(offset) ? 0 : 1);
}
static int ZCALLBACK fclose_mem(voidpf, voidpf)
{
return 0;
}
static int ZCALLBACK ferror_mem(voidpf, voidpf)
{
return 0;
}
};
CZipArchive::CZipArchive(FileReader &file, const std::vector<const char *> &ext) : inFile(file), extensions(ext)
//--------------------------------------------------------------------------------------------------------------
{
zlib_filefunc_def functions =
{
ZipFileAbstraction::fopen_mem,
ZipFileAbstraction::fread_mem,
ZipFileAbstraction::fwrite_mem,
ZipFileAbstraction::ftell_mem,
ZipFileAbstraction::fseek_mem,
ZipFileAbstraction::fclose_mem,
ZipFileAbstraction::ferror_mem,
&inFile
};
zipFile = unzOpen2(nullptr, &functions);
}
CZipArchive::~CZipArchive()
//-------------------------
{
unzClose(zipFile);
delete[] outFile.GetRawData();
}
bool CZipArchive::IsArchive() const
//---------------------------------
{
return (zipFile != nullptr);
}
struct find_str
{
find_str(const char *str): s1(str) { }
bool operator() (const char *s2) const
{
return !strcmp(s1, s2);
}
const char *s1;
};
bool CZipArchive::ExtractFile()
//-----------------------------
{
unz_file_pos bestFile;
unz_file_info info;
uLong biggestFile = 0;
int status = unzGoToFirstFile(zipFile);
unzGetFilePos(zipFile, &bestFile);
while(status == UNZ_OK)
{
char name[256];
unzGetCurrentFileInfo(zipFile, &info, name, sizeof(name), nullptr, 0, nullptr, 0);
// Extract file extension
char *ext = name + info.size_filename;
while(ext > name)
{
ext--;
*ext = tolower(*ext);
if(*ext == '.')
{
ext++;
break;
}
}
// Compare with list of preferred extensions
if(std::find_if(extensions.begin(), extensions.end(), find_str(ext)) != extensions.end())
{
// File has a preferred extension: use it.
unzGetFilePos(zipFile, &bestFile);
break;
}
if(strcmp(ext, "diz")
&& strcmp(ext, "nfo")
&& strcmp(ext, "txt")
&& info.uncompressed_size >= biggestFile)
{
// If this isn't some kind of info file, we should maybe pick it.
unzGetFilePos(zipFile, &bestFile);
biggestFile = info.uncompressed_size;
}
status = unzGoToNextFile(zipFile);
}
if(unzGoToFilePos(zipFile, &bestFile) == UNZ_OK && unzOpenCurrentFile(zipFile) == UNZ_OK)
{
unzGetCurrentFileInfo(zipFile, &info, nullptr, 0, nullptr, 0, nullptr, 0);
delete[] outFile.GetRawData();
char *data = new (std::nothrow) char[info.uncompressed_size];
if(data != nullptr)
{
unzReadCurrentFile(zipFile, data, info.uncompressed_size);
outFile = FileReader(data, info.uncompressed_size);
}
unzCloseCurrentFile(zipFile);
return (data != nullptr);
}
return false;
}
const char *CZipArchive::GetComments(bool get)
//--------------------------------------------
{
unz_global_info info;
if(zipFile == nullptr || unzGetGlobalInfo(zipFile, &info) != UNZ_OK)
{
return nullptr;
}
if(!get)
{
return reinterpret_cast<char *>((info.size_comment > 0) ? 1 : 0);
} else if(info.size_comment > 0)
{
if(info.size_comment < Util::MaxValueOfType(info.size_comment))
{
info.size_comment++;
}
char *comment = new (std::nothrow) char[info.size_comment];
if(comment != nullptr && unzGetGlobalComment(zipFile, comment, info.size_comment) >= 0)
{
comment[info.size_comment - 1] = '\0';
return comment;
} else
{
delete[] comment;
}
}
return nullptr;
}
|
[
"saga-games@56274372-70c3-4bfc-bfc3-4c3a0b034d27"
] |
saga-games@56274372-70c3-4bfc-bfc3-4c3a0b034d27
|
41f148ef3f18d87dec33018d26c1dab40bebfae4
|
e0d41578eb105e9d3663ac17e841963e6cfb9f1b
|
/client/sdl/texture_cache.cpp
|
01a0fd08249e0526ad97d08fdb61300cf31cd34d
|
[] |
no_license
|
azhi/Bomberman-Clone
|
e19b91209b7599dd5e722fc6841c2c695415c303
|
1611ea30add14b0668cf8c0b4341954228f29857
|
refs/heads/master
| 2020-06-04T10:57:52.141308
| 2014-05-05T23:03:03
| 2014-05-05T23:03:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,696
|
cpp
|
#include "texture_cache.h"
#include <string>
SDL_Texture *TextureCache::destructible_texture = NULL;
SDL_Texture *TextureCache::indestructible_texture = NULL;
SDL_Texture *TextureCache::grass_texture = NULL;
SDL_Texture *TextureCache::mc_front_texture = NULL;
SDL_Texture *TextureCache::mc_back_texture = NULL;
SDL_Texture *TextureCache::mc_left_texture = NULL;
SDL_Texture *TextureCache::mc_right_texture = NULL;
SDL_Texture *TextureCache::ec_front_texture = NULL;
SDL_Texture *TextureCache::ec_back_texture = NULL;
SDL_Texture *TextureCache::ec_left_texture = NULL;
SDL_Texture *TextureCache::ec_right_texture = NULL;
SDL_Texture *TextureCache::killed_character_texture = NULL;
SDL_Texture *TextureCache::big_bomb_texture = NULL;
SDL_Texture *TextureCache::medium_bomb_texture = NULL;
SDL_Texture *TextureCache::small_bomb_texture = NULL;
SDL_Texture *TextureCache::explosion_center_texture = NULL;
SDL_Texture *TextureCache::explosion_left_texture = NULL;
SDL_Texture *TextureCache::explosion_left_end_texture = NULL;
SDL_Texture *TextureCache::explosion_right_texture = NULL;
SDL_Texture *TextureCache::explosion_right_end_texture = NULL;
SDL_Texture *TextureCache::explosion_top_texture = NULL;
SDL_Texture *TextureCache::explosion_top_end_texture = NULL;
SDL_Texture *TextureCache::explosion_bottom_texture = NULL;
SDL_Texture *TextureCache::explosion_bottom_end_texture = NULL;
void TextureCache::init(SDLWrapper *sdl_wrapper)
{
init_map(sdl_wrapper);
init_character(sdl_wrapper);
init_bomb(sdl_wrapper);
init_explosion(sdl_wrapper);
}
void TextureCache::init_map(SDLWrapper *sdl_wrapper)
{
std::string texture_path = BASE_TEXTURE_PATH;
texture_path.append(DESTRUCTIBLE_TEXTURE_PATH);
destructible_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(INDESTRUCTIBLE_TEXTURE_PATH);
indestructible_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(GRASS_TEXTURE_PATH);
grass_texture = sdl_wrapper->load_texture(texture_path.c_str());
}
void TextureCache::init_character(SDLWrapper *sdl_wrapper)
{
std::string texture_path = BASE_TEXTURE_PATH;
texture_path.append(MC_FRONT_TEXTURE_PATH);
mc_front_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(MC_BACK_TEXTURE_PATH);
mc_back_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(MC_LEFT_TEXTURE_PATH);
mc_left_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(MC_RIGHT_TEXTURE_PATH);
mc_right_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(EC_FRONT_TEXTURE_PATH);
ec_front_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(EC_BACK_TEXTURE_PATH);
ec_back_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(EC_LEFT_TEXTURE_PATH);
ec_left_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(EC_RIGHT_TEXTURE_PATH);
ec_right_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(KILLED_CHARACTER_TEXTURE);
killed_character_texture = sdl_wrapper->load_texture(texture_path.c_str());
}
void TextureCache::init_bomb(SDLWrapper *sdl_wrapper)
{
std::string texture_path = BASE_TEXTURE_PATH;
texture_path.append(SMALL_BOMB_TEXTURE_PATH);
small_bomb_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(MEDIUM_BOMB_TEXTURE_PATH);
medium_bomb_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(BIG_BOMB_TEXTURE_PATH);
big_bomb_texture = sdl_wrapper->load_texture(texture_path.c_str());
}
void TextureCache::init_explosion(SDLWrapper *sdl_wrapper)
{
std::string texture_path = BASE_TEXTURE_PATH;
texture_path.append(EXPLOSION_CENTER_TEXTURE_PATH);
explosion_center_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(EXPLOSION_LEFT_TEXTURE_PATH);
explosion_left_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(EXPLOSION_LEFT_END_TEXTURE_PATH);
explosion_left_end_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(EXPLOSION_RIGHT_TEXTURE_PATH);
explosion_right_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(EXPLOSION_RIGHT_END_TEXTURE_PATH);
explosion_right_end_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(EXPLOSION_TOP_TEXTURE_PATH);
explosion_top_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(EXPLOSION_TOP_END_TEXTURE_PATH);
explosion_top_end_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(EXPLOSION_BOTTOM_TEXTURE_PATH);
explosion_bottom_texture = sdl_wrapper->load_texture(texture_path.c_str());
texture_path = BASE_TEXTURE_PATH;
texture_path.append(EXPLOSION_BOTTOM_END_TEXTURE_PATH);
explosion_bottom_end_texture = sdl_wrapper->load_texture(texture_path.c_str());
}
|
[
"astzhe@gmail.com"
] |
astzhe@gmail.com
|
4bc6c3645708f41ebf23ed954c55472e2577a86b
|
f6f0f87647e23507dca538760ab70e26415b8313
|
/6.1.0/msvc2019_64/include/QtGui/6.1.0/QtGui/private/qimage_p.h
|
6936663f666419fcd8cb6485752fc396e6bc259b
|
[] |
no_license
|
stenzek/duckstation-ext-qt-minimal
|
a942c62adc5654c03d90731a8266dc711546b268
|
e5c412efffa3926f7a4d5bf0ae0333e1d6784f30
|
refs/heads/master
| 2023-08-17T16:50:21.478373
| 2023-08-15T14:53:43
| 2023-08-15T14:53:43
| 233,179,313
| 3
| 1
| null | 2021-11-16T15:34:28
| 2020-01-11T05:05:34
|
C++
|
UTF-8
|
C++
| false
| false
| 13,934
|
h
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QIMAGE_P_H
#define QIMAGE_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include <QtGui/private/qtguiglobal_p.h>
#include <QtGui/qcolorspace.h>
#include <QtGui/qimage.h>
#include <QtCore/private/qnumeric_p.h>
#include <QtCore/qlist.h>
#include <QtCore/qmap.h>
QT_BEGIN_NAMESPACE
class QImageWriter;
struct Q_GUI_EXPORT QImageData { // internal image data
QImageData();
~QImageData();
static QImageData *create(const QSize &size, QImage::Format format);
static QImageData *create(uchar *data, int w, int h, qsizetype bpl, QImage::Format format, bool readOnly, QImageCleanupFunction cleanupFunction = nullptr, void *cleanupInfo = nullptr);
static QImageData *get(QImage &img) noexcept { return img.d; }
static const QImageData *get(const QImage &img) noexcept { return img.d; }
QAtomicInt ref;
int width;
int height;
int depth;
qsizetype nbytes; // number of bytes data
qreal devicePixelRatio;
QList<QRgb> colortable;
uchar *data;
QImage::Format format;
qsizetype bytes_per_line;
int ser_no; // serial number
int detach_no;
qreal dpmx; // dots per meter X (or 0)
qreal dpmy; // dots per meter Y (or 0)
QPoint offset; // offset in pixels
uint own_data : 1;
uint ro_data : 1;
uint has_alpha_clut : 1;
uint is_cached : 1;
uint is_locked : 1;
QImageCleanupFunction cleanupFunction;
void* cleanupInfo;
bool checkForAlphaPixels() const;
// Convert the image in-place, minimizing memory reallocation
// Return false if the conversion cannot be done in-place.
bool convertInPlace(QImage::Format newFormat, Qt::ImageConversionFlags);
QMap<QString, QString> text;
bool doImageIO(const QImage *image, QImageWriter* io, int quality) const;
QPaintEngine *paintEngine;
QColorSpace colorSpace;
struct ImageSizeParameters {
qsizetype bytesPerLine;
qsizetype totalSize;
bool isValid() const { return bytesPerLine > 0 && totalSize > 0; }
};
static ImageSizeParameters calculateImageParameters(qsizetype width, qsizetype height, qsizetype depth);
};
inline QImageData::ImageSizeParameters
QImageData::calculateImageParameters(qsizetype width, qsizetype height, qsizetype depth)
{
ImageSizeParameters invalid = { -1, -1 };
if (height <= 0)
return invalid;
// calculate the size, taking care of overflows
qsizetype bytes_per_line;
if (mul_overflow(width, depth, &bytes_per_line))
return invalid;
if (add_overflow(bytes_per_line, qsizetype(31), &bytes_per_line))
return invalid;
// bytes per scanline (must be multiple of 4)
bytes_per_line = (bytes_per_line >> 5) << 2; // can't overflow
qsizetype total_size;
if (mul_overflow(height, bytes_per_line, &total_size))
return invalid;
qsizetype dummy;
if (mul_overflow(height, qsizetype(sizeof(uchar *)), &dummy))
return invalid; // why is this here?
#if 1 || QT_VERSION < QT_VERSION_CHECK(6,0,0) // ### can only fix this if QImage dimensions are not int anymore
// Disallow images where width * depth calculations might overflow
if (width > (INT_MAX - 31) / depth)
return invalid;
#endif
return { bytes_per_line, total_size };
}
typedef void (*Image_Converter)(QImageData *dest, const QImageData *src, Qt::ImageConversionFlags);
typedef bool (*InPlace_Image_Converter)(QImageData *data, Qt::ImageConversionFlags);
extern Image_Converter qimage_converter_map[QImage::NImageFormats][QImage::NImageFormats];
extern InPlace_Image_Converter qimage_inplace_converter_map[QImage::NImageFormats][QImage::NImageFormats];
void convert_generic(QImageData *dest, const QImageData *src, Qt::ImageConversionFlags);
void convert_generic_over_rgb64(QImageData *dest, const QImageData *src, Qt::ImageConversionFlags);
bool convert_generic_inplace(QImageData *data, QImage::Format dst_format, Qt::ImageConversionFlags);
bool convert_generic_inplace_over_rgb64(QImageData *data, QImage::Format dst_format, Qt::ImageConversionFlags);
void dither_to_Mono(QImageData *dst, const QImageData *src, Qt::ImageConversionFlags flags, bool fromalpha);
const uchar *qt_get_bitflip_array();
Q_GUI_EXPORT void qGamma_correct_back_to_linear_cs(QImage *image);
#if defined(_M_ARM) && defined(_MSC_VER) // QTBUG-42038
#pragma optimize("", off)
#endif
inline int qt_depthForFormat(QImage::Format format)
{
int depth = 0;
switch(format) {
case QImage::Format_Invalid:
case QImage::NImageFormats:
Q_UNREACHABLE();
case QImage::Format_Mono:
case QImage::Format_MonoLSB:
depth = 1;
break;
case QImage::Format_Indexed8:
case QImage::Format_Alpha8:
case QImage::Format_Grayscale8:
depth = 8;
break;
case QImage::Format_RGB32:
case QImage::Format_ARGB32:
case QImage::Format_ARGB32_Premultiplied:
case QImage::Format_RGBX8888:
case QImage::Format_RGBA8888:
case QImage::Format_RGBA8888_Premultiplied:
case QImage::Format_BGR30:
case QImage::Format_A2BGR30_Premultiplied:
case QImage::Format_RGB30:
case QImage::Format_A2RGB30_Premultiplied:
depth = 32;
break;
case QImage::Format_RGB555:
case QImage::Format_RGB16:
case QImage::Format_RGB444:
case QImage::Format_ARGB4444_Premultiplied:
case QImage::Format_Grayscale16:
depth = 16;
break;
case QImage::Format_RGB666:
case QImage::Format_ARGB6666_Premultiplied:
case QImage::Format_ARGB8565_Premultiplied:
case QImage::Format_ARGB8555_Premultiplied:
case QImage::Format_RGB888:
case QImage::Format_BGR888:
depth = 24;
break;
case QImage::Format_RGBX64:
case QImage::Format_RGBA64:
case QImage::Format_RGBA64_Premultiplied:
depth = 64;
break;
}
return depth;
}
#if defined(_M_ARM) && defined(_MSC_VER)
#pragma optimize("", on)
#endif
inline QImage::Format qt_opaqueVersion(QImage::Format format)
{
switch (format) {
case QImage::Format_ARGB8565_Premultiplied:
return QImage::Format_RGB16;
case QImage::Format_ARGB8555_Premultiplied:
return QImage::Format_RGB555;
case QImage::Format_ARGB6666_Premultiplied:
return QImage::Format_RGB666;
case QImage::Format_ARGB4444_Premultiplied:
return QImage::Format_RGB444;
case QImage::Format_RGBA8888:
case QImage::Format_RGBA8888_Premultiplied:
return QImage::Format_RGBX8888;
case QImage::Format_A2BGR30_Premultiplied:
return QImage::Format_BGR30;
case QImage::Format_A2RGB30_Premultiplied:
return QImage::Format_RGB30;
case QImage::Format_RGBA64:
case QImage::Format_RGBA64_Premultiplied:
return QImage::Format_RGBX64;
case QImage::Format_ARGB32_Premultiplied:
case QImage::Format_ARGB32:
return QImage::Format_RGB32;
case QImage::Format_RGB16:
case QImage::Format_RGB32:
case QImage::Format_RGB444:
case QImage::Format_RGB555:
case QImage::Format_RGB666:
case QImage::Format_RGB888:
case QImage::Format_BGR888:
case QImage::Format_RGBX8888:
case QImage::Format_BGR30:
case QImage::Format_RGB30:
case QImage::Format_RGBX64:
case QImage::Format_Grayscale8:
case QImage::Format_Grayscale16:
return format;
case QImage::Format_Mono:
case QImage::Format_MonoLSB:
case QImage::Format_Indexed8:
case QImage::Format_Alpha8:
case QImage::Format_Invalid:
case QImage::NImageFormats:
break;
}
return QImage::Format_RGB32;
}
inline QImage::Format qt_alphaVersion(QImage::Format format)
{
switch (format) {
case QImage::Format_RGB32:
case QImage::Format_ARGB32:
return QImage::Format_ARGB32_Premultiplied;
case QImage::Format_RGB16:
return QImage::Format_ARGB8565_Premultiplied;
case QImage::Format_RGB555:
return QImage::Format_ARGB8555_Premultiplied;
case QImage::Format_RGB666:
return QImage::Format_ARGB6666_Premultiplied;
case QImage::Format_RGB444:
return QImage::Format_ARGB4444_Premultiplied;
case QImage::Format_RGBX8888:
case QImage::Format_RGBA8888:
return QImage::Format_RGBA8888_Premultiplied;
case QImage::Format_BGR30:
return QImage::Format_A2BGR30_Premultiplied;
case QImage::Format_RGB30:
return QImage::Format_A2RGB30_Premultiplied;
case QImage::Format_RGBX64:
case QImage::Format_RGBA64:
case QImage::Format_Grayscale16:
return QImage::Format_RGBA64_Premultiplied;
case QImage::Format_ARGB32_Premultiplied:
case QImage::Format_ARGB8565_Premultiplied:
case QImage::Format_ARGB8555_Premultiplied:
case QImage::Format_ARGB6666_Premultiplied:
case QImage::Format_ARGB4444_Premultiplied:
case QImage::Format_RGBA8888_Premultiplied:
case QImage::Format_A2BGR30_Premultiplied:
case QImage::Format_A2RGB30_Premultiplied:
case QImage::Format_RGBA64_Premultiplied:
return format;
case QImage::Format_Mono:
case QImage::Format_MonoLSB:
case QImage::Format_Indexed8:
case QImage::Format_RGB888:
case QImage::Format_BGR888:
case QImage::Format_Alpha8:
case QImage::Format_Grayscale8:
case QImage::Format_Invalid:
case QImage::NImageFormats:
break;
}
return QImage::Format_ARGB32_Premultiplied;
}
inline bool qt_highColorPrecision(QImage::Format format, bool opaque = false)
{
// Formats with higher color precision than ARGB32_Premultiplied.
switch (format) {
case QImage::Format_ARGB32:
case QImage::Format_RGBA8888:
return !opaque;
case QImage::Format_BGR30:
case QImage::Format_RGB30:
case QImage::Format_A2BGR30_Premultiplied:
case QImage::Format_A2RGB30_Premultiplied:
case QImage::Format_RGBX64:
case QImage::Format_RGBA64:
case QImage::Format_RGBA64_Premultiplied:
case QImage::Format_Grayscale16:
return true;
default:
break;
}
return false;
}
inline QImage::Format qt_maybeAlphaVersionWithSameDepth(QImage::Format format)
{
const QImage::Format toFormat = qt_alphaVersion(format);
return qt_depthForFormat(format) == qt_depthForFormat(toFormat) ? toFormat : format;
}
inline QImage::Format qt_opaqueVersionForPainting(QImage::Format format)
{
QImage::Format toFormat = qt_opaqueVersion(format);
// If we are switching depth anyway upgrade to RGB32
if (qt_depthForFormat(format) != qt_depthForFormat(toFormat) && qt_depthForFormat(toFormat) <= 32)
toFormat = QImage::Format_RGB32;
return toFormat;
}
inline QImage::Format qt_alphaVersionForPainting(QImage::Format format)
{
QImage::Format toFormat = qt_alphaVersion(format);
#if defined(__ARM_NEON__) || defined(__SSE2__)
// If we are switching depth anyway and we have optimized ARGB32PM routines, upgrade to that.
if (qt_depthForFormat(format) != qt_depthForFormat(toFormat) && qt_depthForFormat(toFormat) <= 32)
toFormat = QImage::Format_ARGB32_Premultiplied;
#endif
return toFormat;
}
Q_GUI_EXPORT QMap<QString, QString> qt_getImageText(const QImage &image, const QString &description);
Q_GUI_EXPORT QMap<QString, QString> qt_getImageTextFromDescription(const QString &description);
QT_END_NAMESPACE
#endif // QIMAGE_P_H
|
[
"stenzek@gmail.com"
] |
stenzek@gmail.com
|
06a0c641b7179d15f14c4864b479f7ff277022d7
|
b297b80f99532e6aff0cb6500a1079a54b830901
|
/src/Ventana.h
|
c93b816cfc193d8681ea1af4fe4364b946a73544
|
[] |
no_license
|
alejandro2014/game
|
e8076a9980d5f0b95a58dd6077b8c511ab7135f5
|
14d44dc6b0ab04fb7757574725ef47f59a314710
|
refs/heads/master
| 2016-09-12T23:32:24.993008
| 2016-04-14T19:27:01
| 2016-04-14T19:27:01
| 56,264,395
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 728
|
h
|
/*
* Juego.h
*
* Created on: 22 Nov 2009
* Author: alejandro
*/
#ifndef VENTANA_H_
#define VENTANA_H_
#include "cabecera.h"
#include "Dcel.h"
#include "Ventana.h"
#include <sys/time.h>
class Ventana {
private:
GLfloat angAlfa, angBeta;
//GLfloat distancia;
SDL_Surface *screen;
int done;
//Variables relacionadas con la medición de los fps
struct timeval tiempo0, tiempo1;
float frameRate;
public:
Ventana();
~Ventana();
void reshape(int width, int height);
void dibujarEscena(GLfloat angAlfa, GLfloat angBeta, GLfloat distancia, Dcel *dcel);
void dibujarEjes(void);
SDL_Surface* getSurface() {return screen;}
//void setDistancia(GLfloat increm) {distancia -= increm;}
};
#endif /* VENTANA_H_ */
|
[
"you@fakemail.com"
] |
you@fakemail.com
|
9b5839ac141839f42142ef616a0b0139309fe86e
|
e006fa41b367201c1772a2cdf5f99deccf5ff45f
|
/src/plato/DynamicCompliance.hpp
|
afe1d0242da76efb8734f306cd0d7660526afbc3
|
[
"BSD-2-Clause"
] |
permissive
|
overfelt/lgrtk
|
9ed00dc9e4d3dac82426c5a0de0b7e84c4a4fc63
|
d359cc17f69c8742c5375adfe6811984b1693410
|
refs/heads/master
| 2020-03-31T10:12:04.527791
| 2019-01-17T00:06:26
| 2019-01-17T00:06:43
| 152,126,312
| 0
| 0
|
NOASSERTION
| 2018-10-08T18:22:33
| 2018-10-08T18:22:33
| null |
UTF-8
|
C++
| false
| false
| 9,047
|
hpp
|
/*
* DynamicCompliance.hpp
*
* Created on: Apr 25, 2018
*/
#ifndef DYNAMICCOMPLIANCE_HPP_
#define DYNAMICCOMPLIANCE_HPP_
#include <memory>
#include <Omega_h_mesh.hpp>
#include <Omega_h_matrix.hpp>
#include <Teuchos_ParameterList.hpp>
#include "ImplicitFunctors.hpp"
#include "LinearElasticMaterial.hpp"
#include "plato/StateValues.hpp"
#include "plato/ApplyPenalty.hpp"
#include "plato/ComplexStrain.hpp"
#include "plato/SimplexFadTypes.hpp"
#include "plato/ApplyProjection.hpp"
#include "plato/PlatoStaticsTypes.hpp"
#include "plato/ComplexLinearStress.hpp"
#include "plato/ComplexElasticEnergy.hpp"
#include "plato/ComplexInertialEnergy.hpp"
#include "plato/AbstractScalarFunction.hpp"
#include "plato/LinearTetCubRuleDegreeOne.hpp"
#include "plato/SimplexStructuralDynamics.hpp"
namespace Plato
{
template<typename EvaluationType, class PenaltyFuncType, class ProjectionFuncType>
class DynamicCompliance:
public Plato::SimplexStructuralDynamics<EvaluationType::SpatialDim, EvaluationType::NumControls>,
public AbstractScalarFunction<EvaluationType>
{
private:
using Plato::SimplexStructuralDynamics<EvaluationType::SpatialDim>::m_numVoigtTerms;
using Plato::SimplexStructuralDynamics<EvaluationType::SpatialDim>::mComplexSpaceDim;
using Plato::SimplexStructuralDynamics<EvaluationType::SpatialDim>::m_numDofsPerNode;
using Plato::SimplexStructuralDynamics<EvaluationType::SpatialDim>::m_numDofsPerCell;
using Plato::SimplexStructuralDynamics<EvaluationType::SpatialDim>::m_numNodesPerCell;
using StateScalarType = typename EvaluationType::StateScalarType;
using ControlScalarType = typename EvaluationType::ControlScalarType;
using ConfigScalarType = typename EvaluationType::ConfigScalarType;
using ResultScalarType = typename EvaluationType::ResultScalarType;
private:
Plato::Scalar mDensity;
PenaltyFuncType mPenaltyFunction;
ProjectionFuncType mProjectionFunction;
Plato::ApplyPenalty<PenaltyFuncType> mApplyPenalty;
Plato::ApplyProjection<ProjectionFuncType> mApplyProjection;
Omega_h::Matrix<m_numVoigtTerms, m_numVoigtTerms> mCellStiffness;
std::shared_ptr<Plato::LinearTetCubRuleDegreeOne<EvaluationType::SpatialDim>> mCubatureRule;
public:
/**************************************************************************/
DynamicCompliance(Omega_h::Mesh& aMesh,
Omega_h::MeshSets& aMeshSets,
Plato::DataMap& aDataMap,
Teuchos::ParameterList& aProblemParams,
Teuchos::ParameterList& aPenaltyParams) :
AbstractScalarFunction<EvaluationType>(aMesh, aMeshSets, aDataMap, "Dynamic Energy"),
mDensity(aProblemParams.get<double>("Material Density", 1.0)),
mProjectionFunction(),
mPenaltyFunction(aPenaltyParams),
mApplyPenalty(mPenaltyFunction),
mApplyProjection(mProjectionFunction),
mCellStiffness(),
mCubatureRule(std::make_shared<Plato::LinearTetCubRuleDegreeOne<EvaluationType::SpatialDim>>())
/**************************************************************************/
{
// Create material model and get stiffness
Plato::ElasticModelFactory<EvaluationType::SpatialDim> tElasticModelFactory(aProblemParams);
auto tMaterialModel = tElasticModelFactory.create();
mCellStiffness = tMaterialModel->getStiffnessMatrix();
}
/**************************************************************************/
DynamicCompliance(Omega_h::Mesh& aMesh, Omega_h::MeshSets& aMeshSets, Plato::DataMap& aDataMap) :
AbstractScalarFunction<EvaluationType>(aMesh, aMeshSets, aDataMap, "Dynamic Energy"),
mDensity(1.0),
mProjectionFunction(),
mPenaltyFunction(),
mApplyPenalty(mPenaltyFunction),
mApplyProjection(mProjectionFunction),
mCellStiffness(),
mCubatureRule(std::make_shared<Plato::LinearTetCubRuleDegreeOne<EvaluationType::SpatialDim>>())
/**************************************************************************/
{
// Create material model and get stiffness
Teuchos::ParameterList tParamList;
tParamList.set < Plato::Scalar > ("Poissons Ratio", 1.0);
tParamList.set < Plato::Scalar > ("Youngs Modulus", 0.3);
Plato::IsotropicLinearElasticMaterial<EvaluationType::SpatialDim> tDefaultMaterialModel(tParamList);
mCellStiffness = tDefaultMaterialModel.getStiffnessMatrix();
}
/**************************************************************************/
virtual ~DynamicCompliance()
{
}
/**************************************************************************/
/*************************************************************************
* Evaluate f(u,z)=\frac{1}{2}u^{T}(K(z) - \omega^2 M(z))u, where u denotes
* states, z denotes controls, K denotes the stiffness matrix and M denotes
* the mass matrix.
**************************************************************************/
void evaluate(const Plato::ScalarMultiVectorT<StateScalarType> & aState,
const Plato::ScalarMultiVectorT<ControlScalarType> & aControl,
const Plato::ScalarArray3DT<ConfigScalarType> & aConfig,
Plato::ScalarVectorT<ResultScalarType> & aResult,
Plato::Scalar aTimeStep = 0.0) const
/**************************************************************************/
{
using StrainScalarType =
typename Plato::fad_type_t<Plato::SimplexStructuralDynamics<EvaluationType::SpatialDim>, StateScalarType, ConfigScalarType>;
// Elastic forces functors
Plato::ComplexElasticEnergy<m_numVoigtTerms> tComputeElasticEnergy;
Plato::ComputeGradientWorkset<EvaluationType::SpatialDim> tComputeGradientWorkset;
Plato::ComplexStrain<EvaluationType::SpatialDim, m_numDofsPerNode> tComputeVoigtStrain;
Plato::ComplexLinearStress<EvaluationType::SpatialDim, m_numVoigtTerms> tComputeVoigtStress(mCellStiffness);
// Inertial forces functors
Plato::StateValues tComputeStateValues;
Plato::ComplexInertialEnergy<EvaluationType::SpatialDim> tComputeInertialEnergy(aTimeStep, mDensity);
// Elastic forces containers
auto tNumCells = aControl.extent(0);
Plato::ScalarVectorT<ConfigScalarType> tCellVolume("CellWeight", tNumCells);
Plato::ScalarArray3DT<StrainScalarType> tCellStrain("CellStrain", tNumCells, mComplexSpaceDim, m_numVoigtTerms);
Plato::ScalarArray3DT<ResultScalarType> tCellStress("CellStress", tNumCells, mComplexSpaceDim, m_numVoigtTerms);
Plato::ScalarArray3DT<ConfigScalarType> tCellGradient("Gradient", tNumCells, m_numNodesPerCell, EvaluationType::SpatialDim);
// Inertial forces containers
Plato::ScalarVectorT<ResultScalarType> tElasticEnergy("ElasticEnergy", tNumCells);
Plato::ScalarVectorT<ResultScalarType> tInertialEnergy("InertialEnergy", tNumCells);
Plato::ScalarMultiVectorT<StateScalarType> tStateValues("StateValues", tNumCells, m_numDofsPerNode);
auto & tApplyPenalty = mApplyPenalty;
auto & tApplyProjection = mApplyProjection;
auto & tPenaltyFunction = mPenaltyFunction;
auto tQuadratureWeight = mCubatureRule->getCubWeight();
auto tBasisFunctions = mCubatureRule->getBasisFunctions();
Kokkos::parallel_for(Kokkos::RangePolicy<>(0, tNumCells), LAMBDA_EXPRESSION(const Plato::OrdinalType & aCellOrdinal)
{
// Internal forces contribution
tComputeGradientWorkset(aCellOrdinal, tCellGradient, aConfig, tCellVolume);
tCellVolume(aCellOrdinal) *= tQuadratureWeight;
tComputeVoigtStrain(aCellOrdinal, aState, tCellGradient, tCellStrain);
tComputeVoigtStress(aCellOrdinal, tCellStrain, tCellStress);
// Apply penalty to internal forces
ControlScalarType tCellDensity = tApplyProjection(aCellOrdinal, aControl);
tApplyPenalty(aCellOrdinal, tCellDensity, tCellStress);
tComputeElasticEnergy(aCellOrdinal, tCellStress, tCellStrain, tElasticEnergy);
tElasticEnergy(aCellOrdinal) *= tCellVolume(aCellOrdinal);
// Inertial forces contribution
tComputeStateValues(aCellOrdinal, tBasisFunctions, aState, tStateValues);
tComputeInertialEnergy(aCellOrdinal, tCellVolume, tStateValues, tInertialEnergy);
ControlScalarType tPenaltyValue = tPenaltyFunction(tCellDensity);
tInertialEnergy(aCellOrdinal) *= tPenaltyValue;
// Add inertial forces contribution
aResult(aCellOrdinal) = static_cast<Plato::Scalar>(0.5) *
( tElasticEnergy(aCellOrdinal) + tInertialEnergy(aCellOrdinal) );
}, "Dynamic Compliance Calculation");
}
};
// class DynamicCompliance
}//namespace Plato
#endif /* DYNAMICCOMPLIANCE_HPP_ */
|
[
"daibane@sandia.gov"
] |
daibane@sandia.gov
|
80001fa9dcaa70301d86206a1a0a3c840c716d11
|
bfa4a77fe5ccc95c6417642da7d6f886d49bd797
|
/src/integrators.cpp
|
cf589145c9daa39df6b989b78928c910ab57b4cc
|
[
"MIT"
] |
permissive
|
FerryT/SiCGp2
|
d3b73e0ce114217efd6aba71b88837b2dc10deb3
|
45a2c821c61a46fe4efe8d30f883b774abf45cec
|
refs/heads/master
| 2021-01-17T19:52:44.070766
| 2016-07-11T00:39:30
| 2016-07-11T00:39:30
| 60,373,381
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,707
|
cpp
|
/**********************************************************************
* Integration functionality -- See header file for more information. *
**********************************************************************/
#include "integrators.h"
namespace Sim {
//------------------------------------------------------------------------------
void Euler::integrate(unit h)
{
for (size_t i = 0; i < system.size; ++i)
{
system.v[i] += h * system.f[i] / system.m[i];
system.x[i] += h * system.v[i];
}
for (size_t i = 0; i < system2.size; ++i)
{
system2.v[i] += h * system2.f[i] / system2.m[i];
system2.x[i] += h * system2.v[i];
system2.w[i] += h * system2.t[i] / (system2.i[i] * system2.m[i]);
system2.o[i] += h * system2.w[i];
}
}
//------------------------------------------------------------------------------
void Verlet::integrate(unit h)
{
for (size_t i = 0; i < system.size; ++i)
{
Vec oldX = system.x[i];
system.x[i] += (h * system.v[i]) + (h * h * system.f[i] / system.m[i]);
system.v[i] = (system.x[i] - oldX) / h;
}
for (size_t i = 0; i < system2.size; ++i)
{
Vec oldX = system2.x[i];
system2.x[i] += (h * system2.v[i]) + (h * h * system2.f[i] / system2.m[i]);
system2.v[i] = (system2.x[i] - oldX) / h;
unit inertia = system2.i[i] * system2.m[i];
unit oldO = system2.o[i];
system2.o[i] += (h * system2.w[i]) + (h * h * system2.t[i] / inertia);
system2.w[i] = (system2.o[i] - oldO) / h;
}
}
//------------------------------------------------------------------------------
void MidPointBase::integrate(unit h)
{
saveState();
subint->integrate(h / 2.0);
calcForces();
restoreState();
subint->integrate(h);
}
//------------------------------------------------------------------------------
void RungeKutta4Base::integrate(unit h)
{
Vecs k1 = system.f;
Vecs u1 = system2.f;
auto v1 = system2.t;
saveState();
subint->integrate(h / 2.0);
calcForces();
restoreState();
Vecs k2 = system.f;
Vecs u2 = system2.f;
auto v2 = system2.t;
saveState();
subint->integrate(h / 2.0);
calcForces();
restoreState();
Vecs k3 = system.f;
Vecs u3 = system2.f;
auto v3 = system2.t;
saveState();
subint->integrate(h);
calcForces();
restoreState();
Vecs k4 = system.f;
Vecs u4 = system2.f;
auto v4 = system2.t;
for (size_t i = 0; i < system.size; ++i)
{
system.f[i] = k1[i]/6 + k2[i]/3 + k3[i]/3 + k4[i]/6;
system2.f[i] = u1[i]/6 + u2[i]/3 + u3[i]/3 + u4[i]/6;
system2.t[i] = v1[i]/6 + v2[i]/3 + v3[i]/3 + v4[i]/6;
}
subint->integrate(h);
}
//------------------------------------------------------------------------------
} /* namespace Sim */
//..............................................................................
|
[
"f.timmers@student.tue.nl"
] |
f.timmers@student.tue.nl
|
ac892e2d4298a4cf99f4948332d4056baacc2be0
|
0b69a011c9ffee099841c140be95ed93c704fb07
|
/problemsets/SPOJ/SPOJ - BR/BALE11.cpp
|
fa62023f937b8bd31b1dcc4d112d52ce1986d025
|
[
"Apache-2.0"
] |
permissive
|
juarezpaulino/coderemite
|
4bd03f4f2780eb6013f07c396ba16aa7dbbceea8
|
a4649d3f3a89d234457032d14a6646b3af339ac1
|
refs/heads/main
| 2023-01-31T11:35:19.779668
| 2020-12-18T01:33:46
| 2020-12-18T01:33:46
| 320,931,351
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 919
|
cpp
|
/**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
long long mergecount (vector<int> &a) {
long long count = 0;
int i, j, k, n = a.size();
if (n <= 1) return 0;
vector<int> b(a.begin(), a.begin()+n/2);
vector<int> c(a.begin()+n/2, a.end());
count += mergecount(b); count += mergecount(c);
for (i = j = k = 0 ; i < n; ++i)
if (k == c.size()) a[i] = b[j++];
else if (j == b.size()) a[i] = c[k++];
else if (b[j] <= c[k]) a[i] = b[j++];
else a[i] = c[k++], count += n/2-j;
return count;
}
int main() {
int N;
scanf("%d", &N);
vector<int> A(N,0);
for (int i = 0; i < N; i++) {
int x;
scanf("%d", &x);
A[i] = x;
}
long long ret = mergecount(A);
printf("%lld\n", ret);
return 0;
}
|
[
"juarez.paulino@gmail.com"
] |
juarez.paulino@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.