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
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 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
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
fd05e0fa40fbaa1c4eba423d29081d7e664956b3
5456502f97627278cbd6e16d002d50f1de3da7bb
/chrome/utility/media_galleries/itunes_pref_parser_win.cc
4202e6a39388655298cb1ab5be2f2e822a7522a2
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,775
cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/utility/media_galleries/itunes_pref_parser_win.h" #include "base/base64.h" #include "base/strings/string_util.h" #include "chrome/utility/media_galleries/iapps_xml_utils.h" #include "third_party/libxml/chromium/libxml_utils.h" namespace itunes { base::FilePath::StringType FindLibraryLocationInPrefXml( const std::string& pref_xml_data) { XmlReader reader; base::FilePath::StringType result; if (!reader.Load(pref_xml_data)) return result; // Find the plist node and then search within that tag. if (!iapps::SeekToNodeAtCurrentDepth(&reader, "plist")) return result; if (!reader.Read()) return result; if (!iapps::SeekToNodeAtCurrentDepth(&reader, "dict")) return result; if (!iapps::SeekInDict(&reader, "User Preferences")) return result; if (!iapps::SeekToNodeAtCurrentDepth(&reader, "dict")) return result; if (!iapps::SeekInDict(&reader, "iTunes Library XML Location:1")) return result; if (!iapps::SeekToNodeAtCurrentDepth(&reader, "data")) return result; std::string pref_value; if (!reader.ReadElementContent(&pref_value)) return result; // The data is a base64 encoded wchar_t*. Because Base64Decode uses // std::strings, the result has to be casted to a wchar_t*. std::string data; if (!base::Base64Decode(base::CollapseWhitespaceASCII(pref_value, true), &data)) return result; return base::FilePath::StringType( reinterpret_cast<const wchar_t*>(data.data()), data.size() / 2); } } // namespace itunes
[ "lixiaodonglove7@aliyun.com" ]
lixiaodonglove7@aliyun.com
c51d26931d737c9bf558713967f3a4128638f93c
5b9092bbddd3e4d887c8e1278599d63156399ded
/Source/SuhDude/SuhDudeCharacter.cpp
40daa7dfa9f012cb15685c428c31673cf5f61dc4
[]
no_license
TristanBarlow/SuhDude
9b95a9d000b7641671f1efa063ae75efefdba3e5
75a279f472a214f47e71704f1f4726518aeb99ce
refs/heads/master
2021-01-21T08:24:07.652949
2017-02-28T19:12:10
2017-02-28T19:12:10
83,342,722
0
0
null
null
null
null
UTF-8
C++
false
false
5,603
cpp
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "SuhDude.h" #include "SuhDudeCharacter.h" #include "PaperFlipbookComponent.h" #include "Components/TextRenderComponent.h" DEFINE_LOG_CATEGORY_STATIC(SideScrollerCharacter, Log, All); ////////////////////////////////////////////////////////////////////////// // ASuhDudeCharacter ASuhDudeCharacter::ASuhDudeCharacter() { // Use only Yaw from the controller and ignore the rest of the rotation. bUseControllerRotationPitch = false; bUseControllerRotationYaw = true; bUseControllerRotationRoll = false; // Set the size of our collision capsule. GetCapsuleComponent()->SetCapsuleHalfHeight(96.0f); GetCapsuleComponent()->SetCapsuleRadius(40.0f); // Create a camera boom attached to the root (capsule) CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->TargetArmLength = 500.0f; CameraBoom->SocketOffset = FVector(0.0f, 0.0f, 75.0f); CameraBoom->bAbsoluteRotation = true; CameraBoom->bDoCollisionTest = false; CameraBoom->RelativeRotation = FRotator(0.0f, -90.0f, 0.0f); // Create an orthographic camera (no perspective) and attach it to the boom SideViewCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("SideViewCamera")); SideViewCameraComponent->ProjectionMode = ECameraProjectionMode::Orthographic; SideViewCameraComponent->OrthoWidth = 2048.0f; SideViewCameraComponent->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Prevent all automatic rotation behavior on the camera, character, and camera component CameraBoom->bAbsoluteRotation = true; SideViewCameraComponent->bUsePawnControlRotation = false; SideViewCameraComponent->bAutoActivate = true; GetCharacterMovement()->bOrientRotationToMovement = false; // Configure character movement GetCharacterMovement()->GravityScale = 2.0f; GetCharacterMovement()->AirControl = 0.80f; GetCharacterMovement()->JumpZVelocity = 1000.f; GetCharacterMovement()->GroundFriction = 3.0f; GetCharacterMovement()->MaxWalkSpeed = 600.0f; GetCharacterMovement()->MaxFlySpeed = 600.0f; // Lock character motion onto the XZ plane, so the character can't move in or out of the screen GetCharacterMovement()->bConstrainToPlane = true; GetCharacterMovement()->SetPlaneConstraintNormal(FVector(0.0f, -1.0f, 0.0f)); // Behave like a traditional 2D platformer character, with a flat bottom instead of a curved capsule bottom // Note: This can cause a little floating when going up inclines; you can choose the tradeoff between better // behavior on the edge of a ledge versus inclines by setting this to true or false GetCharacterMovement()->bUseFlatBaseForFloorChecks = true; // TextComponent = CreateDefaultSubobject<UTextRenderComponent>(TEXT("IncarGear")); // TextComponent->SetRelativeScale3D(FVector(3.0f, 3.0f, 3.0f)); // TextComponent->SetRelativeLocation(FVector(35.0f, 5.0f, 20.0f)); // TextComponent->SetRelativeRotation(FRotator(0.0f, 90.0f, 0.0f)); // TextComponent->SetupAttachment(RootComponent); // Enable replication on the Sprite component so animations show up when networked GetSprite()->SetIsReplicated(true); bReplicates = true; } ////////////////////////////////////////////////////////////////////////// // Animation void ASuhDudeCharacter::UpdateAnimation() { const FVector PlayerVelocity = GetVelocity(); const float PlayerSpeedSqr = PlayerVelocity.SizeSquared(); // Are we moving or standing still? UPaperFlipbook* DesiredAnimation = (PlayerSpeedSqr > 0.0f) ? RunningAnimation : IdleAnimation; if( GetSprite()->GetFlipbook() != DesiredAnimation ) { GetSprite()->SetFlipbook(DesiredAnimation); } } void ASuhDudeCharacter::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); UpdateCharacter(); } ////////////////////////////////////////////////////////////////////////// // Input void ASuhDudeCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { // Note: the 'Jump' action and the 'MoveRight' axis are bound to actual keys/buttons/sticks in DefaultInput.ini (editable from Project Settings..Input) PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping); PlayerInputComponent->BindAxis("MoveRight", this, &ASuhDudeCharacter::MoveRight); PlayerInputComponent->BindTouch(IE_Pressed, this, &ASuhDudeCharacter::TouchStarted); PlayerInputComponent->BindTouch(IE_Released, this, &ASuhDudeCharacter::TouchStopped); } void ASuhDudeCharacter::MoveRight(float Value) { /*UpdateChar();*/ // Apply the input to the character motion AddMovementInput(FVector(1.0f, 0.0f, 0.0f), Value); } void ASuhDudeCharacter::TouchStarted(const ETouchIndex::Type FingerIndex, const FVector Location) { // jump on any touch Jump(); } void ASuhDudeCharacter::TouchStopped(const ETouchIndex::Type FingerIndex, const FVector Location) { StopJumping(); } void ASuhDudeCharacter::UpdateCharacter() { // Update animation to match the motion UpdateAnimation(); // Now setup the rotation of the controller based on the direction we are travelling const FVector PlayerVelocity = GetVelocity(); float TravelDirection = PlayerVelocity.X; // Set the rotation so that the character faces his direction of travel. if (Controller != nullptr) { if (TravelDirection < 0.0f) { Controller->SetControlRotation(FRotator(0.0, 180.0f, 0.0f)); } else if (TravelDirection > 0.0f) { Controller->SetControlRotation(FRotator(0.0f, 0.0f, 0.0f)); } } }
[ "Samandfrodo12" ]
Samandfrodo12
37fe2910c9e83ac4eb6ed50cddeec9a5bac9c2fe
41e79266058dc526a30b81d5a399fc5f8fce36b5
/src/ApiDump/ApiDumpInfo.h
dd3732508723aa993d85459a726ba7b131c15aec
[]
no_license
hyyh619/GLESAPIAnalyzer
c90d5bdafb6eedfe7367c089bf77a3e0a4f22238
a872391f8f8e0f538b0729e64c4de30b86737747
refs/heads/master
2021-01-10T10:12:57.665278
2015-11-27T03:10:54
2015-11-27T03:10:54
46,329,379
0
0
null
null
null
null
UTF-8
C++
false
false
9,144
h
#ifndef __API_DUMPINFO_H #define __API_DUMPINFO_H #include <stdio.h> #include <map> #include <GLES3/gl31.h> #include "utils.h" #include "GLESGlobal.h" #include "GLES3VertexBuffer.h" #include "GLSLShader.h" #include "GLES3Tex.h" #define DRAW_BIN_HEADER "DRAW_BIN" #define API_PERFORMANCE_FRAME_NUM 500 #define API_GL_NAME_MAP_SIZE 0x10000 #define API_GL_NAME_KEY(type, old) (((old >> 16) + (old & 0xFFFF)) | (type << 4)) typedef std::map<GLuint, CShaderObj*> ApiShaderMap; typedef std::map<GLuint, CProgramObj*> ApiProgramMap; class CGLES3Context; // these go into the next 8 bits enum { API_GL_SAMPLER = 0x100, API_GL_PROGRAM = 0x200, API_GL_SHADER = 0x300, API_GL_FRAMEBUFFER = 0x400, API_GL_RENDERBUFFER = 0x500, API_GL_VARRAY = 0x600, API_GL_QUERY = 0x700, API_GL_TFBACK = 0x800, API_GL_SYNC = 0x900, API_GL_TRUE = 0xa00, API_GL_FALSE = 0xb00, API_GL_ARRAY_RECLAIM = 0xc00, API_GL_PIPELINE = 0xd00, API_GL_UNIFORM_BLOCK = 0xe00 }; typedef enum _DumpCommand { Dump_DrawElements = 1, Dump_DrawArrays, Dump_ShaderSource, Dump_BindAttribLocation, Dump_Uniform, Dump_Texture, Dump_ActiveTexture, Dump_BindTexture, Dump_TexParameter, Dump_TexImage2D, Dump_VertexAttribPointer, Dump_ColorMask, Dump_Viewport, Dump_Enable, Dump_Disable, Dump_Clear, Dump_Invalid } DumpCommand; class CFrameInfo { public: CFrameInfo(GLuint nFrame); ~CFrameInfo(); public: GLuint m_nFrame; // frame sequence GLuint m_nFrameTimeBeforeEglSwap; // current frame ticks before eglSwapBuffers GLuint m_nFrameTimeAfterEglSwap; // current frame ticks after eglSwapBuffers GLuint m_nEventStartTime; // current start event ticks GLuint m_nFramePlayEventTimeCost; // only PlayEvent cost time GLfloat m_fFramePlayEventTimeCost; GLfloat m_fFrameTimeCost; // current frame cost between each eglSwapBuffers GLfloat m_fFrameRenderTimeCost; // current frame render cost on GLES driver GLuint m_nTotalEvent; // all event in one frame. /* Draw Info */ GLuint m_nDrawCount; GLuint m_nProcessedVertexCount; GLuint m_nPrimitiveCount; GLuint m_nPixelsCount; /* Texture Info */ GLuint m_nTexImageTotalCount; // Includes glTexImage2D, glTexSubImage2D, glCompressedTexImage2D, glCompressedTexSubImage2D GLuint m_nTexImageTotalDataSize; // Includes glTexImage2D, glTexSubImage2D, glCompressedTexImage2D, glCompressedTexSubImage2D GLuint m_nTexImageCompressedCount; GLuint m_nTexImageCompressedDataSize; // Compressed texture image only GLuint m_nTexImageCount; GLuint m_nTexImageDataSize; // no compressed texture image. /* vertex data info */ GLuint m_nBufferDataCount; // Includes all calls of glBufferData and glBufferSubData GLuint m_nBufferDataSize; // Includes vertex data size of all glBufferData and glBufferSubData GLuint m_nVertexAttribData; // Includes glVertexAttribPointer data. }; typedef std::map<GLuint, CFrameInfo*> FrameInfoMap; class CDumpInfo { public: CDumpInfo(const GLchar *path, CGLES3Context *pContext); ~CDumpInfo(); GLvoid Release(); GLvoid OutputFunCallNum(); GLvoid OutputStatistic(); GLvoid AddFrame(); GLvoid BeginEvent(GLESAPIIndex func); GLvoid EndEvent(GLESAPIIndex func); GLvoid BeginRender(); GLvoid EndRender(); GLvoid BeginFrameInfo(GLESAPIIndex func); GLvoid EndFrameInfo(GLESAPIIndex func); CFrameInfo* FindFrameInfo(GLuint nFrame); GLvoid InsertFrameInfo(CFrameInfo *pFrame); GLboolean IsDrawCommand(GLESAPIIndex name); GLboolean IsDrawCommandWithoutClear(GLESAPIIndex name); GLboolean IsDrawNeedDump(); GLvoid DumpColorBuffer(GLchar *fileName); GLvoid DumpDraw(GLESAPIIndex func); GLvoid DumpDrawStates(); GLvoid DumpDrawElements(GLESAPIIndex func); GLvoid DumpDrawArrays(GLESAPIIndex func); GLvoid DumpVertexData(GLESAPIIndex func, CFrameInfo *pFrame, GLuint vertexCount, GLuint start); GLvoid DumpShader(GLESAPIIndex func, CFrameInfo *pFrame); GLvoid GetVertexAttribData(GLESAPIIndex func, CFrameInfo *pFrame, GLuint vertexCount); GLvoid DumpTexture(GLint loc, GLenum type, GLuint size); GLvoid DumpTextureImage(GLuint unit, stTexImage *pTexImage); GLvoid DumpTextureParameter(GLenum target, GLuint unit); GLvoid DumpUniformValue(GLint loc, GLenum type, GLuint size); GLvoid DumpToFile(FILE *pFile, const GLchar *fmt, ...); GLvoid DumpToSingleFile(GLchar *pInfo, GLuint len); GLvoid SaveIndexFile(GLESAPIIndex func); GLvoid SaveVBO(GLuint vbo, GLuint vertexCount, GLuint strideo, GLuint start); GLvoid SaveVAP(GLuint pointer, GLuint offset, GLuint vertexCount, GLuint stride); GLvoid SaveShaderSource(GLESAPIIndex func, CFrameInfo *pFrame); GLvoid WriteDraw(GLESAPIIndex func); GLvoid WriteDrawElements(GLESAPIIndex func); GLvoid WriteDrawArrays(GLESAPIIndex func); GLvoid WriteShader(GLESAPIIndex func); GLvoid WriteUniformValue(GLint loc, GLenum type, GLuint size); GLvoid WriteTexture(GLint loc, GLenum type, GLuint size); GLvoid WriteTextureParameter(GLenum target, GLuint unit); GLvoid WriteTextureImage(GLuint unit, stTexImage *pTexImage); GLvoid WriteVertexData(GLESAPIIndex func); GLvoid WriteDrawStates(); GLvoid WriteClear(); GLvoid CompressFile(const GLchar *fileName); CShaderObj* FindShaderObject(GLuint name); CProgramObj* FindProgramObject(GLuint name); CAttribObj* FindAttribObjByIndex(GLuint index); CAttribObj* FindAttributeByName(CProgramObj *program, GLchar *name); CUniformObj* FindUniformByOldLoc(GLuint program, GLint location); GLvoid SaveProgram(); GLvoid LoadProgram(); public: CGLES3Context *m_pContext; GLboolean m_bWriteDrawBin; GLboolean m_bTimeOnly; GLboolean m_bCaculateRenderPixels; GLboolean m_bDumpPng; GLuint m_nCurrentFrame; // Record current frame GLuint m_nSampleFrame; // we will sample render info after running each m_nSampleFrame GLfloat m_fCurrentFrameCost; // It's time between eglSwapBuffers. GLuint m_nLastFrameTicks; GLuint m_nEventBeginTicks; GLfloat m_fCurrentFrameEventCost; // It's time of PlayEvent cost between eglSwapBuffers. GLuint m_nRenderStartTime; GLuint m_nRenderEndTime; GLuint m_nRenderTotalTime; GLfloat m_fTotalRenderTime; GLfloat m_fTotalPlayEventTime; GLfloat m_fTotalRunTime; FrameInfoMap m_frameMap; GLboolean m_bDumpEnable; FILE *m_pDumpFile; GLchar *m_strDumpFilePath; FILE *m_pDumpDrawFile; GLchar *m_strDumpDrawFilePath; GLchar *m_strPath; GLchar m_strDrawBinary[256]; FILE *m_pDrawBinFile; FILE *m_pDrawSingleFile; GLchar *m_pPixelBuffers; GLchar *m_pLastPixelBuffers; GLuint m_nPixelBuffersSize; GLuint m_nCurrentPixels; GLuint m_nWidth; GLuint m_nHeight; GLuint m_nDrawTotal; GLuint m_nCurrentProgram; GLuint m_nOrigProgram; GLclampf m_clearColorR; GLclampf m_clearColorG; GLclampf m_clearColorB; GLclampf m_clearColorA; GLclampf m_clearDepth; GLint m_clearStencil; GLint m_clearBits; GLuint m_frameCount; GLuint m_startTime; GLuint m_totalFrames; GLuint m_totalTime; GLboolean m_bOutputFunCallNum; GLint m_nSavedProgram; }; #endif /*__API_DUMPINFO_H*/
[ "hyyh619@hotmail.com" ]
hyyh619@hotmail.com
bd6d32aa345f9cc8a91c9397b724468f8bc6d633
2637de3e42d962914dcb911d8c4f0a9bf3e77219
/SueHW1/book.h
969529feea44b6f15b4c882264ef2fbf69fcaf8e
[]
no_license
cdesch/SueHW1
944d186ef6f31aae44086e05d335ab6b5f3f5311
16b3b29cb7ff91d952c94fd8cf5d2e4d1cc6a662
refs/heads/master
2016-09-10T09:10:34.021280
2014-09-05T20:51:45
2014-09-05T20:51:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
963
h
// // book.h // SueHW1 // // Created by cj on 9/3/14. // Copyright (c) 2014 KickinEspresso. All rights reserved. // #ifndef SueHW1_book_h #define SueHW1_book_h #include <string> #include "personStruct.h" class Book { private: std::string title; PersonStruct author; std::string publisher; std::string language; int rating; int year; public: //Constructor Book(std::string t, PersonStruct a,std::string l,std::string p, int y, int r); //This is the constructor //Deconstructor ~Book(); //Member functions// void printInfo(); //Getters// std::string getTitle(); //****This is where you would put the function declarations for the getters!! //PersonStruct getAuthor(); //Setters// void setTitle(std::string t); //****This is where you would put the function declarations for the setters!! //void setAuthor(PersonStruct person); }; #endif
[ "cdesch@gmail.com" ]
cdesch@gmail.com
fdb37b70d836d8d4ca0ec6f67a306b9314fcaab7
60f5411fbe904a7876068775c053f200ccf4597e
/engine/assets/BmfLoader.hpp
223b037fa710083b1ea4ff03acff7d62f5b8eca3
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
focusgames-fz/ouzel
0ff3b32d9eea5984928b42f8c3678fa8bec535ab
fe3a7bb855ceb5608e90801db7eb2a79e2f9235a
refs/heads/master
2023-04-01T16:36:14.168750
2021-04-23T00:46:59
2021-04-23T00:46:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
502
hpp
// Ouzel by Elviss Strazdins #ifndef OUZEL_ASSETS_BMFLOADER_HPP #define OUZEL_ASSETS_BMFLOADER_HPP #include "Loader.hpp" namespace ouzel::assets { class BmfLoader final: public Loader { public: explicit BmfLoader(Cache& initCache); bool loadAsset(Bundle& bundle, const std::string& name, const std::vector<std::byte>& data, bool mipmaps = true) override; }; } #endif // OUZEL_ASSETS_BMFLOADER_HPP
[ "elviss@elviss.lv" ]
elviss@elviss.lv
de5cf9b008b8c942d74842662032fe947ace7080
9f9660f318732124b8a5154e6670e1cfc372acc4
/Case_save/Case20/case6/1100/T
0d3d90d234766443042c8832a741e3a92028ffe2
[]
no_license
mamitsu2/aircond5
9a6857f4190caec15823cb3f975cdddb7cfec80b
20a6408fb10c3ba7081923b61e44454a8f09e2be
refs/heads/master
2020-04-10T22:41:47.782141
2019-09-02T03:42:37
2019-09-02T03:42:37
161,329,638
0
0
null
null
null
null
UTF-8
C++
false
false
7,218
// -*- C++ -*- // File generated by PyFoam - sorry for the ugliness FoamFile { version 2.0; format ascii; class volScalarField; location "1100"; object T; } dimensions [ 0 0 0 1 0 0 0 ]; internalField nonuniform List<scalar> 459 ( 304.202 303.937 303.928 303.928 303.927 303.925 303.924 303.922 303.92 303.917 303.913 303.905 303.896 303.885 303.873 303.795 303.786 303.782 303.778 303.775 303.773 303.771 303.769 303.767 303.765 303.763 303.761 303.758 303.756 303.754 303.751 303.748 303.745 303.748 304.396 303.975 303.957 303.962 303.967 303.972 303.975 303.977 303.976 303.974 303.965 303.95 303.928 303.9 303.869 303.845 303.827 303.786 303.776 303.77 303.766 303.762 303.759 303.756 303.752 303.748 303.744 303.74 303.736 303.732 303.729 303.726 303.724 303.723 303.722 303.735 304.591 304.02 303.986 303.999 304.014 304.028 304.039 304.048 304.053 304.052 304.042 304.019 303.985 303.942 303.896 303.857 303.828 303.785 303.774 303.77 303.767 303.765 303.763 303.757 303.751 303.745 303.739 303.733 303.728 303.722 303.717 303.713 303.711 303.71 303.711 303.727 304.779 304.078 304.014 304.031 304.055 304.079 304.102 304.121 304.133 304.136 304.125 304.096 304.049 303.99 303.927 303.871 303.826 303.804 303.784 303.776 303.774 303.773 303.772 303.771 303.77 303.768 303.767 303.766 303.764 303.761 303.758 303.755 303.75 303.734 303.719 303.71 303.723 304.953 304.151 304.044 304.054 304.083 304.116 304.148 304.178 304.202 304.211 304.202 304.168 304.11 304.037 303.96 303.891 303.838 303.805 303.786 303.779 303.778 303.78 303.781 303.782 303.782 303.782 303.781 303.78 303.777 303.774 303.769 303.764 303.756 303.744 303.727 303.713 303.718 303.759 303.79 303.799 305.103 304.245 304.101 304.079 304.101 304.134 304.17 304.207 304.242 304.264 304.259 304.221 304.155 304.072 303.985 303.906 303.845 303.806 303.786 303.78 303.783 303.787 303.79 303.792 303.794 303.794 303.793 303.792 303.789 303.785 303.778 303.77 303.761 303.749 303.734 303.719 303.716 303.732 303.741 303.769 305.226 304.4 304.254 304.179 304.158 304.165 304.189 304.221 304.262 304.293 304.287 304.243 304.17 304.082 303.991 303.91 303.846 303.804 303.784 303.781 303.787 303.794 303.799 303.802 303.804 303.805 303.805 303.803 303.8 303.795 303.787 303.776 303.765 303.753 303.74 303.726 303.719 303.723 303.727 303.751 305.426 304.811 304.651 304.505 304.392 304.328 304.303 304.304 304.324 304.329 304.298 304.234 304.149 304.056 303.966 303.889 303.831 303.794 303.779 303.782 303.791 303.8 303.807 303.811 303.814 303.816 303.816 303.814 303.811 303.807 303.8 303.79 303.776 303.764 303.755 303.745 303.742 303.749 303.764 303.884 305.705 305.436 305.161 304.936 304.755 304.622 304.532 304.475 304.431 304.359 304.267 304.167 304.069 303.978 303.9 303.839 303.798 303.775 303.772 303.783 303.795 303.806 303.814 303.819 303.823 303.826 303.827 303.827 303.827 303.825 303.824 303.824 303.828 303.834 303.848 303.868 303.896 303.924 303.946 303.998 297.9 301.808 303.186 303.678 303.886 303.97 303.986 303.982 303.958 303.921 303.877 303.832 303.792 303.766 303.754 303.754 303.767 303.784 303.798 303.809 303.818 303.825 303.831 303.836 303.84 303.843 303.846 303.849 303.852 303.856 303.86 303.867 303.879 303.895 303.913 303.932 303.946 303.963 298.654 301.675 302.659 303.2 303.483 303.618 303.673 303.696 303.707 303.71 303.706 303.698 303.693 303.705 303.723 303.745 303.766 303.783 303.797 303.808 303.817 303.825 303.833 303.839 303.845 303.851 303.855 303.86 303.864 303.867 303.872 303.878 303.886 303.896 303.908 303.921 303.923 303.943 300.724 300.646 300.641 302.374 302.883 303.189 303.445 303.518 303.552 303.567 303.58 303.593 303.604 303.615 303.636 303.696 303.725 303.744 303.76 303.772 303.782 303.791 303.8 303.807 303.814 303.821 303.827 303.833 303.84 303.846 303.852 303.858 303.863 303.869 303.876 303.884 303.891 303.888 303.924 304.01 ) ; boundaryField { floor { type wallHeatTransfer; Tinf uniform 305.2; alphaWall uniform 0.24; value nonuniform List<scalar> 29 ( 304.031 304.029 304.033 304.038 304.042 304.045 304.048 304.054 304.061 304.067 304.074 304.08 304.086 304.092 304.098 304.105 304.112 304.12 304.126 304.149 304.149 304.09 304.054 304.03 304.031 304.029 303.991 303.967 303.958 ) ; } ceiling { type wallHeatTransfer; Tinf uniform 303.2; alphaWall uniform 0.24; value nonuniform List<scalar> 43 ( 300.892 300.807 300.795 302.421 302.902 303.19 303.429 303.495 303.525 303.536 303.546 303.554 303.561 303.567 303.581 303.633 303.66 303.678 303.69 303.699 303.708 303.715 303.721 303.727 303.732 303.737 303.741 303.746 303.751 303.757 303.763 303.771 303.779 303.787 303.796 303.807 303.813 303.804 303.834 303.925 305.585 305.345 298.908 ) ; } sWall { type wallHeatTransfer; Tinf uniform 315.2; alphaWall uniform 0.36; value uniform 302.15; } nWall { type wallHeatTransfer; Tinf uniform 307.2; alphaWall uniform 0.36; value nonuniform List<scalar> 6 ( 304.465 304.427 304.381 304.476 304.451 304.489 ) ; } sideWalls { type empty; } glass1 { type wallHeatTransfer; Tinf uniform 315.2; alphaWall uniform 4.3; value nonuniform List<scalar> 9 ( 312.378 311.688 311.219 310.837 310.517 310.237 310.003 310.044 310.236 ) ; } glass2 { type wallHeatTransfer; Tinf uniform 307.2; alphaWall uniform 4.3; value nonuniform List<scalar> 2 ( 306.021 306.1 ) ; } sun { type wallHeatTransfer; Tinf uniform 305.2; alphaWall uniform 0.24; value nonuniform List<scalar> 14 ( 304.338 304.103 304.097 304.092 304.088 304.084 304.08 304.076 304.073 304.069 304.063 304.057 304.049 304.04 ) ; } heatsource1 { type fixedGradient; gradient uniform 0; } heatsource2 { type fixedGradient; gradient uniform 0; } Table_master { type zeroGradient; } Table_slave { type zeroGradient; } inlet { type fixedValue; value uniform 293.15; } outlet { type zeroGradient; } } // ************************************************************************* //
[ "mitsuaki.makino@tryeting.jp" ]
mitsuaki.makino@tryeting.jp
c6134ae33a22f6163cdc295b734a15e01d8b724a
d6f2d7af06687e423e60e50d416fa8c777c09c36
/OHANISER-14518369-src.cpp
7636be1cbb094053d168c9bb278f77d1801ed081
[]
no_license
curiousTauseef/my-spoj-solutions
b9a70eaddaf0c3b9a43c278b9af1148806aff600
66b11d97073388fcebce3b74025c61839d8d5d18
refs/heads/master
2021-05-30T11:48:41.552433
2016-02-12T16:59:56
2016-02-12T16:59:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
810
cpp
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<cmath> #include<cstdlib> #include<cctype> #include<sstream> #include<vector> #include<algorithm> #define MAX 100005 #define mod 1000000007 using namespace std; long long modex(long long base,long long expo){ if(expo==0) return 1; long long f=modex(base,expo/2); if((expo&1)==0) return (f*f)%mod; return ((f*f)%mod*base%mod)%mod; } int main(){ int t,i; scanf("%d",&t); for(i=1;i<=t;++i){ int n; scanf("%d",&n); if(n==1) printf("Case %d: 1\n",i); else{ --n; long long res=modex(2,n-1); res=res%mod*(n+2)%mod; printf("Case %d: %lld\n",i,res); } } return 0; }
[ "mayank_124@localhost.localdomain" ]
mayank_124@localhost.localdomain
bfd95801ce4f13efcc95c254b8afc675258f1e83
b5c963a7451bc3b6a2aecd099760738ecf8087bb
/test_vds.cpp
2c74a47b8c485a64cd81df4455285029c55efcbc
[]
no_license
CurtHill/VDS
196af05362d3af131836c47432852f513cb43a35
f88df68eb35ad5f3fb809dd1304441f05bb0ce94
refs/heads/master
2020-03-16T12:23:21.932864
2018-05-09T15:25:53
2018-05-09T15:51:21
132,665,581
0
0
null
null
null
null
UTF-8
C++
false
false
1,361
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop USEFORM("..\OBJECTS\userlog\UserLog.cpp", UserLogWindow); USEFORM("..\OBJECTS\about\Curt_About.cpp", CurtAbout); USEFORM("TestFormVDS.cpp", MainForm); USELIB("..\OBJECTS\Objects.lib"); USELIB("x3d_lib.lib"); USEUNIT("Visual_Data_Structure.cpp"); USEUNIT("Pointer_Based_Object.cpp"); USEUNIT("Visual_Pointer.cpp"); USEUNIT("Display_Type.cpp"); USEUNIT("LinkedList.cpp"); USEUNIT("LinkedNode.cpp"); USEUNIT("Visual_Display.cpp"); USEUNIT("CurtNode.cpp"); USEUNIT("CurtTree.cpp"); USEUNIT("Circle_List.cpp"); USEUNIT("vds_memory.cpp"); USEUNIT("PtrStatus.cpp"); //--------------------------------------------------------------------------- WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { try { Application->Initialize(); Application->CreateForm(__classid(TMainForm), &MainForm); Application->CreateForm(__classid(TUserLogWindow), &UserLogWindow); Application->CreateForm(__classid(TCurtAbout), &CurtAbout); Application->Run(); } catch (Exception &exception) { Application->ShowException(&exception); } return 0; } //---------------------------------------------------------------------------
[ "curt.hill@vcsu.edu" ]
curt.hill@vcsu.edu
14f53a36156b921697084a5f80bd640f7121302a
c666cb9dfc26969ef24911d4732b3ecc8152f195
/third_party/blink/renderer/core/layout/ng/inline/ng_fragment_item.h
526f635e5133ff05871233134cdce5518a76dfa4
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause" ]
permissive
winter-txieyyue/chromium
476082ed41ffdfdb70bc6f3e679e124efab232a5
ec74d09215adc6fd83caf2033367df40c26b907c
refs/heads/master
2023-01-12T22:34:40.755233
2019-10-17T02:29:16
2019-10-17T02:29:16
215,688,941
1
0
BSD-3-Clause
2019-10-17T02:45:49
2019-10-17T02:45:49
null
UTF-8
C++
false
false
11,340
h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_NG_FRAGMENT_ITEM_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_NG_FRAGMENT_ITEM_H_ #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/core/layout/geometry/logical_offset.h" #include "third_party/blink/renderer/core/layout/layout_object.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_line_box_fragment_builder.h" #include "third_party/blink/renderer/core/layout/ng/inline/ng_line_height_metrics.h" #include "third_party/blink/renderer/platform/graphics/paint/display_item_client.h" namespace blink { class NGFragmentItems; class NGInlineBreakToken; struct NGTextFragmentPaintInfo; // This class represents a text run or a box in an inline formatting context. // // This class consumes less memory than a full fragment, and can be stored in a // flat list (NGFragmentItems) for easier and faster traversal. class CORE_EXPORT NGFragmentItem : public DisplayItemClient { public: // Represents regular text that exists in the DOM. struct TextItem { scoped_refptr<const ShapeResultView> shape_result; // TODO(kojii): |start_offset| and |end_offset| should match to the offset // in |shape_result|. Consider if we should remove them, or if keeping them // is easier. const unsigned start_offset; const unsigned end_offset; }; // Represents text generated by the layout engine, e.g., hyphen or ellipsis. struct GeneratedTextItem { scoped_refptr<const ShapeResultView> shape_result; String text; }; // A start marker of a line box. struct LineItem { NGLineHeightMetrics metrics; scoped_refptr<const NGInlineBreakToken> inline_break_token; wtf_size_t descendants_count; }; // Represents a box fragment appeared in a line. This includes inline boxes // (e.g., <span>text</span>) and atomic inlines. struct BoxItem { // If this item is an inline box, its children are stored as following // items. |descendants_count_| has the number of such items. // // If this item is a root of another IFC/BFC, children are stored normally, // as children of |box_fragment|. // // Note:|box_fragment| can be null for <span>. scoped_refptr<const NGPhysicalBoxFragment> box_fragment; wtf_size_t descendants_count; }; enum ItemType { kText, kGeneratedText, kLine, kBox }; // TODO(kojii): Should be able to create without once creating fragments. NGFragmentItem(const NGPhysicalTextFragment& text); NGFragmentItem(const NGPhysicalBoxFragment& box, wtf_size_t item_count); NGFragmentItem(const NGPhysicalLineBoxFragment& line, wtf_size_t item_count); ~NGFragmentItem() final; ItemType Type() const { return static_cast<ItemType>(type_); } bool IsAtomicInline() const; bool IsHiddenForPaint() const { return is_hidden_for_paint_; } NGStyleVariant StyleVariant() const { return static_cast<NGStyleVariant>(style_variant_); } bool UsesFirstLineStyle() const { return StyleVariant() == NGStyleVariant::kFirstLine; } // Returns the style for this fragment. // // For a line box, this returns the style of the containing block. This mostly // represents the style for the line box, except 1) |style.Direction()| maybe // incorrect, use |BaseDirection()| instead, and 2) margin/border/padding, // background etc. do not apply to the line box. const ComputedStyle& Style() const { return layout_object_->EffectiveStyle(StyleVariant()); } const LayoutObject* GetLayoutObject() const { return layout_object_; } bool HasSameParent(const NGFragmentItem& other) const; const PhysicalRect& Rect() const { return rect_; } const PhysicalOffset& Offset() const { return rect_.offset; } const PhysicalSize& Size() const { return rect_.size; } void SetOffset(const PhysicalOffset& offset) { rect_.offset = offset; } PhysicalRect LocalRect() const { return {PhysicalOffset(), Size()}; } PhysicalRect SelfInkOverflow() const; // Count of following items that are descendants of this item in the box tree, // including this item. 1 means this is a box (box or line box) without // descendants. 0 if this item type cannot have children. wtf_size_t DescendantsCount() const { if (Type() == kBox) return box_.descendants_count; if (Type() == kLine) return line_.descendants_count; return 0; } // Returns |NGPhysicalBoxFragment| if one is associated with this item. const NGPhysicalBoxFragment* BoxFragment() const { if (Type() == kBox) return box_.box_fragment.get(); return nullptr; } Node* GetNode() const { return layout_object_->GetNode(); } NGTextFragmentPaintInfo TextPaintInfo(const NGFragmentItems& items) const; // DisplayItemClient overrides String DebugName() const override; IntRect VisualRect() const override; // Find |NGFragmentItem|s that are associated with a |LayoutObject|. class CORE_EXPORT ItemsForLayoutObject { STACK_ALLOCATED(); public: ItemsForLayoutObject() = default; ItemsForLayoutObject(const Vector<std::unique_ptr<NGFragmentItem>>& items, unsigned first_index, const NGFragmentItem* first_item) : items_(&items), first_item_(first_item), first_index_(first_index) {} bool IsEmpty() const { return !items_; } class CORE_EXPORT Iterator { public: Iterator(const Vector<std::unique_ptr<NGFragmentItem>>* items, unsigned index, const NGFragmentItem* item) : current_(item), items_(items), index_(index) {} const NGFragmentItem& operator*() const { return *current_; } const NGFragmentItem& operator->() const { return *current_; } Iterator& operator++(); bool operator==(const Iterator& other) const { return current_ == other.current_; } bool operator!=(const Iterator& other) const { return current_ != other.current_; } private: const NGFragmentItem* current_; const Vector<std::unique_ptr<NGFragmentItem>>* items_; unsigned index_; }; using iterator = Iterator; iterator begin() const { return Iterator(items_, first_index_, first_item_); } iterator end() const { return Iterator(nullptr, 0, nullptr); } private: const Vector<std::unique_ptr<NGFragmentItem>>* items_; const NGFragmentItem* first_item_; unsigned first_index_; }; static ItemsForLayoutObject ItemsFor(const LayoutObject& layout_object); static PhysicalRect LocalVisualRectFor(const LayoutObject& layout_object); // Painters can use const methods only, except for these explicitly declared // methods. class MutableForPainting { STACK_ALLOCATED(); public: // TODO(kojii): Add painter functions. private: friend class NGFragmentItem; MutableForPainting(const NGFragmentItem& item) {} }; MutableForPainting GetMutableForPainting() const { return MutableForPainting(*this); } // Functions for |TextItem| and |GeneratedTextItem| bool IsFlowControl() const { DCHECK_EQ(Type(), kText); return is_flow_control_; } bool IsHorizontal() const { return IsHorizontalWritingMode(GetWritingMode()); } WritingMode GetWritingMode() const { DCHECK_EQ(Type(), kText); return Style().GetWritingMode(); } // TODO(yosin): We'll implement following functions. bool IsLineBreak() const { return false; } bool IsEllipsis() const { return false; } bool IsSymbolMarker() const { return false; } const ShapeResultView* TextShapeResult() const; unsigned StartOffset() const; unsigned EndOffset() const; unsigned TextLength() const { return EndOffset() - StartOffset(); } StringView Text(const NGFragmentItems& items) const; String GeneratedText() const { DCHECK_EQ(Type(), kGeneratedText); return generated_text_.text; } // Compute the inline position from text offset, in logical coordinate // relative to this fragment. LayoutUnit InlinePositionForOffset(StringView text, unsigned offset, LayoutUnit (*round_function)(float), AdjustMidCluster) const; LayoutUnit InlinePositionForOffset(StringView text, unsigned offset) const; // Compute line-relative coordinates for given offsets, this is not // flow-relative: // https://drafts.csswg.org/css-writing-modes-3/#line-directions std::pair<LayoutUnit, LayoutUnit> LineLeftAndRightForOffsets( StringView text, unsigned start_offset, unsigned end_offset) const; // The layout box of text in (start, end) range in local coordinate. // Start and end offsets must be between StartOffset() and EndOffset(). PhysicalRect LocalRect(StringView text, unsigned start_offset, unsigned end_offset) const; // The base direction of line. Also known as the paragraph direction. This may // be different from the direction of the container box when first-line style // is used, or when 'unicode-bidi: plaintext' is used. // Note: This is valid only for |LineItem|. TextDirection BaseDirection() const; // Direction of this item valid for |TextItem| and |IsAtomicInline()|. // Note: <span> doesn't have text direction. TextDirection ResolvedDirection() const; private: const LayoutObject* layout_object_; // TODO(kojii): We can make them sub-classes if we need to make the vector of // pointers. Sub-classing from DisplayItemClient prohibits copying and that we // cannot create a vector of this class. union { TextItem text_; GeneratedTextItem generated_text_; LineItem line_; BoxItem box_; }; PhysicalRect rect_; struct NGInkOverflowModel { USING_FAST_MALLOC(NGInkOverflowModel); public: NGInkOverflowModel(const PhysicalRect& self_ink_overflow, const PhysicalRect& contents_ink_overflow); PhysicalRect self_ink_overflow; // TODO(kojii): Some types (e.g., kText) never have |contents_ink_overflow|. // Can/should we optimize the memory usage for those cases? PhysicalRect contents_ink_overflow; }; mutable std::unique_ptr<NGInkOverflowModel> ink_overflow_; // TOOD(kojii): mutable because this is lazily computed, but it may not be // needed if we use |MutableForPainting|. TBD. // Item index delta to the next item for the same |LayoutObject|. // wtf_size_t delta_to_next_for_same_layout_object_ = 0; // Note: We should not add |bidi_level_| because it is used only for layout. unsigned type_ : 2; // ItemType unsigned style_variant_ : 2; // NGStyleVariant // TODO(yosin): We will change |is_flow_control_| to call |IsLineBreak()| and // |TextType() == kFlowControl|. unsigned is_flow_control_ : 1; unsigned is_hidden_for_paint_ : 1; // Note: For |TextItem| and |GeneratedTextItem|, |text_direction_| equals to // |ShapeResult::Direction()|. unsigned text_direction_ : 1; // TextDirection. }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_INLINE_NG_FRAGMENT_ITEM_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
278605b0434721e8ea7605516810b3d82dec0c9f
efd7adff589e37ca98d2e3eb245aaeb23f64496e
/src/libs/utils/projectnamevalidatinglineedit.h
9876335a2ab65c4fb40330d34d1b505ee0099fab
[]
no_license
Andersbakken/CPlusPlus
3cf03c28968243587fa1d4661e7e5a388e62eb43
400f0b8f19de1c3fc9b794228c7aeec2259fce81
refs/heads/master
2021-01-10T20:24:54.067140
2013-05-28T03:46:50
2013-05-28T03:46:50
9,491,173
2
0
null
null
null
null
UTF-8
C++
false
false
2,020
h
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** 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 Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #ifndef PROJECTNAMEVALIDATINGLINEEDIT_H #define PROJECTNAMEVALIDATINGLINEEDIT_H #include "basevalidatinglineedit.h" namespace Utils { class QTCREATOR_UTILS_EXPORT ProjectNameValidatingLineEdit : public BaseValidatingLineEdit { Q_OBJECT public: explicit ProjectNameValidatingLineEdit(QWidget *parent = 0); static bool validateProjectName(const QString &name, QString *errorMessage /* = 0*/); protected: virtual bool validate(const QString &value, QString *errorMessage) const; }; } // namespace Utils #endif // PROJECTNAMEVALIDATINGLINEEDIT_H
[ "jhanssen@gmail.com" ]
jhanssen@gmail.com
b150259c991806378d9c5e7ee0d5230ea3e6202f
6ea50d800eaf5690de87eea3f99839f07c662c8b
/ver.0.15.0.1/FlatLevelSource.h
fea4d89f7668ba9961fa57221fade1810b62989a
[]
no_license
Toku555/MCPE-Headers
73eefeab8754a9ce9db2545fb0ea437328cade9e
b0806aebd8c3f4638a1972199623d1bf686e6497
refs/heads/master
2021-01-15T20:53:23.115576
2016-09-01T15:38:27
2016-09-01T15:38:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
536
h
#pragma once class FlatLevelSource{ public: FlatLevelSource(Level *,Dimension *,std::string const&); FlatLevelSource(Level *,Dimension *,std::string const&); void loadChunk(LevelChunk &); void loadChunk(LevelChunk &); void postProcess(ChunkViewSource &); void postProcess(ChunkViewSource &); void requestChunk(ChunkPos const&,ChunkSource::LoadMode); void requestChunk(ChunkPos const&,ChunkSource::LoadMode); void ~FlatLevelSource(); void ~FlatLevelSource(); void ~FlatLevelSource(); void ~FlatLevelSource(); };
[ "sinigami3427@gmail.com" ]
sinigami3427@gmail.com
f818b0d3b1080455ea0ffb672761e6e04e052b66
53de51273e42fb1bcbf23c6a0bcec9f7575da76b
/src/scenes/font_demo/FontDemo.h
00d36451e91acb988e10882c224edd4fb86d9bf3
[]
no_license
henne90gen/graphics_playground
d5bf223bc180459a99bb590973d83d6ebceb74f2
d66915c2c42d4c46fd9d761c2acfcb073f7208d1
refs/heads/master
2023-09-02T12:27:00.338008
2023-08-31T15:22:51
2023-08-31T15:22:51
174,797,987
1
0
null
2023-08-28T11:13:14
2019-03-10T08:40:08
C
UTF-8
C++
false
false
1,606
h
#pragma once #include <ft2build.h> #include FT_FREETYPE_H #include "Scene.h" #include <functional> #include <Text.h> #include <gl/Shader.h> #include <gl/Texture.h> #include <gl/VertexArray.h> #include <gl/VertexBuffer.h> class FontDemo : public Scene { public: explicit FontDemo() : Scene("FontDemo"){}; ~FontDemo() override = default; void setup() override; void tick() override; void destroy() override; void onAspectRatioChange() override; private: std::shared_ptr<Shader> shader; std::shared_ptr<VertexArray> vertexArray; glm::mat4 projectionMatrix; Text t = {}; #if 0 std::vector<Character> characters = {}; FT_Library library = nullptr; FT_Face face = nullptr; void loadFont(std::string &fontPath, unsigned int characterHeight); Character loadCharacter(char character, unsigned int characterHeight); void loadAlphabet(unsigned int characterHeight); #endif void renderCharacter(const Character &character, const glm::vec2 &translation) const; void renderAlphabet(); void renderText(std::string &text); void renderBaseline(const glm::vec2 &translation, float zoom); }; void showSettings(std::vector<std::string> &fontPaths, glm::vec3 &color, glm::vec2 &translation, float &zoom, unsigned int &characterResolution, unsigned int &selectedFontIndex, bool &shouldRenderAlphabet, Text &t); void showFontInfo(FT_Face &face); bool settingsHaveChanged(unsigned int characterHeight, unsigned int selectedFontIndex); std::string toBits(long number);
[ "henne90gen@gmail.com" ]
henne90gen@gmail.com
7afed15c5f93c97215bf58389a4c1a1e28186abc
87edbb9c97af627a9c16d18f3527f26a62e17bb1
/leetcode/LRU-CPP/main.cpp
4e03ceeea47185821fc83676037279e5d04808a1
[]
no_license
wuzhiguocarter/OnlineJudge
47e31d17dd964189166d990d31bf08af6a83b0e3
a653246039fd4d8f1a9602064a733b7b7ddc4ccd
refs/heads/master
2020-12-02T08:10:45.510467
2019-05-19T07:04:41
2019-05-19T07:04:41
96,782,805
0
0
null
null
null
null
UTF-8
C++
false
false
414
cpp
#include "lru.h" int main(){ LRUCache cache(3); /* capacity */ cache.put(1, 1); cache.put(2, 2); cache.get(1); // returns 1 cache.put(3, 3); // evicts key 2 cache.get(2); // returns -1 (not found) cache.put(4, 4); // evicts key 1 cache.get(1); // returns -1 (not found) cache.get(3); // returns 3 cache.get(4); // returns 4 cache.printCacheList(); return 0; }
[ "noreply@github.com" ]
wuzhiguocarter.noreply@github.com
6713eed570d002168f8c727b5ab63c655d2909e2
88ae8695987ada722184307301e221e1ba3cc2fa
/chrome/browser/ui/views/menu_interactive_uitest.cc
465254b589caf5dd304b708223b8ec46a6daaecf
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
11,620
cc
// Copyright 2018 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/controls/menu/menu_controller.h" #include "base/memory/raw_ptr.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/views/native_widget_factory.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" #include "chrome/test/base/test_browser_window.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/test/browser_test.h" #include "ui/accessibility/ax_node_data.h" #include "ui/base/test/ui_controls.h" #include "ui/gfx/geometry/point.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/menu/menu_item_view.h" #include "ui/views/controls/menu/submenu_view.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/test/ax_event_counter.h" #include "ui/views/test/widget_test.h" #include "ui/views/widget/widget.h" #if !BUILDFLAG(IS_CHROMEOS_ASH) #include "ui/accessibility/platform/ax_platform_node.h" #endif #if BUILDFLAG(IS_WIN) #include "base/win/windows_version.h" #endif namespace views { namespace test { namespace { class TestButton : public Button { public: TestButton() : Button(Button::PressedCallback()) {} TestButton(const TestButton&) = delete; TestButton& operator=(const TestButton&) = delete; ~TestButton() override = default; }; } // namespace class MenuControllerUITest : public InProcessBrowserTest { public: MenuControllerUITest() {} MenuControllerUITest(const MenuControllerUITest&) = delete; MenuControllerUITest& operator=(const MenuControllerUITest&) = delete; // This method creates a MenuRunner, MenuItemView, etc, adds two menu // items, shows the menu so that it can calculate the position of the first // menu item and move the mouse there, and closes the menu. void SetupMenu(Widget* widget) { menu_delegate_ = std::make_unique<MenuDelegate>(); MenuItemView* menu_item = new MenuItemView(menu_delegate_.get()); menu_runner_ = std::make_unique<MenuRunner>( +menu_item, views::MenuRunner::CONTEXT_MENU); first_item_ = menu_item->AppendMenuItem(1, u"One"); menu_item->AppendMenuItem(2, u"Two"); // Run the menu, so that the menu item size will be calculated. menu_runner_->RunMenuAt(widget, nullptr, gfx::Rect(), views::MenuAnchorPosition::kTopLeft, ui::MENU_SOURCE_NONE); RunPendingMessages(); // Figure out the middle of the first menu item. mouse_pos_.set_x(first_item_->width() / 2); mouse_pos_.set_y(first_item_->height() / 2); View::ConvertPointToScreen( menu_item->GetSubmenu()->GetWidget()->GetRootView(), &mouse_pos_); // Move the mouse so that it's where the menu will be shown. base::RunLoop run_loop; ui_controls::SendMouseMoveNotifyWhenDone(mouse_pos_.x(), mouse_pos_.y(), run_loop.QuitClosure()); run_loop.Run(); EXPECT_TRUE(first_item_->IsSelected()); ui::AXNodeData item_node_data; first_item_->GetViewAccessibility().GetAccessibleNodeData(&item_node_data); EXPECT_EQ(item_node_data.role, ax::mojom::Role::kMenuItem); #if !BUILDFLAG(IS_CHROMEOS_ASH) // ChromeOS does not use popup focus override. EXPECT_TRUE(first_item_->GetViewAccessibility().IsFocusedForTesting()); #endif ui::AXNodeData menu_node_data; menu_item->GetSubmenu()->GetViewAccessibility().GetAccessibleNodeData( &menu_node_data); EXPECT_EQ(menu_node_data.role, ax::mojom::Role::kMenu); menu_runner_->Cancel(); RunPendingMessages(); } void RunPendingMessages() { base::RunLoop run_loop; run_loop.RunUntilIdle(); } protected: raw_ptr<MenuItemView, DanglingUntriaged> first_item_ = nullptr; std::unique_ptr<MenuRunner> menu_runner_; std::unique_ptr<MenuDelegate> menu_delegate_; // Middle of first menu item. gfx::Point mouse_pos_; }; IN_PROC_BROWSER_TEST_F(MenuControllerUITest, TestMouseOverShownMenu) { #if !BUILDFLAG(IS_CHROMEOS_ASH) content::testing::ScopedContentAXModeSetter ax_mode_setter( ui::kAXModeComplete); #endif #if BUILDFLAG(IS_WIN) // TODO(crbug.com/1286137): This test is consistently failing on Win11. if (base::win::OSInfo::GetInstance()->version() >= base::win::Version::WIN11) { GTEST_SKIP() << "Skipping test for WIN11_21H2 and greater"; } #endif // Create a parent widget. Widget* widget = new views::Widget; Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); params.bounds = {0, 0, 200, 200}; #if !BUILDFLAG(IS_CHROMEOS_ASH) && !BUILDFLAG(IS_MAC) params.native_widget = CreateNativeWidget( NativeWidgetType::DESKTOP_NATIVE_WIDGET_AURA, &params, widget); #endif widget->Init(std::move(params)); widget->Show(); views::test::WidgetActivationWaiter waiter(widget, true); widget->Activate(); waiter.Wait(); // Create a focused test button, used to assert that it has accessibility // focus before and after menu item is active, but not during. TestButton button; widget->GetContentsView()->AddChildView(&button); FocusManager* focus_manager = widget->GetFocusManager(); focus_manager->SetFocusedView(&button); EXPECT_TRUE(button.HasFocus()); EXPECT_TRUE(button.GetViewAccessibility().IsFocusedForTesting()); // SetupMenu leaves the mouse position where the first menu item will be // when we run the menu. AXEventCounter ax_counter(views::AXEventManager::Get()); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuStart), 0); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuPopupStart), 0); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuPopupEnd), 0); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuEnd), 0); SetupMenu(widget); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuStart), 1); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuPopupStart), 1); // SetupMenu creates, opens and closes a popup menu, so there will be a // a menu popup end. There is also a menu end since it's the last menu. EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuPopupEnd), 1); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuEnd), 1); EXPECT_FALSE(first_item_->IsSelected()); #if !BUILDFLAG(IS_CHROMEOS_ASH) // ChromeOS does not use popup focus override. EXPECT_FALSE(first_item_->GetViewAccessibility().IsFocusedForTesting()); #endif menu_runner_->RunMenuAt(widget, nullptr, gfx::Rect(), views::MenuAnchorPosition::kTopLeft, ui::MENU_SOURCE_NONE); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuStart), 2); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuPopupStart), 2); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuPopupEnd), 1); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuEnd), 1); EXPECT_FALSE(first_item_->IsSelected()); // One or two mouse events are posted by the menu being shown. // Process event(s), and check what's selected in the menu. RunPendingMessages(); EXPECT_FALSE(first_item_->IsSelected()); #if !BUILDFLAG(IS_CHROMEOS_ASH) // ChromeOS does not use popup focus override. EXPECT_FALSE(first_item_->GetViewAccessibility().IsFocusedForTesting()); EXPECT_TRUE(button.GetViewAccessibility().IsFocusedForTesting()); #endif // Move mouse one pixel to left and verify that the first menu item // is selected. mouse_pos_.Offset(-1, 0); base::RunLoop run_loop2; ui_controls::SendMouseMoveNotifyWhenDone(mouse_pos_.x(), mouse_pos_.y(), run_loop2.QuitClosure()); run_loop2.Run(); EXPECT_TRUE(first_item_->IsSelected()); #if !BUILDFLAG(IS_CHROMEOS_ASH) // ChromeOS does not use popup focus override. EXPECT_TRUE(first_item_->GetViewAccessibility().IsFocusedForTesting()); EXPECT_FALSE(button.GetViewAccessibility().IsFocusedForTesting()); #endif menu_runner_->Cancel(); #if !BUILDFLAG(IS_CHROMEOS_ASH) // ChromeOS does not use popup focus override. EXPECT_FALSE(first_item_->GetViewAccessibility().IsFocusedForTesting()); EXPECT_TRUE(button.GetViewAccessibility().IsFocusedForTesting()); #endif EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuStart), 2); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuPopupStart), 2); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuPopupEnd), 2); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuEnd), 2); widget->Close(); } // This test creates a menu without a parent widget, and tests that it // can receive keyboard events. // TODO(davidbienvenu): If possible, get test working for linux and // mac. Only status_icon_win runs a menu with a null parent widget // currently. #if BUILDFLAG(IS_WIN) IN_PROC_BROWSER_TEST_F(MenuControllerUITest, FocusOnOrphanMenu) { // This test is extremely flaky on WIN10_20H2, so disable. // TODO(crbug.com/1225346) Investigate why it's so flaky on that version of // Windows. if (base::win::OSInfo::GetInstance()->version() >= base::win::Version::WIN10_20H2) { GTEST_SKIP() << "Skipping test for WIN10_20H2 and greater"; } // Going into full screen mode prevents pre-test focus and mouse position // state from affecting test, and helps ui_controls function correctly. chrome::ToggleFullscreenMode(browser()); content::testing::ScopedContentAXModeSetter ax_mode_setter( ui::kAXModeComplete); MenuDelegate menu_delegate; MenuItemView* menu_item = new MenuItemView(&menu_delegate); AXEventCounter ax_counter(views::AXEventManager::Get()); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuStart), 0); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuPopupStart), 0); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuPopupEnd), 0); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuEnd), 0); std::unique_ptr<MenuRunner> menu_runner( std::make_unique<MenuRunner>(menu_item, views::MenuRunner::CONTEXT_MENU)); MenuItemView* first_item = menu_item->AppendMenuItem(1, u"One"); menu_item->AppendMenuItem(2, u"Two"); menu_runner->RunMenuAt(nullptr, nullptr, gfx::Rect(), views::MenuAnchorPosition::kTopLeft, ui::MENU_SOURCE_NONE); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuStart), 1); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuPopupStart), 1); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuPopupEnd), 0); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuEnd), 0); base::RunLoop loop; // SendKeyPress fails if the window doesn't have focus. ASSERT_TRUE(ui_controls::SendKeyPressNotifyWhenDone( menu_item->GetSubmenu()->GetWidget()->GetNativeWindow(), ui::VKEY_DOWN, false, false, false, false, loop.QuitClosure())); loop.Run(); EXPECT_TRUE(first_item->IsSelected()); EXPECT_TRUE(first_item->GetViewAccessibility().IsFocusedForTesting()); menu_runner->Cancel(); EXPECT_FALSE(first_item->GetViewAccessibility().IsFocusedForTesting()); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuStart), 1); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuPopupStart), 1); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuPopupEnd), 1); EXPECT_EQ(ax_counter.GetCount(ax::mojom::Event::kMenuEnd), 1); } #endif // BUILDFLAG(IS_WIN) } // namespace test } // namespace views
[ "jengelh@inai.de" ]
jengelh@inai.de
3725f3895c9958ad7e24125b88af210624b6693d
f84da9a7da712409ebb0e8caf89b41b68a1ffb7c
/Codeforces/contest_id_609/The Best Gift.cpp
0fcf81456e4e6c0e42ea2cb8439013e3041b96e4
[]
no_license
mahbubcseju/Programming-Problem-Solutions
7fe674d68ab340b54be64adfa2e2fb33cc64705c
e9de8553f7d0c2c439f62b67e1bf9d6e07d47400
refs/heads/master
2021-08-03T14:37:54.041903
2021-07-18T16:01:12
2021-07-18T16:01:12
199,957,649
0
0
null
null
null
null
UTF-8
C++
false
false
2,891
cpp
/******************************** *MAHBUBCSEJU * *CSE 22 * *JAHANGIRNAGAR UNIVERSITY * *TIMUS:164273FU * *UVA>>LIGHTOJ>>HUST:mahbubcseju * ********************************/ #include<cfloat> #include<climits> #include<fstream> #include<cstdio> #include<cstdlib> #include<cmath> #include<sstream> #include<iostream> #include<algorithm> #include<map> #include<cstring> #include<string> #include<vector> #include<queue> #include<stack> #include<set> #include<string.h> #define ll long long int #define ull unsigned long long int #define I(a) scanf("%d",&a) #define I2(a,b) scanf("%d%d",&a,&b) #define I3(a,b,c) scanf("%d%d%d",&a,&b,&c) #define L(a) scanf("%lld",&a) #define L2(a,b) scanf("%lld%lld",&a,&b) #define L3(a,b,c) scanf("%lld%lld%lld",&a,&b,&c) #define PI(a) printf("%d\n",a) #define PL(a) printf("%lld\n",a) #define PT(t) printf("Case %d: ",t) #define IT(x) for(typeof (x.begin()) it = x.begin(); it != x.end (); it++) #define ITP(x) for(typeof (x.begin()) it = x.begin(); it != x.end (); it++) { cout << *it << " "; } cout << endl; #define PB push_back #define xx first #define yy second #define SC scanf #define PC printf #define NL printf("\n") #define SET(a) memset(a,0,sizeof a) #define SETR(a) memset(a,-1,sizeof a) #define SZ(a) ((int)a.size()) //#define pi 2.0*acos(0.0) #define R(a) freopen(a, "r", stdin); #define W(a) freopen(a, "w", stdout); #define CB(x) __builtin_popcount(x) #define STN(a) stringtonumber<ll>(a) #define lol printf("BUG\n") #define mk make_pair using namespace std; template <class T> inline T BM(T p, T e, T M) { ll ret = 1; for(; e > 0; e >>= 1) { if(e & 1) ret = (ret * p) % M; p = (p * p) % M; } return (T)ret; } template <class T> inline T gcd(T a, T b) { if(b == 0)return a; return gcd(b, a % b); } template <class T> inline T MDINV(T a, T M) { return BM(a, M - 2, M); } template <class T> inline T PW(T p, T e) { ll ret = 1; for(; e > 0; e >>= 1) { if(e & 1) ret = (ret * p); p = (p * p); } return (T)ret; } template <class T>string NTS ( T Number ) { stringstream ss; ss << Number; return ss.str(); } template <class T>T stringtonumber ( const string &Text ) { istringstream ss(Text); T result; return ss >> result ? result : 0; } template <class T>bool ISLEFT ( T a,T b,T c) { if(((a.xx-b.xx)*(b.yy-c.yy)-(b.xx-c.xx)*(a.yy-b.yy))<0.0)return 1;//Uporer dike //A,b,c, x okkher ordera sorted else return 0; } #define mx 300000 #define md 1000000007ll #define maxp 1000004 typedef pair<ll , ll >P; typedef vector<int >V; ////////define value///// int main() { ll n,m; L2(n,m); ll res=0; ll p[20+3]; SET(p); for(ll i=1;i<=n;i++) { ll x; L(x); p[x]++; res+=(i-p[x]); } PL(res); return 0; }
[ "mahbubur.rahman@bjitgroup.com" ]
mahbubur.rahman@bjitgroup.com
a9b6e1d4e938c2bd5499966bab3ce993da459c31
9aee810d0d9d72d3dca7920447872216a3af49fe
/AtCoder/ABC/100-199/ABC134/abc134_d.cpp
469d17f3ef99ad6d7e8ef73e4967de362db26035
[]
no_license
pulcherriman/Programming_Contest
37d014a414d473607a11c2edcb25764040edd686
715308628fc19843b8231526ad95dbe0064597a8
refs/heads/master
2023-08-04T00:36:36.540090
2023-07-30T18:31:32
2023-07-30T18:31:32
163,375,122
3
0
null
2023-01-24T11:02:11
2018-12-28T06:33:16
C++
UTF-8
C++
false
false
2,684
cpp
#include <bits/stdc++.h> using namespace std; using ll=long long; using ull=unsigned long long; using vb=vector<bool>; using vvb=vector<vb>; using vd=vector<double>; using vvd=vector<vd>; using vi=vector<int>; using vvi=vector<vi>; using vl=vector<ll>; using vvl=vector<vl>; using pll=pair<ll,ll>; using tll=tuple<ll,ll>; using tlll=tuple<ll,ll,ll>; using vs=vector<string>; #define all(a) a.begin(),a.end() #define rall(a) a.rbegin(),a.rend() #define rep(i,n) range(i,0,n) #define rrep(i,n) for(ll i=((ll)n)-1;i>=0;i--) #define range(i,a,n) for(ll i=((ll)a);i<((ll)n);i++) #define LINF ((ll)1ll<<60) #define INF ((int)1<<30) #define EPS (1e-9) #define MOD (1000000007ll) #define fcout(a) cout<<setprecision(a)<<fixed #define fs first #define sc second #define PI (3.1415926535897932384) int dx[]={1,0,-1,0,1,-1,-1,1},dy[]={0,1,0,-1,1,1,-1,-1}; template<class T>bool chmax(T&a,T b){if(a<b){a=b; return true;}return false;} template<class T>bool chmin(T&a,T b){if(a>b){a=b; return true;}return false;} template<class S>S sum(vector<S>&a){return accumulate(all(a),S());} template<class S>S max(vector<S>&a){return *max_element(all(a));} template<class S>S min(vector<S>&a){return *min_element(all(a));} ll max(int a,ll b){return max((ll)a,b);} ll max(ll a,int b){return max(a,(ll)b);} int sgn(const double&r){return (r>EPS)-(r<-EPS);} // a>0 : sgn(a)>0 int sgn(const double&a,const double&b){return sgn(a-b);} // b<=c : sgn(b,c)<=0 template<class T>void puta(T&&t){cout<<t<<"\n";} template<class H,class...T>void puta(H&&h,T&&...t){cout<<h<<' ';puta(t...);} template<class S,class T>void tf(bool b,S t,T f){if(b)puta(t);else puta(f);} void YN(bool b){tf(b,"YES","NO");} void Yn(bool b){tf(b,"Yes","No");} void yn(bool b){tf(b,"yes","no");} template<class S,class T>ostream&operator<<(ostream&os,pair<S,T>p){os<<"["<<p.first<<", "<<p.second<<"]";return os;}; template<class S>auto&operator<<(ostream&os,vector<S>t){bool a=1;for(auto s:t){os<<(a?"":" ")<<s;a=0;}return os;} template<class S,class T>auto&operator<<(ostream&os,map<S,T>mp){bool a=1;for(auto p:mp){os<<(a?"":", ")<<p;a=0;}return os;} template<class S>auto&operator>>(istream&is,vector<S>&t){for(S&a:t)cin>>a;return is;} /*他のライブラリを入れる場所*/ int main(){ cin.tie(0); ios::sync_with_stdio(false); ll n; cin>>n; vi a(n);cin>>a; vl c(n+1,0); vi ans; rep(i,n){ ll v=n-i; if(c[v]%2!=a[v-1]){ ans.push_back(v); for(ll j=1;j*j<=v;j++){ if(v%j==0){ c[j]++; if(j!=v/j)c[v/j]++; } } } } puta(ans.size()); puta(ans); return 0; }
[ "tsukasawa_agu@yahoo.co.jp" ]
tsukasawa_agu@yahoo.co.jp
6fb52f7b70b2ca542b1c9506658779709c54f24f
13c3630445d73fb2703e5574b70942742f37fb89
/Stable/LocatorTester/Tester.cpp
17fce240509c59cc699b5bcb6287a37f92d7e2cc
[]
no_license
NovaDV/Gunz1.5
8cb660462c386f4c35d7f5198e614a29d5276547
97e7bc51fd082e37f3de0f02c5e2ce6c33530c50
refs/heads/main
2023-06-14T15:41:07.759755
2021-07-11T18:25:07
2021-07-11T18:25:07
385,099,338
1
0
null
2021-07-12T02:10:18
2021-07-12T02:10:18
null
UHC
C++
false
false
5,250
cpp
#include "stdafx.h" #include "Tester.h" #include "MSafeUDP.h" #include "MSharedCommandTable.h" #include "Msg.h" #include "MCommandCommunicator.h" #include "MXml.h" #include <map> using namespace std; #include <process.h> Tester* g_Test = 0; Tester::Tester() : m_pCmd( 0 ), m_nElapse( 1000 ) { } Tester::~Tester() { } bool Tester::Create() { MAddSharedCommandTable( &m_CommandManager, 0 ); m_pSafeUDP = new MSafeUDP; if( 0 == m_pSafeUDP ) return false; if( m_pSafeUDP->Create(true, 8900) ) { m_pSafeUDP->SetCustomRecvCallback( UDPSocketRecvEvent ); } else return false; if( !CreateTestThread() ) { mlog( "Create fail.\n" ); return false; } mlog( "Created.\n" ); g_Test = this; return true; } bool Tester::CreateTestThread() { HANDLE hThread; DWORD dwThreadId; hThread = CreateThread(NULL, 0, LocatorTesterThread, this, 0, &dwThreadId); return (NULL != hThread); } bool Tester::SendUDPtoLocator() { // 222.111.150.87 // SendCommandByUDP( inet_addr("127.0.0.1"), 8900, GetCommand() ); // SendCommandByUDP( inet_addr("222.111.150.84"), 8900, GetCommand() ); // India // SendCommandByUDP( inet_addr("202.92.10.152"), 8900, GetCommand() ); // SendCommandByUDP( inet_addr("202.92.10.153"), 8900, GetCommand() ); // 넷마블 테스트 서버 IP SendCommandByUDP( inet_addr("220.90.199.189"), 8900, GetCommand() ); // India Test // Brazil // SendCommandByUDP( inet_addr("200.229.52.13"), 8900, GetCommand() ); return true; } DWORD WINAPI Tester::LocatorTesterThread( void* pWorkContext ) { // 미친듯이 보내BoA요~ Tester* pTester = reinterpret_cast<Tester*>(pWorkContext); int nCount = 0; DWORD dwStart = timeGetTime(); DWORD dwEnd; while( true ) { if( pTester->SendUDPtoLocator() ) { ++nCount; } else ASSERT( 0 ); dwEnd = timeGetTime(); if( (0 < nCount) && (10000 < (dwEnd - dwStart)) ) { mlog( "Time:%u Send Count:%d\n", dwEnd - dwStart, nCount / ((dwEnd - dwStart)/1000)); dwStart = timeGetTime(); nCount = 0; } Sleep( 1000 ); } return 0; } const int Tester::MakeCmdPacket( char* pOutPacket, const int nMaxSize, MCommand* pCmd ) { if( (0 == pOutPacket) || (0 > nMaxSize) || (0 == pCmd) ) return -1; MCommandMsg* pMsg = reinterpret_cast< MCommandMsg* >( pOutPacket ); const nCmdSize = nMaxSize - sizeof(MPacketHeader); pMsg->Buffer[ 0 ] = 0; pMsg->nCheckSum = 0; if( pCmd->m_pCommandDesc->IsFlag(MCCT_NON_ENCRYPTED) ) { pMsg->nMsg = MSGID_RAWCOMMAND; const int nGetCmdSize = pCmd->GetData( pMsg->Buffer, nCmdSize ); if( nGetCmdSize != nCmdSize ) return -1; pMsg->nSize = static_cast< unsigned int >( sizeof(MPacketHeader) ) + nGetCmdSize; pMsg->nCheckSum = MBuildCheckSum(pMsg, pMsg->nSize); } else { ASSERT( 0 && "암호화된 커맨드 처리는 없음.\n" ); return -1; } return pMsg->nSize; } void Tester::SendCommandByUDP( DWORD dwIP, int nPort, MCommand* pCmd ) { const int nPacketSize = CalcPacketSize( pCmd ); char* pszPacketBuf = new char[ nPacketSize ]; if( 0 != pszPacketBuf ) { const int nMakePacketSize = MakeCmdPacket( pszPacketBuf, nPacketSize, pCmd ); if( nPacketSize == nMakePacketSize ) { if( !m_pSafeUDP->Send(dwIP, nPort, pszPacketBuf, nMakePacketSize) ) { mlog( "MLocator::SendCommandByUDP - UDP send 실패.\n" ); } } else { delete [] pszPacketBuf; ASSERT( 0 && "Packet을 만드는데 문제가 있음." ); } } } MCommand* Tester::GetCommand() { if( 0 != m_pCmd ) return m_pCmd; MCommandDesc* pCmdDesc = m_CommandManager.GetCommandDescByID( MC_REQUEST_SERVER_LIST_INFO ); if( 0 == pCmdDesc ) { ASSERT( 0 ); mlog( "1" ); return false; } m_pCmd = new MCommand( MC_REQUEST_SERVER_LIST_INFO, MUID(0, 0), MUID(0, 0), &m_CommandManager); if( 0 == m_pCmd ) { ASSERT( 0 ); mlog( "2" ); return false; } return m_pCmd; } void Tester::ReleaseCommand() { if( 0 != m_pCmd ) delete m_pCmd; } bool Tester::UDPSocketRecvEvent( DWORD dwIP, WORD wRawPort, char* pPacket, DWORD dwSize ) { static DWORD dwStart = timeGetTime(); static unsigned int nCount = 0; static DWORD dwEnd; dwEnd = timeGetTime(); ++nCount; // mlog( "(%u:%d) ", dwEnd - dwStart, nCount ); if( 1000 < (dwEnd - dwStart) ) { char szTime[256]=""; SYSTEMTIME tm; GetLocalTime(&tm); string strTime; strTime = "["; wsprintf(szTime, "%02i", tm.wYear%100); strTime += szTime; strTime +="/"; wsprintf(szTime, "%02i", tm.wMonth); strTime += szTime; strTime +="/"; wsprintf(szTime, "%02i", tm.wDay); strTime += szTime; strTime += " "; wsprintf(szTime, "%02i", tm.wHour); strTime += szTime; strTime += ":"; wsprintf(szTime, "%02i", tm.wMinute); strTime += szTime; strTime += ":"; wsprintf(szTime, "%02i", tm.wSecond); strTime += szTime; strTime += "]"; char szBuf[ 1024 ] = {0,}; sprintf( szBuf, "%s Time:%.1f, Recv Count : %d\n", strTime.c_str(), (dwEnd - dwStart) / 1000.0f, nCount ); // mlog( "\nTime:%u, Recv Count : %d\n", dwEnd - dwStart, nCount ); nCount = 0; dwStart = timeGetTime(); if( 0 != g_Test ) { g_Test->GetOut()->SetWindowText( szBuf ); } } return true; } struct ix { string id; string name; string desc; };
[ "jduncan0392@gmail.com" ]
jduncan0392@gmail.com
e9ff98fdf95ae69609c3b556b0157b1d3349f3df
0412b0695101163699d65a366ca4428a7ff84426
/SOUI/src/control/SListView.cpp
292952720226864995826b6bd9fd2e583fb2f32d
[ "MIT" ]
permissive
fhchina/soui
2961951ad0f3b8f2980e1b59bea96656861ac993
4d4a3ec369101ec5e137c196e22006f5aabde43c
refs/heads/master
2020-12-25T12:41:53.908625
2015-09-01T07:26:24
2015-09-01T07:26:24
null
0
0
null
null
null
null
GB18030
C++
false
false
30,356
cpp
#include "souistd.h" #include "control/SListView.h" #include <math.h> namespace SOUI { class SListViewDataSetObserver : public TObjRefImpl<IDataSetObserver> { public: SListViewDataSetObserver(SListView *pView):m_pOwner(pView) { } virtual void onChanged(); virtual void onInvalidated(); protected: SListView * m_pOwner; }; ////////////////////////////////////////////////////////////////////////// void SListViewDataSetObserver::onChanged() { m_pOwner->onDataSetChanged(); } void SListViewDataSetObserver::onInvalidated() { m_pOwner->onDataSetInvalidated(); } ////////////////////////////////////////////////////////////////////////// // SListViewItemLocatorFix SListViewItemLocatorFix::SListViewItemLocatorFix(int nItemHei,int nDividerSize) :m_nItemHeight(nItemHei) ,m_nDividerSize(nDividerSize) { } int SListViewItemLocatorFix::GetScrollLineSize() const { return GetFixItemHeight(); } int SListViewItemLocatorFix::Position2Item(int position) { if(!m_adapter) return -1; int nRet = position/GetFixItemHeight(); if(nRet<0) nRet =0; if(nRet>m_adapter->getCount()) nRet = m_adapter->getCount(); return nRet; } int SListViewItemLocatorFix::Item2Position(int iItem) { return iItem * GetFixItemHeight(); } int SListViewItemLocatorFix::GetTotalHeight() { if(!m_adapter || m_adapter->getCount() == 0) return 0; return m_nItemHeight * m_adapter->getCount() + (m_adapter->getCount()-1)*m_nDividerSize; } void SListViewItemLocatorFix::SetItemHeight(int iItem,int nHeight) { } int SListViewItemLocatorFix::GetItemHeight(int iItem) const { return m_nItemHeight; } bool SListViewItemLocatorFix::IsFixHeight() const { return true; } void SListViewItemLocatorFix::SetAdapter(IAdapter *pAdapter) { m_adapter = pAdapter; } ////////////////////////////////////////////////////////////////////////// // SListViewItemLocatorFlex double logbase(double a, double base) { return log(a) / log(base); } #define SEGMENT_SIZE 50 //数据分组最大长度 #define INDEX_WIDTH 10 //索引表一级最大节点数 SListViewItemLocatorFlex::SListViewItemLocatorFlex(int nItemHei,int nDividerSize) :m_nItemHeight(nItemHei) ,m_nDividerSize(nDividerSize) { } SListViewItemLocatorFlex::~SListViewItemLocatorFlex() { Clear(); } int SListViewItemLocatorFlex::GetScrollLineSize() const { return GetFixItemHeight(); } int SListViewItemLocatorFlex::Position2Item(int position) { if(!m_adapter) return -1; if(position<0 || position>=GetTotalHeight()) return -1; HSTREEITEM hItem = Offset2Branch(STVI_ROOT,position); SASSERT(hItem); int idx = Branch2Index(hItem); int offset = Branch2Offset(hItem); BranchInfo &bi = m_itemPosIndex.GetItemRef(hItem); SASSERT(bi.nBranchHei>=position-offset); int iSeg = idx/SEGMENT_SIZE; int nRemain = position - offset; SegmentInfo *psi = m_segments[iSeg]; for(int i=0;i<psi->nItems;i++) { int nItemHei = psi->pItemHeight[i]==-1?GetFixItemHeight():psi->pItemHeight[i]; if(nRemain<=nItemHei) return idx + i; nRemain -= nItemHei; } SASSERT(FALSE); return -1; } int SListViewItemLocatorFlex::Item2Position(int iItem) { if(!m_adapter) return 0; int iSeg = iItem/SEGMENT_SIZE; int iSubItem = iItem%SEGMENT_SIZE; SegmentInfo *psi = m_segments[iSeg]; int nPos = Branch2Offset(psi->hItem); for(int i=0;i<iSubItem;i++) { nPos += psi->pItemHeight[i]==-1?GetFixItemHeight():psi->pItemHeight[i]; } return nPos; } int SListViewItemLocatorFlex::GetTotalHeight() { if(!m_adapter) return 0; HSTREEITEM hItem = m_itemPosIndex.GetRootItem(); int nRet = m_itemPosIndex.GetItem(hItem).nBranchHei; if(m_adapter->getCount()>0) nRet -= m_nDividerSize; return nRet; } void SListViewItemLocatorFlex::SetItemHeight(int iItem,int nHeight) { if(!m_adapter) return; int iSeg = iItem/SEGMENT_SIZE; int iSubItem = iItem%SEGMENT_SIZE; SegmentInfo *psi = m_segments[iSeg]; int nOldHei = psi->pItemHeight[iSubItem]; if(nOldHei==-1) nOldHei = GetFixItemHeight(); nHeight += m_nDividerSize; psi->pItemHeight[iSubItem] = nHeight; if(nOldHei != nHeight) { int nHeiDif = nHeight - nOldHei; HSTREEITEM hBranch = psi->hItem; while(hBranch) { BranchInfo & bi = m_itemPosIndex.GetItemRef(hBranch); bi.nBranchHei += nHeiDif; hBranch = m_itemPosIndex.GetParentItem(hBranch); } } } int SListViewItemLocatorFlex::GetItemHeight(int iItem) const { if(!m_adapter) return 0; int iSeg = iItem/SEGMENT_SIZE; int iSubItem = iItem%SEGMENT_SIZE; SegmentInfo *psi = m_segments[iSeg]; int nRet = psi->pItemHeight[iSubItem]; if(nRet == -1) nRet = GetFixItemHeight(); nRet -= m_nDividerSize; return nRet; } bool SListViewItemLocatorFlex::IsFixHeight() const { return false; } void SListViewItemLocatorFlex::SetAdapter(IAdapter *pAdapter) { m_adapter = pAdapter; OnDataSetChanged(); } void SListViewItemLocatorFlex::OnDataSetChanged() { Clear(); if(m_adapter) { int nTreeSize = m_adapter->getCount(); int nBranchSize = SEGMENT_SIZE; int nTreeDeep = GetIndexDeep(); for(int i=0;i<nTreeDeep;i++) nBranchSize *= INDEX_WIDTH; InitIndex(STVI_ROOT,nTreeSize,nBranchSize); } } void SListViewItemLocatorFlex::InitIndex(HSTREEITEM hParent,int nItems,int nBranchSize) { BranchInfo bi; bi.nBranchHei = nItems*GetFixItemHeight(); bi.nBranchSize = nItems; HSTREEITEM hBranch = m_itemPosIndex.InsertItem(bi,hParent); if(nItems > SEGMENT_SIZE) {//插入子节点 int nRemain = nItems; int nSubBranchSize = nBranchSize/INDEX_WIDTH; while(nRemain>0) { int nItems2 = nSubBranchSize; if(nItems2>nRemain) nItems2 = nRemain; InitIndex(hBranch,nItems2,nSubBranchSize); nRemain -= nItems2; } }else { m_segments.Add(new SegmentInfo(nItems,hBranch)); } } int SListViewItemLocatorFlex::GetIndexDeep() const { if(!m_adapter) return 0; if(m_adapter->getCount()==0) return 0; return (int)ceil(logbase((m_adapter->getCount()+SEGMENT_SIZE-1)/SEGMENT_SIZE,INDEX_WIDTH)); } void SListViewItemLocatorFlex::Clear() { m_itemPosIndex.DeleteAllItems(); for(int i=0;i<(int)m_segments.GetCount();i++) { delete m_segments[i]; } m_segments.RemoveAll(); } int SListViewItemLocatorFlex::Branch2Offset(HSTREEITEM hBranch) const { int nOffset = 0; HSTREEITEM hPrev = m_itemPosIndex.GetPrevSiblingItem(hBranch); while(hPrev) { nOffset += m_itemPosIndex.GetItem(hPrev).nBranchHei; hPrev = m_itemPosIndex.GetPrevSiblingItem(hPrev); } HSTREEITEM hParent = m_itemPosIndex.GetParentItem(hBranch); if(hParent) { nOffset += Branch2Offset(hParent); } return nOffset; } int SListViewItemLocatorFlex::Branch2Index(HSTREEITEM hBranch) const { int iIndex = 0; HSTREEITEM hPrev = m_itemPosIndex.GetPrevSiblingItem(hBranch); while(hPrev) { iIndex += m_itemPosIndex.GetItem(hPrev).nBranchSize; hPrev = m_itemPosIndex.GetPrevSiblingItem(hPrev); } HSTREEITEM hParent = m_itemPosIndex.GetParentItem(hBranch); if(hParent) { iIndex += Branch2Index(hParent); } return iIndex; } HSTREEITEM SListViewItemLocatorFlex::Offset2Branch(HSTREEITEM hParent,int nOffset) { HSTREEITEM hItem = m_itemPosIndex.GetChildItem(hParent); if(!hItem) return hParent; while(hItem) { BranchInfo bi = m_itemPosIndex.GetItem(hItem); if(nOffset>bi.nBranchHei) { nOffset -= bi.nBranchHei; hItem = m_itemPosIndex.GetNextSiblingItem(hItem); }else { return Offset2Branch(hItem,nOffset); } } return NULL; } ////////////////////////////////////////////////////////////////////////// SListView::SListView() :m_iSelItem(-1) ,m_iFirstVisible(-1) ,m_pHoverItem(NULL) ,m_itemCapture(NULL) ,m_bScrollUpdate(TRUE) ,m_pSkinDivider(NULL) ,m_nDividerSize(0) { m_bFocusable = TRUE; m_observer.Attach(new SListViewDataSetObserver(this)); m_evtSet.addEvent(EVENTID(EventLVSelChanged)); } SListView::~SListView() { m_observer=NULL; m_lvItemLocator=NULL; } BOOL SListView::SetAdapter(IAdapter * adapter) { if(!m_lvItemLocator) { SASSERT_FMT(FALSE,_T("error: A item locator is in need before setting adapter!!!")); return FALSE; } if(m_adapter) { m_adapter->unregisterDataSetObserver(m_observer); //free all itemPanels in recycle for(size_t i=0;i<m_itemRecycle.GetCount();i++) { SList<SItemPanel*> *lstItemPanels = m_itemRecycle.GetAt(i); SPOSITION pos = lstItemPanels->GetHeadPosition(); while(pos) { SItemPanel * pItemPanel = lstItemPanels->GetNext(pos); pItemPanel->DestroyWindow(); } delete lstItemPanels; } m_itemRecycle.RemoveAll(); //free all visible itemPanels SPOSITION pos=m_lstItems.GetHeadPosition(); while(pos) { ItemInfo ii = m_lstItems.GetNext(pos); ii.pItem->DestroyWindow(); } m_lstItems.RemoveAll(); } m_adapter = adapter; if(m_lvItemLocator) m_lvItemLocator->SetAdapter(adapter); if(m_adapter) { m_adapter->registerDataSetObserver(m_observer); for(int i=0;i<m_adapter->getViewTypeCount();i++) { m_itemRecycle.Add(new SList<SItemPanel*>()); } onDataSetChanged(); } return TRUE; } void SListView::UpdateScrollBar() { CRect rcClient=SWindow::GetClientRect(); CSize size = rcClient.Size(); CSize szView; szView.cx = rcClient.Width(); szView.cy = m_lvItemLocator?m_lvItemLocator->GetTotalHeight():0; // 关闭滚动条 m_wBarVisible = SSB_NULL; if (size.cy<szView.cy ) { // 需要纵向滚动条 m_wBarVisible |= SSB_VERT; m_siVer.nMin = 0; m_siVer.nMax = szView.cy-1; m_siVer.nPage = size.cy; m_siVer.nPos = min(m_siVer.nPos,m_siVer.nMax-(int)m_siVer.nPage); } else { // 不需要纵向滚动条 m_siVer.nPage = size.cy; m_siVer.nMin = 0; m_siVer.nMax = size.cy-1; m_siVer.nPos = 0; } SetScrollPos(TRUE, m_siVer.nPos, FALSE); // 重新计算客户区及非客户区 SSendMessage(WM_NCCALCSIZE); InvalidateRect(NULL); } void SListView::onDataSetChanged() { if(!m_adapter) return; if(m_lvItemLocator) m_lvItemLocator->OnDataSetChanged(); UpdateScrollBar(); UpdateVisibleItems(); } void SListView::onDataSetInvalidated() { UpdateVisibleItems(); } void SListView::OnPaint(IRenderTarget *pRT) { SPainter duiDC; BeforePaint(pRT,duiDC); int iFirst = m_iFirstVisible; if(iFirst!=-1) { CRect rcClient; GetClientRect(&rcClient); pRT->PushClipRect(&rcClient,RGN_AND); CRect rcClip,rcInter; pRT->GetClipBox(&rcClip); int nOffset = m_lvItemLocator->Item2Position(iFirst)-m_siVer.nPos; CRect rcItem(rcClient); rcItem.bottom = rcItem.top + nOffset; SPOSITION pos= m_lstItems.GetHeadPosition(); int i=0; for(;pos;i++) { ItemInfo ii = m_lstItems.GetNext(pos); rcItem.top=rcItem.bottom; rcItem.bottom = rcItem.top + m_lvItemLocator->GetItemHeight(iFirst+i); rcInter.IntersectRect(&rcClip,&rcItem); if(!rcInter.IsRectEmpty()) ii.pItem->Draw(pRT,rcItem); rcItem.top = rcItem.bottom; rcItem.bottom += m_lvItemLocator->GetDividerSize(); if(m_pSkinDivider) {//绘制分隔线 m_pSkinDivider->Draw(pRT,rcItem,0); } } pRT->PopClip(); } AfterPaint(pRT,duiDC); } BOOL SListView::OnScroll(BOOL bVertical,UINT uCode,int nPos) { int nOldPos = m_siVer.nPos; __super::OnScroll(bVertical, uCode, nPos); int nNewPos = m_siVer.nPos; if(nOldPos != nNewPos) { UpdateVisibleItems(); //加速滚动时UI的刷新 static DWORD dwTime1=0; DWORD dwTime=GetTickCount(); if(dwTime-dwTime1>50 && m_bScrollUpdate) { UpdateWindow(); dwTime1=dwTime; } } return TRUE; } void SListView::UpdateVisibleItems() { if(!m_adapter) return; int iOldFirstVisible = m_iFirstVisible; int iOldLastVisible = m_iFirstVisible + m_lstItems.GetCount(); int nOldTotalHeight = m_lvItemLocator->GetTotalHeight(); int iNewFirstVisible = m_lvItemLocator->Position2Item(m_siVer.nPos); int iNewLastVisible = iNewFirstVisible; int pos = m_lvItemLocator->Item2Position(iNewFirstVisible); ItemInfo *pItemInfos = new ItemInfo[m_lstItems.GetCount()]; SPOSITION spos = m_lstItems.GetHeadPosition(); int i=0; while(spos) { pItemInfos[i++]=m_lstItems.GetNext(spos); } m_lstItems.RemoveAll(); if(iNewFirstVisible!=-1) { while(pos < m_siVer.nPos + (int)m_siVer.nPage && iNewLastVisible < m_adapter->getCount()) { if(iNewLastVisible>=iOldLastVisible && iNewLastVisible < iOldLastVisible) {//use the old visible item int iItem = iNewLastVisible-(iNewFirstVisible-iOldFirstVisible); SASSERT(iItem>=0 && iItem <= (iOldLastVisible-iOldFirstVisible)); m_lstItems.AddTail(pItemInfos[iItem]); pos += m_lvItemLocator->GetItemHeight(iNewLastVisible); pItemInfos[iItem].pItem = NULL;//标记该行已经被重用 }else {//create new visible item int nItemType = m_adapter->getItemViewType(iNewLastVisible); SList<SItemPanel *> *lstRecycle = m_itemRecycle.GetAt(nItemType); SItemPanel * pItemPanel = NULL; if(lstRecycle->IsEmpty()) {//创建一个新的列表项 pItemPanel = SItemPanel::Create(this,pugi::xml_node(),this); }else { pItemPanel = lstRecycle->RemoveHead(); } pItemPanel->SetItemIndex(iNewLastVisible); CRect rcItem = GetClientRect(); rcItem.MoveToXY(0,0); if(m_lvItemLocator->IsFixHeight()) { rcItem.bottom=m_lvItemLocator->GetItemHeight(iNewLastVisible); pItemPanel->Move(rcItem); } m_adapter->getView(iNewLastVisible,pItemPanel,m_xmlTemplate.first_child()); if(!m_lvItemLocator->IsFixHeight()) { rcItem.bottom=0; CSize szItem = pItemPanel->GetDesiredSize(rcItem); rcItem.bottom = rcItem.top + szItem.cy; pItemPanel->Move(rcItem); m_lvItemLocator->SetItemHeight(iNewLastVisible,szItem.cy); } pItemPanel->UpdateChildrenPosition(); if(iNewLastVisible == m_iSelItem) { pItemPanel->ModifyItemState(WndState_Check,0); } ItemInfo ii; ii.nType = nItemType; ii.pItem = pItemPanel; m_lstItems.AddTail(ii); pos += rcItem.bottom + m_lvItemLocator->GetDividerSize(); } iNewLastVisible ++; } } //move old visible items which were not reused to recycle for(int i=0;i<(iOldLastVisible-iOldFirstVisible);i++) { ItemInfo ii = pItemInfos[i]; if(!ii.pItem) continue; if(ii.pItem == m_pHoverItem) { m_pHoverItem->DoFrameEvent(WM_MOUSELEAVE,0,0); m_pHoverItem=NULL; } if(ii.pItem->GetItemIndex() == m_iSelItem) { ii.pItem->ModifyItemState(0,WndState_Check); ii.pItem->GetFocusManager()->SetFocusedHwnd(0); } m_itemRecycle[ii.nType]->AddTail(ii.pItem); } delete [] pItemInfos; m_iFirstVisible = iNewFirstVisible; if(!m_lvItemLocator->IsFixHeight() && m_lvItemLocator->GetTotalHeight() != nOldTotalHeight) {//update scroll range BOOL hasVertBar1 = m_wBarVisible & SSB_VERT; UpdateScrollBar(); BOOL hasVertBar2 = m_wBarVisible & SSB_VERT; if(hasVertBar1 != hasVertBar2) UpdateVisibleItems();//根据新的滚动条状态重新记录显示列表项 } } void SListView::OnSize(UINT nType, CSize size) { __super::OnSize(nType,size); UpdateScrollBar(); //update item window CRect rcClient=GetClientRect(); SPOSITION pos = m_lstItems.GetHeadPosition(); while(pos) { ItemInfo ii = m_lstItems.GetNext(pos); int idx = (int)ii.pItem->GetItemIndex(); int nHei = m_lvItemLocator->GetItemHeight(idx); CRect rcItem(0,0,rcClient.Width(),nHei); ii.pItem->Move(rcItem); } UpdateVisibleItems(); } void SListView::OnDestroy() { //destroy all itempanel SPOSITION pos = m_lstItems.GetHeadPosition(); while(pos) { ItemInfo ii = m_lstItems.GetNext(pos); ii.pItem->Release(); } m_lstItems.RemoveAll(); for(int i=0;i<(int)m_itemRecycle.GetCount();i++) { SList<SItemPanel*> *pLstTypeItems = m_itemRecycle[i]; SPOSITION pos = pLstTypeItems->GetHeadPosition(); while(pos) { SItemPanel *pItem = pLstTypeItems->GetNext(pos); pItem->Release(); } delete pLstTypeItems; } m_itemRecycle.RemoveAll(); __super::OnDestroy(); } ////////////////////////////////////////////////////////////////////////// void SListView::OnItemRequestRelayout(SItemPanel *pItem) { pItem->UpdateChildrenPosition(); } BOOL SListView::IsItemRedrawDelay() { return TRUE; } BOOL SListView::OnItemGetRect(SItemPanel *pItem,CRect &rcItem) { int iPosition = (int)pItem->GetItemIndex(); int nOffset = m_lvItemLocator->Item2Position(iPosition)-m_siVer.nPos; rcItem = GetClientRect(); rcItem.top += nOffset; rcItem.bottom = rcItem.top + m_lvItemLocator->GetItemHeight(iPosition); return TRUE; } void SListView::OnItemSetCapture(SItemPanel *pItem,BOOL bCapture) { if(bCapture) { GetContainer()->OnSetSwndCapture(m_swnd); m_itemCapture=pItem; }else { GetContainer()->OnReleaseSwndCapture(); m_itemCapture=NULL; } } void SListView::RedrawItem(SItemPanel *pItem) { pItem->InvalidateRect(NULL); } SItemPanel * SListView::HitTest(CPoint & pt) { SPOSITION pos = m_lstItems.GetHeadPosition(); while(pos) { ItemInfo ii = m_lstItems.GetNext(pos); CRect rcItem = ii.pItem->GetItemRect(); if(rcItem.PtInRect(pt)) { pt-=rcItem.TopLeft(); return ii.pItem; } } return NULL; } LRESULT SListView::OnMouseEvent(UINT uMsg,WPARAM wParam,LPARAM lParam) { if(!m_adapter) { SetMsgHandled(FALSE); return 0; } LRESULT lRet=0; CPoint pt(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); if(uMsg == WM_LBUTTONDOWN) __super::OnLButtonDown(wParam,pt); if(m_itemCapture) { CRect rcItem=m_itemCapture->GetItemRect(); pt.Offset(-rcItem.TopLeft()); lRet = m_itemCapture->DoFrameEvent(uMsg,wParam,MAKELPARAM(pt.x,pt.y)); } else { if(m_bFocusable && (uMsg==WM_LBUTTONDOWN || uMsg== WM_RBUTTONDOWN || uMsg==WM_LBUTTONDBLCLK)) SetFocus(); SItemPanel * pHover=HitTest(pt); if(pHover!=m_pHoverItem) { SItemPanel * nOldHover=m_pHoverItem; m_pHoverItem=pHover; if(nOldHover) { nOldHover->DoFrameEvent(WM_MOUSELEAVE,0,0); RedrawItem(nOldHover); } if(m_pHoverItem) { m_pHoverItem->DoFrameEvent(WM_MOUSEHOVER,wParam,MAKELPARAM(pt.x,pt.y)); RedrawItem(m_pHoverItem); } } if(uMsg==WM_LBUTTONDOWN ) {//选择一个新行的时候原有行失去焦点 SWND hHitWnd = 0; int nSelNew = -1; if(m_pHoverItem) { nSelNew = m_pHoverItem->GetItemIndex(); hHitWnd = m_pHoverItem->SwndFromPoint(pt,FALSE); } _SetSel(nSelNew,TRUE,hHitWnd); } if(m_pHoverItem) { m_pHoverItem->DoFrameEvent(uMsg,wParam,MAKELPARAM(pt.x,pt.y)); } } if(uMsg == WM_LBUTTONUP) __super::OnLButtonUp(wParam,pt); return 0; } LRESULT SListView::OnKeyEvent(UINT uMsg,WPARAM wParam,LPARAM lParam) { LRESULT lRet=0; SItemPanel *pItem = GetItemPanel(m_iSelItem); if(pItem) { lRet=pItem->DoFrameEvent(uMsg,wParam,lParam); SetMsgHandled(pItem->IsMsgHandled()); }else { SetMsgHandled(FALSE); } return lRet; } void SListView::OnMouseLeave() { if(m_pHoverItem) { m_pHoverItem->DoFrameEvent(WM_MOUSELEAVE,0,0); m_pHoverItem = NULL; } } void SListView::OnKeyDown( TCHAR nChar, UINT nRepCnt, UINT nFlags ) { if(!m_adapter) { SetMsgHandled(FALSE); return; } int nNewSelItem = -1; SWindow *pOwner = GetOwner(); if (pOwner && (nChar == VK_ESCAPE)) { pOwner->SSendMessage(WM_KEYDOWN, nChar, MAKELONG(nFlags, nRepCnt)); return; } m_bScrollUpdate=FALSE; if (nChar == VK_DOWN && m_iSelItem < m_adapter->getCount() - 1) nNewSelItem = m_iSelItem+1; else if (nChar == VK_UP && m_iSelItem > 0) nNewSelItem = m_iSelItem-1; else if (pOwner && nChar == VK_RETURN) nNewSelItem = m_iSelItem; else if(nChar == VK_PRIOR) { OnScroll(TRUE,SB_PAGEUP,0); if(!m_lstItems.IsEmpty()) { nNewSelItem = m_lstItems.GetHead().pItem->GetItemIndex(); } }else if(nChar == VK_NEXT) { OnScroll(TRUE,SB_PAGEDOWN,0); if(!m_lstItems.IsEmpty()) { nNewSelItem = m_lstItems.GetTail().pItem->GetItemIndex(); } } if(nNewSelItem!=-1) { EnsureVisible(nNewSelItem); SetSel(nNewSelItem); } m_bScrollUpdate=TRUE; } void SListView::EnsureVisible( int iItem ) { if(iItem<0 || iItem>=m_adapter->getCount()) return; int iFirstVisible= m_iFirstVisible; int iLastVisible = m_iFirstVisible + m_lstItems.GetCount(); if(iItem>=iFirstVisible && iItem<iLastVisible) return; int pos = m_lvItemLocator->Item2Position(iItem); if(iItem < iFirstVisible) {//scroll up OnScroll(TRUE,SB_THUMBPOSITION,pos); }else // if(iItem >= iLastVisible) {//scroll down int iTop = iItem; int pos2 = pos; int topSize = m_siVer.nPage - m_lvItemLocator->GetItemHeight(iItem); while(iTop>=0 && (pos - pos2) < topSize) { pos2 = m_lvItemLocator->Item2Position(--iTop); } OnScroll(TRUE,SB_THUMBPOSITION,pos2); } } BOOL SListView::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt) { SItemPanel *pSelItem = GetItemPanel(m_iSelItem); if(pSelItem) { CRect rcItem = pSelItem->GetItemRect(); CPoint pt2=pt-rcItem.TopLeft(); if(pSelItem->DoFrameEvent(WM_MOUSEWHEEL,MAKEWPARAM(nFlags,zDelta),MAKELPARAM(pt2.x,pt2.y))) return TRUE; } return __super::OnMouseWheel(nFlags, zDelta, pt); } int SListView::GetScrollLineSize(BOOL bVertical) { return m_lvItemLocator->GetScrollLineSize(); } SItemPanel * SListView::GetItemPanel(int iItem) { if(iItem<0 || iItem>=m_adapter->getCount()) return NULL; SPOSITION pos = m_lstItems.GetHeadPosition(); while(pos) { ItemInfo ii = m_lstItems.GetNext(pos); if((int)ii.pItem->GetItemIndex() == m_iSelItem) return ii.pItem; } return NULL; } void SListView::SetSel(int iItem,BOOL bNotify/*=FALSE*/) { _SetSel(iItem,bNotify,0); } BOOL SListView::CreateChildren(pugi::xml_node xmlNode) { pugi::xml_node xmlTemplate = xmlNode.child(L"template"); if(xmlTemplate) { m_xmlTemplate.append_copy(xmlTemplate); int nItemHei = xmlTemplate.attribute(L"itemHeight").as_int(-1); if(nItemHei>0) {//指定了itemHeight属性时创建一个固定行高的定位器 IListViewItemLocator * pItemLocator = new SListViewItemLocatorFix(nItemHei,m_nDividerSize); SetItemLocator(pItemLocator); pItemLocator->Release(); }else {//创建一个行高可变的行定位器,从defHeight属性中获取默认行高 IListViewItemLocator * pItemLocator = new SListViewItemLocatorFlex(xmlTemplate.attribute(L"defHeight").as_int(30),m_nDividerSize); SetItemLocator(pItemLocator); pItemLocator->Release(); } } return TRUE; } void SListView::SetItemLocator(IListViewItemLocator *pItemLocator) { m_lvItemLocator = pItemLocator; if(m_lvItemLocator) m_lvItemLocator->SetAdapter(GetAdapter()); onDataSetChanged(); } BOOL SListView::OnUpdateToolTip(CPoint pt, SwndToolTipInfo & tipInfo) { if(!m_pHoverItem) return __super::OnUpdateToolTip(pt,tipInfo); return m_pHoverItem->OnUpdateToolTip(pt,tipInfo); } void SListView::_SetSel(int iItem,BOOL bNotify, SWND hHitWnd) { if(!m_adapter) return; if(iItem>=m_adapter->getCount()) return; if(iItem<0) iItem = -1; int nOldSel = m_iSelItem; int nNewSel = iItem; m_iSelItem = nNewSel; if(bNotify) { EventLVSelChanged evt(this); evt.iOldSel = nOldSel; evt.iNewSel = nNewSel; evt.hHitWnd =hHitWnd; FireEvent(evt); if(evt.bCancel) {//Cancel SetSel and restore selection state m_iSelItem = nOldSel; return; } } if(nOldSel == nNewSel) return; m_iSelItem = nOldSel; SItemPanel *pItem = GetItemPanel(nOldSel); if(pItem) { pItem->ModifyItemState(0,WndState_Check); RedrawItem(pItem); } m_iSelItem = nNewSel; pItem = GetItemPanel(nNewSel); if(pItem) { pItem->ModifyItemState(WndState_Check,0); RedrawItem(pItem); } } }
[ "setoutsoft@qq.com" ]
setoutsoft@qq.com
31f2494a1b05e039603dc136a70165de33851d49
8b4a7f1f5e3299bb85d191d91bb9cc9eef1357a4
/src/selector.h
f17f8efd9eb3a5ecca4af49b12991f4143cb59e3
[]
no_license
d1eg0/touchscreen
b70beadff662dc138d19e852c54dadd5181da1c5
5fa18a6706470573dd46946d4165de7f8ffb0962
refs/heads/master
2020-05-29T22:22:47.024658
2009-07-06T10:22:39
2009-07-06T10:22:39
32,131,106
0
0
null
null
null
null
UTF-8
C++
false
false
2,008
h
/** * @file selector.h * * @author Diego García , kobydiego@gmail.com * * @internal * Company Universitat de les Illes Balears * Copyright Copyright (c) 2009, Diego García * * * This file is part of TouchScreenGUI. * TouchScreenGUI is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * TouchScreenGUI 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 TouchScreenGUI; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * http://www.gnu.org/copyleft/gpl.html * * ===================================================================================== */ #ifndef SELECTOR_H #define SELECTOR_H #include <string> #include <vector> #include <SDL/SDL.h> #include "boton.h" using namespace std; /** * @class Selector * @brief Gestiona la selecci&oacute;n de mapas de un dispositivo USB */ class Selector{ public: /** Constructor de la clase */ Selector(SDL_Surface* pantalla); ~Selector(); /** Obtiene un listado de ficheros del path "ruta" con extensi&oacute; "ext" */ void buscarW(string ruta,string ext); void buscarR(); /** Muestra la lista de ficheros obtenida */ void cargar(); /** Comprueba si la lista de ficheros est&aacute; vac&iacute;a */ bool vacio(); /** Comprueba que plano de la lista ha sido pulsado */ bool handle(int x,int y); private: vector<Boton> lista; SDL_Surface* ventana; string ruta; string ext; vector<string> mapas; int descf[2]; }; #endif
[ "kobydiego@19c347df-c239-0410-ab3b-cf5cc4a55563" ]
kobydiego@19c347df-c239-0410-ab3b-cf5cc4a55563
9da6b3753ed2e9bfe31da084906ca871edbd980e
16863691d6e9b72a8655621bd2663108d144aadc
/l2-rel-1-2/src/l2maxlib/registry/drivers/common/src/l2AbstractRegistryDriver.h
8ddc616ddb9ce6d9cff2a3dccb02ab9723dc4fbf
[]
no_license
L2-Max/l2ChipTuner
9ca3b1a435ef0adcf13105e5b56a4553b9bdffd1
9c54b6cecec29de3c992ec54adf1223549b5d309
refs/heads/master
2020-02-26T13:58:16.082017
2012-07-27T17:31:44
2012-07-27T17:31:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,175
h
/* * l2AbstractRegistryDriver.h * * Created on: 04.09.2009 * Author: L2-Max */ #ifndef L2ABSTRACTREGISTRYDRIVER_H_ #define L2ABSTRACTREGISTRYDRIVER_H_ #include "l2ParserErrorRepository.h" #include "l2CategoryParserDriver.h" #include "l2ParserDriverSynchronization.h" #include <l2RegistryDriverInterface.h> #include <l2Thread.h> #include <l2RefObject.h> #include <fstream> namespace l2max { namespace Registry { namespace Driver { class CAbstractRegistryDriver : public IInterface, public CRefObject, protected CThread { CParserDriverSynchronization _synchronization; CParserErrorRepository _errorRepository; std::string _file; std::ifstream _fstream; HCategory _category; virtual void parse() = 0; virtual unsigned int run(); protected: bool _isModified; void WaitForDriverStop()const; bool isRun()const; bool isModified()const; const CParserDriverSynchronization& synchronization()const; CParserErrorRepository& errorRepository(); const std::string& file()const; std::ifstream& stream(); HCategory category()const; public: CAbstractRegistryDriver(); virtual ~CAbstractRegistryDriver(); virtual bool hasError()const; virtual std::string errorString()const; virtual bool Open( const std::string& aFile ); virtual bool Read( const std::string& aKey, CVariant& aValue )const; virtual bool Write( const std::string& aKey, const CVariant& aValue ); virtual void Clear(); virtual const std::string& parsedFileName()const; virtual TKeyListIterator CategoryList( const std::string& aKey, TKeyList& aList )const; virtual TKeyListIterator VariableList( const std::string& aKey, TKeyList& aList )const; }; } } } #endif /* L2ABSTRACTREGISTRYDRIVER_H_ */
[ "fmax@ukr.net" ]
fmax@ukr.net
648ca82c2dba31bb5114243b2cad0c0d1d93cbcb
1eb6c845c73c0f298e4089574b349d0429d5c6be
/src/qt/transactionfilterproxy.h
0ca9604474b50ca8f41b35c9860dd64ed0b2cefc
[ "MIT" ]
permissive
bicosgb/bicos
d4dbbb6c3df67fb631c95bd662d4dfad1ecf9fa9
83b47498f367558d67ad6476d793973080a4c5a1
refs/heads/master
2020-08-25T01:06:20.606738
2019-10-23T01:41:48
2019-10-23T01:41:48
216,939,128
0
0
null
null
null
null
UTF-8
C++
false
false
2,029
h
// Copyright (c) 2011-2014 The BICOScoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BICOSCOIN_QT_TRANSACTIONFILTERPROXY_H #define BICOSCOIN_QT_TRANSACTIONFILTERPROXY_H #include "amount.h" #include <QDateTime> #include <QSortFilterProxyModel> /** Filter the transaction list according to pre-specified rules. */ class TransactionFilterProxy : public QSortFilterProxyModel { Q_OBJECT public: explicit TransactionFilterProxy(QObject *parent = 0); /** Earliest date that can be represented (far in the past) */ static const QDateTime MIN_DATE; /** Last date that can be represented (far in the future) */ static const QDateTime MAX_DATE; /** Type filter bit field (all types) */ static const quint32 ALL_TYPES = 0xFFFFFFFF; static quint32 TYPE(int type) { return 1<<type; } enum WatchOnlyFilter { WatchOnlyFilter_All, WatchOnlyFilter_Yes, WatchOnlyFilter_No }; void setDateRange(const QDateTime &from, const QDateTime &to); void setAddressPrefix(const QString &addrPrefix); /** @note Type filter takes a bit field created with TYPE() or ALL_TYPES */ void setTypeFilter(quint32 modes); void setMinAmount(const CAmount& minimum); void setWatchOnlyFilter(WatchOnlyFilter filter); /** Set maximum number of rows returned, -1 if unlimited. */ void setLimit(int limit); /** Set whether to show conflicted transactions. */ void setShowInactive(bool showInactive); int rowCount(const QModelIndex &parent = QModelIndex()) const; protected: bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const; private: QDateTime dateFrom; QDateTime dateTo; QString addrPrefix; quint32 typeFilter; WatchOnlyFilter watchOnlyFilter; CAmount minAmount; int limitRows; bool showInactive; }; #endif // BICOSCOIN_QT_TRANSACTIONFILTERPROXY_H
[ "bicosgb@gmail.com" ]
bicosgb@gmail.com
89e3c6980796cea0ece9cc6ff537af40648f71ea
551f2acc6562cb09d9c6e98ebc6448abac13d93b
/third/starrtccoredll/include/XHGroupManager.h
e711a46210167d0e0702ea23f6e17a4550ca5c3e
[]
no_license
answord/starrtc-windows-demo
a277668a753cb5c5ca616ed6237458646b9c5ae3
bebb8387bfee175679b959e99f6816d07ae8eaf1
refs/heads/master
2020-09-08T03:18:03.482720
2019-11-26T11:14:38
2019-11-26T11:14:38
220,998,685
0
0
null
2019-11-25T04:18:43
2019-11-11T14:25:21
C++
GB18030
C++
false
false
1,947
h
#pragma once #ifndef MATH_API #define MATH_API _declspec(dllexport) #endif #include "IGroupManagerListener.h" #include "IGroupGetListListener.h" #include "CGroupManager.h" class MATH_API XHGroupManager { public: /* * 构造函数 * @param pUserManager 用户信息 */ XHGroupManager(IGroupManagerListener* pGroupManagerListener); /* * 析构函数 */ ~XHGroupManager(); public: /* * 添加获取列表后回调函数指针 * @param pChatroomGetListListener 回调函数指针 */ static void addGroupGetListListener(IGroupGetListListener* pGroupGetListListener); /* * 获取群组列表 * @param pUserManager 用户信息 */ static void getGroupList(); /* * 获取群组成员列表 * @param pUserManager 用户信息 * @param strGroupId 群组id */ static void getUserList(string strGroupId); /** * 创建群 * @param groupName */ string createGroup(string groupName); /** * 删除群 * @param groupID */ bool deleteGroup(string groupID); /** * 添加群成员 * @param groupID * @param memberIDs */ void addGroupMembers(string groupID, list<string> memberIDs); /** * 删除群成员 * @param groupID * @param memberIDs */ void deleteGroupMembers(string groupID, list<string> memberIDs); /** * 设置推送开关 * @param groupID * @param enable * @param callback */ void setPushEnable(string groupID, bool enable); /** *发送消息 * @param groupID * @param atUserIDs * @param Message * @return 发出的消息 */ CIMMessage* sendMessage(string groupID, list<string> atUserIDs, string Message); /** *发送消息 * @param groupID * @param atUserIDs * @param Message * @return 发出的消息 */ CIMMessage* sendOnlineMessage(string groupID, list<string> atUserIDs, string Message); private: CGroupManager* m_pGroupManager; };
[ "hnrayer@gmail.com" ]
hnrayer@gmail.com
af8b685070260e6b3d358fe41d364a3b9d99752a
2f3f7fc96fcb96bdd0dd350bbff9eb9c5e8fe55e
/src/cgol_board.cpp
fb763da79dbc519ae47969ee8232038b49fa1045
[]
no_license
simutisernestas/cgol
a9a8dcadceae83bc3fa6bfe4031fe6b35b1b0108
6c14fe4ddb0e5d01a91f54eabaaebc08632e2c10
refs/heads/master
2022-12-30T11:15:33.231110
2020-10-24T14:34:19
2020-10-24T14:34:19
302,068,989
1
0
null
null
null
null
UTF-8
C++
false
false
1,743
cpp
#include <algorithm> #include <QtCore/QMetaType> #include "include/cgol_board.hpp" CGOLBoard::CGOLBoard() : size_{}, rng_{std::random_device()()}, random_dist_{1, 10} { } CGOLBoard::CGOLBoard(const int &size, const CGOLBoard::State &init_state) : size_{size}, rng_{std::random_device()()}, random_dist_{1, 10} { initBoard(size, init_state); } void CGOLBoard::initBoard(const int &size, const CGOLBoard::State &s) { size_ = size; board_.resize(size_ * size_); initState(s); } void CGOLBoard::initState(const CGOLBoard::State &s) { switch (s) { case CGOLBoard::State::Random: initRandom(); break; case CGOLBoard::State::Empty: initEmpty(); break; case CGOLBoard::State::Checkered: initCheckered(); break; } } void CGOLBoard::initEmpty() { for (byte &i : board_) i = byte{0}; } void CGOLBoard::initRandom() { for (byte &i : board_) { auto rand_num = random_dist_(rng_); i = byte{rand_num <= 5}; } } void CGOLBoard::initCheckered() { for (int row = 0; row < size_; ++row) { for (int col = 0; col < size_; ++col) { board_[row * size_ + col] = byte{!((row + col) & 1)}; } } } void CGOLBoard::setAt(const byte &value, const int &row, const int &col) { int index = row * size_ + col; if (index >= size_ * size_ || row < 0 || col < 0) throw std::out_of_range("Board index out of range, while setting tile value."); board_[index] = value; } int CGOLBoard::getSize() const { return size_; } const byte &CGOLBoard::getAt(const int &row, const int &col) const { int index = row * size_ + col; if (index >= size_ * size_ || row < 0 || col < 0) throw std::out_of_range("Board index out of range, while getting tile value."); return board_[index]; } Q_DECLARE_METATYPE(CGOLBoard)
[ "ernestas@neurotechnology.com" ]
ernestas@neurotechnology.com
6323af226b116c8154b9252b809948dab14bb43c
a3ea33d9ffc15dab670195bd61c078513e9b7cd9
/deps/leveldb/leveldb-rocksdb/utilities/backupable/backupable_db.cc
6a5c7458ba30e47f18f97162758f578fa57ec2b5
[ "BSD-3-Clause", "MIT" ]
permissive
a100q100/rocksdb-1
e6eb3fbf52d7f5cd1c3c35de30d11d13d94d27c4
7b4e85f8a4a197303d7fb82e885565ac4e4deb3c
refs/heads/master
2020-04-04T00:22:04.111252
2018-10-25T15:02:44
2018-10-25T15:02:44
155,647,680
1
0
MIT
2018-11-01T01:59:04
2018-11-01T01:59:03
null
UTF-8
C++
false
false
65,158
cc
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #ifndef ROCKSDB_LITE #include "rocksdb/utilities/backupable_db.h" #include "db/filename.h" #include "util/channel.h" #include "util/coding.h" #include "util/crc32c.h" #include "util/file_reader_writer.h" #include "util/logging.h" #include "util/string_util.h" #include "rocksdb/rate_limiter.h" #include "rocksdb/transaction_log.h" #include "port/port.h" #include "util/sync_point.h" #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif // __STDC_FORMAT_MACROS #include <inttypes.h> #include <stdlib.h> #include <algorithm> #include <atomic> #include <functional> #include <future> #include <limits> #include <map> #include <mutex> #include <sstream> #include <string> #include <thread> #include <unordered_map> #include <unordered_set> #include <vector> namespace rocksdb { void BackupStatistics::IncrementNumberSuccessBackup() { number_success_backup++; } void BackupStatistics::IncrementNumberFailBackup() { number_fail_backup++; } uint32_t BackupStatistics::GetNumberSuccessBackup() const { return number_success_backup; } uint32_t BackupStatistics::GetNumberFailBackup() const { return number_fail_backup; } std::string BackupStatistics::ToString() const { char result[50]; snprintf(result, sizeof(result), "# success backup: %u, # fail backup: %u", GetNumberSuccessBackup(), GetNumberFailBackup()); return result; } void BackupableDBOptions::Dump(Logger* logger) const { ROCKS_LOG_INFO(logger, " Options.backup_dir: %s", backup_dir.c_str()); ROCKS_LOG_INFO(logger, " Options.backup_env: %p", backup_env); ROCKS_LOG_INFO(logger, " Options.share_table_files: %d", static_cast<int>(share_table_files)); ROCKS_LOG_INFO(logger, " Options.info_log: %p", info_log); ROCKS_LOG_INFO(logger, " Options.sync: %d", static_cast<int>(sync)); ROCKS_LOG_INFO(logger, " Options.destroy_old_data: %d", static_cast<int>(destroy_old_data)); ROCKS_LOG_INFO(logger, " Options.backup_log_files: %d", static_cast<int>(backup_log_files)); ROCKS_LOG_INFO(logger, " Options.backup_rate_limit: %" PRIu64, backup_rate_limit); ROCKS_LOG_INFO(logger, " Options.restore_rate_limit: %" PRIu64, restore_rate_limit); ROCKS_LOG_INFO(logger, "Options.max_background_operations: %d", max_background_operations); } // -------- BackupEngineImpl class --------- class BackupEngineImpl : public BackupEngine { public: BackupEngineImpl(Env* db_env, const BackupableDBOptions& options, bool read_only = false); ~BackupEngineImpl(); Status CreateNewBackupWithMetadata(DB* db, const std::string& app_metadata, bool flush_before_backup = false, std::function<void()> progress_callback = []() {}) override; Status PurgeOldBackups(uint32_t num_backups_to_keep) override; Status DeleteBackup(BackupID backup_id) override; void StopBackup() override { stop_backup_.store(true, std::memory_order_release); } Status GarbageCollect() override; // The returned BackupInfos are in chronological order, which means the // latest backup comes last. void GetBackupInfo(std::vector<BackupInfo>* backup_info) override; void GetCorruptedBackups(std::vector<BackupID>* corrupt_backup_ids) override; Status RestoreDBFromBackup( BackupID backup_id, const std::string& db_dir, const std::string& wal_dir, const RestoreOptions& restore_options = RestoreOptions()) override; Status RestoreDBFromLatestBackup( const std::string& db_dir, const std::string& wal_dir, const RestoreOptions& restore_options = RestoreOptions()) override { return RestoreDBFromBackup(latest_backup_id_, db_dir, wal_dir, restore_options); } virtual Status VerifyBackup(BackupID backup_id) override; Status Initialize(); private: void DeleteChildren(const std::string& dir, uint32_t file_type_filter = 0); // Extends the "result" map with pathname->size mappings for the contents of // "dir" in "env". Pathnames are prefixed with "dir". Status InsertPathnameToSizeBytes( const std::string& dir, Env* env, std::unordered_map<std::string, uint64_t>* result); struct FileInfo { FileInfo(const std::string& fname, uint64_t sz, uint32_t checksum) : refs(0), filename(fname), size(sz), checksum_value(checksum) {} FileInfo(const FileInfo&) = delete; FileInfo& operator=(const FileInfo&) = delete; int refs; const std::string filename; const uint64_t size; const uint32_t checksum_value; }; class BackupMeta { public: BackupMeta(const std::string& meta_filename, std::unordered_map<std::string, std::shared_ptr<FileInfo>>* file_infos, Env* env) : timestamp_(0), size_(0), meta_filename_(meta_filename), file_infos_(file_infos), env_(env) {} BackupMeta(const BackupMeta&) = delete; BackupMeta& operator=(const BackupMeta&) = delete; ~BackupMeta() {} void RecordTimestamp() { env_->GetCurrentTime(&timestamp_); } int64_t GetTimestamp() const { return timestamp_; } uint64_t GetSize() const { return size_; } uint32_t GetNumberFiles() { return static_cast<uint32_t>(files_.size()); } void SetSequenceNumber(uint64_t sequence_number) { sequence_number_ = sequence_number; } uint64_t GetSequenceNumber() { return sequence_number_; } const std::string& GetAppMetadata() const { return app_metadata_; } void SetAppMetadata(const std::string& app_metadata) { app_metadata_ = app_metadata; } Status AddFile(std::shared_ptr<FileInfo> file_info); Status Delete(bool delete_meta = true); bool Empty() { return files_.empty(); } std::shared_ptr<FileInfo> GetFile(const std::string& filename) const { auto it = file_infos_->find(filename); if (it == file_infos_->end()) return nullptr; return it->second; } const std::vector<std::shared_ptr<FileInfo>>& GetFiles() { return files_; } // @param abs_path_to_size Pre-fetched file sizes (bytes). Status LoadFromFile( const std::string& backup_dir, const std::unordered_map<std::string, uint64_t>& abs_path_to_size); Status StoreToFile(bool sync); std::string GetInfoString() { std::ostringstream ss; ss << "Timestamp: " << timestamp_ << std::endl; char human_size[16]; AppendHumanBytes(size_, human_size, sizeof(human_size)); ss << "Size: " << human_size << std::endl; ss << "Files:" << std::endl; for (const auto& file : files_) { AppendHumanBytes(file->size, human_size, sizeof(human_size)); ss << file->filename << ", size " << human_size << ", refs " << file->refs << std::endl; } return ss.str(); } private: int64_t timestamp_; // sequence number is only approximate, should not be used // by clients uint64_t sequence_number_; uint64_t size_; std::string app_metadata_; std::string const meta_filename_; // files with relative paths (without "/" prefix!!) std::vector<std::shared_ptr<FileInfo>> files_; std::unordered_map<std::string, std::shared_ptr<FileInfo>>* file_infos_; Env* env_; static const size_t max_backup_meta_file_size_ = 10 * 1024 * 1024; // 10MB }; // BackupMeta inline std::string GetAbsolutePath( const std::string &relative_path = "") const { assert(relative_path.size() == 0 || relative_path[0] != '/'); return options_.backup_dir + "/" + relative_path; } inline std::string GetPrivateDirRel() const { return "private"; } inline std::string GetSharedChecksumDirRel() const { return "shared_checksum"; } inline std::string GetPrivateFileRel(BackupID backup_id, bool tmp = false, const std::string& file = "") const { assert(file.size() == 0 || file[0] != '/'); return GetPrivateDirRel() + "/" + rocksdb::ToString(backup_id) + (tmp ? ".tmp" : "") + "/" + file; } inline std::string GetSharedFileRel(const std::string& file = "", bool tmp = false) const { assert(file.size() == 0 || file[0] != '/'); return "shared/" + file + (tmp ? ".tmp" : ""); } inline std::string GetSharedFileWithChecksumRel(const std::string& file = "", bool tmp = false) const { assert(file.size() == 0 || file[0] != '/'); return GetSharedChecksumDirRel() + "/" + file + (tmp ? ".tmp" : ""); } inline std::string GetSharedFileWithChecksum(const std::string& file, const uint32_t checksum_value, const uint64_t file_size) const { assert(file.size() == 0 || file[0] != '/'); std::string file_copy = file; return file_copy.insert(file_copy.find_last_of('.'), "_" + rocksdb::ToString(checksum_value) + "_" + rocksdb::ToString(file_size)); } inline std::string GetFileFromChecksumFile(const std::string& file) const { assert(file.size() == 0 || file[0] != '/'); std::string file_copy = file; size_t first_underscore = file_copy.find_first_of('_'); return file_copy.erase(first_underscore, file_copy.find_last_of('.') - first_underscore); } inline std::string GetBackupMetaDir() const { return GetAbsolutePath("meta"); } inline std::string GetBackupMetaFile(BackupID backup_id) const { return GetBackupMetaDir() + "/" + rocksdb::ToString(backup_id); } // If size_limit == 0, there is no size limit, copy everything. // // Exactly one of src and contents must be non-empty. // // @param src If non-empty, the file is copied from this pathname. // @param contents If non-empty, the file will be created with these contents. Status CopyOrCreateFile(const std::string& src, const std::string& dst, const std::string& contents, Env* src_env, Env* dst_env, bool sync, RateLimiter* rate_limiter, uint64_t* size = nullptr, uint32_t* checksum_value = nullptr, uint64_t size_limit = 0, std::function<void()> progress_callback = []() {}); Status CalculateChecksum(const std::string& src, Env* src_env, uint64_t size_limit, uint32_t* checksum_value); struct CopyOrCreateResult { uint64_t size; uint32_t checksum_value; Status status; }; // Exactly one of src_path and contents must be non-empty. If src_path is // non-empty, the file is copied from this pathname. Otherwise, if contents is // non-empty, the file will be created at dst_path with these contents. struct CopyOrCreateWorkItem { std::string src_path; std::string dst_path; std::string contents; Env* src_env; Env* dst_env; bool sync; RateLimiter* rate_limiter; uint64_t size_limit; std::promise<CopyOrCreateResult> result; std::function<void()> progress_callback; CopyOrCreateWorkItem() {} CopyOrCreateWorkItem(const CopyOrCreateWorkItem&) = delete; CopyOrCreateWorkItem& operator=(const CopyOrCreateWorkItem&) = delete; CopyOrCreateWorkItem(CopyOrCreateWorkItem&& o) ROCKSDB_NOEXCEPT { *this = std::move(o); } CopyOrCreateWorkItem& operator=(CopyOrCreateWorkItem&& o) ROCKSDB_NOEXCEPT { src_path = std::move(o.src_path); dst_path = std::move(o.dst_path); contents = std::move(o.contents); src_env = o.src_env; dst_env = o.dst_env; sync = o.sync; rate_limiter = o.rate_limiter; size_limit = o.size_limit; result = std::move(o.result); progress_callback = std::move(o.progress_callback); return *this; } CopyOrCreateWorkItem(std::string _src_path, std::string _dst_path, std::string _contents, Env* _src_env, Env* _dst_env, bool _sync, RateLimiter* _rate_limiter, uint64_t _size_limit, std::function<void()> _progress_callback = []() {}) : src_path(std::move(_src_path)), dst_path(std::move(_dst_path)), contents(std::move(_contents)), src_env(_src_env), dst_env(_dst_env), sync(_sync), rate_limiter(_rate_limiter), size_limit(_size_limit), progress_callback(_progress_callback) {} }; struct BackupAfterCopyOrCreateWorkItem { std::future<CopyOrCreateResult> result; bool shared; bool needed_to_copy; Env* backup_env; std::string dst_path_tmp; std::string dst_path; std::string dst_relative; BackupAfterCopyOrCreateWorkItem() {} BackupAfterCopyOrCreateWorkItem(BackupAfterCopyOrCreateWorkItem&& o) ROCKSDB_NOEXCEPT { *this = std::move(o); } BackupAfterCopyOrCreateWorkItem& operator=( BackupAfterCopyOrCreateWorkItem&& o) ROCKSDB_NOEXCEPT { result = std::move(o.result); shared = o.shared; needed_to_copy = o.needed_to_copy; backup_env = o.backup_env; dst_path_tmp = std::move(o.dst_path_tmp); dst_path = std::move(o.dst_path); dst_relative = std::move(o.dst_relative); return *this; } BackupAfterCopyOrCreateWorkItem(std::future<CopyOrCreateResult>&& _result, bool _shared, bool _needed_to_copy, Env* _backup_env, std::string _dst_path_tmp, std::string _dst_path, std::string _dst_relative) : result(std::move(_result)), shared(_shared), needed_to_copy(_needed_to_copy), backup_env(_backup_env), dst_path_tmp(std::move(_dst_path_tmp)), dst_path(std::move(_dst_path)), dst_relative(std::move(_dst_relative)) {} }; struct RestoreAfterCopyOrCreateWorkItem { std::future<CopyOrCreateResult> result; uint32_t checksum_value; RestoreAfterCopyOrCreateWorkItem() {} RestoreAfterCopyOrCreateWorkItem(std::future<CopyOrCreateResult>&& _result, uint32_t _checksum_value) : result(std::move(_result)), checksum_value(_checksum_value) {} RestoreAfterCopyOrCreateWorkItem(RestoreAfterCopyOrCreateWorkItem&& o) ROCKSDB_NOEXCEPT { *this = std::move(o); } RestoreAfterCopyOrCreateWorkItem& operator=( RestoreAfterCopyOrCreateWorkItem&& o) ROCKSDB_NOEXCEPT { result = std::move(o.result); checksum_value = o.checksum_value; return *this; } }; bool initialized_; std::mutex byte_report_mutex_; channel<CopyOrCreateWorkItem> files_to_copy_or_create_; std::vector<port::Thread> threads_; // Adds a file to the backup work queue to be copied or created if it doesn't // already exist. // // Exactly one of src_dir and contents must be non-empty. // // @param src_dir If non-empty, the file in this directory named fname will be // copied. // @param fname Name of destination file and, in case of copy, source file. // @param contents If non-empty, the file will be created with these contents. Status AddBackupFileWorkItem( std::unordered_set<std::string>& live_dst_paths, std::vector<BackupAfterCopyOrCreateWorkItem>& backup_items_to_finish, BackupID backup_id, bool shared, const std::string& src_dir, const std::string& fname, // starts with "/" RateLimiter* rate_limiter, uint64_t size_bytes, uint64_t size_limit = 0, bool shared_checksum = false, std::function<void()> progress_callback = []() {}, const std::string& contents = std::string()); // backup state data BackupID latest_backup_id_; std::map<BackupID, unique_ptr<BackupMeta>> backups_; std::map<BackupID, std::pair<Status, unique_ptr<BackupMeta>>> corrupt_backups_; std::unordered_map<std::string, std::shared_ptr<FileInfo>> backuped_file_infos_; std::atomic<bool> stop_backup_; // options data BackupableDBOptions options_; Env* db_env_; Env* backup_env_; // directories unique_ptr<Directory> backup_directory_; unique_ptr<Directory> shared_directory_; unique_ptr<Directory> meta_directory_; unique_ptr<Directory> private_directory_; static const size_t kDefaultCopyFileBufferSize = 5 * 1024 * 1024LL; // 5MB size_t copy_file_buffer_size_; bool read_only_; BackupStatistics backup_statistics_; static const size_t kMaxAppMetaSize = 1024 * 1024; // 1MB }; Status BackupEngine::Open(Env* env, const BackupableDBOptions& options, BackupEngine** backup_engine_ptr) { std::unique_ptr<BackupEngineImpl> backup_engine( new BackupEngineImpl(env, options)); auto s = backup_engine->Initialize(); if (!s.ok()) { *backup_engine_ptr = nullptr; return s; } *backup_engine_ptr = backup_engine.release(); return Status::OK(); } BackupEngineImpl::BackupEngineImpl(Env* db_env, const BackupableDBOptions& options, bool read_only) : initialized_(false), stop_backup_(false), options_(options), db_env_(db_env), backup_env_(options.backup_env != nullptr ? options.backup_env : db_env_), copy_file_buffer_size_(kDefaultCopyFileBufferSize), read_only_(read_only) { if (options_.backup_rate_limiter == nullptr && options_.backup_rate_limit > 0) { options_.backup_rate_limiter.reset( NewGenericRateLimiter(options_.backup_rate_limit)); } if (options_.restore_rate_limiter == nullptr && options_.restore_rate_limit > 0) { options_.restore_rate_limiter.reset( NewGenericRateLimiter(options_.restore_rate_limit)); } } BackupEngineImpl::~BackupEngineImpl() { files_to_copy_or_create_.sendEof(); for (auto& t : threads_) { t.join(); } LogFlush(options_.info_log); } Status BackupEngineImpl::Initialize() { assert(!initialized_); initialized_ = true; if (read_only_) { ROCKS_LOG_INFO(options_.info_log, "Starting read_only backup engine"); } options_.Dump(options_.info_log); if (!read_only_) { // gather the list of directories that we need to create std::vector<std::pair<std::string, std::unique_ptr<Directory>*>> directories; directories.emplace_back(GetAbsolutePath(), &backup_directory_); if (options_.share_table_files) { if (options_.share_files_with_checksum) { directories.emplace_back( GetAbsolutePath(GetSharedFileWithChecksumRel()), &shared_directory_); } else { directories.emplace_back(GetAbsolutePath(GetSharedFileRel()), &shared_directory_); } } directories.emplace_back(GetAbsolutePath(GetPrivateDirRel()), &private_directory_); directories.emplace_back(GetBackupMetaDir(), &meta_directory_); // create all the dirs we need for (const auto& d : directories) { auto s = backup_env_->CreateDirIfMissing(d.first); if (s.ok()) { s = backup_env_->NewDirectory(d.first, d.second); } if (!s.ok()) { return s; } } } std::vector<std::string> backup_meta_files; { auto s = backup_env_->GetChildren(GetBackupMetaDir(), &backup_meta_files); if (s.IsNotFound()) { return Status::NotFound(GetBackupMetaDir() + " is missing"); } else if (!s.ok()) { return s; } } // create backups_ structure for (auto& file : backup_meta_files) { if (file == "." || file == "..") { continue; } ROCKS_LOG_INFO(options_.info_log, "Detected backup %s", file.c_str()); BackupID backup_id = 0; sscanf(file.c_str(), "%u", &backup_id); if (backup_id == 0 || file != rocksdb::ToString(backup_id)) { if (!read_only_) { // invalid file name, delete that auto s = backup_env_->DeleteFile(GetBackupMetaDir() + "/" + file); ROCKS_LOG_INFO(options_.info_log, "Unrecognized meta file %s, deleting -- %s", file.c_str(), s.ToString().c_str()); } continue; } assert(backups_.find(backup_id) == backups_.end()); backups_.insert( std::make_pair(backup_id, unique_ptr<BackupMeta>(new BackupMeta( GetBackupMetaFile(backup_id), &backuped_file_infos_, backup_env_)))); } latest_backup_id_ = 0; if (options_.destroy_old_data) { // Destroy old data assert(!read_only_); ROCKS_LOG_INFO( options_.info_log, "Backup Engine started with destroy_old_data == true, deleting all " "backups"); auto s = PurgeOldBackups(0); if (s.ok()) { s = GarbageCollect(); } if (!s.ok()) { return s; } } else { // Load data from storage std::unordered_map<std::string, uint64_t> abs_path_to_size; for (const auto& rel_dir : {GetSharedFileRel(), GetSharedFileWithChecksumRel()}) { const auto abs_dir = GetAbsolutePath(rel_dir); InsertPathnameToSizeBytes(abs_dir, backup_env_, &abs_path_to_size); } // load the backups if any for (auto& backup : backups_) { InsertPathnameToSizeBytes( GetAbsolutePath(GetPrivateFileRel(backup.first)), backup_env_, &abs_path_to_size); Status s = backup.second->LoadFromFile(options_.backup_dir, abs_path_to_size); if (s.IsCorruption()) { ROCKS_LOG_INFO(options_.info_log, "Backup %u corrupted -- %s", backup.first, s.ToString().c_str()); corrupt_backups_.insert(std::make_pair( backup.first, std::make_pair(s, std::move(backup.second)))); } else if (!s.ok()) { // Distinguish corruption errors from errors in the backup Env. // Errors in the backup Env (i.e., this code path) will cause Open() to // fail, whereas corruption errors would not cause Open() failures. return s; } else { ROCKS_LOG_INFO(options_.info_log, "Loading backup %" PRIu32 " OK:\n%s", backup.first, backup.second->GetInfoString().c_str()); latest_backup_id_ = std::max(latest_backup_id_, backup.first); } } for (const auto& corrupt : corrupt_backups_) { backups_.erase(backups_.find(corrupt.first)); } } ROCKS_LOG_INFO(options_.info_log, "Latest backup is %u", latest_backup_id_); // set up threads perform copies from files_to_copy_or_create_ in the // background for (int t = 0; t < options_.max_background_operations; t++) { threads_.emplace_back([this]() { #if defined(_GNU_SOURCE) && defined(__GLIBC_PREREQ) #if __GLIBC_PREREQ(2, 12) pthread_setname_np(pthread_self(), "backup_engine"); #endif #endif CopyOrCreateWorkItem work_item; while (files_to_copy_or_create_.read(work_item)) { CopyOrCreateResult result; result.status = CopyOrCreateFile( work_item.src_path, work_item.dst_path, work_item.contents, work_item.src_env, work_item.dst_env, work_item.sync, work_item.rate_limiter, &result.size, &result.checksum_value, work_item.size_limit, work_item.progress_callback); work_item.result.set_value(std::move(result)); } }); } ROCKS_LOG_INFO(options_.info_log, "Initialized BackupEngine"); return Status::OK(); } Status BackupEngineImpl::CreateNewBackupWithMetadata( DB* db, const std::string& app_metadata, bool flush_before_backup, std::function<void()> progress_callback) { assert(initialized_); assert(!read_only_); if (app_metadata.size() > kMaxAppMetaSize) { return Status::InvalidArgument("App metadata too large"); } Status s; std::vector<std::string> live_files; VectorLogPtr live_wal_files; uint64_t manifest_file_size = 0; uint64_t sequence_number = db->GetLatestSequenceNumber(); s = db->DisableFileDeletions(); if (s.ok()) { // this will return live_files prefixed with "/" s = db->GetLiveFiles(live_files, &manifest_file_size, flush_before_backup); } // if we didn't flush before backup, we need to also get WAL files if (s.ok() && !flush_before_backup && options_.backup_log_files) { // returns file names prefixed with "/" s = db->GetSortedWalFiles(live_wal_files); } if (!s.ok()) { db->EnableFileDeletions(false); return s; } TEST_SYNC_POINT("BackupEngineImpl::CreateNewBackup:SavedLiveFiles1"); TEST_SYNC_POINT("BackupEngineImpl::CreateNewBackup:SavedLiveFiles2"); BackupID new_backup_id = latest_backup_id_ + 1; assert(backups_.find(new_backup_id) == backups_.end()); auto ret = backups_.insert( std::make_pair(new_backup_id, unique_ptr<BackupMeta>(new BackupMeta( GetBackupMetaFile(new_backup_id), &backuped_file_infos_, backup_env_)))); assert(ret.second == true); auto& new_backup = ret.first->second; new_backup->RecordTimestamp(); new_backup->SetSequenceNumber(sequence_number); new_backup->SetAppMetadata(app_metadata); auto start_backup = backup_env_-> NowMicros(); ROCKS_LOG_INFO(options_.info_log, "Started the backup process -- creating backup %u", new_backup_id); auto private_tmp_dir = GetAbsolutePath(GetPrivateFileRel(new_backup_id, true)); s = backup_env_->FileExists(private_tmp_dir); if (s.ok()) { // maybe last backup failed and left partial state behind, clean it up s = GarbageCollect(); } else if (s.IsNotFound()) { // normal case, the new backup's private dir doesn't exist yet s = Status::OK(); } if (s.ok()) { s = backup_env_->CreateDir(private_tmp_dir); } RateLimiter* rate_limiter = options_.backup_rate_limiter.get(); if (rate_limiter) { copy_file_buffer_size_ = rate_limiter->GetSingleBurstBytes(); } // A set into which we will insert the dst_paths that are calculated for live // files and live WAL files. // This is used to check whether a live files shares a dst_path with another // live file. std::unordered_set<std::string> live_dst_paths; live_dst_paths.reserve(live_files.size() + live_wal_files.size()); // Pre-fetch sizes for data files std::unordered_map<std::string, uint64_t> data_path_to_size; if (s.ok()) { s = InsertPathnameToSizeBytes(db->GetName(), db_env_, &data_path_to_size); } std::vector<BackupAfterCopyOrCreateWorkItem> backup_items_to_finish; // Add a CopyOrCreateWorkItem to the channel for each live file std::string manifest_fname, current_fname; for (size_t i = 0; s.ok() && i < live_files.size(); ++i) { uint64_t number; FileType type; bool ok = ParseFileName(live_files[i], &number, &type); if (!ok) { assert(false); return Status::Corruption("Can't parse file name. This is very bad"); } // we should only get sst, manifest and current files here assert(type == kTableFile || type == kDescriptorFile || type == kCurrentFile || type == kOptionsFile); if (type == kCurrentFile) { // We will craft the current file manually to ensure it's consistent with // the manifest number. This is necessary because current's file contents // can change during backup. current_fname = live_files[i]; continue; } else if (type == kDescriptorFile) { manifest_fname = live_files[i]; } auto data_path_to_size_iter = data_path_to_size.find(db->GetName() + live_files[i]); uint64_t size_bytes = data_path_to_size_iter == data_path_to_size.end() ? port::kMaxUint64 : data_path_to_size_iter->second; // rules: // * if it's kTableFile, then it's shared // * if it's kDescriptorFile, limit the size to manifest_file_size s = AddBackupFileWorkItem( live_dst_paths, backup_items_to_finish, new_backup_id, options_.share_table_files && type == kTableFile, db->GetName(), live_files[i], rate_limiter, size_bytes, (type == kDescriptorFile) ? manifest_file_size : 0, options_.share_files_with_checksum && type == kTableFile, progress_callback); } if (s.ok() && !current_fname.empty() && !manifest_fname.empty()) { // Write the current file with the manifest filename as its contents. s = AddBackupFileWorkItem( live_dst_paths, backup_items_to_finish, new_backup_id, false /* shared */, "" /* src_dir */, CurrentFileName(""), rate_limiter, manifest_fname.size(), 0 /* size_limit */, false /* shared_checksum */, progress_callback, manifest_fname.substr(1) + "\n"); } ROCKS_LOG_INFO(options_.info_log, "begin add wal files for backup -- %" ROCKSDB_PRIszt, live_wal_files.size()); // Add a CopyOrCreateWorkItem to the channel for each WAL file for (size_t i = 0; s.ok() && i < live_wal_files.size(); ++i) { uint64_t size_bytes = live_wal_files[i]->SizeFileBytes(); if (live_wal_files[i]->Type() == kAliveLogFile) { ROCKS_LOG_INFO(options_.info_log, "add wal file for backup %s -- %" PRIu64, live_wal_files[i]->PathName().c_str(), size_bytes); // we only care about live log files // copy the file into backup_dir/files/<new backup>/ s = AddBackupFileWorkItem(live_dst_paths, backup_items_to_finish, new_backup_id, false, /* not shared */ db->GetOptions().wal_dir, live_wal_files[i]->PathName(), rate_limiter, size_bytes, size_bytes); } } ROCKS_LOG_INFO(options_.info_log, "add files for backup done, wait finish."); Status item_status; for (auto& item : backup_items_to_finish) { item.result.wait(); auto result = item.result.get(); item_status = result.status; if (item_status.ok() && item.shared && item.needed_to_copy) { item_status = item.backup_env->RenameFile(item.dst_path_tmp, item.dst_path); } if (item_status.ok()) { item_status = new_backup.get()->AddFile( std::make_shared<FileInfo>(item.dst_relative, result.size, result.checksum_value)); } if (!item_status.ok()) { s = item_status; } } // we copied all the files, enable file deletions db->EnableFileDeletions(false); if (s.ok()) { // move tmp private backup to real backup folder ROCKS_LOG_INFO( options_.info_log, "Moving tmp backup directory to the real one: %s -> %s\n", GetAbsolutePath(GetPrivateFileRel(new_backup_id, true)).c_str(), GetAbsolutePath(GetPrivateFileRel(new_backup_id, false)).c_str()); s = backup_env_->RenameFile( GetAbsolutePath(GetPrivateFileRel(new_backup_id, true)), // tmp GetAbsolutePath(GetPrivateFileRel(new_backup_id, false))); } auto backup_time = backup_env_->NowMicros() - start_backup; if (s.ok()) { // persist the backup metadata on the disk s = new_backup->StoreToFile(options_.sync); } if (s.ok() && options_.sync) { unique_ptr<Directory> backup_private_directory; backup_env_->NewDirectory( GetAbsolutePath(GetPrivateFileRel(new_backup_id, false)), &backup_private_directory); if (backup_private_directory != nullptr) { backup_private_directory->Fsync(); } if (private_directory_ != nullptr) { private_directory_->Fsync(); } if (meta_directory_ != nullptr) { meta_directory_->Fsync(); } if (shared_directory_ != nullptr) { shared_directory_->Fsync(); } if (backup_directory_ != nullptr) { backup_directory_->Fsync(); } } if (s.ok()) { backup_statistics_.IncrementNumberSuccessBackup(); } if (!s.ok()) { backup_statistics_.IncrementNumberFailBackup(); // clean all the files we might have created ROCKS_LOG_INFO(options_.info_log, "Backup failed -- %s", s.ToString().c_str()); ROCKS_LOG_INFO(options_.info_log, "Backup Statistics %s\n", backup_statistics_.ToString().c_str()); // delete files that we might have already written DeleteBackup(new_backup_id); GarbageCollect(); return s; } // here we know that we succeeded and installed the new backup // in the LATEST_BACKUP file latest_backup_id_ = new_backup_id; ROCKS_LOG_INFO(options_.info_log, "Backup DONE. All is good"); // backup_speed is in byte/second double backup_speed = new_backup->GetSize() / (1.048576 * backup_time); ROCKS_LOG_INFO(options_.info_log, "Backup number of files: %u", new_backup->GetNumberFiles()); char human_size[16]; AppendHumanBytes(new_backup->GetSize(), human_size, sizeof(human_size)); ROCKS_LOG_INFO(options_.info_log, "Backup size: %s", human_size); ROCKS_LOG_INFO(options_.info_log, "Backup time: %" PRIu64 " microseconds", backup_time); ROCKS_LOG_INFO(options_.info_log, "Backup speed: %.3f MB/s", backup_speed); ROCKS_LOG_INFO(options_.info_log, "Backup Statistics %s", backup_statistics_.ToString().c_str()); return s; } Status BackupEngineImpl::PurgeOldBackups(uint32_t num_backups_to_keep) { assert(initialized_); assert(!read_only_); ROCKS_LOG_INFO(options_.info_log, "Purging old backups, keeping %u", num_backups_to_keep); std::vector<BackupID> to_delete; auto itr = backups_.begin(); while ((backups_.size() - to_delete.size()) > num_backups_to_keep) { to_delete.push_back(itr->first); itr++; } for (auto backup_id : to_delete) { auto s = DeleteBackup(backup_id); if (!s.ok()) { return s; } } return Status::OK(); } Status BackupEngineImpl::DeleteBackup(BackupID backup_id) { assert(initialized_); assert(!read_only_); ROCKS_LOG_INFO(options_.info_log, "Deleting backup %u", backup_id); auto backup = backups_.find(backup_id); if (backup != backups_.end()) { auto s = backup->second->Delete(); if (!s.ok()) { return s; } backups_.erase(backup); } else { auto corrupt = corrupt_backups_.find(backup_id); if (corrupt == corrupt_backups_.end()) { return Status::NotFound("Backup not found"); } auto s = corrupt->second.second->Delete(); if (!s.ok()) { return s; } corrupt_backups_.erase(corrupt); } std::vector<std::string> to_delete; for (auto& itr : backuped_file_infos_) { if (itr.second->refs == 0) { Status s = backup_env_->DeleteFile(GetAbsolutePath(itr.first)); ROCKS_LOG_INFO(options_.info_log, "Deleting %s -- %s", itr.first.c_str(), s.ToString().c_str()); to_delete.push_back(itr.first); } } for (auto& td : to_delete) { backuped_file_infos_.erase(td); } // take care of private dirs -- GarbageCollect() will take care of them // if they are not empty std::string private_dir = GetPrivateFileRel(backup_id); Status s = backup_env_->DeleteDir(GetAbsolutePath(private_dir)); ROCKS_LOG_INFO(options_.info_log, "Deleting private dir %s -- %s", private_dir.c_str(), s.ToString().c_str()); return Status::OK(); } void BackupEngineImpl::GetBackupInfo(std::vector<BackupInfo>* backup_info) { assert(initialized_); backup_info->reserve(backups_.size()); for (auto& backup : backups_) { if (!backup.second->Empty()) { backup_info->push_back(BackupInfo( backup.first, backup.second->GetTimestamp(), backup.second->GetSize(), backup.second->GetNumberFiles(), backup.second->GetAppMetadata())); } } } void BackupEngineImpl::GetCorruptedBackups( std::vector<BackupID>* corrupt_backup_ids) { assert(initialized_); corrupt_backup_ids->reserve(corrupt_backups_.size()); for (auto& backup : corrupt_backups_) { corrupt_backup_ids->push_back(backup.first); } } Status BackupEngineImpl::RestoreDBFromBackup( BackupID backup_id, const std::string& db_dir, const std::string& wal_dir, const RestoreOptions& restore_options) { assert(initialized_); auto corrupt_itr = corrupt_backups_.find(backup_id); if (corrupt_itr != corrupt_backups_.end()) { return corrupt_itr->second.first; } auto backup_itr = backups_.find(backup_id); if (backup_itr == backups_.end()) { return Status::NotFound("Backup not found"); } auto& backup = backup_itr->second; if (backup->Empty()) { return Status::NotFound("Backup not found"); } ROCKS_LOG_INFO(options_.info_log, "Restoring backup id %u\n", backup_id); ROCKS_LOG_INFO(options_.info_log, "keep_log_files: %d\n", static_cast<int>(restore_options.keep_log_files)); // just in case. Ignore errors db_env_->CreateDirIfMissing(db_dir); db_env_->CreateDirIfMissing(wal_dir); if (restore_options.keep_log_files) { // delete files in db_dir, but keep all the log files DeleteChildren(db_dir, 1 << kLogFile); // move all the files from archive dir to wal_dir std::string archive_dir = ArchivalDirectory(wal_dir); std::vector<std::string> archive_files; db_env_->GetChildren(archive_dir, &archive_files); // ignore errors for (const auto& f : archive_files) { uint64_t number; FileType type; bool ok = ParseFileName(f, &number, &type); if (ok && type == kLogFile) { ROCKS_LOG_INFO(options_.info_log, "Moving log file from archive/ to wal_dir: %s", f.c_str()); Status s = db_env_->RenameFile(archive_dir + "/" + f, wal_dir + "/" + f); if (!s.ok()) { // if we can't move log file from archive_dir to wal_dir, // we should fail, since it might mean data loss return s; } } } } else { DeleteChildren(wal_dir); DeleteChildren(ArchivalDirectory(wal_dir)); DeleteChildren(db_dir); } RateLimiter* rate_limiter = options_.restore_rate_limiter.get(); if (rate_limiter) { copy_file_buffer_size_ = rate_limiter->GetSingleBurstBytes(); } Status s; std::vector<RestoreAfterCopyOrCreateWorkItem> restore_items_to_finish; for (const auto& file_info : backup->GetFiles()) { const std::string &file = file_info->filename; std::string dst; // 1. extract the filename size_t slash = file.find_last_of('/'); // file will either be shared/<file>, shared_checksum/<file_crc32_size> // or private/<number>/<file> assert(slash != std::string::npos); dst = file.substr(slash + 1); // if the file was in shared_checksum, extract the real file name // in this case the file is <number>_<checksum>_<size>.<type> if (file.substr(0, slash) == GetSharedChecksumDirRel()) { dst = GetFileFromChecksumFile(dst); } // 2. find the filetype uint64_t number; FileType type; bool ok = ParseFileName(dst, &number, &type); if (!ok) { return Status::Corruption("Backup corrupted"); } // 3. Construct the final path // kLogFile lives in wal_dir and all the rest live in db_dir dst = ((type == kLogFile) ? wal_dir : db_dir) + "/" + dst; ROCKS_LOG_INFO(options_.info_log, "Restoring %s to %s\n", file.c_str(), dst.c_str()); CopyOrCreateWorkItem copy_or_create_work_item( GetAbsolutePath(file), dst, "" /* contents */, backup_env_, db_env_, false, rate_limiter, 0 /* size_limit */); RestoreAfterCopyOrCreateWorkItem after_copy_or_create_work_item( copy_or_create_work_item.result.get_future(), file_info->checksum_value); files_to_copy_or_create_.write(std::move(copy_or_create_work_item)); restore_items_to_finish.push_back( std::move(after_copy_or_create_work_item)); } Status item_status; for (auto& item : restore_items_to_finish) { item.result.wait(); auto result = item.result.get(); item_status = result.status; // Note: It is possible that both of the following bad-status cases occur // during copying. But, we only return one status. if (!item_status.ok()) { s = item_status; break; } else if (item.checksum_value != result.checksum_value) { s = Status::Corruption("Checksum check failed"); break; } } ROCKS_LOG_INFO(options_.info_log, "Restoring done -- %s\n", s.ToString().c_str()); return s; } Status BackupEngineImpl::VerifyBackup(BackupID backup_id) { assert(initialized_); auto corrupt_itr = corrupt_backups_.find(backup_id); if (corrupt_itr != corrupt_backups_.end()) { return corrupt_itr->second.first; } auto backup_itr = backups_.find(backup_id); if (backup_itr == backups_.end()) { return Status::NotFound(); } auto& backup = backup_itr->second; if (backup->Empty()) { return Status::NotFound(); } ROCKS_LOG_INFO(options_.info_log, "Verifying backup id %u\n", backup_id); std::unordered_map<std::string, uint64_t> curr_abs_path_to_size; for (const auto& rel_dir : {GetPrivateFileRel(backup_id), GetSharedFileRel(), GetSharedFileWithChecksumRel()}) { const auto abs_dir = GetAbsolutePath(rel_dir); InsertPathnameToSizeBytes(abs_dir, backup_env_, &curr_abs_path_to_size); } for (const auto& file_info : backup->GetFiles()) { const auto abs_path = GetAbsolutePath(file_info->filename); if (curr_abs_path_to_size.find(abs_path) == curr_abs_path_to_size.end()) { return Status::NotFound("File missing: " + abs_path); } if (file_info->size != curr_abs_path_to_size[abs_path]) { return Status::Corruption("File corrupted: " + abs_path); } } return Status::OK(); } Status BackupEngineImpl::CopyOrCreateFile( const std::string& src, const std::string& dst, const std::string& contents, Env* src_env, Env* dst_env, bool sync, RateLimiter* rate_limiter, uint64_t* size, uint32_t* checksum_value, uint64_t size_limit, std::function<void()> progress_callback) { assert(src.empty() != contents.empty()); Status s; unique_ptr<WritableFile> dst_file; unique_ptr<SequentialFile> src_file; EnvOptions env_options; env_options.use_mmap_writes = false; // TODO:(gzh) maybe use direct writes here if possible if (size != nullptr) { *size = 0; } if (checksum_value != nullptr) { *checksum_value = 0; } // Check if size limit is set. if not, set it to very big number if (size_limit == 0) { size_limit = std::numeric_limits<uint64_t>::max(); } s = dst_env->NewWritableFile(dst, &dst_file, env_options); if (s.ok() && !src.empty()) { s = src_env->NewSequentialFile(src, &src_file, env_options); } if (!s.ok()) { return s; } unique_ptr<WritableFileWriter> dest_writer( new WritableFileWriter(std::move(dst_file), env_options)); unique_ptr<SequentialFileReader> src_reader; unique_ptr<char[]> buf; if (!src.empty()) { src_reader.reset(new SequentialFileReader(std::move(src_file))); buf.reset(new char[copy_file_buffer_size_]); } Slice data; uint64_t processed_buffer_size = 0; do { if (stop_backup_.load(std::memory_order_acquire)) { return Status::Incomplete("Backup stopped"); } if (!src.empty()) { size_t buffer_to_read = (copy_file_buffer_size_ < size_limit) ? copy_file_buffer_size_ : size_limit; s = src_reader->Read(buffer_to_read, &data, buf.get()); processed_buffer_size += buffer_to_read; } else { data = contents; } size_limit -= data.size(); if (!s.ok()) { return s; } if (size != nullptr) { *size += data.size(); } if (checksum_value != nullptr) { *checksum_value = crc32c::Extend(*checksum_value, data.data(), data.size()); } s = dest_writer->Append(data); if (rate_limiter != nullptr) { rate_limiter->Request(data.size(), Env::IO_LOW, nullptr /* stats */); } if (processed_buffer_size > options_.callback_trigger_interval_size) { processed_buffer_size -= options_.callback_trigger_interval_size; std::lock_guard<std::mutex> lock(byte_report_mutex_); progress_callback(); } } while (s.ok() && contents.empty() && data.size() > 0 && size_limit > 0); if (s.ok() && sync) { s = dest_writer->Sync(false); } if (s.ok()) { s = dest_writer->Close(); } return s; } // fname will always start with "/" Status BackupEngineImpl::AddBackupFileWorkItem( std::unordered_set<std::string>& live_dst_paths, std::vector<BackupAfterCopyOrCreateWorkItem>& backup_items_to_finish, BackupID backup_id, bool shared, const std::string& src_dir, const std::string& fname, RateLimiter* rate_limiter, uint64_t size_bytes, uint64_t size_limit, bool shared_checksum, std::function<void()> progress_callback, const std::string& contents) { assert(!fname.empty() && fname[0] == '/'); assert(contents.empty() != src_dir.empty()); std::string dst_relative = fname.substr(1); std::string dst_relative_tmp; Status s; uint32_t checksum_value = 0; if (shared && shared_checksum) { // add checksum and file length to the file name s = CalculateChecksum(src_dir + fname, db_env_, size_limit, &checksum_value); if (!s.ok()) { return s; } if (size_bytes == port::kMaxUint64) { return Status::NotFound("File missing: " + src_dir + fname); } dst_relative = GetSharedFileWithChecksum(dst_relative, checksum_value, size_bytes); dst_relative_tmp = GetSharedFileWithChecksumRel(dst_relative, true); dst_relative = GetSharedFileWithChecksumRel(dst_relative, false); } else if (shared) { dst_relative_tmp = GetSharedFileRel(dst_relative, true); dst_relative = GetSharedFileRel(dst_relative, false); } else { dst_relative_tmp = GetPrivateFileRel(backup_id, true, dst_relative); dst_relative = GetPrivateFileRel(backup_id, false, dst_relative); } std::string dst_path = GetAbsolutePath(dst_relative); std::string dst_path_tmp = GetAbsolutePath(dst_relative_tmp); // if it's shared, we also need to check if it exists -- if it does, no need // to copy it again. bool need_to_copy = true; // true if dst_path is the same path as another live file const bool same_path = live_dst_paths.find(dst_path) != live_dst_paths.end(); bool file_exists = false; if (shared && !same_path) { Status exist = backup_env_->FileExists(dst_path); if (exist.ok()) { file_exists = true; } else if (exist.IsNotFound()) { file_exists = false; } else { assert(s.IsIOError()); return exist; } } if (!contents.empty()) { need_to_copy = false; } else if (shared && (same_path || file_exists)) { need_to_copy = false; if (shared_checksum) { ROCKS_LOG_INFO(options_.info_log, "%s already present, with checksum %u and size %" PRIu64, fname.c_str(), checksum_value, size_bytes); } else if (backuped_file_infos_.find(dst_relative) == backuped_file_infos_.end() && !same_path) { // file already exists, but it's not referenced by any backup. overwrite // the file ROCKS_LOG_INFO( options_.info_log, "%s already present, but not referenced by any backup. We will " "overwrite the file.", fname.c_str()); need_to_copy = true; backup_env_->DeleteFile(dst_path); } else { // the file is present and referenced by a backup ROCKS_LOG_INFO(options_.info_log, "%s already present, calculate checksum", fname.c_str()); s = CalculateChecksum(src_dir + fname, db_env_, size_limit, &checksum_value); } } live_dst_paths.insert(dst_path); if (!contents.empty() || need_to_copy) { ROCKS_LOG_INFO(options_.info_log, "Copying %s to %s", fname.c_str(), dst_path_tmp.c_str()); CopyOrCreateWorkItem copy_or_create_work_item( src_dir.empty() ? "" : src_dir + fname, dst_path_tmp, contents, db_env_, backup_env_, options_.sync, rate_limiter, size_limit, progress_callback); BackupAfterCopyOrCreateWorkItem after_copy_or_create_work_item( copy_or_create_work_item.result.get_future(), shared, need_to_copy, backup_env_, dst_path_tmp, dst_path, dst_relative); files_to_copy_or_create_.write(std::move(copy_or_create_work_item)); backup_items_to_finish.push_back(std::move(after_copy_or_create_work_item)); } else { std::promise<CopyOrCreateResult> promise_result; BackupAfterCopyOrCreateWorkItem after_copy_or_create_work_item( promise_result.get_future(), shared, need_to_copy, backup_env_, dst_path_tmp, dst_path, dst_relative); backup_items_to_finish.push_back(std::move(after_copy_or_create_work_item)); CopyOrCreateResult result; result.status = s; result.size = size_bytes; result.checksum_value = checksum_value; promise_result.set_value(std::move(result)); } return s; } Status BackupEngineImpl::CalculateChecksum(const std::string& src, Env* src_env, uint64_t size_limit, uint32_t* checksum_value) { *checksum_value = 0; if (size_limit == 0) { size_limit = std::numeric_limits<uint64_t>::max(); } EnvOptions env_options; env_options.use_mmap_writes = false; env_options.use_direct_reads = false; std::unique_ptr<SequentialFile> src_file; Status s = src_env->NewSequentialFile(src, &src_file, env_options); if (!s.ok()) { return s; } unique_ptr<SequentialFileReader> src_reader( new SequentialFileReader(std::move(src_file))); std::unique_ptr<char[]> buf(new char[copy_file_buffer_size_]); Slice data; do { if (stop_backup_.load(std::memory_order_acquire)) { return Status::Incomplete("Backup stopped"); } size_t buffer_to_read = (copy_file_buffer_size_ < size_limit) ? copy_file_buffer_size_ : size_limit; s = src_reader->Read(buffer_to_read, &data, buf.get()); if (!s.ok()) { return s; } size_limit -= data.size(); *checksum_value = crc32c::Extend(*checksum_value, data.data(), data.size()); } while (data.size() > 0 && size_limit > 0); return s; } void BackupEngineImpl::DeleteChildren(const std::string& dir, uint32_t file_type_filter) { std::vector<std::string> children; db_env_->GetChildren(dir, &children); // ignore errors for (const auto& f : children) { uint64_t number; FileType type; bool ok = ParseFileName(f, &number, &type); if (ok && (file_type_filter & (1 << type))) { // don't delete this file continue; } db_env_->DeleteFile(dir + "/" + f); // ignore errors } } Status BackupEngineImpl::InsertPathnameToSizeBytes( const std::string& dir, Env* env, std::unordered_map<std::string, uint64_t>* result) { assert(result != nullptr); std::vector<Env::FileAttributes> files_attrs; Status status = env->FileExists(dir); if (status.ok()) { status = env->GetChildrenFileAttributes(dir, &files_attrs); } else if (status.IsNotFound()) { // Insert no entries can be considered success status = Status::OK(); } const bool slash_needed = dir.empty() || dir.back() != '/'; for (const auto& file_attrs : files_attrs) { result->emplace(dir + (slash_needed ? "/" : "") + file_attrs.name, file_attrs.size_bytes); } return status; } Status BackupEngineImpl::GarbageCollect() { assert(!read_only_); ROCKS_LOG_INFO(options_.info_log, "Starting garbage collection"); if (options_.share_table_files) { // delete obsolete shared files std::vector<std::string> shared_children; { std::string shared_path; if (options_.share_files_with_checksum) { shared_path = GetAbsolutePath(GetSharedFileWithChecksumRel()); } else { shared_path = GetAbsolutePath(GetSharedFileRel()); } auto s = backup_env_->FileExists(shared_path); if (s.ok()) { s = backup_env_->GetChildren(shared_path, &shared_children); } else if (s.IsNotFound()) { s = Status::OK(); } if (!s.ok()) { return s; } } for (auto& child : shared_children) { std::string rel_fname; if (options_.share_files_with_checksum) { rel_fname = GetSharedFileWithChecksumRel(child); } else { rel_fname = GetSharedFileRel(child); } auto child_itr = backuped_file_infos_.find(rel_fname); // if it's not refcounted, delete it if (child_itr == backuped_file_infos_.end() || child_itr->second->refs == 0) { // this might be a directory, but DeleteFile will just fail in that // case, so we're good Status s = backup_env_->DeleteFile(GetAbsolutePath(rel_fname)); ROCKS_LOG_INFO(options_.info_log, "Deleting %s -- %s", rel_fname.c_str(), s.ToString().c_str()); backuped_file_infos_.erase(rel_fname); } } } // delete obsolete private files std::vector<std::string> private_children; { auto s = backup_env_->GetChildren(GetAbsolutePath(GetPrivateDirRel()), &private_children); if (!s.ok()) { return s; } } for (auto& child : private_children) { BackupID backup_id = 0; bool tmp_dir = child.find(".tmp") != std::string::npos; sscanf(child.c_str(), "%u", &backup_id); if (!tmp_dir && // if it's tmp_dir, delete it (backup_id == 0 || backups_.find(backup_id) != backups_.end())) { // it's either not a number or it's still alive. continue continue; } // here we have to delete the dir and all its children std::string full_private_path = GetAbsolutePath(GetPrivateFileRel(backup_id, tmp_dir)); std::vector<std::string> subchildren; backup_env_->GetChildren(full_private_path, &subchildren); for (auto& subchild : subchildren) { Status s = backup_env_->DeleteFile(full_private_path + subchild); ROCKS_LOG_INFO(options_.info_log, "Deleting %s -- %s", (full_private_path + subchild).c_str(), s.ToString().c_str()); } // finally delete the private dir Status s = backup_env_->DeleteDir(full_private_path); ROCKS_LOG_INFO(options_.info_log, "Deleting dir %s -- %s", full_private_path.c_str(), s.ToString().c_str()); } return Status::OK(); } // ------- BackupMeta class -------- Status BackupEngineImpl::BackupMeta::AddFile( std::shared_ptr<FileInfo> file_info) { auto itr = file_infos_->find(file_info->filename); if (itr == file_infos_->end()) { auto ret = file_infos_->insert({file_info->filename, file_info}); if (ret.second) { itr = ret.first; itr->second->refs = 1; } else { // if this happens, something is seriously wrong return Status::Corruption("In memory metadata insertion error"); } } else { if (itr->second->checksum_value != file_info->checksum_value) { return Status::Corruption( "Checksum mismatch for existing backup file. Delete old backups and " "try again."); } ++itr->second->refs; // increase refcount if already present } size_ += file_info->size; files_.push_back(itr->second); return Status::OK(); } Status BackupEngineImpl::BackupMeta::Delete(bool delete_meta) { Status s; for (const auto& file : files_) { --file->refs; // decrease refcount } files_.clear(); // delete meta file if (delete_meta) { s = env_->FileExists(meta_filename_); if (s.ok()) { s = env_->DeleteFile(meta_filename_); } else if (s.IsNotFound()) { s = Status::OK(); // nothing to delete } } timestamp_ = 0; return s; } Slice kMetaDataPrefix("metadata "); // each backup meta file is of the format: // <timestamp> // <seq number> // <metadata(literal string)> <metadata> (optional) // <number of files> // <file1> <crc32(literal string)> <crc32_value> // <file2> <crc32(literal string)> <crc32_value> // ... Status BackupEngineImpl::BackupMeta::LoadFromFile( const std::string& backup_dir, const std::unordered_map<std::string, uint64_t>& abs_path_to_size) { assert(Empty()); Status s; unique_ptr<SequentialFile> backup_meta_file; s = env_->NewSequentialFile(meta_filename_, &backup_meta_file, EnvOptions()); if (!s.ok()) { return s; } unique_ptr<SequentialFileReader> backup_meta_reader( new SequentialFileReader(std::move(backup_meta_file))); unique_ptr<char[]> buf(new char[max_backup_meta_file_size_ + 1]); Slice data; s = backup_meta_reader->Read(max_backup_meta_file_size_, &data, buf.get()); if (!s.ok() || data.size() == max_backup_meta_file_size_) { return s.ok() ? Status::Corruption("File size too big") : s; } buf[data.size()] = 0; uint32_t num_files = 0; char *next; timestamp_ = strtoull(data.data(), &next, 10); data.remove_prefix(next - data.data() + 1); // +1 for '\n' sequence_number_ = strtoull(data.data(), &next, 10); data.remove_prefix(next - data.data() + 1); // +1 for '\n' if (data.starts_with(kMetaDataPrefix)) { // app metadata present data.remove_prefix(kMetaDataPrefix.size()); Slice hex_encoded_metadata = GetSliceUntil(&data, '\n'); bool decode_success = hex_encoded_metadata.DecodeHex(&app_metadata_); if (!decode_success) { return Status::Corruption( "Failed to decode stored hex encoded app metadata"); } } num_files = static_cast<uint32_t>(strtoul(data.data(), &next, 10)); data.remove_prefix(next - data.data() + 1); // +1 for '\n' std::vector<std::shared_ptr<FileInfo>> files; Slice checksum_prefix("crc32 "); for (uint32_t i = 0; s.ok() && i < num_files; ++i) { auto line = GetSliceUntil(&data, '\n'); std::string filename = GetSliceUntil(&line, ' ').ToString(); uint64_t size; const std::shared_ptr<FileInfo> file_info = GetFile(filename); if (file_info) { size = file_info->size; } else { std::string abs_path = backup_dir + "/" + filename; try { size = abs_path_to_size.at(abs_path); } catch (std::out_of_range&) { return Status::Corruption("Size missing for pathname: " + abs_path); } } if (line.empty()) { return Status::Corruption("File checksum is missing for " + filename + " in " + meta_filename_); } uint32_t checksum_value = 0; if (line.starts_with(checksum_prefix)) { line.remove_prefix(checksum_prefix.size()); checksum_value = static_cast<uint32_t>( strtoul(line.data(), nullptr, 10)); if (line != rocksdb::ToString(checksum_value)) { return Status::Corruption("Invalid checksum value for " + filename + " in " + meta_filename_); } } else { return Status::Corruption("Unknown checksum type for " + filename + " in " + meta_filename_); } files.emplace_back(new FileInfo(filename, size, checksum_value)); } if (s.ok() && data.size() > 0) { // file has to be read completely. if not, we count it as corruption s = Status::Corruption("Tailing data in backup meta file in " + meta_filename_); } if (s.ok()) { files_.reserve(files.size()); for (const auto& file_info : files) { s = AddFile(file_info); if (!s.ok()) { break; } } } return s; } Status BackupEngineImpl::BackupMeta::StoreToFile(bool sync) { Status s; unique_ptr<WritableFile> backup_meta_file; EnvOptions env_options; env_options.use_mmap_writes = false; env_options.use_direct_writes = false; s = env_->NewWritableFile(meta_filename_ + ".tmp", &backup_meta_file, env_options); if (!s.ok()) { return s; } unique_ptr<char[]> buf(new char[max_backup_meta_file_size_]); size_t len = 0, buf_size = max_backup_meta_file_size_; len += snprintf(buf.get(), buf_size, "%" PRId64 "\n", timestamp_); len += snprintf(buf.get() + len, buf_size - len, "%" PRIu64 "\n", sequence_number_); if (!app_metadata_.empty()) { std::string hex_encoded_metadata = Slice(app_metadata_).ToString(/* hex */ true); if (hex_encoded_metadata.size() + kMetaDataPrefix.size() + 1 > buf_size - len) { return Status::Corruption("Buffer too small to fit backup metadata"); } memcpy(buf.get() + len, kMetaDataPrefix.data(), kMetaDataPrefix.size()); len += kMetaDataPrefix.size(); memcpy(buf.get() + len, hex_encoded_metadata.data(), hex_encoded_metadata.size()); len += hex_encoded_metadata.size(); buf[len++] = '\n'; } len += snprintf(buf.get() + len, buf_size - len, "%" ROCKSDB_PRIszt "\n", files_.size()); for (const auto& file : files_) { // use crc32 for now, switch to something else if needed len += snprintf(buf.get() + len, buf_size - len, "%s crc32 %u\n", file->filename.c_str(), file->checksum_value); } s = backup_meta_file->Append(Slice(buf.get(), len)); if (s.ok() && sync) { s = backup_meta_file->Sync(); } if (s.ok()) { s = backup_meta_file->Close(); } if (s.ok()) { s = env_->RenameFile(meta_filename_ + ".tmp", meta_filename_); } return s; } // -------- BackupEngineReadOnlyImpl --------- class BackupEngineReadOnlyImpl : public BackupEngineReadOnly { public: BackupEngineReadOnlyImpl(Env* db_env, const BackupableDBOptions& options) : backup_engine_(new BackupEngineImpl(db_env, options, true)) {} virtual ~BackupEngineReadOnlyImpl() {} // The returned BackupInfos are in chronological order, which means the // latest backup comes last. virtual void GetBackupInfo(std::vector<BackupInfo>* backup_info) override { backup_engine_->GetBackupInfo(backup_info); } virtual void GetCorruptedBackups( std::vector<BackupID>* corrupt_backup_ids) override { backup_engine_->GetCorruptedBackups(corrupt_backup_ids); } virtual Status RestoreDBFromBackup( BackupID backup_id, const std::string& db_dir, const std::string& wal_dir, const RestoreOptions& restore_options = RestoreOptions()) override { return backup_engine_->RestoreDBFromBackup(backup_id, db_dir, wal_dir, restore_options); } virtual Status RestoreDBFromLatestBackup( const std::string& db_dir, const std::string& wal_dir, const RestoreOptions& restore_options = RestoreOptions()) override { return backup_engine_->RestoreDBFromLatestBackup(db_dir, wal_dir, restore_options); } virtual Status VerifyBackup(BackupID backup_id) override { return backup_engine_->VerifyBackup(backup_id); } Status Initialize() { return backup_engine_->Initialize(); } private: std::unique_ptr<BackupEngineImpl> backup_engine_; }; Status BackupEngineReadOnly::Open(Env* env, const BackupableDBOptions& options, BackupEngineReadOnly** backup_engine_ptr) { if (options.destroy_old_data) { return Status::InvalidArgument( "Can't destroy old data with ReadOnly BackupEngine"); } std::unique_ptr<BackupEngineReadOnlyImpl> backup_engine( new BackupEngineReadOnlyImpl(env, options)); auto s = backup_engine->Initialize(); if (!s.ok()) { *backup_engine_ptr = nullptr; return s; } *backup_engine_ptr = backup_engine.release(); return Status::OK(); } } // namespace rocksdb #endif // ROCKSDB_LITE
[ "cjihrig@gmail.com" ]
cjihrig@gmail.com
be7f59ecbad5f8b464fadf3c1c0a0e75517367f9
d90c0ebe7605ce082845b7bfc907378f0978f014
/LLS_ChangeServoBaud/LLS_ChangeServoBaud.ino
671be0503b0b464f849aaad2e4fde554c95662c9
[]
no_license
KurtE/LSS_Test_sketches
68f0959cb06f356a9db588bf908548f29dbc7079
d6057ba6d740bfd932082807a461dec487a36688
refs/heads/master
2023-08-11T13:06:10.885842
2021-09-29T17:08:04
2021-09-29T17:08:04
263,476,805
1
4
null
2021-06-14T19:16:34
2020-05-12T23:36:02
C
UTF-8
C++
false
false
1,357
ino
static const uint32_t from_speed = 115200; static const uint32_t to_speed = 500000 ; void setup() { while (!Serial && millis() < 5000) ; Serial.printf("Change all LSS Servos from %u to %u baud\n", from_speed, to_speed); } void loop() { Serial1.begin(from_speed); Serial.printf("Scan servos at %u\n", from_speed); bool Servos_found = ScanServos(); if (Servos_found) { Serial.println("Press any key to continue"); while (Serial.read() == -1) ; while (Serial.read() != -1) ; delay(250); Serial.println("Try set baud command"); Serial1.printf("#254CB%u\r", to_speed); delay(250); Serial.println("Reset"); Serial1.print("#254RESET\r"); delay(3000); Serial1.end(); Serial1.begin(to_speed); delay(250); Serial.printf("Scan servos at %u\n", to_speed); ScanServos(); } Serial1.end(); Serial.println("Press any key to try again"); while (Serial.read() == -1) ; while (Serial.read() != -1) ; } bool ScanServos() { bool found_servo = false; for (uint8_t servo_id = 0; servo_id < 254; servo_id++) { Serial1.printf("#%uQD\r", servo_id); Serial1.flush(); delay(25); if (Serial1.available()) { int ch; while ((ch = Serial1.read()) != -1) { Serial.write(ch); } found_servo = true; Serial.println(); } } return found_servo; }
[ "kurte@rockisland.com" ]
kurte@rockisland.com
fec2f22a94512067b7d1d9e5234a1d1eab6bf96a
778130aa46378f00937f727acc5134535153c641
/C++_Class/Final_Q2/WindowLibrary2.cpp
7d3936ee4c952910976c3aa36748e03d27bafbf9
[]
no_license
krausjordan/C-Class
57e5544e2002e25db4cfd370bae239f0505077b8
073eee3046300643e98b4735a7875dd74e6e59ad
refs/heads/master
2020-12-31T07:11:41.284721
2017-05-03T05:59:18
2017-05-03T05:59:18
80,597,616
0
0
null
null
null
null
UTF-8
C++
false
false
813
cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: WindowLibrary2.cpp * Author: krausjn1 * * Created on May 1, 2017, 11:06 PM */ #include "WindowLibrary2.h" WindowLibrary2::WindowLibrary2() { } WindowLibrary2::WindowLibrary2(const WindowLibrary2& orig) { } WindowLibrary2::~WindowLibrary2() { } //Prints library 2 close output void WindowLibrary2::winClose(){ cout<<"New Window Library 2 Close window"<<endl; } //Prints library 2 move output void WindowLibrary2::winMove(){ cout<<"New Window Library 2 Move window"<<endl; } //Prints library 2 open output void WindowLibrary2::winOpen(){ cout<<"New Window Library 2 Open window"<<endl; }
[ "jordan.kraus@jhuapl.edu" ]
jordan.kraus@jhuapl.edu
288343ea3cabca2db429203dc38d31e5e02a5327
0f2b08b31fab269c77d4b14240b8746a3ba17d5e
/onnxruntime/core/providers/dnnl/subgraph/dnnl_reduce.h
d3e5852b5b42b951c7dabe205290cdb95694b0a0
[ "MIT" ]
permissive
microsoft/onnxruntime
f75aa499496f4d0a07ab68ffa589d06f83b7db1d
5e747071be882efd6b54d7a7421042e68dcd6aff
refs/heads/main
2023-09-04T03:14:50.888927
2023-09-02T07:16:28
2023-09-02T07:16:28
156,939,672
9,912
2,451
MIT
2023-09-14T21:22:46
2018-11-10T02:22:53
C++
UTF-8
C++
false
false
610
h
// Copyright(C) 2021 Intel Corporation // Licensed under the MIT License #pragma once #include "dnnl_subgraph.h" #include "dnnl_subgraph_primitive.h" namespace onnxruntime { namespace ort_dnnl { class DnnlReduce { public: enum InputTensors : int { IN_DATA = 0, IN_AXES = 1 }; enum OutputTensors : int { OUT_REDUCED = 0 }; DnnlReduce(); void CreatePrimitive(DnnlSubgraphPrimitive& sp, DnnlNode& node); std::vector<int64_t> ReadAxes(DnnlNode& node); bool Keepdims(DnnlNode& node); bool NoOpWithEmptyAxes(DnnlNode& node); }; } // namespace ort_dnnl } // namespace onnxruntime
[ "noreply@github.com" ]
microsoft.noreply@github.com
12f767aedaeabb91911864a6c1ee87510ca2166d
2adbd4d0f315cac38ca076d84b2bb259d837be6a
/3dScanner/Vector3D.h
927127a257e097a8c07b8d1b93c99ef7fc00f4eb
[]
no_license
burakkoray/3dScanner
bcf916d26ef2ca56c41ae648d68b759ee6a2c228
a92144d51e14acf7b114da0b15394ac3f4b5ee47
refs/heads/master
2020-05-17T15:21:23.824396
2014-07-12T12:37:46
2014-07-12T12:37:46
21,766,760
2
2
null
null
null
null
UTF-8
C++
false
false
3,039
h
#ifndef VECTOR3D_H #define VECTOR3D_H #include <cmath> class Vector3D { public: float x; float y; float z; Vector3D() {} Vector3D(Vector3D *po){ x = po->x; y = po->y; z = po->z; } Vector3D(float r, float s, float t) { x = r; y = s; z = t; } Vector3D& Set(float r, float s, float t) { x = r; y = s; z = t; return (*this); } float& operator [](long k) { return ((&x)[k]); } const float& operator [](long k) const { return ((&x)[k]); } Vector3D& operator +=(const Vector3D& v) { x += v.x; y += v.y; z += v.z; return (*this); } Vector3D& operator -=(const Vector3D v) { this->x -= v.x; this->y -= v.y; this->z -= v.z; return (*this); } Vector3D& operator *=(float t) { x *= t; y *= t; z *= t; return (*this); } Vector3D& operator /=(float t) { float f = 1.0F / t; x *= f; y *= f; z *= f; return (*this); } Vector3D& operator %=(const Vector3D& v) { float r, s; r = y * v.z - z * v.y; s = z * v.x - x * v.z; z = x * v.y - y * v.x; x = r; y = s; return (*this); } Vector3D& operator &=(const Vector3D& v) { x *= v.x; y *= v.y; z *= v.z; return (*this); } Vector3D operator -(void) const { return (Vector3D(-x, -y, -z)); } Vector3D operator +(const Vector3D& v) const { return (Vector3D(x + v.x, y + v.y, z + v.z)); } Vector3D operator -(const Vector3D& v) const { return (Vector3D(x - v.x, y - v.y, z - v.z)); } Vector3D operator *(float t) const { return (Vector3D(x * t, y * t, z * t)); } Vector3D operator /(float t) const { float f = 1.0F / t; return (Vector3D(x * f, y * f, z * f)); } float operator *(const Vector3D& v) const { return (x * v.x + y * v.y + z * v.z); } Vector3D operator %(const Vector3D& v) const { return (Vector3D(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x)); } Vector3D operator &(const Vector3D& v) const { return (Vector3D(x * v.x, y * v.y, z * v.z)); } bool operator ==(const Vector3D& v) const { return ((x == v.x) && (y == v.y) && (z == v.z)); } bool operator !=(const Vector3D& v) const { return ((x != v.x) || (y != v.y) || (z != v.z)); } Vector3D& Normalize(void) { return (*this /= sqrtf(x * x + y * y + z * z)); } Vector3D& RotateAboutX(float angle); Vector3D& RotateAboutY(float angle); Vector3D& RotateAboutZ(float angle); Vector3D& RotateAboutAxis(float angle, const Vector3D& axis); }; inline Vector3D operator *(float t, const Vector3D& v) { return (Vector3D(t * v.x, t * v.y, t * v.z)); } inline float Dot(const Vector3D& v1, const Vector3D& v2) { return (v1 * v2); } inline Vector3D Cross(const Vector3D& v1, const Vector3D& v2) { return (v1 % v2); } inline float Magnitude(const Vector3D& v) { return (sqrtf(v.x * v.x + v.y * v.y + v.z * v.z)); } inline float InverseMag(const Vector3D& v) { return (1.0F / sqrtf(v.x * v.x + v.y * v.y + v.z * v.z)); } inline float SquaredMag(const Vector3D& v) { return (v.x * v.x + v.y * v.y + v.z * v.z); } #endif
[ "burakkorayk@gmail.com" ]
burakkorayk@gmail.com
73100796655d8c4f2d50856e969a8b9c71cd4e63
97cad10b5cbc0b8965bb7f44b03cdec17b6c3a22
/基础练习 查找整数.cpp
21713668065105b21748b8d88d108f2553097db3
[]
no_license
candy-Tong/C_plus_plus_practice
10f4382357b14d32b4a31f122028f3fd7e542d7a
7574973d757733a159afa06cd4c90780e323c8ab
refs/heads/master
2021-03-30T20:50:00.458263
2019-01-27T10:19:54
2019-01-27T10:19:54
124,971,848
0
0
null
null
null
null
UTF-8
C++
false
false
474
cpp
#define LOCAL #include<stdio.h> #include<iostream> using namespace std; int main(){ #ifdef LOCAL freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif int a[1000]; int n; int find_num; int count=0; int find=0; cin>>n; for(int i=0;i<n;i++){ cin>>a[i]; } cin>>find_num; for(int i=0;i<n;i++){ count++; if(a[i]==find_num){ find=1; cout<<count<<endl; break; } } if(find==0){ cout<<-1<<endl; } return 0; }
[ "5633778816@qq.com" ]
5633778816@qq.com
6d95df456950517c2441bb982912060e9839270f
b2e2b269e930a399d011398c3b9beef19da94d8b
/benchmarks/SpanningForest/LiuTarjan/SpanningForest.cc
8348b49ffdc0057b8338c5a05d53b0dafe67884c
[ "MIT" ]
permissive
jiangjiaqi6/gbbs
b81df575fdfc2e0b24b9ec7eaafbdd1c3f7390cc
ff372b104e4c66766230ecafd34c2840726aee92
refs/heads/master
2023-08-23T15:14:46.536379
2021-10-13T18:41:40
2021-10-13T18:41:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,288
cc
// This code is part of the project "Theoretically Efficient Parallel Graph // Algorithms Can Be Fast and Scalable", presented at Symposium on Parallelism // in Algorithms and Architectures, 2018. // Copyright (c) 2018 Laxman Dhulipala, Guy Blelloch, and Julian Shun // // 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 "SpanningForest.h" #include "gbbs/gbbs.h" #include "benchmarks/SpanningForest/BFSSF/SpanningForest.h" #include "benchmarks/SpanningForest/check.h" namespace gbbs { template <class Graph> double SF_runner(Graph& G, commandLine P) { std::cout << "### Application: SpanningForest (LiuTarjan-based)" << std::endl; std::cout << "### Graph: " << P.getArgument(0) << std::endl; std::cout << "### Threads: " << num_workers() << std::endl; std::cout << "### n: " << G.n << std::endl; std::cout << "### m: " << G.m << std::endl; std::cout << "### ------------------------------------" << std::endl; timer t; t.start(); auto n = G.n; auto parents = sequence<parent>::from_function(n, [&] (size_t i) { return i; }); auto edges = sequence<edge>(n, empty_edge); auto opt_connect = lt::template get_connect_function<parent_connect>(); auto opt_update = lt::template get_update_function<root_update>(); auto opt_shortcut = lt::template get_shortcut_function<full_shortcut>(); auto alg = lt::LiuTarjanAlgorithm< decltype(opt_connect), parent_connect, decltype(opt_update), root_update, decltype(opt_shortcut), full_shortcut, Graph>(G, n, opt_connect, opt_update, opt_shortcut); alg.initialize(parents, edges); alg.template compute_spanning_forest<no_sampling>(parents, edges); auto filtered_edges = parlay::filter(make_slice(edges), [&] (const edge& e) { return e != empty_edge; }); std::cout << "sf has: " << filtered_edges.size() << " many edges" << std::endl; double tt = t.stop(); std::cout << "### Running Time: " << tt << std::endl; if (P.getOptionValue("-check")) { auto bfs_edges = bfs_sf::SpanningForestDet(G); spanning_forest::check_spanning_forest(G.n, bfs_edges, filtered_edges); } return tt; } } // namespace gbbs generate_main(gbbs::SF_runner, false);
[ "laxmandhulipala@gmail.com" ]
laxmandhulipala@gmail.com
547dac437f4a01b60a99a5e533906ee1d95d6db7
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/chrome/browser/policy/policy_startup_browsertest.cc
4efa409fb843f3c0ced6d605dea488b62d5f3019
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
1,952
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Warning: this file will not be compiled for ChromeOS because the test // PolicyMakeDefaultBrowserTest is not valid for this platform. #include "base/command_line.h" #include "base/macros.h" #include "chrome/common/chrome_result_codes.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" #include "components/policy/policy_constants.h" #include "content/public/test/browser_test.h" class PolicyMakeDefaultBrowserTest : public InProcessBrowserTest { protected: PolicyMakeDefaultBrowserTest() : InProcessBrowserTest() { set_expected_exit_code(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY); } void SetUpInProcessBrowserTestFixture() override { base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kMakeDefaultBrowser); EXPECT_CALL(provider_, IsInitializationComplete(testing::_)) .WillRepeatedly(testing::Return(true)); policy::BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_); policy::PolicyMap values; values.Set(policy::key::kDefaultBrowserSettingEnabled, policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_MACHINE, policy::POLICY_SOURCE_CLOUD, std::make_unique<base::Value>(false), nullptr); provider_.UpdateChromePolicy(values); } private: policy::MockConfigurationPolicyProvider provider_; DISALLOW_COPY_AND_ASSIGN(PolicyMakeDefaultBrowserTest); }; IN_PROC_BROWSER_TEST_F(PolicyMakeDefaultBrowserTest, MakeDefaultDisabled) { }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
29814d6a70dcbb31267eded0c57dad6d8d97c9f8
d481adc11cc48d5297ff00c1c7a0e00f2071eda0
/026. Remove Duplicates from Sorted Array/test.cpp
611b3d1be35472809d30145e1c8c3c5b9232791a
[]
no_license
AnselCmy/LeetCode
e2113bcb10500e0ad80299c39ab41777fab144a8
db0677bc858a391e1c87fb8bef6c52ec066edb06
refs/heads/master
2020-03-15T07:02:59.948945
2018-05-03T16:25:37
2018-05-03T16:25:37
132,020,884
0
0
null
null
null
null
UTF-8
C++
false
false
493
cpp
// // Created by Chen on 2018/2/5. // #include "../Catch2/single_include/catch.hpp" #include "solution.h" TEST_CASE("Remove Duplicates from Sorted Array", "[removeDuplicates]") { Solution s; vector<int> v1{1, 1, 2, 3}; vector<int> v4{1, 2, 3}; REQUIRE((s.removeDuplicates(v1) == 3)); REQUIRE(v1 == v4); vector<int> v2{4, 5, 5, 5, 6, 6, 7}; REQUIRE((s.removeDuplicates(v2) == 4)); vector<int> v3{4, 5, 6, 6, 6}; REQUIRE((s.removeDuplicates(v3) == 3)); }
[ "anselcmy@foxmail.com" ]
anselcmy@foxmail.com
b66e1e6dd6d8a97ecef72e66b503e35f87e6a825
df8a3763947ff91e26c325b830ee12937c6a7519
/informdialog.h
20b434e68ebd0f3cf3336b9cc4eba0a1fde3bf14
[]
no_license
devkrin/ChatLite
e60af43d7b7e38de22e3069698585885c73ac020
1ac17e5aef78748c53eb47d12fd1ca9397832349
refs/heads/master
2022-11-13T10:23:12.695522
2020-07-13T11:44:36
2020-07-13T11:44:36
279,285,995
0
0
null
null
null
null
UTF-8
C++
false
false
385
h
#ifndef INFORMDIALOG_H #define INFORMDIALOG_H #include <QDialog> namespace Ui { class InformDialog; } class InformDialog : public QDialog { Q_OBJECT public: explicit InformDialog(QWidget *parent = nullptr); ~InformDialog(); void print(QString innfo); private slots: void on_closeBtn_clicked(); private: Ui::InformDialog *ui; }; #endif // INFORMDIALOG_H
[ "krin-lai@qq.com" ]
krin-lai@qq.com
b98161e1166f656830bd1f02e0b19ef15cd51313
45874c847c5a2fc4e89e05a7fc8ad9b63d8c4860
/sycl/source/detail/mem_alloc_helper.hpp
517058d9dece479bc5dd0fa00139774bccc90046
[ "LicenseRef-scancode-unknown-license-reference", "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
intel/llvm
2f023cefec793a248d8a237267410f5e288116c5
a3d10cf63ddbdcc23712c45afd1b6b0a2ff5b190
refs/heads/sycl
2023-08-24T18:53:49.800759
2023-08-24T17:38:35
2023-08-24T17:38:35
166,008,577
1,050
735
NOASSERTION
2023-09-14T20:35:07
2019-01-16T09:05:33
null
UTF-8
C++
false
false
1,481
hpp
//==-------- mem_alloc_helper.hpp - SYCL mem alloc helper ------------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #pragma once #include <sycl/detail/pi.h> namespace sycl { inline namespace _V1 { namespace detail { void memBufferCreateHelper(const PluginPtr &Plugin, pi_context Ctx, pi_mem_flags Flags, size_t Size, void *HostPtr, pi_mem *RetMem, const pi_mem_properties *Props = nullptr); void memReleaseHelper(const PluginPtr &Plugin, pi_mem Mem); void memBufferMapHelper(const PluginPtr &Plugin, pi_queue command_queue, pi_mem buffer, pi_bool blocking_map, pi_map_flags map_flags, size_t offset, size_t size, pi_uint32 num_events_in_wait_list, const pi_event *event_wait_list, pi_event *event, void **ret_map); void memUnmapHelper(const PluginPtr &Plugin, pi_queue command_queue, pi_mem memobj, void *mapped_ptr, pi_uint32 num_events_in_wait_list, const pi_event *event_wait_list, pi_event *event); } // namespace detail } // namespace _V1 } // namespace sycl
[ "noreply@github.com" ]
intel.noreply@github.com
2ab719c71c46d0366bf11abff7422a70938ae3d3
3735e368e3cfdb5c508499c05388569bd19841ec
/compareStrings.h
87036465bd3d96cb8e8126f5d116a96eae2c9438
[]
no_license
spectrogram/dns-server
e920d93eb74c08aceb5c7d25a0ba6ae590b355ae
975c5cda54bdb9bcb9ec38821f448cd666880a28
refs/heads/master
2021-06-18T14:22:21.369461
2017-05-30T14:58:04
2017-05-30T14:58:04
92,562,860
0
0
null
null
null
null
UTF-8
C++
false
false
324
h
#pragma once #include <iostream> #include <algorithm> #include <memory> #include "edge.h" class compareStrings { int index; public: compareStrings(int i) { index = i; } int operator()(std::unique_ptr<Edge> const &a, std::unique_ptr<Edge> const &b) { return compareFunc(a->getLabel(), b->getLabel(), index); } };
[ "arkfellerkonan@hotmail.com" ]
arkfellerkonan@hotmail.com
b83f7cf108f4d1173ed1c8aa908e4ede8d2142ae
146a00de80c999965a23037e579342deb0034b64
/GUI/Vector/Vector2.inl
49c3115151fc97f375b7581ad60ce4498ebedead
[]
no_license
tjel/infpro-5
2f0291e3311c5aa09c9cd9c9a1dc996461da83a5
74b4bc1cd1c5a459ffbf47f0c2c62e70a98bf668
refs/heads/master
2021-01-10T02:35:57.735539
2016-01-20T21:45:21
2016-01-20T21:45:21
43,469,259
0
0
null
null
null
null
UTF-8
C++
false
false
324
inl
template <typename T> inline Vector2<T>::Vector2():a(0),b(0) { } template <typename T> inline Vector2<T>::Vector2(T A,T B):a(A),b(B) { } template <typename T> template <typename U> inline Vector2<T>::Vector2(const Vector2<U>& vector) : a(static_cast<T>(vector.a)), b(static_cast<T>(vector.b)) { }
[ "borys59@onet.eu" ]
borys59@onet.eu
34abbca3baf2f06d003e60b40d2d8891e5a5f4ac
109c4979b32f89c30c803911dd353684e477a3a3
/toolz.h
94d8caa82946be351fe1a36c8ccc616b61436281
[]
no_license
dsth/capmon
220df5d53e093e1284b35f674790197150fbcee1
00f6f24abfc2eeb2f4fa28373923bcb7002b0075
refs/heads/master
2020-05-31T17:48:38.103426
2013-05-15T17:15:12
2013-05-15T17:15:12
2,133,067
0
0
null
null
null
null
UTF-8
C++
false
false
23,885
h
#ifndef CAPMON_TOOLZ_H #define CAPMON_TOOLZ_H #include <sstream> #include <cassert> #include <curl/curl.h> #include <mysql/mysql.h> #include <sqlite3.h> #include <string> #include <cstring> #include <algorithm> #include <vector> // #include <type_traits> #include <sys/stat.h> #include <stdexcept> // brought in by exceptions.h #include "exceptions.h" #include "config.h" typedef std::vector<std::string> ROW; typedef std::vector<std::vector<std::string>> TABLE; #ifndef NSUBMISSION #include "json/json.h" #endif #define STRING_LENGTH 250 #define SHORT_STRING 100 #define MAGIC_NUMBER 2500 #define SEP1 "','" // really must run this stuff through valgrind?!? // this is really, really nasty!? #ifndef NSUBMISSION struct SUBMISSION { // really ought to make it at least a little private int sbm_id; std::string submitter_name; std::string user; std::string user_email; std::string species; std::string file_name; std::string file_md5; std::string file_type; std::string file_desc; std::string timestamp; unsigned long file_size; int sbm_status; // ought to be an enum?! explicit SUBMISSION (const Json::Value& sbm) : sbm_id(atoi(sbm["sbm_id"].asCString())), // postgres frontend changes... //user(sbm["user"].asString()), //user_email(sbm["user_email"].asString()), user(sbm["name"].asString()), user_email(sbm["name_email"].asString()), species(sbm["species_version"].asString()), file_name(sbm["file_name"].asString()), file_md5(sbm["file_md5"].asString()), file_type(sbm["file_type"].asString()), timestamp(sbm["timestamp"].asString()), file_size(atoi(sbm["file_size"].asCString())) { std::string sbmname = sbm["submitter_name"].asString(); sbmname.erase(std::remove(sbmname.begin(),sbmname.end(),'\''),sbmname.end()); sbmname.erase(std::remove(sbmname.begin(),sbmname.end(),'"'),sbmname.end()); this->submitter_name=sbmname; std::string desc = sbm["file_desc"].asString(); desc.erase(std::remove(desc.begin(),desc.end(),'\''),desc.end()); desc.erase(std::remove(desc.begin(),desc.end(),'"'),desc.end()); file_desc = desc; } explicit SUBMISSION (ROW& r) : sbm_id(std::stoi(r.at(2))), file_name(r.at(0)), file_md5(r.at(1)), file_type(r.at(3)), file_size(std::stol(r.at(4))), sbm_status(std::stol(r.at(5))) { /* construct */ } SUBMISSION ( int _sbm_id, std::string _a, std::string _b, std::string _c, std::string _d, std::string _e ) : sbm_id(_sbm_id), submitter_name(_a), user_email(_b), species(_c), file_name(_d), file_type(_e) {}; std::string to_sqlstring() { // horrible!? std:: stringstream ss; ss << "insert into cap_files (" <<" sbm_id, sbm_status, submitter_name, " <<" user, user_email, species, " <<" file_name, file_type, file_md5, " <<" file_desc, file_size, rts " <<") values (" <<this->sbm_id<<"," <<FILE_NEW<<",'" <<submitter_name<<SEP1 <<user<<SEP1 <<user_email<<SEP1 <<species<<SEP1 <<file_name<<SEP1 <<file_type<<SEP1 <<file_md5<<SEP1 <<file_desc<<"'," <<file_size<<",'" <<timestamp<<"')"; std::string blah(ss.str()); return std::move(blah); } }; typedef std::vector<SUBMISSION> SUBMISSIONLIST; #endif inline size_t my_curl_write(void * ptr, size_t, size_t, std::stringstream & stream) { std::string blah((char*)ptr); stream << blah; return blah.size(); // must return length or truncates } inline void set_cap_status (sqlite3 * db, int status) { char buf[STRING_LENGTH]; sprintf(buf,SQL_CAP_STATUS,status); char * zErrMsg = NULL; if(sqlite3_exec(db, buf, NULL, NULL, &zErrMsg)!=SQLITE_OK) throw std::runtime_error(zErrMsg); sqlite3_free(zErrMsg); } struct SPECIES { std::string name; DB_PARAMS dbp; std::string prefix; unsigned int max_id; SPECIES(std::string _n, std::string _d, std::string _p = "", unsigned int _m = 0) : name(_n), dbp(_d), prefix(_p), max_id(_m) {} SPECIES()=delete; }; namespace toolz { inline bool file_exists(const char* dbname) { struct stat sts; bool x = (stat(dbname, &sts) == -1 && errno == ENOENT); return !x; } inline static int internal_meta_callback(void *blah, int, char **argv, char **){ std::map<std::string,std::string>* _meta = static_cast<std::map<std::string,std::string>*>(blah); _meta->insert(std::pair<std::string,std::string>(argv[0],argv[1])); // _meta[argv[0]]=argv[1]; return 0; } /* class ADAPTOR { virtual ~ADAPTOR = 0; }; */ class MYSQL_ADAPTOR { // private: static MYSQL_ADAPTOR* me_ptr; MYSQL* conn; DB_PARAMS& dp; MYSQL_ADAPTOR(DB_PARAMS& _dp) : dp(_dp) { conn = mysql_init(NULL); // very naughty...?!? const char * msg_str1 = "could not connect to species-specific e! cap database"; size_t len1 = strlen(msg_str1); size_t len2 = strlen(dp.dbname()); char * msg_full = (char*) malloc(len1 + len2 + 2); memcpy(msg_full, msg_str1, len1); msg_full[len1] = ' '; memcpy(msg_full+len1+1, dp.dbname(), len2+1); if(mysql_real_connect(conn,dp.host(),dp.user(),dp.pass(),dp.dbname(),dp.port(),NULL,0) == NULL) { std::string s(msg_full); free(msg_full); throw MySqlError(s); } free(msg_full); } ~MYSQL_ADAPTOR() { mysql_close(conn); } MYSQL_ADAPTOR(const MYSQL_ADAPTOR&) = delete; public: static MYSQL_ADAPTOR* get_instance() { if(!me_ptr) throw std::runtime_error("pointer to sqlite object is not initialised"); return me_ptr; } static void connect(DB_PARAMS& dp) { if(!me_ptr) me_ptr = new MYSQL_ADAPTOR(dp); } static void disconnect() { if(me_ptr) delete me_ptr; me_ptr = NULL; // return me_ptr; } int no_return_query(const char* q) { mysql_query(conn,q); return mysql_affected_rows(conn); } void func_helper2 (std::string q, int& x) { MYSQL_RES *result; MYSQL_ROW row; if (mysql_query(conn,q.c_str())) throw std::runtime_error("unable to query mysql instance"); if(!(result = mysql_store_result(conn))) throw std::runtime_error("result set pointer is null"); else { row = mysql_fetch_row(result); if (row == 0) throw std::runtime_error("no results for integer query " + q); x=atoi(row[0]); } mysql_free_result(result); } void func_helper2 (std::string q, std::string& x) { MYSQL_RES *result; MYSQL_ROW row; if (mysql_query(conn,q.c_str())) throw std::runtime_error("unable to query mysql instance"); if(!(result = mysql_store_result(conn))) throw std::runtime_error("result set pointer is null"); else { row = mysql_fetch_row(result); if (row == 0) throw std::runtime_error("no results for string query " + q); x=row[0]; } mysql_free_result(result); } void func_helper2 (std::string q, TABLE& x) { MYSQL_RES *result; MYSQL_ROW row; if (mysql_query(conn,q.c_str())) throw std::runtime_error("unable to query mysql instance"); if(!(result = mysql_store_result(conn))) throw std::runtime_error("result set pointer is null"); int num_fields = mysql_num_fields(result); while ((row = mysql_fetch_row(result))) { std::vector<std::string> s; for(int i = 0; i < num_fields; i++) s.push_back(row[i]); x.push_back(std::move(s)); } mysql_free_result(result); } template <typename T> T generic_query(std::string y) { T x; func_helper2(y, x); return std::move(x); } }; class SQLITE_ADAPTOR { // private: std::map<std::string,std::string> _meta; static SQLITE_ADAPTOR* me_ptr; sqlite3* database; char* db_name; sqlite3_stmt* statement; SQLITE_ADAPTOR(char* dbname) : db_name(dbname) { if(!file_exists(dbname)) throw std::runtime_error("the db doesn't exist " + std::string(db_name)); sqlite3_open(dbname, &database); } ~SQLITE_ADAPTOR() { sqlite3_close(database); /* std::cout << "\ndtor! - just closed connection\n"; */ } SQLITE_ADAPTOR(const SQLITE_ADAPTOR&) = delete; public: static SQLITE_ADAPTOR* get_instance() { if(!me_ptr) throw std::runtime_error("pointer to sqlite object is not initialised"); return me_ptr; } static void connect(char* dbname) { if(!me_ptr) me_ptr = new SQLITE_ADAPTOR(dbname); // return me_ptr; } static void disconnect() { if(me_ptr) delete me_ptr; me_ptr = NULL; // return me_ptr; } void pull_files(const char*, int&) { std::cout << "this is the single int form\n"; } void pull_files(const char*, std::string&) { std::cout << "this is the single string form\n"; } void func_helper2 (std::string q, double& x); void func_helper2 (std::string q, std::string& x) { if(sqlite3_prepare_v2(database, q.c_str(), -1, &statement, 0) == SQLITE_OK) { if(sqlite3_step(statement)== SQLITE_ROW) x=reinterpret_cast<const char*>(sqlite3_column_text(statement, 0)); else throw std::runtime_error("no rows!?!"); } else { sqlite3_finalize(statement); throw std::runtime_error("error in response"); } sqlite3_finalize(statement); } void func_helper2 (std::string q, int& x) { if(sqlite3_prepare_v2(database, q.c_str(), -1, &statement, 0) == SQLITE_OK) { if(sqlite3_step(statement)== SQLITE_ROW) { x=sqlite3_column_int(statement, 0); // x=atoi(reinterpret_cast<const char*>(sqlite3_column_text(statement, 0))); } else throw std::runtime_error("no rows!?!"); } else { sqlite3_finalize(statement); throw std::runtime_error("error in response"); } sqlite3_finalize(statement); } void func_helper2 (std::string q, ROW& x) { if(sqlite3_prepare_v2(database, q.c_str(), -1, &statement, 0) == SQLITE_OK) { int cols = sqlite3_column_count(statement); int result = sqlite3_step(statement); if(result == SQLITE_ROW) { std::vector<std::string> s; for(int col = 0; col < cols; col++) x.push_back(reinterpret_cast<const char*>(sqlite3_column_text(statement, col))); } else throw std::runtime_error("error in response"); } else { throw std::runtime_error("error in response"); } sqlite3_finalize(statement); } void func_helper2 (std::string q, TABLE& x) { if(sqlite3_prepare_v2(database, q.c_str(), -1, &statement, 0) == SQLITE_OK) { int cols = sqlite3_column_count(statement); int result = 0; int row =0; while(true) { result = sqlite3_step(statement); if(result == SQLITE_ROW) { row++; std::vector<std::string> s; for(int col = 0; col < cols; col++) // basic_string::_S_construct NULL not valid : trying to create a string with a NULL char * pointer. s.push_back(reinterpret_cast<const char*>(sqlite3_column_text(statement, col))); x.push_back(std::move(s)); } else break; } } sqlite3_finalize(statement); } template <typename T> T generic_query(std::string y) { T x; func_helper2(y, x); return std::move(x); } template <typename T> T func_helper (T t, std::true_type) { std::cout << t << " : true" << std::endl; } template <typename T> T func_helper (T t, std::false_type) { std::cout << t << " : false" << std::endl; } template <typename T> T main_func(std::string y) { T x; std::cout << "here we are = "<< y<<"\n"; x = func_helper(x, typename std::is_integral<T>::type()); return x; } void pull_files(const char*, std::vector<std::string>&) { if(sqlite3_prepare_v2(database, "select * from cap_files", -1, &statement, 0) == SQLITE_OK) { int cols = sqlite3_column_count(statement); int result = 0; int row =0; while(true) { result = sqlite3_step(statement); if(result == SQLITE_ROW) { row++; for(int col = 0; col < cols; col++) { std::cout << " [" << col<<"] " << sqlite3_column_text(statement, col); std::string s = (char*)sqlite3_column_text(statement, col); } std::cout << "\n"; } else break; break; } sqlite3_finalize(statement); } } unsigned int check_capdb_status () { if (!me_ptr) throw std::runtime_error("you have to connect first!"); int cap_status = me_ptr->generic_query<int>(SQL_CHECK_DB); if (cap_status==0) { std::cout << "Cap_status table appears to be empty\nexiting" << std::endl; exit(0); } else if (cap_status>0) { cap_status = me_ptr->generic_query<int>(SQL_QUERY_STATUS); } else throw Sqlite3Error("hmm"); switch (cap_status) { case CAP_STATUS_READY: std::cout << "Capdb has status 'ready'\n"; std::cout << "Setting status to 'looping'\n"; // get rid of this!? set_cap_status(database,CAP_STATUS_LOOPING); break; case CAP_STATUS_LOOPING: std::cout << "The database wasn't not shut down shut down properly - run the ready command" << std::endl; exit(0); break; case CAP_STATUS_LOCKED: std::cout << "Please reset database state with ready command" << std::endl; exit(0); break; default: std::cout << "Unknown status" << std::endl; exit(1); } } void update(const char* q) { char* zErrMsg = NULL; if(sqlite3_exec(database, q, NULL, NULL, &zErrMsg)!=SQLITE_OK) // throw std::runtime_error(zErrMsg); throw std::runtime_error(THROW_DEFAULT("unable to update sqlite3 db")); sqlite3_free(zErrMsg); } #ifndef NSUBMISSION void get_local_file_list (SUBMISSIONLIST& sb) { char* buf = (char*)malloc((strlen(SQL_GET_LOCALFILES)+1)); sprintf(buf,SQL_GET_LOCALFILES,FILE_LOCALSTORE); // not much point in snprintf?!? if(sqlite3_prepare_v2(database, buf, -1, &statement, 0) == SQLITE_OK) { int cols = sqlite3_column_count(statement); int result = 0; int row =0; while(true) { result = sqlite3_step(statement); if(result == SQLITE_ROW) { row++; int sbm_id = 0; std::string sbmname; std::string email; std::string species; std::string fname; std::string type; for(int col = 0; col < cols; col++) { // if (col ==0) sbm_id = atoi((char*)sqlite3_column_text(statement, col)); // else if (col == 1) sbmname = (char*)sqlite3_column_text(statement, col); switch (col) { case 0: sbm_id = atoi((char*)sqlite3_column_text(statement, col)); break; case 1: sbmname = (char*)sqlite3_column_text(statement, col); break; case 2: email = (char*)sqlite3_column_text(statement, col); break; case 3: species = (char*)sqlite3_column_text(statement, col); break; case 4: fname = (char*)sqlite3_column_text(statement, col); break; case 5: type = (char*)sqlite3_column_text(statement, col); break; } } SUBMISSION sbm(sbm_id, sbmname, email, species, fname, type); sb.push_back(sbm); } else break; } } free(buf); sqlite3_finalize(statement); } #endif void update_file_status(int sbm_id, int status) { char* buf = (char*) malloc(STRING_LENGTH*sizeof(char)); assert(buf!=0); snprintf(buf, STRING_LENGTH, SQL_SET_STATUS ,status,sbm_id); char * zErrMsg = NULL; if(sqlite3_exec(database, buf, NULL, NULL, &zErrMsg)!=SQLITE_OK) throw std::runtime_error(zErrMsg); free(buf); sqlite3_free(zErrMsg); } void update_cap_status(int status) { char buf[STRING_LENGTH]; sprintf(buf,SQL_CAP_STATUS,status); char * zErrMsg = NULL; if(sqlite3_exec(database, buf, NULL, NULL, &zErrMsg)!=SQLITE_OK) throw std::runtime_error(zErrMsg); sqlite3_free(zErrMsg); } void meta_insert(const char* k,const char* v) { char query[SHORT_STRING]; sprintf(query,"insert into cap_meta values ('%s','%s');",k,v); char* zErrMsg = NULL; if(sqlite3_exec(database, query, NULL, NULL, &zErrMsg)!=SQLITE_OK) throw Sqlite3Error(THROW_DEFAULT("unable to insert meta key/value pair into capdb")); sqlite3_free(zErrMsg); } void generic_insert(const std::string& q) { // it's really not appropriate to handle problems with normal flow - i.e. bool in this context - just throw?!? char* zErrMsg = NULL; if(sqlite3_exec(database, q.c_str(), NULL, NULL, &zErrMsg)!=SQLITE_OK) // throw std::runtime_error(zErrMsg); throw Sqlite3Error(THROW_DEFAULT("unable to insert into capdb")); sqlite3_free(zErrMsg); } void query_species(std::vector<SPECIES>& vs, std::string s="") { // just overload it - nah default args?! char buf[STRING_LENGTH]; s = s.empty() ? "" : " where species like '%%" + s + "%%';"; s = "select species,dsn,prefix,max_id from cap_species" + s; if(sqlite3_prepare_v2(database, s.c_str(), -1, &statement, 0) == SQLITE_OK) { while(sqlite3_step(statement)== SQLITE_ROW) { std::string species = (char*)sqlite3_column_text(statement,0); std::string dsn = (char*)sqlite3_column_text(statement,1); //try { if(sqlite3_column_type(statement,2)!=SQLITE_NULL) { std::string prefix = (char*)sqlite3_column_text(statement, 2); unsigned int max_id = (int)sqlite3_column_int(statement, 3); vs.push_back(SPECIES(species,dsn,prefix,max_id)); } else { vs.push_back(SPECIES(species,dsn)); } // } catch (...) { // } } } else throw std::runtime_error(buf); sqlite3_finalize(statement); } std::string meta_value(const char* key) { if(_meta.find(key)!=_meta.end()) // safe to use [] without generating entry return _meta[key]; char q[SHORT_STRING]; sprintf(q,"select value from cap_meta where key = '%s'",key); std::string local; if(sqlite3_prepare_v2(database, q, -1, &statement, 0) == SQLITE_OK) { if(sqlite3_step(statement)== SQLITE_ROW) { local=reinterpret_cast<const char*>(sqlite3_column_text(statement, 0)); } else { // sqlite3_finalize(statement); // ?!? throw std::runtime_error("Cannot find entry for " + std::string(key)); // just use sprintf?!? } } else { sqlite3_finalize(statement); throw std::runtime_error("error in response"); } // if(local=="local.perl5lib") std::for_each(perl5lib.begin(),perl5lib.end(),[](char& n){if(n==',')n=':';}); sqlite3_finalize(statement); return std::move(local); } void meta_populate() { char *zErrMsg = 0; int rc = sqlite3_exec(database, "select * from cap_meta", internal_meta_callback, &_meta, &zErrMsg); // int rc = sqlite3_exec(database, "select * from cap_meta", internal_meta_callback, 0, &zErrMsg); if(rc!=SQLITE_OK) fprintf(stderr, "SQL error: %s\n", zErrMsg); } bool species_info(std::string species, std::string& dsn, std::string& prefix, int& max_id) { char* buf = (char*)malloc(STRING_LENGTH); snprintf(buf, STRING_LENGTH, "select dsn, prefix, max_id from cap_species where species = '%s'", species.c_str()); if(sqlite3_prepare_v2(database, buf, -1, &statement, 0) == SQLITE_OK) { if(sqlite3_step(statement)== SQLITE_ROW) { dsn = (char*)sqlite3_column_text(statement, 0); if(sqlite3_column_type(statement,1)==SQLITE_NULL) prefix.clear(); else { prefix = (char*)sqlite3_column_text(statement, 1); max_id = (int)sqlite3_column_int(statement, 2); } // max_id = atoi((char*)sqlite3_column_text(statement, 2)); } else return false; //throw std::runtime_error("no rows!?!"); } else throw std::runtime_error(buf); free(buf); sqlite3_finalize(statement); return true; } }; class CURL_ADAPTOR { CURL* curl; bool xcurl; std::string cookie_file; static CURL_ADAPTOR* me_ptr; CURL_ADAPTOR(bool xc,std::string ck) : xcurl(xc), cookie_file(ck) { if(!xcurl) { curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); } } ~CURL_ADAPTOR() { curl_easy_cleanup(curl); if(me_ptr) delete me_ptr; me_ptr = NULL; } CURL_ADAPTOR(const CURL_ADAPTOR&) = delete; public: void set_xcurl (bool b) { xcurl = b; } int get_xcurl () const { return xcurl; } static CURL_ADAPTOR* get_instance(bool xterm = false, std::string ck = COOKIE) { if(!me_ptr) me_ptr = new CURL_ADAPTOR(xterm, ck); return me_ptr; } void pull(std::string uri, std::stringstream& strstrm) { if (!xcurl) { // ND being a pain and have to supress SSL problems...?! curl_easy_setopt(this->curl, CURLOPT_URL, uri.c_str()); curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookie_file.c_str()); // COOKIE); curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookie_file.c_str()); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_curl_write); // curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &strstrm); curl_easy_perform(curl); } else { char tmp[MAGIC_NUMBER]; std::string cmd("curl -k -s -c " + cookie_file + " -b " + cookie_file + " "); cmd += uri; //std::cout << "using "<<cmd<<"\n"; FILE * f2 = popen(cmd.c_str(), "r"); while(( fgets( tmp, MAGIC_NUMBER, f2 )) != NULL ) strstrm << tmp; pclose(f2); } } }; // odd multiple inclusion issue and not time to locate problem - make inline?! inline int query_integer (char * query) { int db_return(0); sqlite3 * database; db_return = sqlite3_open("new_sqlite.db", &database); sqlite3_stmt * statement; if(sqlite3_prepare_v2(database, query, -1, &statement, 0) == SQLITE_OK) { if(sqlite3_step(statement)== SQLITE_ROW) { db_return = atoi((char*)sqlite3_column_text(statement, 0)); } else throw std::runtime_error("no rows!?!"); } else throw std::runtime_error("error in response"); sqlite3_finalize(statement); return db_return; } } #endif
[ "dsth@ebi.ac.uk" ]
dsth@ebi.ac.uk
c37502b9af66476dd0e94fbb9e9758f7e50f6ffd
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_new_hunk_3757.cpp
5569578fc86ad2e519b9fbc5df3e98cf23ecf7d9
[]
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
2,649
cpp
} expiry += apr_time_now(); i2d_OCSP_RESPONSE(rsp, &p); if (mc->stapling_cache->flags & AP_SOCACHE_FLAG_NOTMPSAFE) stapling_cache_mutex_on(s); rv = mc->stapling_cache->store(mc->stapling_cache_context, s, cinf->idx, sizeof(cinf->idx), expiry, resp_der, stored_len, pool); if (mc->stapling_cache->flags & AP_SOCACHE_FLAG_NOTMPSAFE) stapling_cache_mutex_off(s); if (rv != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01929) "stapling_cache_response: OCSP response session store error!"); return FALSE; } return TRUE; } static void stapling_get_cached_response(server_rec *s, OCSP_RESPONSE **prsp, BOOL *pok, certinfo *cinf, apr_pool_t *pool) { SSLModConfigRec *mc = myModConfig(s); apr_status_t rv; OCSP_RESPONSE *rsp; unsigned char resp_der[MAX_STAPLING_DER]; const unsigned char *p; unsigned int resp_derlen = MAX_STAPLING_DER; if (mc->stapling_cache->flags & AP_SOCACHE_FLAG_NOTMPSAFE) stapling_cache_mutex_on(s); rv = mc->stapling_cache->retrieve(mc->stapling_cache_context, s, cinf->idx, sizeof(cinf->idx), resp_der, &resp_derlen, pool); if (mc->stapling_cache->flags & AP_SOCACHE_FLAG_NOTMPSAFE) stapling_cache_mutex_off(s); if (rv != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01930) "stapling_get_cached_response: cache miss"); return; } if (resp_derlen <= 1) { /* should-not-occur; must have at least valid-when-stored flag + * OCSPResponseStatus */ ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01931) "stapling_get_cached_response: response length invalid??"); return; } p = resp_der; if (*p) /* valid when stored */ *pok = TRUE; else *pok = FALSE; p++; resp_derlen--; rsp = d2i_OCSP_RESPONSE(NULL, &p, resp_derlen); if (!rsp) { ap_log_error(APLOG_MARK, APLOG_ERR, 0, s, APLOGNO(01932) "stapling_get_cached_response: response parse error??"); return; } ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(01933) "stapling_get_cached_response: cache hit"); *prsp = rsp; } static int stapling_set_response(SSL *ssl, OCSP_RESPONSE *rsp) { int rspderlen; unsigned char *rspder = NULL;
[ "993273596@qq.com" ]
993273596@qq.com
b9fa14e0460010800d24972246446452ebb5352d
edabddd23276d9a40c7f8bf6d6986fb451adbc34
/Category/Math/F.cpp
ef2d29c6445abcfd6edba5a9aa01510d13d09051
[]
no_license
Akatsukis/ACM_Training
b70f49435b8c7bada6b52366e4a6a8010ff80ef9
0503f50bc033ba01c7993de346ac241b0d9d5625
refs/heads/master
2021-06-06T09:00:15.665775
2019-12-24T20:13:14
2019-12-24T20:13:14
103,283,338
2
0
null
null
null
null
UTF-8
C++
false
false
2,017
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define pii pair<int, int> #define pb push_back #define mk make_pair #define fi first #define se second #define ALL(A) A.begin(), A.end() #define sqr(x) ((x)*(x)) #define sc(x) scanf("%d", &x) #define pr(x) printf(">>>"#x":%d\n", x) #define fastio ios::sync_with_stdio(0),cin.tie(0) #define frein freopen("in.txt", "r", stdin) #define freout freopen("out.txt", "w", stdout) #define debug cout<<">>>STOP"<<endl const int INF = 0x3f3f3f3f; const ll INF64 = 0x3f3f3f3f3f3f3f3f; const double eps = 1e-7; template<class T> T gcd(T a, T b){if(!b)return a;return gcd(b,a%b);} const int maxn = 10; ll mod; struct Mat { ll a[maxn][maxn]; void init() { memset(a, 0, sizeof(a)); } void set(int n) { init(); for(int i = 0; i < n; i++)a[i][i] = 1; } }; int sz = 3; Mat mul(Mat m1, Mat m2) { Mat ret; ret.init(); for(int i = 0; i < sz; i++){ for(int k = 0; k < sz; k++){ for(int j = 0; j < sz; j++){ ret.a[i][j] = (ret.a[i][j]+m1.a[i][k]*m2.a[k][j])%(mod-1); } } } return ret; } Mat mpow(Mat m, ll n) { Mat ret; ret.set(sz); while(n){ if(n&1LL)ret = mul(ret, m); m = mul(m, m); n >>= 1; } return ret; } int qpow(ll a, ll n) { ll ret = 1; while(n){ if(n&1LL)ret = ret*a%mod; a = a*a%mod; n >>= 1; } return ret; } int main() { int T; sc(T); while(T--){ ll n, a, b, c; scanf("%lld%lld%lld%lld%lld", &n, &a, &b, &c, &mod); Mat m; m.init(); m.a[0][0] = c, m.a[0][1] = m.a[0][2] = m.a[1][0] = m.a[2][2] = 1; ll mi = 0; if(n == 1)mi = 0; else{ m = mpow(m, n-2); mi = b*(m.a[0][0]+m.a[0][2])%(mod-1); } int ans = qpow(a, mi); if(a%mod == 0)ans = 0; printf("%d\n", ans); } return 0; }
[ "dreandawn@gmail.com" ]
dreandawn@gmail.com
7c6bd24d092cf432d6fc31da5c7bd679a946e37d
3fd42c9e70e4b3a569902613df5295d969b596df
/WordClock-NeoMatrix8x8/WordClock_NeoMatrix8x8/displayTime.ino
7616d225937a8bcc0a3393fda4e5b99b8c805950
[ "Apache-2.0" ]
permissive
tdamdouni/AdaBox-Projects
8dbbab1e47ebc1a7fb447ec9c2e7f99f55ffa6e7
ea5a83592baf7484f17ccffd849fd63184e167f8
refs/heads/master
2018-09-06T19:55:48.667134
2018-08-26T14:24:57
2018-08-26T14:24:57
103,637,655
6
0
null
null
null
null
UTF-8
C++
false
false
4,428
ino
// function to generate the right "phrase" based on the time void displayTime(void) { // get time from the RTC //DateTime theTime = RTC.now(); theTime = calculateTime(); // takes into account DST // serial print current time /* Serial.print(theTime.year(), DEC); Serial.print('/'); Serial.print(theTime.month(), DEC); Serial.print('/'); Serial.print(theTime.day(), DEC); Serial.print(' '); Serial.print(theTime.hour(), DEC); Serial.print(':'); Serial.print(theTime.minute(), DEC); Serial.print(':'); Serial.print(theTime.second(), DEC); Serial.println(); */ // time we display the appropriate theTime.minute() counter if ((theTime.minute() > 4) && (theTime.minute() < 10)) { MFIVE; //Serial.print("five"); } if ((theTime.minute() > 9) && (theTime.minute() < 15)) { MTEN; //Serial.print("ten"); } if ((theTime.minute() > 14) && (theTime.minute() < 20)) { AQUARTER; //Serial.print("a quarter"); } if ((theTime.minute() > 19) && (theTime.minute() < 25)) { TWENTY; //Serial.print("twenty"); } if ((theTime.minute() > 24) && (theTime.minute() < 30)) { TWENTY; MFIVE; //Serial.print("twenty five"); } if ((theTime.minute() > 29) && (theTime.minute() < 35)) { HALF; //Serial.print("half"); } if ((theTime.minute() > 34) && (theTime.minute() < 40)) { TWENTY; MFIVE; //Serial.print("twenty five"); } if ((theTime.minute() > 39) && (theTime.minute() < 45)) { TWENTY; //Serial.print("twenty"); } if ((theTime.minute() > 44) && (theTime.minute() < 50)) { AQUARTER; //Serial.print("a quarter"); } if ((theTime.minute() > 49) && (theTime.minute() < 55)) { MTEN; //Serial.print("ten"); } if (theTime.minute() > 54) { MFIVE; //Serial.print("five"); } if ((theTime.minute() < 5)) { switch (theTime.hour()) { case 1: case 13: ONE; break; case 2: case 14: TWO; break; case 3: case 15: THREE; break; case 4: case 16: FOUR; break; case 5: case 17: FIVE; break; case 6: case 18: SIX; break; case 7: case 19: SEVEN; break; case 8: case 20: EIGHT; break; case 9: case 21: NINE; break; case 10: case 22: TEN; break; case 11: case 23: ELEVEN; break; case 0: case 12: TWELVE; break; } } else if ((theTime.minute() < 35) && (theTime.minute() > 4)) { PAST; //Serial.print(" past "); switch (theTime.hour()) { case 1: case 13: ONE; break; case 2: case 14: TWO; break; case 3: case 15: THREE; break; case 4: case 16: FOUR; break; case 5: case 17: FIVE; break; case 6: case 18: SIX; break; case 7: case 19: SEVEN; break; case 8: case 20: EIGHT; break; case 9: case 21: NINE; break; case 10: case 22: TEN; break; case 11: case 23: ELEVEN; break; case 0: case 12: TWELVE; break; } } else { // if we are greater than 34 minutes past the hour then display // the next hour, as we will be displaying a 'to' sign TO; //Serial.print(" to "); switch (theTime.hour()) { case 1: case 13: TWO; break; case 14: case 2: THREE; break; case 15: case 3: FOUR; break; case 4: case 16: FIVE; break; case 5: case 17: SIX; break; case 6: case 18: SEVEN; break; case 7: case 19: EIGHT; break; case 8: case 20: NINE; break; case 9: case 21: TEN; break; case 10: case 22: ELEVEN; break; case 11: case 23: TWELVE; break; case 0: case 12: ONE; break; } } applyMask(); // apply phrase mask to colorshift function }
[ "tdamdouni@users.noreply.github.com" ]
tdamdouni@users.noreply.github.com
f1b451fafc89d47b36f7b43f833f966a2a811298
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_Buff_ChargeEmitter_Foliage_FlashBang_parameters.hpp
b68d13ef5ceedf9eaf6856673cbbd25e3d622649
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
1,851
hpp
#pragma once // ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Buff_ChargeEmitter_Foliage_FlashBang_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function Buff_ChargeEmitter_Foliage_FlashBang.Buff_ChargeEmitter_Foliage_FlashBang_C.GetActorsToIgnoreOnRaycast struct ABuff_ChargeEmitter_Foliage_FlashBang_C_GetActorsToIgnoreOnRaycast_Params { class AActor** emitterActor; // (Parm, ZeroConstructor, IsPlainOldData) TArray<class AActor*> ActorsToIgnore; // (Parm, OutParm, ZeroConstructor) }; // Function Buff_ChargeEmitter_Foliage_FlashBang.Buff_ChargeEmitter_Foliage_FlashBang_C.CanEmitCharge struct ABuff_ChargeEmitter_Foliage_FlashBang_C_CanEmitCharge_Params { bool canEmit; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function Buff_ChargeEmitter_Foliage_FlashBang.Buff_ChargeEmitter_Foliage_FlashBang_C.UserConstructionScript struct ABuff_ChargeEmitter_Foliage_FlashBang_C_UserConstructionScript_Params { }; // Function Buff_ChargeEmitter_Foliage_FlashBang.Buff_ChargeEmitter_Foliage_FlashBang_C.ExecuteUbergraph_Buff_ChargeEmitter_Foliage_FlashBang struct ABuff_ChargeEmitter_Foliage_FlashBang_C_ExecuteUbergraph_Buff_ChargeEmitter_Foliage_FlashBang_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
3e4d717c49b30062d6ad82f5da95adf8e7cf98df
fd5d274d6a94db9e9a2d10a544bdc625d2f443eb
/Rush00/Enemy.cpp
2da05b0a07be17239f0785052445fb6f4bc4dff2
[]
no_license
opogiba/PiscineCplusplus
26943f87bc8ab5091f1eeaa3999eb9ce9c478046
b644ecb09f4e856ae67f5dff3da88f54e9a4d036
refs/heads/master
2021-08-12T02:59:33.802880
2017-11-14T10:43:22
2017-11-14T10:43:22
110,676,361
0
0
null
null
null
null
UTF-8
C++
false
false
469
cpp
#include "Enemy.hpp" Enemy::Enemy() : Entry() { _charters.shape = ENEMY; _charters.color = 4; _speed = 1; } Enemy::Enemy(int x, int y) : Entry(x,y) { _charters.shape = ENEMY; _coord.X = x; _coord.Y = y; _charters.color = 4; _level = 1; _CHP = 1; _speed = 1; _Max_HP = 1; _damage = _Max_HP; _radius = 2; } Enemy::Enemy (const Enemy &val) : Entry(val) { *this = val; } Enemy::~Enemy(){ } void Enemy::move (int amount) { amount++; this->_coord.X--; }
[ "opogiba@e2r3p10.unit.ua" ]
opogiba@e2r3p10.unit.ua
25767696873c9b562c49f328a285978a9958a0a0
c43b0d1e041d004d1fa8e1469f57b62d4d4bea88
/zircon/kernel/platform/halt_helper.cc
0e52410ff72a0e50de800b7900efe81f8f53edfa
[ "BSD-3-Clause", "MIT" ]
permissive
ZVNexus/fuchsia
75122894e09c79f26af828d6132202796febf3f3
c5610ad15208208c98693618a79c705af935270c
refs/heads/master
2023-01-12T10:48:06.597690
2019-07-04T05:09:11
2019-07-04T05:09:11
195,169,207
0
0
BSD-3-Clause
2023-01-05T20:35:36
2019-07-04T04:34:33
C++
UTF-8
C++
false
false
615
cc
// Copyright 2019 The Fuchsia Authors // // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT #include <lib/debuglog.h> #include <platform/halt_helper.h> void platform_graceful_halt_helper(platform_halt_action action) { thread_migrate_to_cpu(BOOT_CPU_ID); platform_halt_secondary_cpus(); // Delay shutdown of debuglog to ensure log messages emitted by above calls will be written. dlog_shutdown(); platform_halt(action, HALT_REASON_SW_RESET); panic("ERROR: failed to halt the platform\n"); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
f9a848a8e22deb03bfa7f0bfabed9e1fe1191f07
bc4af97c7903e2817f3f24a1922f7bb705e7b4b4
/bak/josephus.cpp
4ff9b564839415275e6f134271f3cba28810f762
[]
no_license
GingerNg/Cpp_Stack
82e13646cd5bae0e0ac1546bc74cd752f4d76099
43209e3ad8c6cded2cb70bc9f758927744379622
refs/heads/master
2023-08-09T15:00:50.421672
2023-07-31T02:13:20
2023-07-31T02:13:20
275,848,171
0
0
null
null
null
null
UTF-8
C++
false
false
448
cpp
#include <stdio.h> /* 序列:0,1,2,3,4...n-1 n 表示当前序列长度 f[n] 胜利者的编号 f[1] = 0 (f[n-1]+m)%n */ void whoWin() // 求出最后的胜利者的序号 { int n, m, i, s = 0; printf ("N M = "); scanf("%d%d", &n, &m); for (i = 2; i <= n; i++) { s = (s + m) % i; printf("%d\n",s); } printf ("\nThe winner is %d\n", s+1); } void newSeq() { } int main() { whoWin(); }
[ "jinjie603809@163.com" ]
jinjie603809@163.com
12575323da6a283ac06046670f98e522ecda6b5c
61829ade844fc9e5b1c3fb346f9626cfb3ba8987
/src/des_base64.hpp
7d5b0e5565d8a6e697326b891251bb1669211cd2
[]
no_license
iCodeIN/DesGpu
50261db0def0a400097b68c67254a5150c06bf34
ad8c6d161ac0232f06a7ee1c98b56ea2d7f06a49
refs/heads/main
2023-06-10T05:41:09.779096
2021-06-30T11:35:41
2021-06-30T11:35:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
231
hpp
#pragma once #include <cstdint> #include <string> std::string salt_to_string(uint32_t salt); uint32_t salt_to_int(const std::string& str); std::string hash_to_string(uint64_t hash); uint64_t hash_to_int(const std::string& str);
[ "tanguy@fautre.com" ]
tanguy@fautre.com
41e4573908fc966742347cc981c7f5f6913ea308
fd2754ec7ab1fbb7da19a605c650c51081d09feb
/devel/.private/mavros_msgs/include/mavros_msgs/ActuatorControl.h
6916444f362c018de6ee9d74e9ef086ae062da1c
[]
no_license
thehummingbird/MavrosToPx4
133a82093c2678bd233577b192f5c91941d55237
7378f0d1abd02e538a75ace62ebb515f924c9afb
refs/heads/master
2020-09-15T13:35:10.893704
2019-11-23T14:07:12
2019-11-23T14:07:12
223,458,088
1
0
null
null
null
null
UTF-8
C++
false
false
7,389
h
// Generated by gencpp from file mavros_msgs/ActuatorControl.msg // DO NOT EDIT! #ifndef MAVROS_MSGS_MESSAGE_ACTUATORCONTROL_H #define MAVROS_MSGS_MESSAGE_ACTUATORCONTROL_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <std_msgs/Header.h> namespace mavros_msgs { template <class ContainerAllocator> struct ActuatorControl_ { typedef ActuatorControl_<ContainerAllocator> Type; ActuatorControl_() : header() , group_mix(0) , controls() { controls.assign(0.0); } ActuatorControl_(const ContainerAllocator& _alloc) : header(_alloc) , group_mix(0) , controls() { (void)_alloc; controls.assign(0.0); } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef uint8_t _group_mix_type; _group_mix_type group_mix; typedef boost::array<float, 8> _controls_type; _controls_type controls; enum { PX4_MIX_FLIGHT_CONTROL = 0u, PX4_MIX_FLIGHT_CONTROL_VTOL_ALT = 1u, PX4_MIX_PAYLOAD = 2u, PX4_MIX_MANUAL_PASSTHROUGH = 3u, }; typedef boost::shared_ptr< ::mavros_msgs::ActuatorControl_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::mavros_msgs::ActuatorControl_<ContainerAllocator> const> ConstPtr; }; // struct ActuatorControl_ typedef ::mavros_msgs::ActuatorControl_<std::allocator<void> > ActuatorControl; typedef boost::shared_ptr< ::mavros_msgs::ActuatorControl > ActuatorControlPtr; typedef boost::shared_ptr< ::mavros_msgs::ActuatorControl const> ActuatorControlConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::mavros_msgs::ActuatorControl_<ContainerAllocator> & v) { ros::message_operations::Printer< ::mavros_msgs::ActuatorControl_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace mavros_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'geographic_msgs': ['/opt/ros/melodic/share/geographic_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/melodic/share/std_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/melodic/share/sensor_msgs/cmake/../msg'], 'mavros_msgs': ['/home/sharad/catkin_ws/src/mavros/mavros_msgs/msg'], 'geometry_msgs': ['/opt/ros/melodic/share/geometry_msgs/cmake/../msg'], 'uuid_msgs': ['/opt/ros/melodic/share/uuid_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::mavros_msgs::ActuatorControl_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::mavros_msgs::ActuatorControl_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::mavros_msgs::ActuatorControl_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::mavros_msgs::ActuatorControl_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::mavros_msgs::ActuatorControl_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::mavros_msgs::ActuatorControl_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::mavros_msgs::ActuatorControl_<ContainerAllocator> > { static const char* value() { return "9eea0a80c88944fe2fb67f3b3768854b"; } static const char* value(const ::mavros_msgs::ActuatorControl_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x9eea0a80c88944feULL; static const uint64_t static_value2 = 0x2fb67f3b3768854bULL; }; template<class ContainerAllocator> struct DataType< ::mavros_msgs::ActuatorControl_<ContainerAllocator> > { static const char* value() { return "mavros_msgs/ActuatorControl"; } static const char* value(const ::mavros_msgs::ActuatorControl_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::mavros_msgs::ActuatorControl_<ContainerAllocator> > { static const char* value() { return "# raw servo values for direct actuator controls\n" "#\n" "# about groups, mixing and channels:\n" "# https://pixhawk.org/dev/mixing\n" "\n" "# constant for mixer group\n" "uint8 PX4_MIX_FLIGHT_CONTROL = 0\n" "uint8 PX4_MIX_FLIGHT_CONTROL_VTOL_ALT = 1\n" "uint8 PX4_MIX_PAYLOAD = 2\n" "uint8 PX4_MIX_MANUAL_PASSTHROUGH = 3\n" "#uint8 PX4_MIX_FC_MC_VIRT = 4\n" "#uint8 PX4_MIX_FC_FW_VIRT = 5\n" "\n" "std_msgs/Header header\n" "uint8 group_mix\n" "float32[8] controls\n" "\n" "================================================================================\n" "MSG: std_msgs/Header\n" "# Standard metadata for higher-level stamped data types.\n" "# This is generally used to communicate timestamped data \n" "# in a particular coordinate frame.\n" "# \n" "# sequence ID: consecutively increasing ID \n" "uint32 seq\n" "#Two-integer timestamp that is expressed as:\n" "# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n" "# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n" "# time-handling sugar is provided by the client library\n" "time stamp\n" "#Frame this data is associated with\n" "string frame_id\n" ; } static const char* value(const ::mavros_msgs::ActuatorControl_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::mavros_msgs::ActuatorControl_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.group_mix); stream.next(m.controls); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct ActuatorControl_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::mavros_msgs::ActuatorControl_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::mavros_msgs::ActuatorControl_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "group_mix: "; Printer<uint8_t>::stream(s, indent + " ", v.group_mix); s << indent << "controls[]" << std::endl; for (size_t i = 0; i < v.controls.size(); ++i) { s << indent << " controls[" << i << "]: "; Printer<float>::stream(s, indent + " ", v.controls[i]); } } }; } // namespace message_operations } // namespace ros #endif // MAVROS_MSGS_MESSAGE_ACTUATORCONTROL_H
[ "sharadmaheshwari19@gmail.com" ]
sharadmaheshwari19@gmail.com
46200825d4a95d5608aec962371dcf80849f9576
d031c3667516189cc85fefaa697801938037067e
/levelChase.h
502e787e0e6f173a160ffe1f3e98307d8e64013a
[]
no_license
VladimirKuznetsov/MOTRS
19eda4e0c2711a858b828f8776ac2ae116f7a1f8
3a736d082e2378e4419a136d5d22e37f6d462cf1
refs/heads/master
2016-09-06T13:14:08.254695
2015-03-06T14:41:57
2015-03-06T14:41:57
30,161,700
0
0
null
null
null
null
UTF-8
C++
false
false
424
h
#ifndef LEVELCHASE_H #define LEVELCHASE_H #include <QObject> #include "level.h" class LevelChase : public Level { Q_OBJECT public: LevelChase(QGraphicsView * parent); void followEnemy(); void mousePressEvent(QMouseEvent * event); void mouseDoubleClickEvent(QMouseEvent * event); void mouseReleaseEvent(QMouseEvent * event); signals: public slots: void checkRules(); }; #endif // LEVELCHASE_H
[ "kzntsv.vldmr@gmail.com" ]
kzntsv.vldmr@gmail.com
420c7c072ee3df3aff51e1df7857bc1bc104ee2e
169e75df163bb311198562d286d37aad14677101
/tensorflow/core/kernels/parameterized_truncated_normal_op.cc
0ab9ff9f650e137017b49d5d279f1a28ff45fa29
[ "Apache-2.0" ]
permissive
zylo117/tensorflow-gpu-macosx
e553d17b769c67dfda0440df8ac1314405e4a10a
181bc2b37aa8a3eeb11a942d8f330b04abc804b3
refs/heads/master
2022-10-19T21:35:18.148271
2020-10-15T02:33:20
2020-10-15T02:33:20
134,240,831
116
26
Apache-2.0
2022-10-04T23:36:22
2018-05-21T08:29:12
C++
UTF-8
C++
false
false
16,672
cc
/* Copyright 2016 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. ==============================================================================*/ // See docs in ../ops/random_ops.cc. // NOTE: If the algorithm is changed, please run the test // .../python/kernel_tests:parameterized_truncated_normal_op_test // commenting out the "tf.set_random_seed(seed)" lines, and using the // "--runs-per-test=1000" flag. This tests the statistical correctness of the // op results. #define EIGEN_USE_THREADS #include "tensorflow/core/kernels/parameterized_truncated_normal_op.h" #include <algorithm> #include <cmath> #include <memory> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/lib/random/random_distributions.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/util/guarded_philox_random.h" #include "tensorflow/core/util/work_sharder.h" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; namespace functor { using random::PhiloxRandom; template <typename T> struct TruncatedNormalFunctor<CPUDevice, T> { static const int kMaxIterations = 100; void operator()(OpKernelContext* ctx, const CPUDevice& d, int64 num_batches, int64 samples_per_batch, int64 num_elements, typename TTypes<T>::ConstFlat means, typename TTypes<T>::ConstFlat stddevs, typename TTypes<T>::ConstFlat minvals, typename TTypes<T>::ConstFlat maxvals, const random::PhiloxRandom& gen, typename TTypes<T>::Flat output) { auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads()); auto DoWork = [samples_per_batch, num_elements, &ctx, &means, &stddevs, &minvals, &maxvals, &gen, &output](int start_batch, int limit_batch) { // Capturing "gen" by-value would only make a copy for the _shared_ // lambda. Since we want to let each worker have its own copy, we pass // "gen" by reference and explicitly do a copy assignment here. random::PhiloxRandom gen_copy = gen; // Skip takes units of 128 bytes. +3 is so rounding doesn't lead to // us using the same state in different batches. // The sample from each iteration uses 2 random numbers. gen_copy.Skip(start_batch * 2 * kMaxIterations * (samples_per_batch + 3) / 4); typedef random::UniformDistribution<random::PhiloxRandom, T> Uniform; Uniform dist; // Vectorized intermediate calculations for uniform rejection sampling. // We always generate at most 4 samples. Eigen::array<T, 4> z; Eigen::array<T, 4> g; for (int64 b = start_batch; b < limit_batch; ++b) { // We are passed a flat array for each of the parameter tensors. // The input is either a scalar broadcasted to all batches or a vector // with length num_batches, but the scalar becomes an array of length 1. T mean = means((means.dimension(0) == 1) ? 0 : b); T stddev = stddevs((stddevs.dimension(0) == 1) ? 0 : b); T minval = minvals((minvals.dimension(0) == 1) ? 0 : b); T maxval = maxvals((maxvals.dimension(0) == 1) ? 0 : b); // The last batch can be short, if we adjusted num_batches and // samples_per_batch. const int64 limit_sample = std::min((b + 1) * samples_per_batch, num_elements); int64 sample = b * samples_per_batch; // On GPU, this check will just fill samples with NAN if it fails. OP_REQUIRES(ctx, stddev > T(0) && minval < maxval && (Eigen::numext::isfinite(minval) || Eigen::numext::isfinite(maxval)), errors::InvalidArgument("Invalid parameters")); int numIterations = 0; // If possible, make one-sided bound be the lower bound, or make both // bounds positive. Otherwise, the bounds are on either side of the // mean. if ((Eigen::numext::isinf(minval) && minval < T(0)) || maxval < mean) { // Reverse all calculations. normMin and normMax will be flipped. std::swap(minval, maxval); stddev = -stddev; } // Calculate normalized samples, then convert them. const T normMin = (minval - mean) / stddev; const T normMax = (maxval - mean) / stddev; // Determine the method to use. const T sqrtFactor = Eigen::numext::sqrt((normMin * normMin) + T(4)); const T cutoff = T(2) * Eigen::numext::exp(T(0.5) + (normMin * (normMin - sqrtFactor)) / T(4)) / (normMin + sqrtFactor); const T diff = normMax - normMin; if (diff < cutoff) { // Sample from a uniform distribution on [normMin, normMax]. const T plusFactor = (normMin < T(0)) ? T(0) : normMin * normMin; while (sample < limit_sample) { const auto rand = dist(&gen_copy); const int size = rand.size(); // NOTE(ringwalt): These loops seem to only generate packed AVX // instructions for float32. for (int i = 0; i < size; i++) { z[i] = rand[i] * diff + normMin; } for (int i = 0; i < size; i++) { g[i] = (plusFactor - z[i] * z[i]) / T(2.0); } const auto u = dist(&gen_copy); for (int i = 0; i < size; i++) { if (u[i] <= Eigen::numext::exp(g[i]) || numIterations + 1 >= kMaxIterations) { // Accept the sample z. // If we run out of iterations, just use the current uniform // sample. Emperically, the probability of accepting each sample // is at least 50% for typical inputs, so we will always accept // by 100 iterations. // This introduces a slight inaccuracy when at least one bound // is large, minval is negative and maxval is positive. output(sample) = z[i] * stddev + mean; sample++; if (sample >= limit_sample) { break; } numIterations = 0; } else { numIterations++; } } } } else { // Sample from an exponential distribution with alpha maximizing // acceptance probability, offset by normMin from the origin. // Accept only if less than normMax. const T alpha = (normMin + Eigen::numext::sqrt((normMin * normMin) + T(4))) / T(2); while (sample < limit_sample) { auto rand = dist(&gen_copy); const int size = rand.size(); int i = 0; while (i < size) { const T z = -Eigen::numext::log(rand[i]) / alpha + normMin; i++; const T x = normMin < alpha ? alpha - z : normMin - alpha; const T g = Eigen::numext::exp(-x * x / T(2.0)); const T u = rand[i]; i++; if ((u <= g && z < normMax) || numIterations + 1 >= kMaxIterations) { output(sample) = z * stddev + mean; sample++; if (sample >= limit_sample) { break; } numIterations = 0; } else { numIterations++; } } } } } }; // The cost of the initial calculations for the batch. const int64 batchInitCost = // normMin, normMax (Eigen::TensorOpCost::AddCost<T>() + Eigen::TensorOpCost::MulCost<T>()) * 2 // sqrtFactor + Eigen::TensorOpCost::AddCost<T>() + Eigen::TensorOpCost::MulCost<T>() + Eigen::internal::functor_traits< Eigen::internal::scalar_sqrt_op<T>>::Cost // cutoff + Eigen::TensorOpCost::MulCost<T>() * 4 + Eigen::internal::functor_traits<Eigen::internal::scalar_exp_op<T>>::Cost // diff + Eigen::TensorOpCost::AddCost<T>(); const int64 uniformSampleCost = random::PhiloxRandom::kElementCost + random::UniformDistribution<random::PhiloxRandom, T>::kElementCost; // The cost of a single uniform sampling round. const int64 uniformRejectionSamplingCost = uniformSampleCost + Eigen::TensorOpCost::MulCost<T>() + Eigen::TensorOpCost::AddCost<T>() + Eigen::TensorOpCost::MulCost<T>() * 2 + Eigen::TensorOpCost::AddCost<T>() + uniformSampleCost + Eigen::internal::functor_traits< Eigen::internal::scalar_exp_op<T>>::Cost + Eigen::TensorOpCost::MulCost<T>() + Eigen::TensorOpCost::AddCost<T>(); // Estimate the cost for an entire batch. // Assume we use uniform sampling, and accept the 2nd sample on average. const int64 batchCost = batchInitCost + uniformRejectionSamplingCost * 2 * samples_per_batch; Shard(worker_threads.num_threads, worker_threads.workers, num_batches, batchCost, DoWork); } }; } // namespace functor namespace { // Samples from a truncated normal distribution, using the given parameters. template <typename Device, typename T> class ParameterizedTruncatedNormalOp : public OpKernel { // Reshape batches so each batch is this size if possible. static const int32 kDesiredBatchSize = 100; public: explicit ParameterizedTruncatedNormalOp(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, generator_.Init(context)); } void Compute(OpKernelContext* ctx) override { const Tensor& shape_tensor = ctx->input(0); const Tensor& means_tensor = ctx->input(1); const Tensor& stddevs_tensor = ctx->input(2); const Tensor& minvals_tensor = ctx->input(3); const Tensor& maxvals_tensor = ctx->input(4); OP_REQUIRES( ctx, TensorShapeUtils::IsVector(shape_tensor.shape()), errors::InvalidArgument("Input shape should be a vector, got shape: ", shape_tensor.shape().DebugString())); int32 num_batches = shape_tensor.flat<int32>()(0); int32 samples_per_batch = 1; const int32 num_dims = shape_tensor.dim_size(0); for (int32 i = 1; i < num_dims; i++) { samples_per_batch *= shape_tensor.flat<int32>()(i); } const int32 num_elements = num_batches * samples_per_batch; // Allocate the output before fudging num_batches and samples_per_batch. auto shape_vec = shape_tensor.flat<int32>(); TensorShape tensor_shape; OP_REQUIRES_OK(ctx, TensorShapeUtils::MakeShape( shape_vec.data(), shape_vec.size(), &tensor_shape)); Tensor* samples_tensor; OP_REQUIRES_OK(ctx, ctx->allocate_output(0, tensor_shape, &samples_tensor)); // Parameters must be 0-d or 1-d. OP_REQUIRES(ctx, means_tensor.dims() <= 1, errors::InvalidArgument( "Input means should be a scalar or vector, got shape: ", means_tensor.shape().DebugString())); OP_REQUIRES(ctx, stddevs_tensor.dims() <= 1, errors::InvalidArgument( "Input stddevs should be a scalar or vector, got shape: ", stddevs_tensor.shape().DebugString())); OP_REQUIRES(ctx, minvals_tensor.dims() <= 1, errors::InvalidArgument( "Input minvals should be a scalar or vector, got shape: ", minvals_tensor.shape().DebugString())); OP_REQUIRES(ctx, maxvals_tensor.dims() <= 1, errors::InvalidArgument( "Input maxvals should be a scalar or vector, got shape: ", maxvals_tensor.shape().DebugString())); if ((means_tensor.dims() == 0 || means_tensor.dim_size(0) == 1) && (stddevs_tensor.dims() == 0 || stddevs_tensor.dim_size(0) == 1) && minvals_tensor.dims() == 0 && maxvals_tensor.dims() == 0) { // All batches have the same parameters, so we can update the batch size // to a reasonable value to improve parallelism (ensure enough batches, // and no very small batches which have high overhead). int32 size = num_batches * samples_per_batch; int32 adjusted_samples = kDesiredBatchSize; // Ensure adjusted_batches * adjusted_samples >= size. int32 adjusted_batches = Eigen::divup(size, adjusted_samples); num_batches = adjusted_batches; samples_per_batch = adjusted_samples; } else { // Parameters must be broadcastable to the shape [num_batches]. OP_REQUIRES( ctx, TensorShapeUtils::IsScalar(means_tensor.shape()) || means_tensor.dim_size(0) == 1 || means_tensor.dim_size(0) == num_batches, errors::InvalidArgument( "Input means should have length 1 or shape[0], got shape: ", means_tensor.shape().DebugString())); OP_REQUIRES( ctx, TensorShapeUtils::IsScalar(stddevs_tensor.shape()) || stddevs_tensor.dim_size(0) == 1 || stddevs_tensor.dim_size(0) == num_batches, errors::InvalidArgument( "Input stddevs should have length 1 or shape[0], got shape: ", stddevs_tensor.shape().DebugString())); OP_REQUIRES( ctx, TensorShapeUtils::IsScalar(minvals_tensor.shape()) || minvals_tensor.dim_size(0) == 1 || minvals_tensor.dim_size(0) == num_batches, errors::InvalidArgument( "Input minvals should have length 1 or shape[0], got shape: ", minvals_tensor.shape().DebugString())); OP_REQUIRES( ctx, TensorShapeUtils::IsScalar(maxvals_tensor.shape()) || maxvals_tensor.dim_size(0) == 1 || maxvals_tensor.dim_size(0) == num_batches, errors::InvalidArgument( "Input maxvals should have length 1 or shape[0], got shape: ", maxvals_tensor.shape().DebugString())); } auto truncFunctor = functor::TruncatedNormalFunctor<Device, T>(); // Each worker has the fudge factor for samples_per_batch, so use it here. random::PhiloxRandom rng = generator_.ReserveSamples128( num_batches * 2 * truncFunctor.kMaxIterations * (samples_per_batch + 3) / 4); truncFunctor(ctx, ctx->eigen_device<Device>(), num_batches, samples_per_batch, num_elements, means_tensor.flat<T>(), stddevs_tensor.flat<T>(), minvals_tensor.flat<T>(), maxvals_tensor.flat<T>(), rng, samples_tensor->flat<T>()); } private: GuardedPhiloxRandom generator_; TF_DISALLOW_COPY_AND_ASSIGN(ParameterizedTruncatedNormalOp); }; } // namespace #define REGISTER(TYPE) \ REGISTER_KERNEL_BUILDER(Name("ParameterizedTruncatedNormal") \ .Device(DEVICE_CPU) \ .TypeConstraint<TYPE>("dtype"), \ ParameterizedTruncatedNormalOp<CPUDevice, TYPE>) TF_CALL_half(REGISTER); TF_CALL_float(REGISTER); TF_CALL_double(REGISTER); #undef REGISTER #if GOOGLE_CUDA #define REGISTER(TYPE) \ REGISTER_KERNEL_BUILDER(Name("ParameterizedTruncatedNormal") \ .Device(DEVICE_GPU) \ .HostMemory("shape") \ .TypeConstraint<TYPE>("dtype"), \ ParameterizedTruncatedNormalOp<GPUDevice, TYPE>) TF_CALL_half(REGISTER); TF_CALL_float(REGISTER); TF_CALL_double(REGISTER); #undef REGISTER #endif // GOOGLE_CUDA } // end namespace tensorflow
[ "zylo117@hotmail.com" ]
zylo117@hotmail.com
8a71a2b06e898ab0bb38279cbdb1683ef3ec404b
f53a79a1cee7e2ba44e06fe0a94d4032bb9ee43f
/BOJ/2702.cpp
51d1b658638b4962ce620d5a8a22247739c5c24a
[]
no_license
SOFTK2765/PS
f576a416da21034d5ebea60538fcd263b6d042f3
a9215bc9c41530ad6a1a7352716c64e6d73354a7
refs/heads/master
2021-06-21T00:39:34.065445
2021-01-01T12:45:51
2021-01-01T12:45:51
152,511,667
2
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
#include <bits/stdc++.h> using namespace std; int gcd(int a, int b) { int c = a%b; while(c!=0) { a = b; b = c; c = a%b; } return b; } int main() { int t; scanf("%d", &t); while(t--) { int a, b; scanf(" %d %d", &a, &b); printf("%d %d\n", a*b/gcd(a, b), gcd(a, b)); } return 0; }
[ "44043820+SOFTK2765@users.noreply.github.com" ]
44043820+SOFTK2765@users.noreply.github.com
756bc9d4a3ea8c3d226d070d5217fd8f26ed16a2
e64edb063f0ce73e84814e3de29a72b0b5f71641
/geeksforgeeks/Sum-of-eaf-nodes-BST.cpp
ab4abfa4e5e6bcbb75a4628f99bc87cc2f80af23
[ "MIT" ]
permissive
chunhou-liu/OnlineJudge
d7a8aff287826d6473b4d1a1c5c96c1b9d7830f3
b79c8e05acf05411d8cf172214aa42e49cc20867
refs/heads/master
2020-05-02T04:50:01.145766
2019-06-12T13:47:59
2019-06-12T13:47:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
238
cpp
struct Node{ int data; Node *left,*right; }; int sumOfLeafNodes(Node *r ){ if(r==nullptr)return 0; if(r->left==nullptr && r->right==nullptr)return r->data; return sumOfLeafNodes(r->left) + sumOfLeafNodes(r->right); }
[ "liuchunhou@gmail.com" ]
liuchunhou@gmail.com
f42a9c1e4fc8b423b1657e654d1336268ad213e7
fbf0977fbec6a8c9c0223f6b583a3fe7eef1059d
/babymonitorcode.ino
cad589b8da4ad4aaaa0e3ce492af6d849255300f
[]
no_license
reshmarenee/IOT-Based-Baby-Monitor
50671c4c6a38370a4ca150f74be447a4495aa35f
8945d3d80f5e5f17fa3925b4820f2c523154a9f6
refs/heads/main
2023-04-25T19:12:30.813596
2021-05-23T21:45:20
2021-05-23T21:45:20
370,157,013
0
0
null
null
null
null
UTF-8
C++
false
false
1,955
ino
#include <SoftwareSerial.h> int volume; //variable to read the value from Sound sensor int inputPin = 2; // choose the input pin (for PIR sensor) int buzzerPin = 9; //choose the input pin (for buzzer) int val = 0; //variable to read the value from PIR sensor SoftwareSerial sim(10, 11); //10-Rx,11-Tx used for communication String number = "+911234567890"; // mobile number to which alert message has to be sent void setup() { delay(7000); //delay for 7 seconds to make sure the modules get the signal pinMode(inputPin, INPUT); // declare sensor as input pinMode(buzzerPin, OUTPUT); // declare the pin as output mode Serial.begin(9600); // Serial port begin (or) Setting the baud rate of Serial Monitor (Arduino) sim.begin(9600); // Setting the baud rate of GSM Module } void loop() { volume = analogRead(A0); // Reads the value from the Analog PIN A0 - here we connect sound sensor out pin to A0 val = digitalRead(inputPin); // read input value (from pin 2) Serial.println(volume); //Serial print level if (volume > 50) { Serial.println(val); if (val > 0) // check the existence of person { Serial.println("Motion detected!"); tone(buzzerPin, 50, 1000); // used to activate the buzzer with frequency and time val = 0; } SendMessage(); // calling the function delay(1000); } delay(1000); } void SendMessage() { //Serial.println ("Sending Message"); sim.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode delay(1000); //Serial.println ("Set SMS Number"); sim.println("AT+CMGS=\"" + number + "\"\r"); //Mobile phone number to send message delay(1000); String SMS = "Hello, how are you?"; sim.println(SMS); delay(100); sim.println((char)26); // ASCII code of CTRL+Z delay(1000); }
[ "noreply@github.com" ]
reshmarenee.noreply@github.com
149524c3fa477568a9b179c36d54fb01de71706d
2b41dd58d3272d95be362decf2047d8f33ec5d14
/MMX3/DemoDirectX/DemoDirectX/MapReader/TmxImage.cpp
2433e27d28fd6d9618d0ad493c6a5b841b0657e7
[]
no_license
NhapMonPhatTrienGame/GameDirectX
c40dbbd8251a81c6af7dbbdc5111bb604634e4b3
558cd3618cabc413e259bc46d63b475fc781dc2c
refs/heads/master
2021-10-08T06:40:23.156743
2018-12-09T14:39:45
2018-12-09T14:39:45
156,981,588
1
0
null
null
null
null
UTF-8
C++
false
false
2,134
cpp
//----------------------------------------------------------------------------- // TmxImage.cpp // // Copyright (c) 2010-2014, Tamir Atias // 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. // // 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 TAMIR ATIAS 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. // // Author: Tamir Atias //----------------------------------------------------------------------------- #include "tinyxml2.h" #include "TmxImage.h" namespace Tmx { Image::Image() : source() , width() , height() , transparent_color() {} Image::~Image() {} void Image::Parse(const tinyxml2::XMLNode* imageNode) { const tinyxml2::XMLElement* imageElem = imageNode->ToElement(); // Read all the attribute into member variables. source = imageElem->Attribute("source"); width = imageElem->IntAttribute("width"); height = imageElem->IntAttribute("height"); const char* trans = imageElem->Attribute("trans"); if (trans) { transparent_color = trans; } } }
[ "phanvanluom97bd@gmail.com" ]
phanvanluom97bd@gmail.com
0fba5f92eeb1d182b99ae433014b7e88808dd71e
9ef7ae27f57d24b7fa194ed9fc22d95a2ea2f4fa
/MathQ/combinatorics/rectangles.cpp
0984df5de41b073884528f1dfd548e6b8ab3f571
[]
no_license
Rahul365/Coding_Practice
e093b745da5e0d589b57d31ff8d4d5bdae46c583
4430401991defdd79522da229f040c5e48718487
refs/heads/master
2022-07-30T19:59:21.839107
2022-07-02T08:10:50
2022-07-02T08:10:50
241,954,353
1
1
null
null
null
null
UTF-8
C++
false
false
726
cpp
#include<bits/stdc++.h> using namespace std; // https://codeforces.com/problemset/problem/844/B int main(){ int n,m; cin >> n >> m; vector<vector<int>> dp(n,vector<int>(m)); for(int i = 0;i<n;++i) for(int j = 0;j<m;++j){ cin >> dp[i][j]; } long long int answer = 0; for(int r = 0;r < n;++r){ int cnt0 = 0; for(int i = 0 ;i<m;++i) cnt0 += dp[r][i]==0; answer += (1LL<<cnt0) + (1LL<<(m-cnt0)) - 2; } for(int c = 0; c < m;++c){ int cnt0 = 0; for(int r = 0;r < n;++r) cnt0 += dp[r][c]==0; answer += (1LL<<cnt0) + (1LL<<(n-cnt0)) - 2; } //answer - common sets; cout << (answer - (n*m)) <<"\n"; return 0; }
[ "rahul.dhiman365@gmail.com" ]
rahul.dhiman365@gmail.com
4ef5c877725eccdb6ed4b8fc78d6524f86fcfd38
9a3ec3eb5371a0e719b50bbf832a732e829b1ce4
/NPC RavensDust/Safe.h
937f7359e7417a00c8fca254a4fe2c4a1d6e9eb7
[]
no_license
elestranobaron/T4C-Serveur-Multiplateformes
5cb4dac8b8bd79bfd2bbd2be2da6914992fa7364
f4a5ed21db1cd21415825cc0e72ddb57beee053e
refs/heads/master
2022-10-01T20:13:36.217655
2022-09-22T02:43:33
2022-09-22T02:43:33
96,352,559
12
8
null
null
null
null
UTF-8
C++
false
false
291
h
#include "NPCStructure.h" #ifndef __SAFE_H #define __SAFE_H class Safe : public NPCstructure{ public: Safe(); ~Safe(); void Create( void ); void OnAttacked ( UNIT_FUNC_PROTOTYPE ); void OnTalk( UNIT_FUNC_PROTOTYPE ); void OnInitialise( UNIT_FUNC_PROTOTYPE ); }; #endif
[ "lloancythomas@hotmail.co" ]
lloancythomas@hotmail.co
eef316e82ae569e56e73c92d54c7dc635a21e5c5
9d0d8b8f1df362e8e6c7c38984cb30c67b8e4c23
/src/UniformSetters.cpp
9c6f6978ac031e86e4f4278b19525ce4cf156ea0
[ "MIT" ]
permissive
AlphaZoneR/ModernGL
c700b45970f05388531da3de7acd18dc0a6066eb
b8117297398cb744fc90add6858e3949069c35c6
refs/heads/master
2021-09-04T03:55:02.757362
2017-11-28T08:03:50
2017-11-28T08:03:50
114,154,438
0
0
null
2017-12-13T18:21:21
2017-12-13T18:21:21
null
UTF-8
C++
false
false
25,469
cpp
#include "Uniform.hpp" #include "Error.hpp" int MGLUniform_invalid_setter(MGLUniform * self, PyObject * value) { MGLError_Set("cannot detect uniform type"); return -1; } int MGLUniform_bool_value_setter(MGLUniform * self, PyObject * value) { int c_value; if (value == Py_True) { c_value = 1; } else if (value == Py_False) { c_value = 0; } else { MGLError_Set("the value must be a bool not %s", Py_TYPE(value)->tp_name); return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, 1, &c_value); return 0; } int MGLUniform_int_value_setter(MGLUniform * self, PyObject * value) { int c_value = PyLong_AsLong(value); if (PyErr_Occurred()) { MGLError_Set("cannot convert value to int"); return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, 1, &c_value); return 0; } int MGLUniform_uint_value_setter(MGLUniform * self, PyObject * value) { unsigned c_value = PyLong_AsUnsignedLong(value); if (PyErr_Occurred()) { MGLError_Set("the value must be an unsigned int not %s", Py_TYPE(value)->tp_name); return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, 1, &c_value); return 0; } int MGLUniform_float_value_setter(MGLUniform * self, PyObject * value) { float c_value = (float)PyFloat_AsDouble(value); if (PyErr_Occurred()) { MGLError_Set("cannot convert value to float"); return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, 1, &c_value); return 0; } int MGLUniform_double_value_setter(MGLUniform * self, PyObject * value) { double c_value = PyFloat_AsDouble(value); if (PyErr_Occurred()) { MGLError_Set("cannot convert value to double"); return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, 1, &c_value); return 0; } int MGLUniform_sampler_value_setter(MGLUniform * self, PyObject * value) { int c_value = PyLong_AsLong(value); if (PyErr_Occurred()) { MGLError_Set("cannot convert value to int"); return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, 1, &c_value); return 0; } int MGLUniform_bool_array_value_setter(MGLUniform * self, PyObject * value) { if (Py_TYPE(value) != &PyList_Type) { MGLError_Set("the value must be a list not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyList_GET_SIZE(value); if (size != self->array_length) { MGLError_Set("the value must be a list of size %d not %d", self->array_length, size); return -1; } int * c_values = new int[size]; for (int k = 0; k < size; ++k) { PyObject * v = PyList_GET_ITEM(value, k); if (v == Py_True) { c_values[k] = 1; } else if (v == Py_False) { c_values[k] = 0; } else { MGLError_Set("value[%d] must be a bool not %s", k, Py_TYPE(value)->tp_name); delete[] c_values; return -1; } } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, size, c_values); delete[] c_values; return 0; } int MGLUniform_int_array_value_setter(MGLUniform * self, PyObject * value) { if (Py_TYPE(value) != &PyList_Type) { MGLError_Set("the value must be a list not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyList_GET_SIZE(value); if (size != self->array_length) { MGLError_Set("the value must be a list of size %d not %d", self->array_length, size); return -1; } int * c_values = new int[size]; for (int k = 0; k < size; ++k) { c_values[k] = PyLong_AsLong(PyList_GET_ITEM(value, k)); } if (PyErr_Occurred()) { MGLError_Set("cannot convert value to int"); delete[] c_values; return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, size, c_values); delete[] c_values; return 0; } int MGLUniform_uint_array_value_setter(MGLUniform * self, PyObject * value) { if (Py_TYPE(value) != &PyList_Type) { MGLError_Set("the value must be a list not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyList_GET_SIZE(value); if (size != self->array_length) { MGLError_Set("the value must be a list of size %d not %d", self->array_length, size); return -1; } unsigned * c_values = new unsigned[size]; for (int k = 0; k < size; ++k) { c_values[k] = PyLong_AsUnsignedLong(PyList_GET_ITEM(value, k)); } if (PyErr_Occurred()) { MGLError_Set("cannot convert value to unsigned int"); delete[] c_values; return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, size, c_values); delete[] c_values; return 0; } int MGLUniform_float_array_value_setter(MGLUniform * self, PyObject * value) { if (Py_TYPE(value) != &PyList_Type) { MGLError_Set("the value must be a list not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyList_GET_SIZE(value); if (size != self->array_length) { MGLError_Set("the value must be a list of size %d not %d", self->array_length, size); return -1; } float * c_values = new float[size]; for (int k = 0; k < size; ++k) { c_values[k] = (float)PyFloat_AsDouble(PyList_GET_ITEM(value, k)); } if (PyErr_Occurred()) { MGLError_Set("cannot convert value to float"); delete[] c_values; return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, size, c_values); delete[] c_values; return 0; } int MGLUniform_double_array_value_setter(MGLUniform * self, PyObject * value) { if (Py_TYPE(value) != &PyList_Type) { MGLError_Set("the value must be a list not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyList_GET_SIZE(value); if (size != self->array_length) { MGLError_Set("the value must be a list of size %d not %d", self->array_length, size); return -1; } double * c_values = new double[size]; for (int k = 0; k < size; ++k) { c_values[k] = PyFloat_AsDouble(PyList_GET_ITEM(value, k)); } if (PyErr_Occurred()) { MGLError_Set("cannot convert value to double"); delete[] c_values; return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, size, c_values); delete[] c_values; return 0; } int MGLUniform_sampler_array_value_setter(MGLUniform * self, PyObject * value) { if (Py_TYPE(value) != &PyList_Type) { MGLError_Set("the value must be a list not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyList_GET_SIZE(value); if (size != self->array_length) { MGLError_Set("the value must be a list of size %d not %d", self->array_length, size); return -1; } int * c_values = new int[size]; for (int k = 0; k < size; ++k) { c_values[k] = PyLong_AsLong(PyList_GET_ITEM(value, k)); } if (PyErr_Occurred()) { MGLError_Set("cannot convert value to int"); delete[] c_values; return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, size, c_values); delete[] c_values; return 0; } template <int N> int MGLUniform_bvec_value_setter(MGLUniform * self, PyObject * value) { int c_values[N]; if (Py_TYPE(value) != &PyTuple_Type) { MGLError_Set("the value must be a tuple not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyTuple_GET_SIZE(value); if (size != N) { MGLError_Set("the value must be a tuple of size %d not %d", N, size); return -1; } for (int i = 0; i < N; ++i) { PyObject * v = PyTuple_GET_ITEM(value, i); if (v == Py_True) { c_values[i] = 1; } else if (v == Py_False) { c_values[i] = 0; } else { MGLError_Set("value[%d] must be a bool not %s", i, Py_TYPE(value)->tp_name); return -1; } } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, 1, c_values); return 0; } template <int N> int MGLUniform_ivec_value_setter(MGLUniform * self, PyObject * value) { int c_values[N]; if (Py_TYPE(value) != &PyTuple_Type) { MGLError_Set("the value must be a tuple not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyTuple_GET_SIZE(value); if (size != N) { MGLError_Set("the value must be a tuple of size %d not %d", N, size); return -1; } for (int i = 0; i < N; ++i) { c_values[i] = PyLong_AsLong(PyTuple_GET_ITEM(value, i)); } if (PyErr_Occurred()) { MGLError_Set("cannot convert value to int"); return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, 1, c_values); return 0; } template <int N> int MGLUniform_uvec_value_setter(MGLUniform * self, PyObject * value) { unsigned c_values[N]; if (Py_TYPE(value) != &PyTuple_Type) { MGLError_Set("the value must be a tuple not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyTuple_GET_SIZE(value); if (size != N) { MGLError_Set("the value must be a tuple of size %d not %d", N, size); return -1; } for (int i = 0; i < N; ++i) { c_values[i] = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(value, i)); } if (PyErr_Occurred()) { MGLError_Set("cannot convert value to unsigned int"); return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, 1, c_values); return 0; } template <int N> int MGLUniform_vec_value_setter(MGLUniform * self, PyObject * value) { float c_values[N]; if (Py_TYPE(value) != &PyTuple_Type) { MGLError_Set("the value must be a tuple not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyTuple_GET_SIZE(value); if (size != N) { MGLError_Set("the value must be a tuple of size %d not %d", N, size); return -1; } for (int i = 0; i < N; ++i) { c_values[i] = (float)PyFloat_AsDouble(PyTuple_GET_ITEM(value, i)); } if (PyErr_Occurred()) { MGLError_Set("cannot convert value to float"); return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, 1, c_values); return 0; } template <int N> int MGLUniform_dvec_value_setter(MGLUniform * self, PyObject * value) { double c_values[N]; if (Py_TYPE(value) != &PyTuple_Type) { MGLError_Set("the value must be a tuple not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyTuple_GET_SIZE(value); if (size != N) { MGLError_Set("the value must be a tuple of size %d not %d", N, size); return -1; } for (int i = 0; i < N; ++i) { c_values[i] = PyFloat_AsDouble(PyTuple_GET_ITEM(value, i)); } if (PyErr_Occurred()) { MGLError_Set("cannot convert value to double"); return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, 1, c_values); return 0; } template <int N> int MGLUniform_bvec_array_value_setter(MGLUniform * self, PyObject * value) { if (Py_TYPE(value) != &PyList_Type) { MGLError_Set("the value must be a list not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyList_GET_SIZE(value); if (size != self->array_length) { MGLError_Set("the value must be a list of size %d not %d", self->array_length, size); return -1; } int cnt = 0; int * c_values = new int[size * N]; for (int k = 0; k < size; ++k) { PyObject * tuple = PyList_GET_ITEM(value, k); if (Py_TYPE(tuple) != &PyTuple_Type) { MGLError_Set("value[%d] must be a tuple not %s", k, Py_TYPE(value)->tp_name); delete[] c_values; return -1; } int tuple_size = (int)PyTuple_GET_SIZE(tuple); if (tuple_size != N) { MGLError_Set("value[%d] must be a tuple of size %d not %d", k, N, tuple_size); delete[] c_values; return -1; } for (int i = 0; i < N; ++i) { PyObject * v = PyTuple_GET_ITEM(tuple, i); if (v == Py_True) { c_values[cnt++] = 1; } else if (v == Py_False) { c_values[cnt++] = 0; } else { MGLError_Set("value[%d][%d] must be a bool not %s", k, i, Py_TYPE(value)->tp_name); delete[] c_values; return -1; } } } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, size * N, c_values); delete[] c_values; return 0; } template <int N> int MGLUniform_ivec_array_value_setter(MGLUniform * self, PyObject * value) { if (Py_TYPE(value) != &PyList_Type) { MGLError_Set("the value must be a list not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyList_GET_SIZE(value); if (size != self->array_length) { MGLError_Set("the value must be a list of size %d not %d", self->array_length, size); return -1; } int cnt = 0; int * c_values = new int[size * N]; for (int k = 0; k < size; ++k) { PyObject * tuple = PyList_GET_ITEM(value, k); if (Py_TYPE(tuple) != &PyTuple_Type) { MGLError_Set("value[%d] must be a tuple not %s", k, Py_TYPE(value)->tp_name); delete[] c_values; return -1; } int tuple_size = (int)PyTuple_GET_SIZE(tuple); if (tuple_size != N) { MGLError_Set("value[%d] must be a tuple of size %d not %d", k, N, tuple_size); delete[] c_values; return -1; } for (int i = 0; i < N; ++i) { c_values[cnt++] = PyLong_AsLong(PyTuple_GET_ITEM(tuple, i)); } } if (PyErr_Occurred()) { MGLError_Set("cannot convert value to int"); delete[] c_values; return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, size * N, c_values); delete[] c_values; return 0; } template <int N> int MGLUniform_uvec_array_value_setter(MGLUniform * self, PyObject * value) { if (Py_TYPE(value) != &PyList_Type) { MGLError_Set("the value must be a list not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyList_GET_SIZE(value); if (size != self->array_length) { MGLError_Set("the value must be a list of size %d not %d", self->array_length, size); return -1; } int cnt = 0; unsigned * c_values = new unsigned[size * N]; for (int k = 0; k < size; ++k) { PyObject * tuple = PyList_GET_ITEM(value, k); if (Py_TYPE(tuple) != &PyTuple_Type) { MGLError_Set("value[%d] must be a tuple not %s", k, Py_TYPE(value)->tp_name); delete[] c_values; return -1; } int tuple_size = (int)PyTuple_GET_SIZE(tuple); if (tuple_size != N) { MGLError_Set("value[%d] must be a tuple of size %d not %d", k, N, tuple_size); delete[] c_values; return -1; } for (int i = 0; i < N; ++i) { c_values[cnt++] = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(tuple, i)); } } if (PyErr_Occurred()) { MGLError_Set("cannot convert value to unsigned int"); delete[] c_values; return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, size * N, c_values); delete[] c_values; return 0; } template <int N> int MGLUniform_vec_array_value_setter(MGLUniform * self, PyObject * value) { if (Py_TYPE(value) != &PyList_Type) { MGLError_Set("the value must be a list not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyList_GET_SIZE(value); if (size != self->array_length) { MGLError_Set("the value must be a list of size %d not %d", self->array_length, size); return -1; } int cnt = 0; float * c_values = new float[size * N]; for (int k = 0; k < size; ++k) { PyObject * tuple = PyList_GET_ITEM(value, k); if (Py_TYPE(tuple) != &PyTuple_Type) { MGLError_Set("value[%d] must be a tuple not %s", k, Py_TYPE(value)->tp_name); delete[] c_values; return -1; } int tuple_size = (int)PyTuple_GET_SIZE(tuple); if (tuple_size != N) { MGLError_Set("value[%d] must be a tuple of size %d not %d", k, N, tuple_size); delete[] c_values; return -1; } for (int i = 0; i < N; ++i) { c_values[cnt++] = (float)PyFloat_AsDouble(PyTuple_GET_ITEM(tuple, i)); } } if (PyErr_Occurred()) { MGLError_Set("cannot convert value to float"); delete[] c_values; return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, size * N, c_values); delete[] c_values; return 0; } template <int N> int MGLUniform_dvec_array_value_setter(MGLUniform * self, PyObject * value) { if (Py_TYPE(value) != &PyList_Type) { MGLError_Set("the value must be a list not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyList_GET_SIZE(value); if (size != self->array_length) { MGLError_Set("the value must be a list of size %d not %d", self->array_length, size); return -1; } int cnt = 0; double * c_values = new double[size * N]; for (int k = 0; k < size; ++k) { PyObject * tuple = PyList_GET_ITEM(value, k); if (Py_TYPE(tuple) != &PyTuple_Type) { MGLError_Set("value[%d] must be a tuple not %s", k, Py_TYPE(value)->tp_name); delete[] c_values; return -1; } int tuple_size = (int)PyTuple_GET_SIZE(tuple); if (tuple_size != N) { MGLError_Set("value[%d] must be a tuple of size %d not %d", k, N, tuple_size); delete[] c_values; return -1; } for (int i = 0; i < N; ++i) { c_values[cnt++] = PyFloat_AsDouble(PyTuple_GET_ITEM(tuple, i)); } } if (PyErr_Occurred()) { MGLError_Set("cannot convert value to double"); delete[] c_values; return -1; } ((gl_uniform_vector_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, size * N, c_values); delete[] c_values; return 0; } template <typename T, int N, int M> int MGLUniform_matrix_value_setter(MGLUniform * self, PyObject * value) { T c_values[N * M]; if (Py_TYPE(value) != &PyTuple_Type) { MGLError_Set("the value must be a tuple not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyTuple_GET_SIZE(value); if (size != N * M) { MGLError_Set("the value must be a tuple of size %d not %d", N * M, size); return -1; } for (int i = 0; i < N * M; ++i) { c_values[i] = (T)PyFloat_AsDouble(PyTuple_GET_ITEM(value, i)); } if (PyErr_Occurred()) { MGLError_Set("invalid values"); return -1; } ((gl_uniform_matrix_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, 1, false, c_values); return 0; } template <typename T, int N, int M> int MGLUniform_matrix_array_value_setter(MGLUniform * self, PyObject * value) { if (Py_TYPE(value) != &PyList_Type) { MGLError_Set("the value must be a list not %s", Py_TYPE(value)->tp_name); return -1; } int size = (int)PyList_GET_SIZE(value); if (size != self->array_length) { MGLError_Set("the value must be a list of size %d not %d", self->array_length, size); return -1; } int cnt = 0; T * c_values = new T[size * N * M]; for (int k = 0; k < size; ++k) { PyObject * tuple = PyList_GET_ITEM(value, k); if (Py_TYPE(tuple) != &PyTuple_Type) { MGLError_Set("value[%d] must be a tuple not %s", k, Py_TYPE(value)->tp_name); delete[] c_values; return -1; } int tuple_size = (int)PyTuple_GET_SIZE(tuple); if (tuple_size != N * M) { MGLError_Set("value[%d] must be a tuple of size %d not %d", k, N * M, tuple_size); delete[] c_values; return -1; } for (int i = 0; i < N * M; ++i) { c_values[cnt++] = (T)PyFloat_AsDouble(PyTuple_GET_ITEM(tuple, i)); } } if (PyErr_Occurred()) { MGLError_Set("invalid values"); delete[] c_values; return -1; } ((gl_uniform_matrix_writer_proc)self->gl_value_writer_proc)(self->program_obj, self->location, size, false, c_values); delete[] c_values; return 0; } template int MGLUniform_bvec_value_setter<2>(MGLUniform * self, PyObject * value); template int MGLUniform_bvec_value_setter<3>(MGLUniform * self, PyObject * value); template int MGLUniform_bvec_value_setter<4>(MGLUniform * self, PyObject * value); template int MGLUniform_ivec_value_setter<2>(MGLUniform * self, PyObject * value); template int MGLUniform_ivec_value_setter<3>(MGLUniform * self, PyObject * value); template int MGLUniform_ivec_value_setter<4>(MGLUniform * self, PyObject * value); template int MGLUniform_uvec_value_setter<2>(MGLUniform * self, PyObject * value); template int MGLUniform_uvec_value_setter<3>(MGLUniform * self, PyObject * value); template int MGLUniform_uvec_value_setter<4>(MGLUniform * self, PyObject * value); template int MGLUniform_vec_value_setter<2>(MGLUniform * self, PyObject * value); template int MGLUniform_vec_value_setter<3>(MGLUniform * self, PyObject * value); template int MGLUniform_vec_value_setter<4>(MGLUniform * self, PyObject * value); template int MGLUniform_dvec_value_setter<2>(MGLUniform * self, PyObject * value); template int MGLUniform_dvec_value_setter<3>(MGLUniform * self, PyObject * value); template int MGLUniform_dvec_value_setter<4>(MGLUniform * self, PyObject * value); template int MGLUniform_bvec_array_value_setter<2>(MGLUniform * self, PyObject * value); template int MGLUniform_bvec_array_value_setter<3>(MGLUniform * self, PyObject * value); template int MGLUniform_bvec_array_value_setter<4>(MGLUniform * self, PyObject * value); template int MGLUniform_ivec_array_value_setter<2>(MGLUniform * self, PyObject * value); template int MGLUniform_ivec_array_value_setter<3>(MGLUniform * self, PyObject * value); template int MGLUniform_ivec_array_value_setter<4>(MGLUniform * self, PyObject * value); template int MGLUniform_uvec_array_value_setter<2>(MGLUniform * self, PyObject * value); template int MGLUniform_uvec_array_value_setter<3>(MGLUniform * self, PyObject * value); template int MGLUniform_uvec_array_value_setter<4>(MGLUniform * self, PyObject * value); template int MGLUniform_vec_array_value_setter<2>(MGLUniform * self, PyObject * value); template int MGLUniform_vec_array_value_setter<3>(MGLUniform * self, PyObject * value); template int MGLUniform_vec_array_value_setter<4>(MGLUniform * self, PyObject * value); template int MGLUniform_dvec_array_value_setter<2>(MGLUniform * self, PyObject * value); template int MGLUniform_dvec_array_value_setter<3>(MGLUniform * self, PyObject * value); template int MGLUniform_dvec_array_value_setter<4>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<float, 2, 2>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<float, 2, 3>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<float, 2, 4>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<float, 3, 2>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<float, 3, 3>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<float, 3, 4>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<float, 4, 2>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<float, 4, 3>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<float, 4, 4>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<double, 2, 2>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<double, 2, 3>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<double, 2, 4>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<double, 3, 2>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<double, 3, 3>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<double, 3, 4>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<double, 4, 2>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<double, 4, 3>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_value_setter<double, 4, 4>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<float, 2, 2>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<float, 2, 3>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<float, 2, 4>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<float, 3, 2>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<float, 3, 3>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<float, 3, 4>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<float, 4, 2>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<float, 4, 3>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<float, 4, 4>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<double, 2, 2>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<double, 2, 3>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<double, 2, 4>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<double, 3, 2>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<double, 3, 3>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<double, 3, 4>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<double, 4, 2>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<double, 4, 3>(MGLUniform * self, PyObject * value); template int MGLUniform_matrix_array_value_setter<double, 4, 4>(MGLUniform * self, PyObject * value);
[ "cprogrammer1994@gmail.com" ]
cprogrammer1994@gmail.com
4590dc9f5807c34daaf8735f6ef67a6b8bd09926
7ce91a98ae434dbb48099699b0b6bcaa705ba693
/TestModule/HK1/Users/20110301/BAI4.CPP
67f7c5b5a3033b841d7f19f93d52fdd9ae7478ee
[]
no_license
ngthvan1612/OJCore
ea2e33c1310c71f9375f7c5cd0a7944b53a1d6bd
3ec0752a56c6335967e5bb4c0617f876caabecd8
refs/heads/master
2023-04-25T19:41:17.050412
2021-05-12T05:29:40
2021-05-12T05:29:40
357,612,534
0
0
null
null
null
null
UTF-8
C++
false
false
954
cpp
#include<stdio.h> void nhap(int A[][100], int &m, int &n); int laNT(int a); void tinhTong(int A[][100], int B[], int m, int n, int &nB); int timMin(int B[], int nB); void xuat(int kq); int main(){ int A[100][100]; int B[100]; int nB; int m,n; nhap(A,m,n); tinhTong(A,B,m,n,nB); int kq = timMin(B,nB); xuat(kq); return 0; } void nhap(int A[][100], int &m, int &n){ scanf("%d%d", &m,&n); for (int i=0; i<m; i++) for (int j=0; j<n; j++) scanf("%d", &A[i][j]); } void xuat(int kq){ printf("%d", kq); } void tinhTong(int A[][100], int B[], int m, int n, int &nB){ nB=0; int i=0; while (i<m){ int s=0; for (int j=0; j<n; j++){ if (laNT(A[i][j])==1) s+=A[i][j]; } B[nB++]=s; i++; } } int timMin(int B[], int nB){ int min=B[0]; for (int i=0; i<nB; i++) if (B[i]<min) min=B[i]; return min; } int laNT(int a){ int d=0; for (int i=1; i<=a; i++) if (a%i==0) d++; if (d==2) return 1; else return 0; }
[ "Nguyen Van@DESKTOP-8HI58DE" ]
Nguyen Van@DESKTOP-8HI58DE
b18c5d0283acd24227523705219756242d9fe58c
69dd4bd4268e1c361d8b8d95f56b5b3f5264cc96
/GPU Pro1/10_Beyond Pixels & Triangles/05_Real-Time Interaction between Particles and Dynamic Mesh on GPU/DVD/Code/Deps/FBX/include/kfbxplugins/kfbxsubdeformer.h
ca595bc2b8225402c261ee6a6882560b7fcaee89
[ "MIT" ]
permissive
AnabaenaQing/Source-Code_ShaderX_GPU-Pro_GPU-Zen
65c16710d1abb9207fd7e1116290336a64ddfc86
f442622273c6c18da36b61906ec9acff3366a790
refs/heads/master
2022-12-15T00:40:42.931271
2020-09-07T16:48:25
2020-09-07T16:48:25
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
5,073
h
/*! \file kfbxsubdeformer.h */ #ifndef _FBXSDK_SUB_DEFORMER_H_ #define _FBXSDK_SUB_DEFORMER_H_ /************************************************************************************** Copyright © 2001 - 2008 Autodesk, Inc. and/or its licensors. All Rights Reserved. The coded instructions, statements, computer programs, and/or related material (collectively the "Data") in these files contain unpublished information proprietary to Autodesk, Inc. and/or its licensors, which is protected by Canada and United States of America federal copyright law and by international treaties. The Data may not be disclosed or distributed to third parties, in whole or in part, without the prior written consent of Autodesk, Inc. ("Autodesk"). THE DATA IS PROVIDED "AS IS" AND WITHOUT WARRANTY. ALL WARRANTIES ARE EXPRESSLY EXCLUDED AND DISCLAIMED. AUTODESK MAKES NO WARRANTY OF ANY KIND WITH RESPECT TO THE DATA, EXPRESS, IMPLIED OR ARISING BY CUSTOM OR TRADE USAGE, AND DISCLAIMS ANY IMPLIED WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR USE. WITHOUT LIMITING THE FOREGOING, AUTODESK DOES NOT WARRANT THAT THE OPERATION OF THE DATA WILL BE UNINTERRUPTED OR ERROR FREE. IN NO EVENT SHALL AUTODESK, ITS AFFILIATES, PARENT COMPANIES, LICENSORS OR SUPPLIERS ("AUTODESK GROUP") BE LIABLE FOR ANY LOSSES, DAMAGES OR EXPENSES OF ANY KIND (INCLUDING WITHOUT LIMITATION PUNITIVE OR MULTIPLE DAMAGES OR OTHER SPECIAL, DIRECT, INDIRECT, EXEMPLARY, INCIDENTAL, LOSS OF PROFITS, REVENUE OR DATA, COST OF COVER OR CONSEQUENTIAL LOSSES OR DAMAGES OF ANY KIND), HOWEVER CAUSED, AND REGARDLESS OF THE THEORY OF LIABILITY, WHETHER DERIVED FROM CONTRACT, TORT (INCLUDING, BUT NOT LIMITED TO, NEGLIGENCE), OR OTHERWISE, ARISING OUT OF OR RELATING TO THE DATA OR ITS USE OR ANY OTHER PERFORMANCE, WHETHER OR NOT AUTODESK HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGE. **************************************************************************************/ #include <kaydaradef.h> #ifndef KFBX_DLL #define KFBX_DLL K_DLLIMPORT #endif #include <kaydara.h> #include <kfbxplugins/kfbxtakenodecontainer.h> #include <kfbxplugins/kfbxgroupname.h> #include <kfbxmath/kfbxmatrix.h> #include <klib/kerror.h> #include <kbaselib_forward.h> #include <fbxfilesdk_nsbegin.h> class KFbxGeometry; class KFbxSdkManager; /** FBX SDK subdeformer class * \nosubgrouping */ class KFBX_DLL KFbxSubDeformer : public KFbxTakeNodeContainer { KFBXOBJECT_DECLARE(KFbxSubDeformer,KFbxTakeNodeContainer); public: /** Set multi layer state flag. * \param pMultiLayer If \c true, multi-layering is enabled. */ void SetMultiLayer(bool pMultiLayer); /** Get multilayer state. * \return The state of the multi-layer flag. */ bool GetMultiLayer(); /** \enum ESubDeformerType SubDeformer types. * - \e eCLUSTER */ typedef enum { eUNIDENTIFIED, eCLUSTER, eSUBDEFORMER_COUNT } ESubDeformerType; /** Get the type of the sub deformer. * \return SubDeformer type identifier. */ virtual ESubDeformerType GetSubDeformerType() { return eUNIDENTIFIED; } /** * \name Error Management */ //@{ /** Retrieve error object. * \return Reference to error object. */ KError& GetError(); /** \enum EError Error identifiers. * - \e eERROR */ typedef enum { eERROR, eERROR_COUNT } EError; /** Get last error code. * \return Last error code. */ EError GetLastErrorID() const; /** Get last error string. * \return Textual description of the last error. */ const char* GetLastErrorString() const; //@} /////////////////////////////////////////////////////////////////////////////// // // WARNING! // // Anything beyond these lines may not be documented accurately and is // subject to change without notice. // /////////////////////////////////////////////////////////////////////////////// protected: KFbxSubDeformer(KFbxSdkManager& pManager, char const* pName); virtual ~KFbxSubDeformer(); virtual KString GetTypeName() const { return KString(""); } virtual KStringList GetTypeFlags() const { return KStringList(); } // Local KError mError; bool mMultiLayer; friend class KFbxGeometry; friend class KFbxReaderFbx; friend class KFbxReaderFbx6; friend class KFbxWriterFbx; friend class KFbxWriterFbx6; friend class KFbxScene; }; typedef KFbxSubDeformer* HKFbxSubDeformer; #include <fbxfilesdk_nsend.h> #endif // _FBXSDK_SUB_DEFORMER_H_
[ "IRONKAGE@gmail.com" ]
IRONKAGE@gmail.com
8ef7fda4069cdc3b570f9ce646b54f08025170fb
f5bd250b8bbd0977e262e8e2d79f0a9829cc0813
/test/server/serverapp.cpp
955c3d09f7d9423f1ce8667cd5f7b9efc40c76f5
[]
no_license
itbestbear/fakengine
0d56599ebbecb32c26fae63723582b220f05e9fa
46490fee5ad6be9c956e9e1c7368936e11e0350a
refs/heads/master
2022-01-18T17:08:11.045106
2019-05-09T08:27:06
2019-05-09T08:27:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
583
cpp
#include "fakengine.h" #include "serverapp.h" bool serverapp::ini( int argc, char *argv[] ) { mycmdparser cp; cp.parse(argc, argv); stringc ip; cp.get("ip", ip); int32_t port; cp.get("port", port); LOG_DEBUG("%s:%d", ip.c_str(), port); tcp_socket_server_param param; bool ret = m_mynetserver.ini(param); if (!ret) { return false; } return true; } bool serverapp::heartbeat() { m_mynetserver.tick(); return true; } bool serverapp::exit() { return true; } serverapp::serverapp() : mainapp("serverapp") { }
[ "esrrhs@localhost" ]
esrrhs@localhost
82609212c365f8e395a4b66971ac17c2efa84a83
25bda6c3a9eaf9b33c03f4210291ebc8fc2a8643
/challenge.h
8d2976dbea5c41a7001669d3885e00154383ca07
[ "MIT" ]
permissive
DKDouzi/OrderManager
dc279d4a48684f3c00e8072df56e8eead46d3e7b
7606392d651dd13460e2628261be5cf07efad8c6
refs/heads/master
2020-04-07T04:13:51.160013
2018-11-18T09:26:05
2018-11-18T09:26:05
158,045,964
2
0
null
null
null
null
UTF-8
C++
false
false
1,932
h
#pragma once #include <stdint.h> #include <string> // company's order identifier struct OrderIdentifier { OrderIdentifier() = default; OrderIdentifier(uint16_t m, uint16_t d, uint16_t t, uint32_t s) : _market(m) , _desk(d) , _trader(t) , _sequence(s) {} uint16_t _market{ 0 }; uint16_t _desk{ 0 }; uint16_t _trader{ 0 }; uint32_t _sequence{ 0 }; // increments with each order from a particular trader }; // // The order router will call these methods as it receives order operations from the // trader and exchange. // Note: // 1. Thread safety needs to be considered for your implementation of this class: e.g. // - OnTraderXXX may be called from different threads // - You can assume OnExchangeXXX will only be called from a single thread. // - But OnTraderXXX and OnExchangeXXX maybe called from different threads. // 2. Performance, in terms of latency, of all the interface functions are important. // class IOrderManager { public: // trader operations - these return false if there is a problem virtual bool OnTraderEnter(const OrderIdentifier& aInternal, uint32_t aPrice, uint32_t aQuantity) = 0; virtual bool OnTraderCancel(const OrderIdentifier& aInternal) = 0; // exchange operations - these return false if there is a problem virtual bool OnExchangeNew(const OrderIdentifier& aInternal, const std::string& aExternal) = 0; virtual bool OnExchangeTrade(const std::string& aExternal, uint32_t aQuantity) = 0; virtual bool OnExchangeCancel(const std::string& aExternal) = 0; virtual bool IsOrderActive(const OrderIdentifier& aInternal) const = 0; virtual bool IsOrderActive(const std::string& aExternal) const = 0; // returns the quantity of the order that is active in the market, // or zero if the order isn't recognised or is not active virtual uint32_t GetActiveOrderQuantity(const OrderIdentifier& aInternal) const = 0; };
[ "noreply@github.com" ]
DKDouzi.noreply@github.com
1b40c575a4e710dd872febe98362d6f9339270b5
422090af64ce3038241344e5529abf334db45471
/Plugins/VictoryPlugin/Source/VictoryBPLibrary/Public/VictoryBPFunctionLibrary.h
2fc999677f4e38aeae56af73f26e9e90c184c8e9
[ "MIT" ]
permissive
QuinnSixense/EditSaber
92c49b0fa9cd32080285bef93217ea6b0f14f787
ce0e728064bb356e9a86b4d3e50ca89d824faa5d
refs/heads/master
2021-05-27T01:30:53.665206
2020-04-08T21:23:32
2020-04-08T21:23:32
254,201,766
0
0
MIT
2020-04-08T21:12:37
2020-04-08T21:12:37
null
UTF-8
C++
false
false
106,080
h
/* By Rama */ #pragma once //to prevent nodes from getting called in constructors: //meta=(UnsafeDuringActorConstruction = "true") #include "VictoryISM.h" //~~~~~~~~~~~~ UMG ~~~~~~~~~~~~~~~ #include "Runtime/UMG/Public/UMG.h" #include "Runtime/UMG/Public/UMGStyle.h" #include "Runtime/UMG/Public/Slate/SObjectWidget.h" #include "Runtime/UMG/Public/IUMGModule.h" #include "Runtime/UMG/Public/Blueprint/UserWidget.h" //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //AI #include "AIController.h" //MoveToWithFilter //Audio #include "Components/AudioComponent.h" #include "AudioDecompress.h" #include "AudioDevice.h" #include "ActiveSound.h" #include "Audio.h" #include "Developer/TargetPlatform/Public/Interfaces/IAudioFormat.h" #include "VorbisAudioInfo.h" //Texture2D //#include "Engine/Texture2D.h" #include "DDSLoader.h" //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #include "VictoryBPFunctionLibrary.generated.h" // BP Library for You // // Written by Rama //note about UBlueprintFunctionLibrary // This class is a base class for any function libraries exposed to blueprints. // Methods in subclasses are expected to be static, and no methods should be added to the base class. //~~~~~~~~~~~~~~~~~~~~~~ // Key Modifiers //~~~~~~~~~~~~~~~~~~~~~~ UENUM(BlueprintType) enum class EJoyImageFormats : uint8 { JPG UMETA(DisplayName="JPG "), PNG UMETA(DisplayName="PNG "), BMP UMETA(DisplayName="BMP "), ICO UMETA(DisplayName="ICO "), EXR UMETA(DisplayName="EXR "), ICNS UMETA(DisplayName="ICNS ") }; //! REMOVE THIS AFTER A FEW VERSIONS //! //! UENUM(BlueprintType) enum class EVictoryHMDDevice : uint8 { None UMETA(DisplayName="None"), OculusRift UMETA(DisplayName="Oculus Rift"), Morpheus UMETA(DisplayName="Morpheus"), ES2GenericStereoMesh UMETA(DisplayName="ES2 Generic Stereo Mesh"), SteamVR UMETA(DisplayName="Vive (Steam VR)"), GearVR UMETA(DisplayName="Gear VR") }; USTRUCT(BlueprintType) struct FVictoryInput { GENERATED_USTRUCT_BODY() UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Input Song") FString ActionName; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Input Song") FKey Key; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Input Song") FString KeyAsString; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Input Song") uint32 bShift:1; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Input Song") uint32 bCtrl:1; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Input Song") uint32 bAlt:1; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Input Song") uint32 bCmd:1; FVictoryInput(){} FVictoryInput(const FString InActionName, const FKey InKey, const bool bInShift, const bool bInCtrl, const bool bInAlt, const bool bInCmd) : Key(InKey) , KeyAsString(InKey.GetDisplayName().ToString()) , bShift(bInShift) , bCtrl(bInCtrl) , bAlt(bInAlt) , bCmd(bInCmd) { ActionName = InActionName; } FVictoryInput(const FInputActionKeyMapping& Action) : Key(Action.Key) , KeyAsString(Action.Key.GetDisplayName().ToString()) , bShift(Action.bShift) , bCtrl(Action.bCtrl) , bAlt(Action.bAlt) , bCmd(Action.bCmd) { ActionName = Action.ActionName.ToString(); } }; USTRUCT(BlueprintType) struct FVictoryInputAxis { GENERATED_USTRUCT_BODY() UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Input Song") FString AxisName = ""; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Input Song") FString KeyAsString = ""; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Input Song") FKey Key; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Input Song") float Scale = 1; FVictoryInputAxis(){} FVictoryInputAxis(const FString InAxisName, FKey InKey, float InScale) : AxisName(InAxisName) , KeyAsString(InKey.GetDisplayName().ToString()) , Key(InKey) , Scale(InScale) { } FVictoryInputAxis(const FInputAxisKeyMapping& Axis) : KeyAsString(Axis.Key.GetDisplayName().ToString()) , Key(Axis.Key) , Scale(Axis.Scale) { AxisName = Axis.AxisName.ToString(); } }; UENUM(BlueprintType) namespace EJoyGraphicsFullScreen { //256 entries max enum Type { FullScreen UMETA(DisplayName="Regular Full Screen"), WindowedFullScreen UMETA(DisplayName="Windowed Full Screen High Quality"), WindowedFullScreenPerformance UMETA(DisplayName="Windowed Full Screen (Default)"), //~~~ //256th entry EJoyGraphicsFullScreen_Max UMETA(Hidden), }; } USTRUCT(BlueprintType) struct FLevelStreamInstanceInfo { GENERATED_USTRUCT_BODY() UPROPERTY(Category = "LevelStreaming", BlueprintReadWrite) FName PackageName; UPROPERTY(Category = "LevelStreaming", BlueprintReadWrite) FName PackageNameToLoad; UPROPERTY(Category = "LevelStreaming", BlueprintReadWrite) FVector Location; UPROPERTY(Category = "LevelStreaming", BlueprintReadWrite) FRotator Rotation; UPROPERTY(Category = "LevelStreaming", BlueprintReadWrite) uint8 bShouldBeLoaded:1; UPROPERTY(Category = "LevelStreaming", BlueprintReadWrite) uint8 bShouldBeVisible:1; UPROPERTY(Category = "LevelStreaming", BlueprintReadWrite) uint8 bShouldBlockOnLoad:1; UPROPERTY(Category = "LevelStreaming", BlueprintReadWrite) int32 LODIndex; FLevelStreamInstanceInfo() {} FLevelStreamInstanceInfo(ULevelStreamingKismet* LevelInstance); FString ToString() const { return FString::Printf(TEXT("PackageName: %s\nPackageNameToLoad:%s\nLocation:%s\nRotation:%s\nbShouldBeLoaded:%s\nbShouldBeVisible:%s\nbShouldBlockOnLoad:%s\nLODIndex:%i") , *PackageName.ToString() , *PackageNameToLoad.ToString() , *Location.ToString() , *Rotation.ToString() , (bShouldBeLoaded) ? TEXT("True") : TEXT("False") , (bShouldBeVisible) ? TEXT("True") : TEXT("False") , (bShouldBlockOnLoad) ? TEXT("True") : TEXT("False") , LODIndex); } }; UCLASS() class VICTORYBPLIBRARY_API UVictoryBPFunctionLibrary : public UBlueprintFunctionLibrary { GENERATED_UCLASS_BODY() //~~~~~~~~~~~~~~~~~~ // Level Generation //~~~~~~~~~~~~~~~~~~ /** Load a level to a specific location and rotation, can create multiple of the same level! * * Ensure that each InstanceNumber is unique to spawn multiple instances of the same level! * * <3 Rama * * @param MapFolderOffOfContent - Maps or Maps/TileSets/TileSet1 etc * @param LevelName - Just the level name itself, such as Tile1 * @param InstanceNumber - Ensure this is unique by keeping count to spawn as many instances of same level as you want! * @param Location - Worldspace location where the level should be spawned * @param Rotation - Worldspace rotation for rotating the entire level * @return false if the level name was not found */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Dynamic Level Generation",meta=(DeprecatedFunction, DeprecationMessage="My LoadLevelInstance BP node is in the main UE4 Engine as of 4.13! This version is deprecated and will be removed in the near future. <3 -Rama",WorldContext="WorldContextObject")) static ULevelStreaming* VictoryLoadLevelInstance(UObject* WorldContextObject, FString MapFolderOffOfContent, FString LevelName, int32 InstanceNumber, FVector Location, FRotator Rotation,bool& Success); //~~~~~~~~~~ // AI //~~~~~~~~~~ /** Move to Location with optional Query Filter! * * 1. Create Custon Nav Area Classes. * * 2. Use Nav Modifier Volumes to apply custom area class data within the level, then * * 3. Create Query Filters which alter/exclude those custom nav areas. * * 4. Can then choose to use the filters per character or even per Move To using this node. * * <3 Rama * * @param FilterClass - Allows different types of units to path in different ways all the time, or path differently per Move To using this node! * @param bProjectDestinationToNavigation - Whether to attempt to find a nearby point on the nav mesh below/above/close to the supplied point. Uses the Agent's Nav Extent for the projection * @param bStopOnOverlap - Add pawn's radius to AcceptanceRadius * @param bCanStrafe - Set focus related flag: bAllowStrafe * @return Whether the Pawn's AI Controller is valid and goal can be pathed to */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|AI") static EPathFollowingRequestResult::Type Victory_AI_MoveToWithFilter( APawn* Pawn, const FVector& Dest, TSubclassOf<UNavigationQueryFilter> FilterClass = NULL, float AcceptanceRadius = 0, bool bProjectDestinationToNavigation = false, bool bStopOnOverlap = false, bool bCanStrafe = false ); //~~~~~~~~~~~~~~~~ // GPU <3 Rama //~~~~~~~~~~~~~~~~ UFUNCTION(BlueprintPure,Category="Victory BP Library|GPU") static FString Victory_GetGPUBrand() { return FPlatformMisc::GetPrimaryGPUBrand(); } UFUNCTION(BlueprintPure,Category="Victory BP Library|GPU", meta=(Keywords="GPU")) static FString Victory_GetGRHIAdapterName() { return GRHIAdapterName; } UFUNCTION(BlueprintPure,Category="Victory BP Library|GPU") static void Victory_GetGPUInfo(FString& DeviceDescription, FString& Provider, FString& DriverVersion, FString& DriverDate); //~~~~~~~~~~ // Core //~~~~~~~~~~ /** Launch a new process, if it is not set to be detached, UE4 will not fully close until the other process completes. The new process id is returned! Priority options: -2 idle, -1 low, 0 normal, 1 high, 2 higher ♥ Rama */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|System") static void VictoryCreateProc(int32& ProcessId, FString FullPathOfProgramToRun,TArray<FString> CommandlineArgs,bool Detach,bool Hidden, int32 Priority=0, FString OptionalWorkingDirectory=""); /** You can obtain ProcessID from processes you initiate via VictoryCreateProc */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|System") static FString VictoryGetApplicationName(int32 ProcessId) { //Please note it should really be uint32 but that is not supported by BP yet return FPlatformProcess::GetApplicationName(ProcessId); } /** You can obtain ProcessID from processes you initiate via VictoryCreateProc */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|System") static bool VictoryIsApplicationRunning( int32 ProcessId ) { //Please note it should really be uint32 but that is not supported by BP yet return FPlatformProcess::IsApplicationRunning(ProcessId); } /* Blueprints does not support int64 so at some pt in future int32 will not be enough, probably by then dolphins will rule the world, or UE4 BP will support int64, or both! <3 Rama*/ UFUNCTION(BlueprintPure, Category = "Victory BP Library|System") static int32 GetUnixTimeStamp(const FDateTime& UTCTime) { //Please note it should really be int64 but that is not supported by BP yet return UTCTime.ToUnixTimestamp(); } /* Blueprints does not support int64 so at some pt in future int32 will not be enough, probably by then dolphins will rule the world, or UE4 BP will support int64, or both! <3 Rama*/ UFUNCTION(BlueprintPure, Category = "Victory BP Library|System") static void GetUTCFromUnixTimeStamp(int32 UnixTimeStamp, FDateTime& UTCTime) { //Please note it should really be int64 but that is not supported by BP yet UTCTime = FDateTime::FromUnixTimestamp( UnixTimeStamp ); } UFUNCTION(BlueprintPure, Category = "Rama Save System|File IO") static void UTCToLocal(const FDateTime& UTCTime, FDateTime& LocalTime) { //Turn UTC into local ♥ Rama FTimespan UTCOffset = FDateTime::Now() - FDateTime::UtcNow(); LocalTime = UTCTime; LocalTime += UTCOffset; //♥ Rama } /** Game thread may pause while hashing is ocurring. Please note that hashing multi-gb size files is very very slow, smaller files will process much faster :) <3 Rama*/ UFUNCTION(BlueprintCallable,Category="Victory BP Library|MD5") static bool CreateMD5Hash(FString FileToHash, FString FileToStoreHashTo ); /** Game thread may pause while hashing is ocurring. Please note that hashing multi-gb size files is very very slow, smaller files will process much faster :) <3 Rama */ UFUNCTION(BlueprintCallable,Category="Victory BP Library|MD5") static bool CompareMD5Hash(FString MD5HashFile1, FString MD5HashFile2 ); /** Dynamically change how frequently in seconds a component will tick! Can be altered at any point during game-time! ♥ Rama */ UFUNCTION(BlueprintCallable,Category="Victory BP Library|System") static void SetComponentTickRate(UActorComponent* Component, float Seconds) { if(!Component) return; Component->PrimaryComponentTick.TickInterval = Seconds; } /** Retrieves command line arguments that were passed into unreal */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|System") static const FString GetCommandLine() { return FCommandLine::Get(); } /** * Create a new Texture Render Target 2D, ideal for use with Scene Capture Components created during runtime that need their own unique Render Targets * @param Width Texture Width * @param Height Texture Height * @param ClearColor The color the texture is cleared to * @param Gamma Will override FTextureRenderTarget2DResource::GetDisplayGamma if > 0. * @return A new Texture Render Target 2D! * */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Misc") static UTextureRenderTarget2D* CreateTextureRenderTarget2D(int32 Width=256, int32 Height=256, FLinearColor ClearColor = FLinearColor::White, float Gamma = 1) { UTextureRenderTarget2D* NewRenderTarget2D = NewObject<UTextureRenderTarget2D>(); if(!NewRenderTarget2D) { return nullptr; } NewRenderTarget2D->ClearColor = FLinearColor::White; NewRenderTarget2D->TargetGamma = Gamma; NewRenderTarget2D->InitAutoFormat(Width, Height); return NewRenderTarget2D; } //~~~~~~~~~~ // Physics //~~~~~~~~~~ /** Update the Angular Damping during runtime! Make sure the component is simulating physics before calling this! Returns false if the new value could not be set. */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Physics") static bool VictoryPhysics_UpdateAngularDamping(UPrimitiveComponent* CompToUpdate, float NewAngularDamping); UFUNCTION(BlueprintPure, Category = "Victory BP Library|Physics", meta=(Keywords="Closest Surface")) static float GetDistanceToCollision(UPrimitiveComponent* CollisionComponent, const FVector& Point, FVector& ClosestPointOnCollision); UFUNCTION(BlueprintPure, Category = "Victory BP Library|Physics", meta=(Keywords="Closest Surface")) static float GetDistanceBetweenComponentSurfaces(UPrimitiveComponent* CollisionComponent1, UPrimitiveComponent* CollisionComponent2, FVector& PointOnSurface1, FVector& PointOnSurface2); UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Physics", meta=(Keywords="APEX Piece fracture damage PhysX Physics")) static bool VictoryDestructible_DestroyChunk(UDestructibleComponent* DestructibleComp, int32 HitItem); //~~~~~~~~~~ // Joy ISM //~~~~~~~~~~ /** Retrieve an array of all of the Victory Instanced Static Mesh Actors that have been created during runtime! */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Instanced Static Mesh",meta=(WorldContext="WorldContextObject")) static void VictoryISM_GetAllVictoryISMActors(UObject* WorldContextObject, TArray<AVictoryISM*>& Out); /** Finds all instances of a specified Blueprint or class, and all subclasses of this class, and converts them into a single Instanced Static Mesh Actor! Returns the created Victory ISM actors. Please note all actors of subclasses are found as well, so use a very specific blueprint / class if you only want to generate Victory ISM actors for specific classes! Ignores actor classes that dont have a static mesh component. Please note that instanced static mesh actors can only be created for actors sharing the same static mesh asset. Different Instanced Static Mesh Actors are created for each unique static mesh asset found in the whole group of actors! */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Instanced Static Mesh",meta=(WorldContext="WorldContextObject")) static void VictoryISM_ConvertToVictoryISMActors(UObject* WorldContextObject, TSubclassOf<AActor> ActorClass, TArray<AVictoryISM*>& CreatedISMActors, bool DestroyOriginalActors=true, int32 MinCountToCreateISM=2); //~~~~~~~~~~ // File I/O //~~~~~~~~~~ /** Obtain all files in a provided directory, with optional extension filter. All files are returned if Ext is left blank. Returns false if operation could not occur. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|File IO") static bool JoyFileIO_GetFiles(TArray<FString>& Files, FString RootFolderFullPath, FString Ext); /** Obtain all files in a provided root directory, including all subdirectories, with optional extension filter. All files are returned if Ext is left blank. The full file path is returned because the file could be in any subdirectory. Returns false if operation could not occur. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|File IO") static bool JoyFileIO_GetFilesInRootAndAllSubFolders(TArray<FString>& Files, FString RootFolderFullPath, FString Ext); /** Obtain a listing of all SaveGame file names that were saved using the Blueprint Save Game system. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|File IO") static void SaveGameObject_GetAllSaveSlotFileNames(TArray<FString>& FileNames); /** Returns false if the new file could not be created. The folder path must be absolute, such as C:\Users\Self\Documents\YourProject\MyPics. You can use my other Paths nodes to easily get absolute paths related to your project! <3 Rama */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Screenshots", meta=(Keywords="High resolution")) static bool ScreenShots_Rename_Move_Most_Recent(FString& OriginalFileName, FString NewName, FString NewAbsoluteFolderPath, bool HighResolution=true); //~~~~ Key Re Binding ! ~~~~ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Key Rebinding") static void VictoryGetAllAxisAndActionMappingsForKey(FKey Key, TArray<FVictoryInput>& ActionBindings, TArray<FVictoryInputAxis>& AxisBindings); // Axis Mapping UFUNCTION(BlueprintPure, Category = "Victory BP Library|Key Rebinding") static FVictoryInputAxis VictoryGetVictoryInputAxis(const FKeyEvent& KeyEvent); UFUNCTION(BlueprintPure, Category = "Victory BP Library|Key Rebinding") static void VictoryGetAllAxisKeyBindings(TArray<FVictoryInputAxis>& Bindings); UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Key Rebinding") static void VictoryRemoveAxisKeyBind(FVictoryInputAxis ToRemove); /** You can leave the AsString field blank :) Returns false if the key could not be found as an existing mapping! Enjoy! <3 Rama */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Key Rebinding") static bool VictoryReBindAxisKey(FVictoryInputAxis Original, FVictoryInputAxis NewBinding); static FORCEINLINE void UpdateAxisMapping(FInputAxisKeyMapping& Destination, const FVictoryInputAxis& VictoryInputBind) { Destination.Key = VictoryInputBind.Key; Destination.Scale = VictoryInputBind.Scale; } // Action Mapping UFUNCTION(BlueprintPure, Category = "Victory BP Library|Key Rebinding") static FVictoryInput VictoryGetVictoryInput(const FKeyEvent& KeyEvent); static FORCEINLINE void UpdateActionMapping(FInputActionKeyMapping& Destination, const FVictoryInput& VictoryInputBind) { Destination.Key = VictoryInputBind.Key; Destination.bShift = VictoryInputBind.bShift; Destination.bCtrl = VictoryInputBind.bCtrl; Destination.bAlt = VictoryInputBind.bAlt; Destination.bCmd = VictoryInputBind.bCmd; } UFUNCTION(BlueprintPure, Category = "Victory BP Library|Key Rebinding") static void VictoryGetAllActionKeyBindings(TArray<FVictoryInput>& Bindings); /** You can leave the AsString field blank :) Returns false if the key could not be found as an existing mapping! Enjoy! <3 Rama */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Key Rebinding") static bool VictoryReBindActionKey(FVictoryInput Original, FVictoryInput NewBinding); UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Key Rebinding") static void VictoryRemoveActionKeyBind(FVictoryInput ToRemove); //~~~~~~~~~~~~~~~~~~~~ /** Change volume of Sound class of your choosing, sets the volume instantly! Returns false if the sound class was not found and volume was not set. */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Sound") static bool VictorySoundVolumeChange(USoundClass* SoundClassObject, float NewVolume); /** Get Current Sound Volume! Returns -1 if sound class was not found*/ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Sound") static float VictoryGetSoundVolume(USoundClass* SoundClassObject); //~~~~~~~~~~~~~~~~~~~~ /** The number of seconds that this actor has been in play, relative to Get Game Time In Seconds. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Actor") static float GetTimeInPlay(AActor* Actor) { if(!Actor) return -1; UWorld* World = Actor->GetWorld(); //Use FApp Current Time as a back up float CurrentTime = (World) ? World->GetTimeSeconds() : FApp::GetCurrentTime(); return CurrentTime - Actor->CreationTime; } /** * Creates a plane centered on a world space point with a facing direction of Normal. * * @param Center The world space point the plane should be centered on (easy to observe with DrawDebugPlane) * @param Normal The facing direction of the plane (can receive a Rotator) * @return Plane coordinates */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Math|Plane", meta=(Keywords="make base plane")) static FPlane CreatePlane(FVector Center, FVector Normal) { return FPlane(Center,Normal); } /** >0: point is in front of the plane, <0: behind, =0: on the plane **/ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Math|Plane") static void PointDistanceToPlane(const FPlane& Plane, FVector Point,float& Distance) { Distance = Plane.PlaneDot(Point); } /** Use a larger tolerance to allow inaccuracy of measurement in certain situations */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Math|Plane") static bool IsPointOnPlane(const FPlane& Plane, FVector Point, float Tolerance= 0.01) { return FMath::Abs(Plane.PlaneDot(Point)) < Tolerance; } /** Easily add to an integer! <3 Rama*/ UFUNCTION(BlueprintCallable, meta = (CompactNodeTitle = "+=",Keywords = "increment integer"), Category = "Victory BP Library|Math|Integer") static void VictoryIntPlusEquals(UPARAM(ref) int32& Int, int32 Add, int32& IntOut); /** Easily subtract from an integer! <3 Rama*/ UFUNCTION(BlueprintCallable, meta = (CompactNodeTitle = "-=",Keywords = "decrement integer"), Category = "Victory BP Library|Math|Integer") static void VictoryIntMinusEquals(UPARAM(ref) int32& Int, int32 Sub, int32& IntOut); /** Easily add to a float! <3 Rama*/ UFUNCTION(BlueprintCallable, meta = (CompactNodeTitle = "+=",Keywords = "increment float"), Category = "Victory BP Library|Math|Float") static void VictoryFloatPlusEquals(UPARAM(ref) float& Float, float Add, float& FloatOut); /** Easily subtract from a float! <3 Rama*/ UFUNCTION(BlueprintCallable, meta = (CompactNodeTitle = "-=",Keywords = "decrement float"), Category = "Victory BP Library|Math|Float") static void VictoryFloatMinusEquals(UPARAM(ref) float& Float, float Sub, float& FloatOut); /** Sort an integer array, smallest value will be at index 0 after sorting. Modifies the input array, no new data created. <3 Rama */ UFUNCTION(BlueprintCallable, meta = (Keywords = "sort integer array"), Category = "Victory BP Library|Array") static void VictorySortIntArray(UPARAM(ref) TArray<int32>& IntArray, TArray<int32>& IntArrayRef); /** Sort a float array, smallest value will be at index 0 after sorting. Modifies the input array, no new data created. */ UFUNCTION(BlueprintCallable, meta = (Keywords = "sort float array"), Category = "Victory BP Library|Array") static void VictorySortFloatArray(UPARAM(ref) TArray<float>& FloatArray, TArray<float>& FloatArrayRef); /* Returns true if vector2D A is equal to vector2D B (A == B) within a specified error tolerance */ UFUNCTION(BlueprintPure, meta=(DisplayName = "Equal (vector2D)", CompactNodeTitle = "==", Keywords = "== equal"), Category="Victory BP Library|Math|Vector2D") static bool EqualEqual_Vector2DVector2D(FVector2D A, FVector2D B, float ErrorTolerance = 1.e-4f) { return A.Equals(B,ErrorTolerance); } /* Returns true if vector2D A is not equal to vector2D B (A != B) within a specified error tolerance */ UFUNCTION(BlueprintPure, meta=(DisplayName = "Not Equal (vector2D)", CompactNodeTitle = "!=", Keywords = "!= not equal"), Category="Victory BP Library|Math|Vector2D") static bool NotEqual_Vector2DVector2D(FVector2D A, FVector2D B, float ErrorTolerance = 1.e-4f) { return !A.Equals(B,ErrorTolerance); } //~~~ /** * Tries to reach Target based on distance from Current position, giving a nice smooth feeling when tracking a position. * * @param Current Actual position * @param Target Target position * @param DeltaTime Time since last tick * @param InterpSpeed Interpolation speed * @return New interpolated position */ //UFUNCTION(BlueprintPure, Category="Math|Interpolation", meta=(Keywords="position")) UFUNCTION(BlueprintPure, Category="Victory BP Library|Math", meta=(Keywords="position")) static FVector2D Vector2DInterpTo(FVector2D Current, FVector2D Target, float DeltaTime, float InterpSpeed); /** * Tries to reach Target at a constant rate. * * @param Current Actual position * @param Target Target position * @param DeltaTime Time since last tick * @param InterpSpeed Interpolation speed * @return New interpolated position */ //UFUNCTION(BlueprintPure, Category="Math|Interpolation", meta=(Keywords="position")) UFUNCTION(BlueprintPure, Category="Victory BP Library|Math", meta=(Keywords="position")) static FVector2D Vector2DInterpTo_Constant(FVector2D Current, FVector2D Target, float DeltaTime, float InterpSpeed); //~~~ Text To Number ~~~ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Conversion") static bool Text_IsNumeric(const FText& Text) { return Text.IsNumeric(); } UFUNCTION(BlueprintPure, Category = "Victory BP Library|Conversion", meta=(AdvancedDisplay = "1")) static float Text_ToFloat(const FText& Text, bool UseDotForThousands=false) { //because commas lead to string number being truncated, FText 10,000 becomes 10 for FString FString StrFloat = Text.ToString(); TextNumFormat(StrFloat,UseDotForThousands); return FCString::Atof(*StrFloat); } UFUNCTION(BlueprintPure, Category = "Victory BP Library|Conversion", meta=(AdvancedDisplay = "1")) static int32 Text_ToInt(const FText& Text, bool UseDotForThousands=false) { //because commas lead to string number being truncated, FText 10,000 becomes 10 for FString FString StrInt = Text.ToString(); TextNumFormat(StrInt,UseDotForThousands); return FCString::Atoi(*StrInt); } static void TextNumFormat(FString& StrNum, bool UseDotForThousands) { //10.000.000,997 if(UseDotForThousands) { StrNum.ReplaceInline(TEXT("."),TEXT("")); //no dots as they truncate StrNum.ReplaceInline(TEXT(","),TEXT(".")); //commas become decimal } //10,000,000.997 else { StrNum.ReplaceInline(TEXT(","),TEXT("")); //decimal can stay, commas would truncate so remove } } //~~~ End of Text To Number ~~~ /** Returns Value mapped from one range into another where the value is clamped to the output range. (e.g. 0.5 normalized from the range 0->1 to 0->50 would result in 25) */ UFUNCTION(BlueprintPure, Category="Victory BP Library|Math", meta=(Keywords = "get mapped value clamped")) static float MapRangeClamped(float Value, float InRangeA, float InRangeB, float OutRangeA, float OutRangeB); /** Server Travel! This is an async load level process which allows you to put up a UMG widget while the level loading occurs! */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|System",meta=(WorldContext="WorldContextObject")) static void ServerTravel(UObject* WorldContextObject,FString MapName, bool bNotifyPlayers=true); /** Get a Player Start by Name! */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|System",meta=(WorldContext="WorldContextObject")) static APlayerStart* GetPlayerStart(UObject* WorldContextObject,FString PlayerStartName); /** Convert String Back To Vector. IsValid indicates whether or not the string could be successfully converted. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Conversion",meta=(DisplayName = "String to Vector", CompactNodeTitle = "->")) static void Conversions__StringToVector(const FString& String, FVector& ConvertedVector, bool& IsValid); /** Convert String Back To Rotator. IsValid indicates whether or not the string could be successfully converted. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Conversion",meta=(DisplayName = "String to Rotator", CompactNodeTitle = "->")) static void Conversions__StringToRotator(const FString& String, FRotator& ConvertedRotator, bool& IsValid); /** Convert String Back To Color. IsValid indicates whether or not the string could be successfully converted. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Conversion",meta=(DisplayName = "String to Color", CompactNodeTitle = "->")) static void Conversions__StringToColor(const FString& String, FLinearColor& ConvertedColor, bool& IsValid); /** Convert Color to String! */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Conversion",meta=(DisplayName = "Color to String ", CompactNodeTitle = "~>")) static void Conversions__ColorToString(const FLinearColor& Color, FString& ColorAsString); /** Get Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ //UFUNCTION(BlueprintPure, Category = "Victory BP Library|Custom Config Vars!") //static uint8 Victory_ConvertStringToByte(UEnum* Enum,FString String); //! not working yet, always getting 255 /** Get Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Custom Config Vars") static bool VictoryGetCustomConfigVar_Bool(FString SectionName, FString VariableName, bool& IsValid); /** Get Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Custom Config Vars") static int32 VictoryGetCustomConfigVar_Int(FString SectionName, FString VariableName, bool& IsValid); /** Get Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Custom Config Vars") static float VictoryGetCustomConfigVar_Float(FString SectionName, FString VariableName, bool& IsValid); /** Get Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Custom Config Vars") static FVector VictoryGetCustomConfigVar_Vector(FString SectionName, FString VariableName, bool& IsValid); /** Get Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Custom Config Vars") static FRotator VictoryGetCustomConfigVar_Rotator(FString SectionName, FString VariableName, bool& IsValid); /** Get Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Custom Config Vars") static FLinearColor VictoryGetCustomConfigVar_Color(FString SectionName, FString VariableName, bool& IsValid); /** Get Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Custom Config Vars") static FString VictoryGetCustomConfigVar_String(FString SectionName, FString VariableName, bool& IsValid); UFUNCTION(BlueprintPure, Category = "Victory BP Library|Custom Config Vars") static FVector2D VictoryGetCustomConfigVar_Vector2D(FString SectionName, FString VariableName, bool& IsValid); //~~~~~~~~~~~~~~~~~~~~ /** Set Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Custom Config Vars") static void VictorySetCustomConfigVar_Vector2D(FString SectionName, FString VariableName, FVector2D Value); /** Set Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Custom Config Vars") static void VictorySetCustomConfigVar_Bool(FString SectionName, FString VariableName, bool Value); /** Set Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Custom Config Vars") static void VictorySetCustomConfigVar_Int(FString SectionName, FString VariableName, int32 Value); /** Set Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Custom Config Vars") static void VictorySetCustomConfigVar_Float(FString SectionName, FString VariableName, float Value); /** Set Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Custom Config Vars") static void VictorySetCustomConfigVar_Vector(FString SectionName, FString VariableName, FVector Value); /** Set Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Custom Config Vars") static void VictorySetCustomConfigVar_Rotator(FString SectionName, FString VariableName, FRotator Value); /** Set Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Custom Config Vars") static void VictorySetCustomConfigVar_Color(FString SectionName, FString VariableName, FLinearColor Value); /** Set Custom Config Var! These are stored in Saved/Config/Windows/Game.ini */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Custom Config Vars") static void VictorySetCustomConfigVar_String(FString SectionName, FString VariableName, FString Value); UFUNCTION(BlueprintPure, Category = "Victory BP Library|Transform") FRotator TransformVectorToActorSpaceAngle(AActor* Actor, const FVector& InVector); UFUNCTION(BlueprintPure, Category = "Victory BP Library|Transform") FVector TransformVectorToActorSpace(AActor* Actor, const FVector& InVector); UFUNCTION(BlueprintPure, Category = "Victory BP Library|UMG", meta=(keywords="HMD vive oculus rift gearvr morpheus")) static FName GetHeadMountedDisplayDeviceType(); /** The FName that is expected is the exact same format as when you right click on asset -> Copy Reference! You can directly paste copied references into this node! IsValid lets you know if the path was correct or not and I was able to load the object. MAKE SURE TO SAVE THE RETURNED OBJECT AS A VARIABLE. Otherwise your shiny new asset will get garbage collected. I recommend you cast the return value to the appropriate object and then promote it to a variable :) -Rama */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Misc") static UObject* LoadObjectFromAssetPath(TSubclassOf<UObject> ObjectClass, FName Path, bool& IsValid); /** Uses the same format as I use for LoadObjectFromAssetPath! Use this node to get the asset path of objects in the world! -Rama */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Misc") static FName GetObjectPath(UObject* Obj); /** Find all widgets of a certain class! Top level only means only widgets that are directly added to the viewport will be found */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|UMG", meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject", DeterminesOutputType = "WidgetClass", DynamicOutputParam = "FoundWidgets")) static void GetAllWidgetsOfClass(UObject* WorldContextObject, TSubclassOf<UUserWidget> WidgetClass, TArray<UUserWidget*>& FoundWidgets, bool TopLevelOnly = true); /** Remove all widgets of a certain class from viewport! */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|UMG", meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject")) static void RemoveAllWidgetsOfClass(UObject* WorldContextObject, TSubclassOf<UUserWidget> WidgetClass); UFUNCTION(BlueprintPure, Category = "Victory BP Library|UMG", meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject")) static bool IsWidgetOfClassInViewport(UObject* WorldContextObject, TSubclassOf<UUserWidget> WidgetClass); /** Handy helper to check if a Key Event was for specified Key ♥ Rama*/ UFUNCTION(BlueprintPure,Category="Victory BP Library|UMG", meta = (Keywords = "== match same equal")) static void JoyIsKey(const FKeyEvent& KeyEvent, FKey Key, bool& Ctrl, bool& Shift, bool& Alt, bool& Cmd, bool& Match) { Ctrl = KeyEvent.IsControlDown(); Alt = KeyEvent.IsAltDown(); Shift = KeyEvent.IsShiftDown(); Cmd = KeyEvent.IsCommandDown(); Match = KeyEvent.GetKey() == Key; } /** Retrieves the unique net ID for the local player as a number! The number itself will vary based on what Online Subsystem is being used, but you are guaranteed that this number is unique per player! */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Networking") static int32 GetPlayerUniqueNetID(); /** Call this periodically in a huge loop you are intentionally using to reset the BP runaway loop system. Caution, if you have an infinite loop this will permanently hang your system until you turn your computer off. Use very very carefully! When constructing a new loop and you are not sure if it is totally stable, do NOT use this node! Always test new loops normally to ensure you dont truly have a runaway loop that would hang your computer forever. */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Misc") static void Loops_ResetBPRunawayCounter(); /** Set the Max Frame Rate. Min value is 10. */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Graphics Settings") static void GraphicsSettings__SetFrameRateCap(float NewValue); /** Only hardware dependent, no smoothing */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Graphics Settings") static void GraphicsSettings__SetFrameRateToBeUnbound(); UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Misc") static FVector2D ProjectWorldToScreenPosition(const FVector& WorldLocation); /** Make sure to save off the return value as a global variable in one of your BPs or else it will get garbage collected! */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Misc", meta = (DeprecatedFunction, DeprecationMessage="Epic has introduced Construct Object as of 4.9.0, I recommend you use that instead! -Rama", HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject")) static UObject* CreateObject(UObject* WorldContextObject, UClass* TheObjectClass); /** Make sure to save off the return value as a global variable in one of your BPs or else it will get garbage collected! */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Misc", meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject")) static UPrimitiveComponent* CreatePrimitiveComponent(UObject* WorldContextObject, TSubclassOf<UPrimitiveComponent> CompClass, FName Name, FVector Location, FRotator Rotation); /** Spawn an Actor and choose which level you want them to spawn into! */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Actor", meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject")) static AActor* SpawnActorIntoLevel(UObject* WorldContextObject, TSubclassOf<AActor> ActorClass, FName Level = NAME_None, FVector Location = FVector::ZeroVector, FRotator Rotation = FRotator::ZeroRotator, bool SpawnEvenIfColliding = true); /** Get the names of all currently loaded and visible levels! */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|System", meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject")) static void GetNamesOfLoadedLevels(UObject* WorldContextObject, TArray<FString>& NamesOfLoadedLevels); /** Obtain the scaled,rotated, and translated vertex positions for any static mesh! Returns false if operation could not occur because the comp or static mesh asset was invalid. <3 Rama */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Actor") static bool GetStaticMeshVertexLocations(UStaticMeshComponent* Comp, TArray<FVector>& VertexPositions); UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Actor") static void AddToActorRotation(AActor* TheActor, FRotator AddRot); UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Misc", meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject")) static void DrawCircle( UObject* WorldContextObject, FVector Center, float Radius, int32 NumPoints = 32, float Thickness = 7, FLinearColor LineColor = FLinearColor::Red, FVector YAxis = FVector(0, 1, 0), FVector ZAxis = FVector(0, 0, 1), float Duration = 0, bool PersistentLines = false ); UFUNCTION(BlueprintPure, Category = "Victory BP Library|AI",meta=(WorldContext="WorldContextObject")) static AActor* GetClosestActorOfClassInRadiusOfLocation(UObject* WorldContextObject, TSubclassOf<AActor> ActorClass, FVector Center, float Radius, bool& IsValid); UFUNCTION(BlueprintPure, Category = "Victory BP Library|AI",meta=(WorldContext="WorldContextObject")) static AActor* GetClosestActorOfClassInRadiusOfActor(UObject* WorldContextObject, TSubclassOf<AActor> ActorClass, AActor* ActorCenter, float Radius, bool& IsValid); /** * Generates a box that is guaranteed to contain all of the supplied points. * * @param Points The world space points that the box will encompass. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Misc") static void GetBoxContainingWorldPoints(const TArray<FVector>& Points, FVector& Center, FVector& Extent) { FBox Box(ForceInit); for(const FVector& Each : Points) { Box += Each; } Center = Box.GetCenter(); Extent = Box.GetExtent(); } /** Implementation of a Selection Marquee / Selection Box as a BP Node. AnchorPoint is the first clicked point, which user then drags from to make the box. Class filter is optional way to narrow the scope of actors that can be selected by the selection box! -Rama*/ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Misc", meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject")) static void Selection_SelectionBox(UObject* WorldContextObject, TArray<AActor*>& SelectedActors, FVector2D AnchorPoint, FVector2D DraggedPoint, TSubclassOf<AActor> ClassFilter); /** Get the Controller ID for a supplied Player Controller <3 Rama. Returns false if operation could not occur. */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Controller") static bool PlayerController_GetControllerID(APlayerController* ThePC, int32& ControllerID); /** Get the Unique PlayerID from the PlayerState for a supplied Player Controller. Returns false if operation could not occur. Epic accepted my pull request for this a while back so now you can just GetPlayerState and directly access <3 Rama*/ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Networking") static bool PlayerState_GetPlayerID(APlayerController* ThePC, int32& PlayerID); /** Returns whether this game instance is single player. <3 Rama*/ UFUNCTION(BlueprintPure, Category="Victory BP Library|Networking", meta=(Keywords="SinglePlayer multiplayer", WorldContext="WorldContextObject")) static bool IsStandAlone(UObject* WorldContextObject) { UWorld* World = GEngine->GetWorldFromContextObjectChecked( WorldContextObject ); return World ? (World->GetNetMode() == NM_Standalone) : false; } /** Launches the specified URL in the OS default web browser :) <3 Rama */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|System") static void Open_URL_In_Web_Browser(FString TheURL); /** Returns which platform the game code is running in.*/ UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Victory BP Library|System") static void OperatingSystem__GetCurrentPlatform( bool& Windows_, bool& Mac, bool& Linux, bool& iOS, bool& Android, bool& Android_ARM, bool& Android_Vulkan, bool& PS4, bool& XBoxOne, bool& HTML5, bool& Apple ); //~~~ /** Retrieves the OS system Date and Time as a string at the instant this BP node runs. Use my other RealWorldTime node to get the time passed since the return value of this node! You can use this to record milliseconds/seconds/minutes/hours between events in game logic! */ UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Victory BP Library|System") static FString RealWorldTime__GetCurrentOSTime( int32& MilliSeconds, int32& Seconds, int32& Minutes, int32& Hours12, int32& Hours24, int32& Day, int32& Month, int32& Year ); /** Get the amount of seconds/minutes/hours since the the supplied DateTime string! You can use this to record milliseconds/seconds/minutes/hours between events in game logic! */ UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Victory BP Library|System") static void RealWorldTime__GetTimePassedSincePreviousTime( const FString& PreviousTime, float& Milliseconds, float& Seconds, float& Minutes, float& Hours ); /** Get the difference between two recorded times! You can use this to record milliseconds/seconds/minutes/hours between events in game logic! */ UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Victory BP Library|System") static void RealWorldTime__GetDifferenceBetweenTimes( const FString& PreviousTime1, const FString& PreviousTime2, float& Milliseconds, float& Seconds, float& Minutes, float& Hours ); //~~~ /** Loads a text file from hard disk and parses it into a String array, where each entry in the string array is 1 line from the text file. Option to exclude lines that are only whitespace characters or '\n'. Returns the size of the final String Array that was created. Returns false if the file could be loaded from hard disk. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|File IO") static bool LoadStringArrayFromFile(TArray<FString>& StringArray, int32& ArraySize, FString FullFilePath = "Enter Full File Path", bool ExcludeEmptyLines = false); /** Load a text file to a single string that you can use ParseIntoArray on newline characters if you want same format as LoadStringArrayFromFile. This version supports unicode characters! */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|File IO") static bool LoadStringFromFile(FString& Result, FString FullFilePath = "Enter Full File Path") { return FFileHelper::LoadFileToString( Result, *FullFilePath); } //~~~ /** Max of all array entries. Returns -1 if the supplied array is empty. Returns the index of the max value as well as the value itself. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Array") static void MaxOfFloatArray(const TArray<float>& FloatArray, int32& IndexOfMaxValue, float& MaxValue); /** Max of all array entries. Returns -1 if the supplied array is empty. Returns the index of the max value as well as the value itself. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Array") static void MaxOfIntArray(const TArray<int32>& IntArray, int32& IndexOfMaxValue, int32& MaxValue); /** Min of all array entries. Returns -1 if the supplied array is empty. Returns the index of the min value as well as the value itself. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Array") static void MinOfFloatArray(const TArray<float>& FloatArray, int32& IndexOfMinValue, float& MinValue); /** Min of all array entries. Returns -1 if the supplied array is empty. Returns the index of the min value as well as the value itself. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Array") static void MinOfIntArray(const TArray<int32>& IntArray, int32& IndexOfMinValue, int32& MinValue); //~~~ /** Set Max Move Speed. Supply the Character whose Character Movement to change! Returns false if operation could not occur due to invalid Character or MovementComponent could not be obtained.*/ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Character", meta = (DefaultToSelf = "TheCharacter")) static bool CharacterMovement__SetMaxMoveSpeed(ACharacter* TheCharacter, float NewMaxMoveSpeed); //~~~ /** Converts a float to a rounded Integer, examples: 1.4 becomes 1, 1.6 becomes 2 */ UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Victory BP Library|Math") static int32 Conversion__FloatToRoundedInteger(float IN_Float); UFUNCTION(BlueprintPure, Category = "Victory BP Library|String") static int32 CountOccurrancesOfSubString(FString Source, FString SubString, ESearchCase::Type SearchCase = ESearchCase::IgnoreCase) { return Source.ReplaceInline(*SubString,TEXT(""),SearchCase); } UFUNCTION(BlueprintCallable, Category = "Victory BP Library|String", meta=( Keywords = "concatenate append")) static void VictoryAppendInline(UPARAM(ref) FString& String, const FString& ToAppend, FString& Result, bool AppendNewline=false) { String += ToAppend; if(AppendNewline) String += LINE_TERMINATOR; Result = String; } /** Handy option to trim any extra 00: 's while keeping a base set of 00:ss as per user expectation. 00:05:30 will become 05:30. ♥ Rama */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|System") static FString Victory_SecondsToHoursMinutesSeconds(float Seconds, bool TrimZeroes=true); UFUNCTION(BlueprintPure, Category = "Victory BP Library|String") static bool IsAlphaNumeric(const FString& String); UFUNCTION(BlueprintPure, Category = "Victory BP Library|String") static void Victory_GetStringFromOSClipboard(FString& FromClipboard); UFUNCTION(BlueprintCallable, Category = "Victory BP Library|String") static void Victory_SaveStringToOSClipboard(const FString& ToClipboard); /** * Returns whether or not the SearchIn string contains the supplied Substring. * Ex: "cat" is a contained within "concatenation" as a substring. * @param SearchIn The string to search within * @param Substring The string to look for in the SearchIn string * @param bUseCase Whether or not to be case-sensitive * @param bSearchFromEnd Whether or not to start the search from the end of the string instead of the beginning */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|String") static bool HasSubstring(const FString& SearchIn, const FString& Substring, ESearchCase::Type SearchCase = ESearchCase::IgnoreCase, ESearchDir::Type SearchDir = ESearchDir::FromStart); /** Combines two strings together! The Separator and the Labels are optional*/ UFUNCTION(BlueprintPure, Category = "Victory BP Library|String") static FString String__CombineStrings(FString StringFirst, FString StringSecond, FString Separator = "", FString StringFirstLabel = "", FString StringSecondLabel = ""); /** Separator is always a space */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|String", meta=( Keywords = "concatenate append", CommutativeAssociativeBinaryOperator = "true")) static FString String__CombineStrings_Multi(FString A, FString B); /** Returns three arrays containing all of the resolutions and refresh rates for the current computer's current display adapter. You can loop over just 1 of the arrays and use the current index for the other two arrays, as all 3 arrays will always have the same length. Returns false if operation could not occur. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|System", meta = (Keywords = "screen resolutions display adapter")) static bool OptionsMenu__GetDisplayAdapterScreenResolutions(TArray<int32>& Widths, TArray<int32>& Heights, TArray<int32>& RefreshRates, bool IncludeRefreshRates = false); UFUNCTION(BlueprintPure, Category = "Victory BP Library|GPU", meta=(Keyword="amd nvidia graphics card brand make model")) static void GetUserDisplayAdapterBrand(bool& IsAMD, bool& IsNvidia, bool& IsIntel, bool& IsUnknown, int32& UnknownId); /** Clones an actor by obtaining its class and creating a copy. Returns the created Actor. The cloned actor is set to have the rotation and location of the initial actor. You can optionally specify location / rotation offsets for the new clone from original actor. Use IsValid to know if the actor was able to be cloned. */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Actor", meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject")) static AStaticMeshActor* Clone__StaticMeshActor(UObject* WorldContextObject, bool&IsValid, AStaticMeshActor* ToClone, FVector LocationOffset = FVector(0, 0, 0), FRotator RotationOffset = FRotator(0, 0, 0)); /** Teleport Actor To Actor. Moves an actor instantly to the position and rotation of another actor. Useful for player starts, notes, triggers, and any other destination actors who dont have collision. Returns false if the operation could not occur. */ UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Victory BP Library|Actor") static bool Actor__TeleportToActor(AActor* ActorToTeleport, AActor* DestinationActor); /** Is this game logic running in the Editor world? */ UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Victory BP Library|System", meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject")) static bool WorldType__InEditorWorld(UObject* WorldContextObject); /** Is this game logic running in the PIE world? */ UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Victory BP Library|System", meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject")) static bool WorldType__InPIEWorld(UObject* WorldContextObject); /** Is this game logic running in an actual independent game instance? */ UFUNCTION(BlueprintCallable, BlueprintPure, Category = "Victory BP Library|System", meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject")) static bool WorldType__InGameInstanceWorld(UObject* WorldContextObject); /** Cause a supplied Character (casted from Actor internally) to enter Ragdoll physics. A check will be done to see if the character has a physics asset. */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Physics") static bool Physics__EnterRagDoll(AActor* TheCharacter); /** Cause a supplied Character (casted from Actor internally) to exit Ragdoll physics. HeightAboveRBMesh is how far above the RB Mesh the Actor Capsule should be moved to upon exiting. Pass in the InitLocation and InitRotation from InitializeVictoryRagdoll */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Physics") static bool Physics__LeaveRagDoll(AActor* TheCharacter, bool SetToFallingMovementMode=true, float HeightAboveRBMesh = 64, const FVector& InitLocation = FVector(0, 0, 0), const FRotator& InitRotation = FRotator(0, 0, 0)); /** Returns whether or not a supplied Character is in Ragdoll Physics. Cast from Actor done internally for your convenience. */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Physics") static bool Physics__IsRagDoll(AActor* TheCharacter); /** Get the Ragdoll Position of the supplied actor, casted to Character internally. Returns false if operation could not occur. */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Physics") static bool Physics__GetLocationofRagDoll(AActor* TheCharacter, FVector& RagdollLocation); /** Initialize Victory Ragdoll Mode, by Obtaining the Default Relative Rotation and Location for this Character's Mesh. The Output Location and Rotation must be saved for use with LeaveRagdoll. Returns false if operation could not occur */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Physics") static bool Physics__InitializeVictoryRagDoll(AActor* TheCharacter, FVector&InitLocation, FRotator&InitRotation); /** Update the TheCharacter's Capsule Location and Camera to the Current Location of the Ragdoll. InterpSpeed is how fast the camera keeps up with the moving ragdoll! HeightOffset is the height above the ragdoll that the camera should stay. Returns false if operation could not occur or if Mesh was not in ragdoll */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Physics") static bool Physics__UpdateCharacterCameraToRagdollLocation(AActor* TheCharacter, float HeightOffset = 128, float InterpSpeed = 3); /** This node checks all Scalar, Vector, and Texture parameters of a material to see if the supplied parameter name is an actual parameter in the material! ♥ Rama*/ UFUNCTION(BlueprintPure,Category="Victory BP Library|Material") static bool DoesMaterialHaveParameter(UMaterialInterface* Mat, FName Parameter); /** Get Name as String*/ UFUNCTION(BlueprintPure, Category = "Victory BP Library|String") static FString Accessor__GetNameAsString(const UObject* TheObject); /** Get Socket Local Transform. Returns false if operation could not occur.*/ //UFUNCTION(BlueprintCallable, Category = "Victory BP Library") //static bool Accessor__GetSocketLocalTransform(const USkeletalMeshComponent* Mesh, FTransform& LocalTransform, FName SocketName=FName("SocketName")); /** Get Player Character's Player Controller. Requires: The Passed in Actor must be a character and it must be a player controlled character. IsValid will tell you if the return value is valid, make sure to do a Branch to confirm this! */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Character") static APlayerController* Accessor__GetPlayerController(AActor* TheCharacter, bool&IsValid); UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Input") static void VictorySimulateMouseWheel(const float& Delta); UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Input") static void VictorySimulateKeyPress(APlayerController* ThePC, FKey Key, EInputEvent EventType); /** This handy node lets you turn the rendering of the entire world on or off! Does not affect UMG or HUD, which allows you to use loading screens effectively! <3 Rama. Returns false if player controller could not be used to get the viewport. */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|System", meta=(keywords="disable show hide loading screen")) static bool Viewport__EnableWorldRendering(const APlayerController* ThePC, bool RenderTheWorld); /** SET the Mouse Position! Returns false if the operation could not occur */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Input") static bool Viewport__SetMousePosition(const APlayerController* ThePC, const float& PosX, const float& PosY); /** Get the Cursor Position within the Player's Viewport. This will return a result consistent with SET Mouse Position Returns false if the operation could not occur */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Game Window") static bool Viewport__GetMousePosition(const APlayerController* ThePC, float& PosX, float& PosY); /** Get the coordinates of the center of the player's screen / viewport. Returns false if the operation could not occur */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Game Window") static bool Viewport__GetCenterOfViewport(const APlayerController* ThePC, float& PosX, float& PosY); /** Convert Vector to Rotator*/ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Conversion") static FRotator Conversions__VectorToRotator(const FVector& TheVector); /** Convert Rotator to Vector */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Conversion") static FVector Conversions__RotatorToVector(const FRotator& TheRotator); /** Input Actor is expected to be a ACharacter, conversion done internally for your convenience */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Conversion") static FRotator Character__GetControllerRotation(AActor * TheCharacter); /** Draw 3D Line of Chosen Thickness From Socket on Character's Mesh to Destination, conversion of AActor to ACharacter done internally for your convenience. Duration is in Seconds */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|3d Lines") static void Draw__Thick3DLineFromCharacterSocket(AActor* TheCharacter, const FVector& EndPoint, FName Socket = FName("SocketName"), FLinearColor LineColor = FLinearColor(1, 0, 0, 1), float Thickness = 7, float Duration = -1.f); /** Draw 3D Line of Chosen Thickness From Mesh Socket to Destination. Duration is in Seconds */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|3d Lines") static void Draw__Thick3DLineFromSocket(USkeletalMeshComponent* Mesh, const FVector& EndPoint, FName Socket = FName("SocketName"), FLinearColor LineColor = FLinearColor(0, 1, 0, 1), float Thickness = 7, float Duration = -1.f); /** Draw 3D Line of Chosen Thickness Between Two Actors. Duration is in Seconds */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|3d Lines") static void Draw__Thick3DLineBetweenActors(AActor* StartActor, AActor* EndActor, FLinearColor LineColor = FLinearColor(0, 0, 1, 1), float Thickness = 7, float Duration = -1.f); /** AnimBPOwner - Must be a Character, Conversion Internally For Convenience.\n\nRetrieves the Aim Offsets Pitch & Yaw Based On the Rotation of the Controller of The Character Owning The Anim Instance.\n\nThe Pitch and Yaw are meant to be used with a Blend Space going from -90,-90 to 90,90.\n Returns true if function filled the pitch and yaw vars successfully */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Aim Offset") static bool Animation__GetAimOffsets(AActor* AnimBPOwner, float& Pitch, float& Yaw); /** AnimBPOwner - Must be a Character, Conversion Internally For Convenience.\n\nRetrieves the Aim Offsets Pitch & Yaw for the AnimBPOwner Based On the supplied Rotation.\n\nThe Pitch and Yaw are meant to be used with a Blend Space going from -90,-90 to 90,90.\n Returns true if function filled the pitch and yaw vars successfully */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Aim Offset") static bool Animation__GetAimOffsetsFromRotation(AActor * AnimBPOwner, const FRotator & TheRotation, float & Pitch, float & Yaw); /** Saves text to filename of your choosing, make sure include whichever file extension you want in the filename, ex: SelfNotes.txt . Make sure to include the entire file path in the save directory, ex: C:\MyGameDir\BPSavedTextFiles */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|File IO") static bool FileIO__SaveStringTextToFile(FString SaveDirectory, FString JoyfulFileName, FString SaveText, bool AllowOverWriting = false); /** Saves multiple Strings to filename of your choosing, with each string on its own line! Make sure include whichever file extension you want in the filename, ex: SelfNotes.txt . Make sure to include the entire file path in the save directory, ex: C:\MyGameDir\BPSavedTextFiles */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|File IO") static bool FileIO__SaveStringArrayToFile(FString SaveDirectory, FString JoyfulFileName, TArray<FString> SaveText, bool AllowOverWriting = false); /** Obtain an Array of Actors Rendered Recently. You can specifiy what qualifies as "Recent" in seconds. */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Actor", meta=(WorldContext="WorldContextObject")) static void Visibility__GetRenderedActors(UObject* WorldContextObject, TArray<AActor*>& CurrentlyRenderedActors, float MinRecentTime = 0.01); /** Obtain an Array of Actors NOT Rendered Recently! You can specifiy what qualifies as "Recent" in seconds. */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Actor", meta=(WorldContext="WorldContextObject")) static void Visibility__GetNotRenderedActors(UObject* WorldContextObject, TArray<AActor*>& CurrentlyNotRenderedActors, float MinRecentTime = 0.01); /** Is the Current Game Window the Foreground window in the OS, or in the Editor? This will be accurate in standalone running of the game as well as in the editor PIE */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Game Window") static bool ClientWindow__GameWindowIsForeGroundInOS(); /** Flashes the game on the windows OS task bar! Please note this won't look the best in PIE, flashing is smoother in Standalone or packaged game. You can use GameWindowIsForeGroundInOS to see if there is a need to get the user's attention! <3 Rama */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Game Window") static void FlashGameOnTaskBar(APlayerController* PC, bool FlashContinuous=false, int32 MaxFlashCount = 3, int32 FlashFrequencyMilliseconds=500); /** Freeze Game Render, Does Not Stop Game Logic, Just Rendering. This is not like Pausing. Mainly useful for freezing render when window is not in the foreground */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Game Window") static void Rendering__FreezeGameRendering(); /** Unfreeze Game Render. This is not an unpause function, it's just for actual screen rendering */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Game Window") static void Rendering__UnFreezeGameRendering(); /** Compare Source Vector against Array of Vectors. Returns: Returns the Closest Vector to Source and what that closest Distance is, or -1 if there was an error such as array being empty. Ignores: Ignores Source if source is in the array */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Misc") static float Calcs__ClosestPointToSourcePoint(const FVector & Source, const TArray<FVector>& OtherPoints, FVector& ClosestPoint); /** Takes in an actor (for convenience) and tries to cast it to Character and return an array of Vectors of all of the current bone locations of the character's Mesh. Locations are in World Space. Returns: false if the operation could not occur. Requires: Character Mesh Component must be valid */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Actor") static bool Data__GetCharacterBoneLocations(AActor * TheCharacter, TArray<FVector>& BoneLocations); /** Retrieves the "Mesh" component of a Character. IsValid lets you know if the data is valid, make sure to check if it is! Requires: the passed in Actor must be a Character */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Character") static USkeletalMeshComponent* Accessor__GetCharacterSkeletalMesh(AActor* TheCharacter, bool& IsValid); /** * Get All Bone Names Below Bone, requires a physics asset, by Rama * * @param StartingBoneName The name of the bone to find all bones below. * * @param BoneNames , all of the bone names below the starting bone. * * @return total number of bones found */ UFUNCTION(BlueprintCallable, Category="Victory BP Library|Components|SkinnedMesh") static int32 GetAllBoneNamesBelowBone(USkeletalMeshComponent* SkeletalMeshComp, FName StartingBoneName, TArray<FName>& BoneNames ); /** Does Not Do A Trace, But Obtains the Start and End for doing a Trace:\n\nTakes in an actor (for convenience) and tries to cast it to Character. Takes in a socket name to find on the Character's Mesh component, the socket location will be the start of the trace.\n\nAlso takes in the Angle / Rotator and the length of the trace you want to do. Option to draw the trace with variable thickness as it occurs.\n\nReturns what the Trace Start and End should be so you can plug these into any existing trace node you want.\n\nRequires: Character Mesh Component must be valid. Returns False if trace could not be done */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Traces") static bool TraceData__GetTraceDataFromCharacterSocket(FVector& TraceStart, FVector& TraceEnd, AActor * TheCharacter, const FRotator& TraceRotation, float TraceLength = 10240, FName Socket = "SocketName", bool DrawTraceData = true, FLinearColor TraceDataColor = FLinearColor(1, 0, 0, 1), float TraceDataThickness = 7); /** Does Not Do A Trace, But Obtains the Start and End for doing a Trace:\n\nTakes in a Skeletal Mesh Component and a socket name to trace from. Also takes in the Angle / Rotator and the length of the trace you want to do.\n\nOption to draw the trace as a variable thickness line\n\nReturns what the Trace Start and End should be so you can plug these into any existing trace node you want.\n\n Requires: Mesh must be valid. Returns False if trace could not be done */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Traces") static bool TraceData__GetTraceDataFromSkeletalMeshSocket(FVector& TraceStart, FVector& TraceEnd, USkeletalMeshComponent* Mesh, const FRotator& TraceRotation, float TraceLength = 10240, FName Socket = "SocketName", bool DrawTraceData = true, FLinearColor TraceDataColor = FLinearColor(1, 0, 0, 1), float TraceDataThickness = 7); /** Does a simple line trace given Trace Start and End, and if a Character is hit by the trace, then a component trace is performed on that character's mesh. Trace Owner is ignored when doing the trace.\n\nReturns the Character that was hit, as an Actor, as well as the name of the bone that was closest to the impact point of the trace. Also returns the impact point itself as well as the impact normal.\n\nUsing component trace ensures accuracy for testing against bones and sockets.\n\nIsValid: Will be true only if the component trace also hit someting. But the Returned Actor will contain an actor if any actor at all was hit by the simple trace. */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Traces") static AActor* Traces__CharacterMeshTrace___ClosestBone(AActor* TraceOwner, const FVector& TraceStart, const FVector& TraceEnd, FVector& OutImpactPoint, FVector& OutImpactNormal, FName& ClosestBoneName, FVector & ClosestBoneLocation, bool&IsValid); /** Does a simple line trace given Trace Start and End, and if a Character is hit by the trace, then a component trace is performed on that character's mesh. Returns the name of the socket that was closest to the impact point of the trace. Also returns the impact point itself as well as the impact normal. Also returns the Socket Location. Using component trace ensures accuracy for testing against bones and sockets.*/ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Traces",meta=(WorldContext="WorldContextObject")) static AActor* Traces__CharacterMeshTrace___ClosestSocket(UObject* WorldContextObject, const AActor * TraceOwner, const FVector& TraceStart, const FVector& TraceEnd, FVector& OutImpactPoint, FVector& OutImpactNormal, FName& ClosestSocketName, FVector & SocketLocation, bool&IsValid); /** Returns the float as a String with Precision, Precision 0 = no decimal value. Precison 1 = 1 decimal place. The re-precisioned result is rounded appropriately. */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Conversion") static void StringConversion__GetFloatAsStringWithPrecision(float TheFloat, FString & TheString, int32 Precision = 2, bool IncludeLeadingZero=true); /** Rotator out value is the degrees of difference between the player camera and the direction of player to light source. Returns false if the operation could not occur. */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Misc") static bool LensFlare__GetLensFlareOffsets(APlayerController* PlayerController, AActor* LightSource, float& PitchOffset, float& YawOffset, float& RollOffset); /** Retrieve Distance of given point to any Surface point on a Static Mesh Actor. Returns the distance as well as the exact closest point on the mesh surface to the given point. Returns -1 if an error occurred*/ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Misc") static float DistanceToSurface__DistaceOfPointToMeshSurface(AStaticMeshActor* TheSMA, const FVector& TestPoint, FVector& ClosestSurfacePoint); /** Change the Mobility of a Static Mesh Component, can be used in Constructor Script or in Event Graph! Returns false if operation could not occur.*/ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Misc") static bool Mobility__SetSceneCompMobility(USceneComponent* SceneComp, EComponentMobility::Type NewMobility); //~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Paths /** InstallDir/GameName/Binaries/Win64 */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Paths") static FString VictoryPaths__Win64Dir_BinaryLocation(); /** InstallDir/WindowsNoEditor/ */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Paths") static FString VictoryPaths__WindowsNoEditorDir(); /** InstallDir/GameName */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Paths") static FString VictoryPaths__GameRootDirectory(); /** InstallDir/GameName/Saved */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Paths") static FString VictoryPaths__SavedDir(); /** InstallDir/GameName/Saved/Config/ */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Paths") static FString VictoryPaths__ConfigDir(); /** InstallDir/GameName/Saved/Screenshots/Windows */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Paths") static FString VictoryPaths__ScreenShotsDir(); /** InstallDir/GameName/Saved/Logs */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Paths") static FString VictoryPaths__LogsDir(); //~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Graphics Settings Sample //~~~~~~~~~~~~~~~~~~ // FullScreen //~~~~~~~~~~~~~~~~~~ /** Get Full Screen Type */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Graphics Settings") static TEnumAsByte<EJoyGraphicsFullScreen::Type> JoyGraphicsSettings__FullScreen_Get(); /** Set Full Screen Type */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Graphics Settings") static void JoyGraphicsSettings__FullScreen_Set(TEnumAsByte<EJoyGraphicsFullScreen::Type> NewSetting); //~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~ // CPP FUNCTION LIBRARY static FORCEINLINE void JoyCC(const FString& Str, const int32 Value) { TObjectIterator<APlayerController> PC; if (!PC) return; //~~~~~~ PC->ConsoleCommand(Str + " " + FString::FromInt(Value)); } static FORCEINLINE void JoyGraphics_FullScreen_SetFullScreenType(int32 Value) { JoyCC("r.FullScreenMode", Value); } static FORCEINLINE int32 JoyGraphics_FullScreen_GetFullScreenType() { static const auto CVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.FullScreenMode")); return CVar->GetValueOnGameThread(); } static FORCEINLINE void JoyGraphics_SetFullScreen_NonWindowed() { /*"r.FullScreenMode"), 2, TEXT("Defines how we do full screen when requested (e.g. command line option -fullscreen or in ini [SystemSettings] fullscreen=true)\n") */ JoyCC("r.FullScreenMode", 0); } static FORCEINLINE void JoyGraphics_SetFullScreen_Windowed() { //TEXT(" 2: windowed full screen, specified resolution (like 1 but no unintuitive performance cliff, can be blurry, default)\n") JoyCC("r.FullScreenMode", 2); } static FORCEINLINE void JoyGraphics_SetFullScreen_WindowedHighestQuality() { //TEXT(" 1: windowed full screen, desktop resolution (quick switch between applications and window mode, full quality)\n") JoyCC("r.FullScreenMode", 1); } //Min and Max of Array static FORCEINLINE float Min(const TArray<float>& Values, int32* MinIndex = NULL) { if (MinIndex) { *MinIndex = 0; } if (Values.Num() <= 0) { return -1; } float CurMin = Values[0]; for (const float EachValue : Values) { CurMin = FMath::Min(CurMin, EachValue); } if (MinIndex) { *MinIndex = Values.Find(CurMin); } return CurMin; } static FORCEINLINE float Max(const TArray<float>& Values, int32* MaxIndex = NULL) { if (MaxIndex) { *MaxIndex = 0; } if (Values.Num() <= 0) { return -1; } float CurMax = Values[0]; for (const float EachValue : Values) { CurMax = FMath::Max(CurMax, EachValue); } if (MaxIndex) { *MaxIndex = Values.Find(CurMax); } return CurMax; } static FORCEINLINE int32 Min(const TArray<int32>& Values, int32* MinIndex = NULL) { if (MinIndex) { *MinIndex = 0; } if (Values.Num() <= 0) { return -1; } int32 CurMin = Values[0]; for (const int32 EachValue : Values) { CurMin = FMath::Min(CurMin, EachValue); } if (MinIndex) { *MinIndex = Values.Find(CurMin); } return CurMin; } static FORCEINLINE int32 Max(const TArray<int32>& Values, int32* MaxIndex = NULL) { if (MaxIndex) { *MaxIndex = 0; } if (Values.Num() <= 0) { return -1; } int32 CurMax = Values[0]; for (const int32 EachValue : Values) { CurMax = FMath::Max(CurMax, EachValue); } if (MaxIndex) { *MaxIndex = Values.Find(CurMax); } return CurMax; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~ //~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Contributed by Others /** * * Contributed by: Mindfane * * Split a string into an array of substrings based on the given delimitter. * Unlike ParseIntoArray() function which expects single character delimitters, this function can accept a delimitter that is also a string. * * @param InputString - The string that is to be exploded. * @param Separator - The delimitter that is used for splitting (multi character strings are allowed) * @param limit - If greater than zero, returns only the first x strings. Otherwsie returns all the substrings * @param bTrimElelements - If True, then each subsctring is processed and any leading or trailing whitespcaes are trimmed. */ UFUNCTION(BlueprintPure, meta = (DisplayName = "Victory BP Library|String", Keywords = "split explode string"), Category = String) static void String__ExplodeString(TArray<FString>& OutputStrings, FString InputString, FString Separator = ",", int32 limit = 0, bool bTrimElements = false); //NOT QUITE WORKING, REQUIRES INVESTIGATION /** Load a Texture 2D from a DDS file! Contributed by UE4 forum member n00854180t! */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Load Texture From File",meta=(Keywords="image DDS")) static UTexture2D* LoadTexture2D_FromDDSFile(const FString& FullFilePath); /** Load a Texture2D from a JPG,PNG,BMP,ICO,EXR,ICNS file! IsValid tells you if file path was valid or not. Enjoy! -Rama */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Load Texture From File",meta=(Keywords="image png jpg jpeg bmp bitmap ico icon exr icns")) static UTexture2D* Victory_LoadTexture2D_FromFile(const FString& FullFilePath,EJoyImageFormats ImageFormat,bool& IsValid, int32& Width, int32& Height); /** Load a Texture2D from a JPG,PNG,BMP,ICO,EXR,ICNS file! IsValid tells you if file path was valid or not. Enjoy! -Rama */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Load Texture From File",meta=(Keywords="image png jpg jpeg bmp bitmap ico icon exr icns")) static UTexture2D* Victory_LoadTexture2D_FromFile_Pixels(const FString& FullFilePath,EJoyImageFormats ImageFormat,bool& IsValid, int32& Width, int32& Height, TArray<FLinearColor>& OutPixels); /** Retrieve a pixel color value given the pixel array, the image height, and the coordinates. Returns false if the coordinates were not valid. Pixel coordinates start from upper left corner as 0,0. X= horizontal, Y = vertical */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Load Texture From File",meta=(Keywords="image coordinate index map value")) static bool Victory_Get_Pixel(const TArray<FLinearColor>& Pixels, int32 ImageHeight, int32 x, int32 y, FLinearColor& FoundColor); /** Save an array of pixels to disk as a PNG! It is very important that you supply the curret width and height of the image! Returns false if Width * Height != Array length or file could not be saved to the location specified. I return an ErrorString to clarify what the exact issue was. -Rama */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Load Texture From File",meta=(Keywords="create image png jpg jpeg bmp bitmap ico icon exr icns")) static bool Victory_SavePixels(const FString& FullFilePath,int32 Width, int32 Height, const TArray<FLinearColor>& ImagePixels, bool SaveAsBMP, bool sRGB, FString& ErrorString); /** This will modify the original T2D to remove sRGB and change compression to VectorDisplacementMap to ensure accurate pixel reading. -Rama*/ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Load Texture From File",meta=(Keywords="create image png jpg jpeg bmp bitmap ico icon exr icns")) static bool Victory_GetPixelFromT2D(UTexture2D* T2D, int32 X, int32 Y, FLinearColor& PixelColor); /** This will modify the original T2D to remove sRGB and change compression to VectorDisplacementMap to ensure accurate pixel reading. -Rama*/ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Load Texture From File",meta=(Keywords="create image png jpg jpeg bmp bitmap ico icon exr icns")) static bool Victory_GetPixelsArrayFromT2D(UTexture2D* T2D, int32& TextureWidth, int32& TextureHeight,TArray<FLinearColor>& PixelArray); /** This will modify the original T2D to remove sRGB and change compression to VectorDisplacementMap to ensure accurate pixel reading. -Rama*/ //UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Load Texture From File",meta=(Keywords="create image png jpg jpeg bmp bitmap ico icon exr icns")) static bool Victory_GetPixelsArrayFromT2DDynamic(UTexture2DDynamic* T2D, int32& TextureWidth, int32& TextureHeight,TArray<FLinearColor>& PixelArray); /** Contributed by UE4 forum member n00854180t! Plays a .ogg sound from file, attached to and following the specified component. This is a fire and forget sound. Replication is also not handled at this point. * @param FilePath - Path to sound file to play * @param AttachComponent - Component to attach to. * @param AttachPointName - Optional named point within the AttachComponent to play the sound at * @param Location - Depending on the value of Location Type this is either a relative offset from the attach component/point or an absolute world position that will be translated to a relative offset * @param LocationType - Specifies whether Location is a relative offset or an absolute world position * @param bStopWhenAttachedToDestroyed - Specifies whether the sound should stop playing when the owner of the attach to component is destroyed. * @param VolumeMultiplier - Volume multiplier * @param PitchMultiplier - PitchMultiplier * @param AttenuationSettings - Override attenuation settings package to play sound with */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Sound", meta = (VolumeMultiplier = "1.0", PitchMultiplier = "1.0", AdvancedDisplay = "2", UnsafeDuringActorConstruction = "true")) static class UAudioComponent* PlaySoundAttachedFromFile(const FString& FilePath, class USceneComponent* AttachToComponent, FName AttachPointName = NAME_None, FVector Location = FVector(ForceInit), EAttachLocation::Type LocationType = EAttachLocation::SnapToTarget, bool bStopWhenAttachedToDestroyed = false, float VolumeMultiplier = 1.f, float PitchMultiplier = 1.f, float StartTime = 0.f, class USoundAttenuation* AttenuationSettings = NULL); /** Contributed by UE4 forum member n00854180t! Plays a .ogg sound at the given location. This is a fire and forget sound and does not travel with any actor. Replication is also not handled at this point. * * NOT SUPPORTED ON PS4. * * @param FilePath - Path to sound file to play * @param Location - World position to play sound at * @param World - The World in which the sound is to be played * @param VolumeMultiplier - Volume multiplier * @param PitchMultiplier - PitchMultiplier * @param AttenuationSettings - Override attenuation settings package to play sound with */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Sound", meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject", VolumeMultiplier = "1.0", PitchMultiplier = "1.0", AdvancedDisplay = "3", UnsafeDuringActorConstruction = "true")) static void PlaySoundAtLocationFromFile(UObject* WorldContextObject, const FString& FilePath, FVector Location, float VolumeMultiplier = 1.f, float PitchMultiplier = 1.f, float StartTime = 0.f, class USoundAttenuation* AttenuationSettings = NULL); /** Contributed by UE4 forum member n00854180t! Creates a USoundWave* from file path. * Read .ogg header file and refresh USoundWave metadata. * * NOT SUPPORTED ON PS4. * * @param FilePath path to file to create sound wave from */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Sound") static class USoundWave* GetSoundWaveFromFile(const FString& FilePath); #if !PLATFORM_PS4 private: // Thanks to @keru for the base code for loading an Ogg into a USoundWave: // https://forums.unrealengine.com/showthread.php?7936-Custom-Music-Player&p=97659&viewfull=1#post97659 /** * Read .ogg header file and refresh USoundWave metadata. NOT SUPPORTED BY PS4 * @param sw wave to put metadata * @param rawFile pointer to src file in memory * @return 0 if everything is ok * 1 if couldn't read metadata. */ static int32 fillSoundWaveInfo(USoundWave* sw, TArray<uint8>* rawFile); /** * Tries to find out FSoundSource object associated to the USoundWave. NOT SUPPORTED BY PS4 * @param sw wave, search key * @return 0 if wave found and correctly set * -1 if error: sound device not set * -2 if error: sound wave not found */ static int32 findSource(class USoundWave* sw, class FSoundSource* out_audioSource); #endif //PLATFORM_PS4 /** * Contributed by: SaxonRah * Better random numbers. Seeded with a random device. if the random device's entropy is 0; defaults to current time for seed. * can override with seed functions; */ //----------------------------------------------------------------------------------------------BeginRANDOM public: /** Construct a random device, returns either a random device or the default random engine; system dependant; */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Random") static void constructRand(); /** Seed Rand with value passed * @param seed - value to pass to the prng as the seed */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Random") static void seedRand(int32 seed); /** Seed Rand with current time */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Random") static void seedRandWithTime(); /** Seed Rand with entropy * @param seed - value to pass to the prng as the seed */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Random") static void seedRandWithEntropy(); /** Random Bool - Bernoulli distribution * @param fBias - Bias of Bernoulli distribution * @return uniformly distributed bool based on bias parameter */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Random") static bool RandBool_Bernoulli(float fBias); /** Random Integer - Zero to One Uniform distribution * @return int32 - uniform distribution from 0 to 1 */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Random") static int32 RandInt_uniDis(); /** Random Integer - MIN to MAX Uniform distribution * @param iMin - Minimum value of uniform distribution * @param iMax - Maximum value of uniform distribution * @return int32 - uniform distribution from iMin to iMax parameters */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Random") static int32 RandInt_MINMAX_uniDis(int32 iMin, int32 iMax); /** Random Double - Zero to One Uniform distribution * @return double - uniform distribution from 0 to 1 */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Random") static float RandFloat_uniDis(); /** Random Double - Uniform distribution based on MIN to MAX parameters * @param iMin - Minimum value of uniform distribution * @param iMax - Maximum value of uniform distribution * @return double - uniform distribution from iMin to iMax parameters */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Random") static float RandFloat_MINMAX_uniDis(float iMin, float iMax); /** Random Bool - Bernoulli distribution - Mersenne Twister * @param fBias - Bias of Bernoulli distribution * @return uniformly distributed bool based on bias parameter */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Random") static bool RandBool_Bernoulli_MT(float fBias); /** Random Integer - Zero to One Uniform distribution - Mersenne Twister * @return int32 - uniform distribution from 0 to 1 */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Random") static int32 RandInt_uniDis_MT(); /** Random Integer - MIN to MAX Uniform distribution - Mersenne Twister * @param iMin - Minimum value of uniform distribution * @param iMax - Maximum value of uniform distribution * @return int32 - uniform distribution from iMin to iMax parameters */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Random") static int32 RandInt_MINMAX_uniDis_MT(int32 iMin, int32 iMax); /** Random Float - Zero to One Uniform distribution - Mersenne Twister * @return float - uniform distribution from 0 to 1 */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Random") static float RandFloat_uniDis_MT(); /** Random Float - Uniform distribution based on MIN to MAX parameters - Mersenne Twister * @param iMin - Minimum value of uniform distribution * @param iMax - Maximum value of uniform distribution * @return float - uniform distribution from iMin to iMax parameters */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Random") static float RandFloat_MINMAX_uniDis_MT(float iMin, float iMax); //----------------------------------------------------------------------------------------------ENDRANDOM /** Inspired by Sahkan! */ UFUNCTION(BlueprintPure, Category = "Victory BP Library|Actor|Get Immediate Attached Actors") static void Actor__GetAttachedActors(AActor* ParentActor,TArray<AActor*>& ActorsArray); /** Modify the bloom intensity of a post process volume, by Community Member Sahkan */ UFUNCTION(BlueprintCallable, Category = "Victory BP Library|Post Process") static void SetBloomIntensity(APostProcessVolume* PostProcessVolume,float Intensity); //~~~ Kris ~~~ /* *See if index is a valid index for this array * *@param TargetArray The array to perform the operation on *@param Index The index to check. *@return Bool if integer is valid index for this array */ UFUNCTION(Category="Victory BP Library|Utilities|Array", BlueprintPure, CustomThunk, meta=(DisplayName = "Valid Index", CompactNodeTitle = "VALID INDEX", ArrayParm = "TargetArray")) static bool Array_IsValidIndex(const TArray<int32>& TargetArray, int32 Index); static bool GenericArray_IsValidIndex(void* TargetArray, const UArrayProperty* ArrayProp, int32 Index); DECLARE_FUNCTION(execArray_IsValidIndex) { Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<UArrayProperty>(NULL); void* ArrayAddr = Stack.MostRecentPropertyAddress; UArrayProperty* ArrayProperty = Cast<UArrayProperty>(Stack.MostRecentProperty); if (!ArrayProperty) { Stack.bArrayContextFailed = true; return; } P_GET_PROPERTY(UIntProperty, Index); P_FINISH; bool WasValid = GenericArray_IsValidIndex(ArrayAddr, ArrayProperty, Index); *(bool*)RESULT_PARAM = WasValid; } /** Get the time target actor was created. */ UFUNCTION(Category = "Victory BP Library|Actor", BlueprintPure, Meta = (DefaultToSelf = "Target")) static float GetCreationTime(const AActor* Target); /** Get the time target actor has been alive. */ UFUNCTION(Category = "Victory BP Library|Actor", BlueprintPure, Meta = (DefaultToSelf = "Target")) static float GetTimeAlive(const AActor* Target); /** Contributed by Community Member Kris! */ UFUNCTION(Category = "Victory BP Library|SceneCapture", BlueprintPure) static bool CaptureComponent2D_Project(class USceneCaptureComponent2D* Target, FVector Location, FVector2D& OutPixelLocation); /** Contributed by Community Member Kris! */ UFUNCTION(Category = "Victory BP Library|SceneCapture", BlueprintPure, Meta = (DefaultToSelf = "Target")) static bool Capture2D_Project(class ASceneCapture2D* Target, FVector Location, FVector2D& OutPixelLocation); /** Currently the only supported format for this function is B8G8R8A8. Make sure to include the appropriate image extension in your file path! Recommended: .bmp, .jpg, .png. Contributed by Community Member Kris! */ UFUNCTION(Category = "Victory BP Library|SceneCapture", BlueprintCallable) static bool CaptureComponent2D_SaveImage(class USceneCaptureComponent2D* Target, const FString ImagePath, const FLinearColor ClearColour); /** Currently the only supported format for this function is B8G8R8A8. Make sure to include the appropriate image extension in your file path! Recommended: .bmp, .jpg, .png. Contributed by Community Member Kris! */ UFUNCTION(Category = "Victory BP Library|SceneCapture", BlueprintCallable, Meta = (DefaultToSelf = "Target")) static bool Capture2D_SaveImage(class ASceneCapture2D* Target, const FString ImagePath, const FLinearColor ClearColour); /** Make sure your image path has a valid extension! Supported types can be seen in the BP node Victory_LoadTexture2D_FromFile. Contributed by Community Member Kris! */ UFUNCTION(Category = "Victory BP Library|Load Texture From File", BlueprintCallable) static UTexture2D* LoadTexture2D_FromFileByExtension(const FString& ImagePath, bool& IsValid, int32& OutWidth, int32& OutHeight); /** * Find first widget of a certain class and return it. * @param WidgetClass The widget class to filter by. * @param TopLevelOnly Only a widget that is a direct child of the viewport will be returned. */ UFUNCTION(Category = "Victory BP Library|UMG", BlueprintCallable, BlueprintCosmetic, Meta = (WorldContext = "WorldContextObject", DeterminesOutputType = "WidgetClass")) static UUserWidget* GetFirstWidgetOfClass(UObject* WorldContextObject, TSubclassOf<UUserWidget> WidgetClass, bool TopLevelOnly); /** * Recurses up the list of parents and returns true if this widget is a descendant of the PossibleParent * @return true if this widget is a child of the PossibleParent */ UFUNCTION(Category = "Victory BP Library|UMG", BlueprintCallable, BlueprintCosmetic, Meta = (DefaultToSelf = "ChildWidget")) static bool WidgetIsChildOf(UWidget* ChildWidget, UWidget* PossibleParent); /** * Recurses up the list of parents until it finds a widget of WidgetClass. * @return widget that is Parent of ChildWidget that matches WidgetClass. */ UFUNCTION(Category = "Victory BP Library|UMG", BlueprintCallable, BlueprintCosmetic, Meta = (DefaultToSelf = "ChildWidget", DeterminesOutputType = "WidgetClass")) static UUserWidget* WidgetGetParentOfClass(UWidget* ChildWidget, TSubclassOf<UUserWidget> WidgetClass); UFUNCTION(Category = "Victory BP Library|UMG", BlueprintCallable, BlueprintCosmetic, Meta = (DefaultToSelf = "ParentWidget", DeterminesOutputType = "WidgetClass", DynamicOutputParam = "ChildWidgets")) static void WidgetGetChildrenOfClass(UWidget* ParentWidget, TArray<UUserWidget*>& ChildWidgets, TSubclassOf<UUserWidget> WidgetClass, bool bImmediateOnly); UFUNCTION(Category = "Victory BP Library|UMG", BlueprintCallable, BlueprintCosmetic, Meta = (DefaultToSelf = "ParentUserWidget")) static UWidget* GetWidgetFromName(UUserWidget* ParentUserWidget, const FName& Name); UFUNCTION(Category = "Victory BP Library|Team", BlueprintPure) static uint8 GetGenericTeamId(AActor* Target); UFUNCTION(Category = "Victory BP Library|Team", BlueprintCallable) static void SetGenericTeamId(AActor* Target, uint8 NewTeamId); UFUNCTION(Category = "Victory BP Library|LevelStreaming", BlueprintCallable) static FLevelStreamInstanceInfo GetLevelInstanceInfo(ULevelStreamingKismet* LevelInstance); UFUNCTION(Category = "Victory BP Library|LevelStreaming", BlueprintCallable, Meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject")) static void AddToStreamingLevels(UObject* WorldContextObject, const FLevelStreamInstanceInfo& LevelInstanceInfo); UFUNCTION(Category = "Victory BP Library|LevelStreaming", BlueprintCallable, Meta = (HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject")) static void RemoveFromStreamingLevels(UObject* WorldContextObject, const FLevelStreamInstanceInfo& LevelInstanceInfo); UFUNCTION(Category = "Victory BP Library|LevelStreaming", BlueprintCallable, Meta = (keywords="remove")) static void HideStreamingLevel(ULevelStreamingKismet* LevelInstance) { if(LevelInstance) LevelInstance->bShouldBeVisible = false; } UFUNCTION(Category = "Victory BP Library|LevelStreaming", BlueprintCallable, Meta = (keywords="remove")) static void UnloadStreamingLevel(ULevelStreamingKismet* LevelInstance) { if(LevelInstance) LevelInstance->bShouldBeLoaded = false; } static bool GenericArray_SortCompare(const UProperty* LeftProperty, void* LeftValuePtr, const UProperty* RightProperty, void* RightValuePtr); /** * Sort the elements of an array by FString, FName, FText, float, int or boolean. * Supports struct and object based arrays. * * @param TargetArray The array to sort. * @param bAscendingOrder If true, sort by ascending order. * @param VariableName If a struct or object based array, the name of the variable to sort by. */ UFUNCTION(Category = "Victory BP Library|Utilities|Array", BlueprintCallable, CustomThunk, Meta = (DisplayName = "Sort", ArrayParm = "TargetArray", AdvancedDisplay = "bAscendingOrder,VariableName")) static void Array_Sort(const TArray<int32>& TargetArray, bool bAscendingOrder = true, FName VariableName = NAME_None); static void GenericArray_Sort(void* TargetArray, const UArrayProperty* ArrayProp, bool bAscendingOrder = true, FName VariableName = NAME_None); DECLARE_FUNCTION(execArray_Sort) { Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<UArrayProperty>(NULL); void* ArrayAddr = Stack.MostRecentPropertyAddress; UArrayProperty* ArrayProperty = Cast<UArrayProperty>(Stack.MostRecentProperty); if (!ArrayProperty) { Stack.bArrayContextFailed = true; return; } P_GET_UBOOL(bAscendingOrder); P_GET_PROPERTY(UNameProperty, VariableName); P_FINISH; P_NATIVE_BEGIN; GenericArray_Sort(ArrayAddr, ArrayProperty, bAscendingOrder, VariableName); P_NATIVE_END; } /** * Calls PrestreamTextures() for all the actor's meshcomponents. * PrestreamTextures() tells the streaming system to start loading all textures with all mip-levels. * @param Seconds - Number of seconds to force all mip-levels to be resident * @param bEnableStreaming - Whether to start (true) or stop (false) streaming * @param CinematicTextureGroups - Bitfield indicating which texture groups that use extra high-resolution mips */ UFUNCTION(Category = "Victory BP Library|Actor", BlueprintCallable, Meta = (DisplayName = "PrestreamTextures (Actor)")) static void Actor_PrestreamTextures(AActor* Target, float Seconds = 1.0f, bool bEnableStreaming = true, int32 CinematicTextureGroups = 0); /** * Tells the streaming system to start loading all textures with all mip-levels. * @param Seconds - Number of seconds to force all mip-levels to be resident * @param bEnableStreaming - Whether to start (true) or stop (false) streaming * @param CinematicTextureGroups - Bitfield indicating which texture groups that use extra high-resolution mips */ UFUNCTION(Category = "Victory BP Library|Components", BlueprintCallable, Meta = (DisplayName = "PrestreamTextures (Component)")) static void Component_PrestreamTextures(UMeshComponent* Target, float Seconds = 1.0f, bool bEnableStreaming = true, int32 CinematicTextureGroups = 0); /** * Converts the screen position (primary screen's top left corner) supplied by pointer events or similar * to the local space of viewport related to WorldContextObject. * * @param WorldContextObject World context. * @param ScreenPosition Coordinates from FPointerEvent GetScreenSpacePosition() or similar. * @param OutViewportPosition Coordinates based on the local viewport (fullscreen or otherwise). * * @return True if OutViewportPosition is not 0,0. */ UFUNCTION(Category = "Victory BP Library|Game|Viewport", BlueprintCallable, meta=(WorldContext="WorldContextObject")) static bool GetViewportPosition(UObject* WorldContextObject, const FVector2D& ScreenPosition, FVector2D& OutViewportPosition); /** * Does a line collision trace based the viewport position and returns the first blocking hit encountered. * This trace finds the objects that RESPOND to the given TraceChannel * * @param WorldContextObject World context. * @param ViewportPosition Local space of viewport from GetViewportPosition() or similar. * @param TraceChannel * @param bTraceComplex True to test against complex collision, false to test against simplified collision. * @param OutHitResult Properties of the trace hit. * * @return True if there was a hit, false otherwise. */ UFUNCTION(Category = "Victory BP Library|Game|Viewport", BlueprintCallable, Meta = (WorldContext="WorldContextObject", bTraceComplex = true, TraceChannel = ECC_Visibility)) static bool GetViewportPositionHitResultByChannel(UObject* WorldContextObject, const FVector2D& ViewportPosition, ECollisionChannel TraceChannel, bool bTraceComplex, FHitResult& OutHitResult); /** * Transforms the viewport position into a world space origin and direction. * * @param WorldContextObject World context. * @param ViewportPosition Local space of viewport from GetViewportPosition() or similar. * @param OutWorldOrigin Corresponding 3D location in world space. * @param OutWorldDirection World space direction vector away from the camera at the given 2d point. * * @return false if something went wrong during the deproject process. */ UFUNCTION(Category = "Victory BP Library|Game|Viewport", BlueprintCallable, Meta = (WorldContext="WorldContextObject")) static bool ViewportPositionDeproject(UObject* WorldContextObject, const FVector2D& ViewportPosition, FVector& OutWorldOrigin, FVector& OutWorldDirection); /** * Inserts child widget into panel widget at given location. * NOTE: The child widgets "Construct" event will be fired again! * * @param Parent - The panel to insert the child into. * @param Index - Where to insert the new widget. * @param Content - The child widget to insert. * @return slot assigned to content. */ UFUNCTION(Category = "Victory BP Library|Widget|Panel", BlueprintCallable) static class UPanelSlot* InsertChildAt(class UWidget* Parent, int32 Index, UWidget* Content); /** Flushes the current key state for target player controller. */ UFUNCTION(Category = "Victory BP Library|Input", BlueprintCallable) static void FlushPressedKeys(class APlayerController* PlayerController); UFUNCTION(Category = "Victory BP Library|Vector", BlueprintPure) static FVector GetVectorRelativeLocation(FVector ParentLocation, FRotator ParentRotation, FVector ChildLocation); UFUNCTION(Category = "Victory BP Library|Components", BlueprintPure, Meta = (DefaultToSelf = "ChildComponent")) static FVector GetComponentRelativeLocation(class USceneComponent* ParentComponent, class USceneComponent* ChildComponent); UFUNCTION(Category = "Victory BP Library|Actor", BlueprintPure, Meta = (DefaultToSelf = "ChildActor")) static FVector GetActorRelativeLocation(class AActor* ParentActor, class AActor* ChildActor); UFUNCTION(Category = "Victory BP Library|Rotator", BlueprintPure) static FRotator GetRotatorRelativeRotation(FRotator ParentRotation, FRotator ChildRotation); UFUNCTION(Category = "Victory BP Library|Components", BlueprintPure, Meta = (DefaultToSelf = "ChildComponent")) static FRotator GetComponentRelativeRotation(class USceneComponent* ParentComponent, class USceneComponent* ChildComponent); UFUNCTION(Category = "Victory BP Library|Actor", BlueprintPure, Meta = (DefaultToSelf = "ChildActor")) static FRotator GetActorRelativeRotation(class AActor* ParentActor, class AActor* ChildActor); /** * Helper function to calculate vertical FOV from horizontal FOV and aspect ratio. * Useful to for determining distance from camera fit in-game objects to the width of the screen. */ UFUNCTION(Category = "Victory BP Library|Game|Viewport", BlueprintPure) static float HorizontalFOV(float VerticalFOV, float AspectRatio); /** * Helper function to calculate vertical FOV from horizontal FOV and aspect ratio. * Useful to for determining distance from camera fit in-game objects to the height of the screen. */ UFUNCTION(Category = "Victory BP Library|Game|Viewport", BlueprintPure) static float VerticalFOV(float HorizontalFOV, float AspectRatio); UFUNCTION(Category = "Victory BP Library|Utilities|String", BlueprintPure, Meta = (DisplayName = "IsEmpty")) static bool StringIsEmpty(const FString& Target); //~~~~~~~~~ //~~~ KeyToTruth ~~~ //.h /* Addition of strings (A + B) with pins. Contributed by KeyToTruth */ UFUNCTION(BlueprintPure, meta = (DisplayName = "Append Multiple", Keywords = "concatenate combine append strings", CommutativeAssociativeBinaryOperator = "true"), Category = "Victory BP Library|String") static FString AppendMultiple(FString A, FString B); //~~~ Mhousse ~~~ };
[ "evann.delaunay@gmail.com" ]
evann.delaunay@gmail.com
db2835c0dc9fbd52c7b5e560f5b209098f6a8601
b3f810cde78ba2ccd79b6b3402349f9b46daf669
/C_C++/Qt/MyQBuffer/widget.cpp
aa3ea0efb4c193c7a9c9ef123a76ee2fefa5a989
[]
no_license
zhouchaozhong/study_notes
3c7e87f1c5766039034b4e4744d7248268263796
2415da1bb0465e01869a19499b9ae53c5b3175ac
refs/heads/master
2023-05-24T23:26:14.607902
2023-05-11T09:01:28
2023-05-11T09:01:28
92,481,698
0
0
null
null
null
null
UTF-8
C++
false
false
943
cpp
#include "widget.h" #include "ui_widget.h" #include <QBuffer> #include <QDataStream> #include <QDebug> Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); QByteArray array; QBuffer memFile(&array); //创建内存文件 memFile.open(QIODevice::WriteOnly); memFile.write("11111111111111"); memFile.write("22222222222222222"); memFile.close(); qDebug() << memFile.buffer(); qDebug() << "array" << array; QBuffer memFile1; memFile1.open(QIODevice::WriteOnly); QDataStream stream(&memFile1); stream << QString("测试") << 250; memFile1.close(); qDebug() << memFile1.buffer(); memFile1.open(QIODevice::ReadOnly); QDataStream dstream; dstream.setDevice(&memFile1); QString str; int a; dstream >> str >> a; memFile1.close(); qDebug() << str.toUtf8().data() << a; } Widget::~Widget() { delete ui; }
[ "charles@gmail.com" ]
charles@gmail.com
7c0fe4cdd5ed280355f8a875bef854ad3445f3e2
c33327dcd5ddbd9df102851b9d6d41e99a6c5abf
/C_C++/course/course_A.cpp
cc1c3406f24fe26bbc491bd694c19b194c7a8971
[]
no_license
Zxilly/Study-From-Zero
310d9dce6b8db9ae5fd9818b066d1fa3cc71ffa7
47df4c573671c9372f8c9092a127439927f42e2a
refs/heads/master
2023-07-23T23:07:55.633622
2023-07-11T03:19:57
2023-07-11T03:20:57
208,585,532
0
0
null
2023-07-19T01:44:46
2019-09-15T11:43:57
C++
UTF-8
C++
false
false
775
cpp
#include <iostream> // input/output stream using namespace std; // standard n. 标准 void inta() { } int main() { int a; // integer 整形 long a2; long long a3; float b; // 浮点 double b2; int dsjfklsdjflsdjfldskf = 3; int ThisIsAVar = 4; int _this_is_also_a_var = 5; int c2 = 6; int d = 4; cout << ((double) dsjfklsdjflsdjfldskf / d) << endl; cin >> d; if (d > 40) { // > < == != >= <= cout << ">40" << endl; cout << "sajdasldjkas" << endl; } else if (d > 30) { cout << ">30" << endl; } else if (d > 20) { cout << ">20" << endl; } // (type) var //cin >> a; //cout << a << endl; cout << "Hello,world" << endl; //character out / end line return 0; }
[ "zhouxinyu1001@gmail.com" ]
zhouxinyu1001@gmail.com
858cadf83edc13d5806502a665473663b118457e
e24a366a7ac5dfb5975a468046c8626a9d56fa6d
/Obfuscator/Source/include/llvm/DebugInfo/PDB/PDBSymbolUsingNamespace.h
4e8c99fc8d89060cd2a1a43a06a23784131fc0e3
[ "NCSA", "MIT" ]
permissive
fengjixuchui/iOS-Reverse
01e17539bdbff7f2a783821010d3f36b5afba910
682a5204407131c29588dd22236babd1f8b2889d
refs/heads/master
2021-06-26T17:25:41.993771
2021-02-11T10:33:32
2021-02-11T10:33:32
210,527,924
0
0
MIT
2021-02-11T10:33:33
2019-09-24T06:26:57
null
UTF-8
C++
false
false
884
h
//===- PDBSymbolUsingNamespace.h - using namespace info ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_DEBUGINFO_PDB_PDBSYMBOLUSINGNAMESPACE_H #define LLVM_DEBUGINFO_PDB_PDBSYMBOLUSINGNAMESPACE_H #include "PDBSymbol.h" #include "PDBTypes.h" namespace llvm { class raw_ostream; namespace pdb { class PDBSymbolUsingNamespace : public PDBSymbol { DECLARE_PDB_SYMBOL_CONCRETE_TYPE(PDB_SymType::UsingNamespace) public: void dump(PDBSymDumper &Dumper) const override; FORWARD_SYMBOL_ID_METHOD(getLexicalParent) FORWARD_SYMBOL_METHOD(getName) }; } // namespace llvm } #endif // LLVM_DEBUGINFO_PDB_PDBSYMBOLUSINGNAMESPACE_H
[ "374619540@qq.com" ]
374619540@qq.com
5567d892725ad850195cc09af66ecd165e5fd873
608a2e871c7b534a3922914595c294dc147a5310
/Intermediate/Build/Win64/UE4Editor/Inc/FireAndIce/PlatformAppearing.gen.cpp
7ed4217919b2dffa3975e97a8e91badecd4c84a3
[]
no_license
aokeefe97/FireAndIce-Test
0214094f2e8f2d1ed3cb06981b67c2265d8e58c9
e665709bc18d384c5046164105b59e7a46d2b27d
refs/heads/master
2020-03-11T10:09:48.629277
2018-04-17T16:31:16
2018-04-17T16:31:16
129,934,656
0
0
null
null
null
null
UTF-8
C++
false
false
6,800
cpp
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "GeneratedCppIncludes.h" #include "PlatformAppearing.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodePlatformAppearing() {} // Cross Module References FIREANDICE_API UClass* Z_Construct_UClass_APlatformAppearing_NoRegister(); FIREANDICE_API UClass* Z_Construct_UClass_APlatformAppearing(); FIREANDICE_API UClass* Z_Construct_UClass_APlatformBase(); UPackage* Z_Construct_UPackage__Script_FireAndIce(); <<<<<<< HEAD // End Cross Module References void APlatformAppearing::StaticRegisterNativesAPlatformAppearing() { ======= FIREANDICE_API UFunction* Z_Construct_UFunction_APlatformAppearing_BeginOverlap(); ENGINE_API UClass* Z_Construct_UClass_AActor_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_UStaticMeshComponent_NoRegister(); // End Cross Module References void APlatformAppearing::StaticRegisterNativesAPlatformAppearing() { UClass* Class = APlatformAppearing::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "BeginOverlap", (Native)&APlatformAppearing::execBeginOverlap }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, ARRAY_COUNT(Funcs)); } UFunction* Z_Construct_UFunction_APlatformAppearing_BeginOverlap() { struct PlatformAppearing_eventBeginOverlap_Parms { AActor* OtherActor; }; static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { static const UE4CodeGen_Private::FObjectPropertyParams NewProp_OtherActor = { UE4CodeGen_Private::EPropertyClass::Object, "OtherActor", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000080, 1, nullptr, STRUCT_OFFSET(PlatformAppearing_eventBeginOverlap_Parms, OtherActor), Z_Construct_UClass_AActor_NoRegister, METADATA_PARAMS(nullptr, 0) }; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_OtherActor, }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[] = { { "ModuleRelativePath", "PlatformAppearing.h" }, }; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams = { (UObject*(*)())Z_Construct_UClass_APlatformAppearing, "BeginOverlap", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, sizeof(PlatformAppearing_eventBeginOverlap_Parms), PropPointers, ARRAY_COUNT(PropPointers), 0, 0, METADATA_PARAMS(Function_MetaDataParams, ARRAY_COUNT(Function_MetaDataParams)) }; UE4CodeGen_Private::ConstructUFunction(ReturnFunction, FuncParams); } return ReturnFunction; >>>>>>> e11e291622e225cea3163c65daa8690dd96a2d02 } UClass* Z_Construct_UClass_APlatformAppearing_NoRegister() { return APlatformAppearing::StaticClass(); } UClass* Z_Construct_UClass_APlatformAppearing() { static UClass* OuterClass = nullptr; if (!OuterClass) { static UObject* (*const DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_APlatformBase, (UObject* (*)())Z_Construct_UPackage__Script_FireAndIce, }; <<<<<<< HEAD ======= static const FClassFunctionLinkInfo FuncInfo[] = { { &Z_Construct_UFunction_APlatformAppearing_BeginOverlap, "BeginOverlap" }, // 2863568161 }; >>>>>>> e11e291622e225cea3163c65daa8690dd96a2d02 #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[] = { { "IncludePath", "PlatformAppearing.h" }, { "ModuleRelativePath", "PlatformAppearing.h" }, }; #endif <<<<<<< HEAD ======= #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_IsFrozen_MetaData[] = { { "Category", "Appearing" }, { "ModuleRelativePath", "PlatformAppearing.h" }, }; #endif auto NewProp_IsFrozen_SetBit = [](void* Obj){ ((APlatformAppearing*)Obj)->IsFrozen = 1; }; static const UE4CodeGen_Private::FBoolPropertyParams NewProp_IsFrozen = { UE4CodeGen_Private::EPropertyClass::Bool, "IsFrozen", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000005, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(APlatformAppearing), &UE4CodeGen_Private::TBoolSetBitWrapper<decltype(NewProp_IsFrozen_SetBit)>::SetBit, METADATA_PARAMS(NewProp_IsFrozen_MetaData, ARRAY_COUNT(NewProp_IsFrozen_MetaData)) }; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MeltedMesh_MetaData[] = { { "Category", "Mesh" }, { "EditInline", "true" }, { "ModuleRelativePath", "PlatformAppearing.h" }, }; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_MeltedMesh = { UE4CodeGen_Private::EPropertyClass::Object, "MeltedMesh", RF_Public|RF_Transient|RF_MarkAsNative, 0x00100000000a000d, 1, nullptr, STRUCT_OFFSET(APlatformAppearing, MeltedMesh), Z_Construct_UClass_UStaticMeshComponent_NoRegister, METADATA_PARAMS(NewProp_MeltedMesh_MetaData, ARRAY_COUNT(NewProp_MeltedMesh_MetaData)) }; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_IsFrozen, (const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_MeltedMesh, }; >>>>>>> e11e291622e225cea3163c65daa8690dd96a2d02 static const FCppClassTypeInfoStatic StaticCppClassTypeInfo = { TCppClassTypeTraits<APlatformAppearing>::IsAbstract, }; static const UE4CodeGen_Private::FClassParams ClassParams = { &APlatformAppearing::StaticClass, DependentSingletons, ARRAY_COUNT(DependentSingletons), 0x00900080u, <<<<<<< HEAD nullptr, 0, nullptr, 0, ======= FuncInfo, ARRAY_COUNT(FuncInfo), PropPointers, ARRAY_COUNT(PropPointers), >>>>>>> e11e291622e225cea3163c65daa8690dd96a2d02 nullptr, &StaticCppClassTypeInfo, nullptr, 0, METADATA_PARAMS(Class_MetaDataParams, ARRAY_COUNT(Class_MetaDataParams)) }; UE4CodeGen_Private::ConstructUClass(OuterClass, ClassParams); } return OuterClass; } <<<<<<< HEAD IMPLEMENT_CLASS(APlatformAppearing, 3265369876); ======= IMPLEMENT_CLASS(APlatformAppearing, 2396696722); >>>>>>> e11e291622e225cea3163c65daa8690dd96a2d02 static FCompiledInDefer Z_CompiledInDefer_UClass_APlatformAppearing(Z_Construct_UClass_APlatformAppearing, &APlatformAppearing::StaticClass, TEXT("/Script/FireAndIce"), TEXT("APlatformAppearing"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(APlatformAppearing); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
[ "aidan.okeefe@gmail.com" ]
aidan.okeefe@gmail.com
5abffb06dda42c4947e164b91782c3181905ece0
50fd35d59a684f78eeb9b20184b297671a31df87
/src/drone/sbus.cpp
2bf03f1b86ec1a59c0a1d891a9abea4d3c1bfe01
[ "Apache-2.0" ]
permissive
ConnorChristie/kendryte-drone-ai
83148f841a6503b60577d148d8037b7718113e4f
beeeb7606555ff64be630bd4413151255b7ab83c
refs/heads/master
2020-08-16T03:12:08.976284
2019-10-19T17:30:10
2019-10-19T17:30:10
215,447,701
0
0
null
null
null
null
UTF-8
C++
false
false
1,290
cpp
#include "sbus.h" namespace SBUS { void init(uart_device_number_t device_number) { sbus_buffer_s buffer; buffer.ring_buffer = new RingBuffer(SBUS_FRAME_SIZE); uart_init(device_number); uart_config(device_number, 100000, UART_BITWIDTH_8BIT, UART_STOP_2, UART_PARITY_EVEN); uart_receive_data_dma_irq(device_number, DMAC_CHANNEL3, buffer.read_buffer, SBUS_READ_BUFFER_SIZE, on_sbus_rcv, &buffer, 1); } int on_sbus_rcv(void *ctx) { sbus_buffer_s *buffer = (sbus_buffer_s*)ctx; printk("inside here\n"); for (int i = 0; i < SBUS_READ_BUFFER_SIZE; i++) { if (buffer->ring_buffer->enqueue(buffer->read_buffer[i])) { // Check if head and tail make for a valid frame if (buffer->ring_buffer->at(0) == SBUS_FRAME_BEGIN && buffer->ring_buffer->at(SBUS_FRAME_SIZE - 1) == SBUS_FRAME_END) { sbus_frame_t frame; buffer->ring_buffer->getBuffer(frame.bytes); buffer->ring_buffer->clear(); } } } uart_receive_data_dma_irq(UART_DEVICE_2, DMAC_CHANNEL3, buffer->read_buffer, SBUS_READ_BUFFER_SIZE, on_sbus_rcv, ctx, 1); return 0; } uint16_t raw_value_to_normal(const unsigned int raw_val) { return (5 * raw_val / 8) + 880; } };
[ "chillercraft@hotmail.com" ]
chillercraft@hotmail.com
65a4719224a794b598563c606d7baccfac55fa55
1ef180f25651e3de4327aad2cf7304272248008d
/render/include/camera.h
c51b74def1693edb16388427bba9d543466947dd
[]
no_license
Rboin/engine
ed28582228803e8b30995bc969de87d82fd05d8c
fcfded4ef1bfc3156aa1a6967180f8c0b4b45aa5
refs/heads/master
2021-06-17T23:58:27.216460
2019-08-11T12:39:36
2019-08-11T12:39:36
141,564,037
0
0
null
null
null
null
UTF-8
C++
false
false
2,142
h
#ifndef CAMERA_HPP #define CAMERA_HPP #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtc/type_ptr.hpp> #include <memory> #include "axis.h" #include "openglfunctionproxy.h" enum Direction { UP = 1, DOWN = 2, FORWARD = 4, BACKWARD = 8, RIGHT = 16, LEFT = 32 }; struct projection_information { float fov, near, far; }; struct view_information { glm::vec3 position, up, look, right; }; class Camera { public: Camera(const projection_information &p, glm::vec3 position); /** * Adds the given movement direction to the movement buffer. Can be undone * using the Camera::undoMove(Direction) method. * @brief move * @param direction */ void move(Direction direction); /** * Undoes the move done by Camera::move(Direction). * @brief undoMove * @param direction */ void undoMove(Direction direction); /** * Add a vector of rotations (in degrees) to the rotation buffer. * @brief rotate * @param delta */ void rotate(const glm::vec3 delta); const glm::vec3 &getRotationVector() const; /** * Adds the given vector to the position buffer. * @brief addPosition * @param dp */ void addPosition(const glm::vec3 dp); void setPosition(glm::vec3 p); const glm::vec3 &getPosition() const; void setRotation(glm::vec3 r); const glm::mat4 &getViewMatrix(); glm::mat4 &getProjectionMatrix(); std::shared_ptr<Axis> &getAxis(); virtual void update(const double delta) = 0; virtual glm::mat4 getRotation() const = 0; virtual void updateViewMatrix() = 0; virtual void updateProjectionMatrix(const int width, const int height) = 0; protected: int _movement; float _fov, _near, _far; glm::vec3 _position, _position_buffer, _rotation, _rotation_buffer; glm::mat4 _view, _projection; std::shared_ptr<Axis> _axis; /** * Gets the current forward and right directions and adds these * vectors to the position buffer based on whether a certain * key has been pressed. * @brief updatePositionBuffer */ void updatePositionBuffer(); }; #endif // CAMERA_HPP
[ "robin.t.koning@gmail.com" ]
robin.t.koning@gmail.com
012817e5fbec3eb043d77d932956421ffc9ade13
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE23_Relative_Path_Traversal/s02/CWE23_Relative_Path_Traversal__char_file_ifstream_51a.cpp
95998c04020ec3979165db1f89e1d60bdf8c9e58
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
3,146
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE23_Relative_Path_Traversal__char_file_ifstream_51a.cpp Label Definition File: CWE23_Relative_Path_Traversal.label.xml Template File: sources-sink-51a.tmpl.cpp */ /* * @description * CWE: 23 Relative Path Traversal * BadSource: file Read input from a file * GoodSource: Use a fixed file name * Sink: ifstream * BadSink : Open the file named in data using ifstream::open() * Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files * * */ #include "std_testcase.h" #ifdef _WIN32 #define BASEPATH "c:\\temp\\" #else #include <wchar.h> #define BASEPATH "/tmp/" #endif #ifdef _WIN32 #define FILENAME "C:\\temp\\file.txt" #else #define FILENAME "/tmp/file.txt" #endif #include <fstream> using namespace std; namespace CWE23_Relative_Path_Traversal__char_file_ifstream_51 { #ifndef OMITBAD /* bad function declaration */ void badSink(char * data); void bad() { char * data; char dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; { /* Read input from a file */ size_t dataLen = strlen(data); FILE * pFile; /* if there is room in data, attempt to read the input from a file */ if (FILENAME_MAX-dataLen > 1) { pFile = fopen(FILENAME, "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read data from a file */ if (fgets(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL) { printLine("fgets() failed"); /* Restore NUL terminator if fgets fails */ data[dataLen] = '\0'; } fclose(pFile); } } } badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ void goodG2BSink(char * data); /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { char * data; char dataBuffer[FILENAME_MAX] = BASEPATH; data = dataBuffer; /* FIX: Use a fixed file name */ strcat(data, "file.txt"); goodG2BSink(data); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE23_Relative_Path_Traversal__char_file_ifstream_51; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
8c1f527dd735e840b103cb2ae09bb7a8dd333a01
f351c51426cba00bca8143e7cb70a95eb762f894
/Problem/SwordToOffer/p73add.cpp
964a01448529d138c36ad2d0661e58a561816a15
[]
no_license
Cesareans/CPP
d7c4474ee19143b635d482e5ccd676db42dd945d
c06bc48c9be296cbd2c0a1307c704b21bb5fa5dc
refs/heads/master
2020-08-07T04:50:40.314025
2020-05-31T01:37:10
2020-05-31T01:37:10
208,958,625
0
0
null
null
null
null
UTF-8
C++
false
false
294
cpp
#include <iostream> using namespace std; class Solution { public: int add(int num1, int num2) { while (num2) { num1 = num1 ^ num2; num2 = ((num1 ^ num2) & num2) << 1; } return num1; } }; int main() { cout << Solution().add(1, 4); }
[ "1357959025@qq.com" ]
1357959025@qq.com
c748444ad1d571b227c9d944d7819ba192293ff1
b84a050160789566caa56445f856360f6cea89f2
/Stacks/StackArr.cpp
dbac45342ed8c897bd1dba8000f2fe41d1be9f41
[]
no_license
Mohamed-Motaz/ASU-DataStructuresCourse
5f708afe43c3d4e26d1e0cf85ddbe754908f32e5
58f156ffe6a5780dd19958e9a5f52a2566e8fe35
refs/heads/master
2023-05-28T19:36:14.584230
2021-06-21T22:53:29
2021-06-21T22:53:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,044
cpp
// // Created by Mohamed El Zein on 5/30/21. // #include "StackArr.h" #include <assert.h> #include <iostream> using namespace std; template <class T> StackArr<T>::StackArr() { elements = 0; capacity = 2; arr = new T[capacity]; } template <class T> void StackArr<T>::push(T value) { if (elements == capacity) expand(); arr[elements] = value; elements++; } template <class T> void StackArr<T>::expand() { capacity *= 2; T *tmp = new T[capacity]; for (int i = 0; i < elements; i++){ tmp[i] = arr[i]; } delete[] arr; arr = tmp; } template <class T> void StackArr<T>::pop() { assert(elements != 0); elements--; } template <class T> T StackArr<T>::top() { assert(elements != 0); return arr[elements - 1]; } template <class T> bool StackArr<T>::empty() { return elements == 0; } template <class T> int StackArr<T>::length() { return elements; } template <class T> StackArr<T>::~StackArr() { cout << "Stack about to be deleted" << endl; delete[] arr; }
[ "mohamedmotaz247@yahoo.com" ]
mohamedmotaz247@yahoo.com
a5b0402b493e58d10b2aeacd181ca3420a6c57c7
0f0bb82d5b53cbb8a8b24086dfc4cfcad143af03
/title_17.cpp
dbc7f6b07766ae820d7639c8a1c96d96f73cf73b
[]
no_license
bartsimpson89/C-_problem
af88fe7d758fb3ff6032fa3e0f48f2b2aea94cc7
22e205f6466419a69f854028effe5e6e0d0eff73
refs/heads/master
2020-04-22T15:07:33.525084
2019-03-05T11:10:13
2019-03-05T11:10:13
170,467,368
1
0
null
null
null
null
UTF-8
C++
false
false
2,120
cpp
#include<iostream> #include <vector> using namespace std; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; class Solution { public: void Mirror(TreeNode *pRoot) { if (pRoot == NULL) return; TreeNode *pTmp = pRoot->right; pRoot->right = pRoot->left; pRoot->left = pTmp; Mirror(pRoot->right); Mirror(pRoot->left); } TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { int pre_len = pre.size(); if (pre_len == 0) return NULL; TreeNode *node = new TreeNode(pre[0]); int vin_len = vin.size(); int root_index = 0; for(int i=0; i<vin_len; i++) { if (pre[0] == vin[i]) { root_index = i; break; } } vector<int> lpre, rpre, lvin, rvin; for (int i=1; i<pre_len; i++) { if (i<=root_index) lpre.push_back(pre[i]); else rpre.push_back(pre[i]); } for (int i=0; i<vin_len; i++) { if (i == root_index) continue; else if (i < root_index) lvin.push_back(vin[i]); else rvin.push_back(vin[i]); } node->left = reConstructBinaryTree(lpre, lvin); node->right = reConstructBinaryTree(rpre, rvin); return node; } void printPreOrderBinaryTree(TreeNode *head) { if (head == NULL) return; cout<<head->val<<" ";// 打印根节点 printPreOrderBinaryTree(head->left); printPreOrderBinaryTree(head->right); } }; int main() { vector<int> preOrder = {8, 6, 5, 7, 10, 9, 11}; vector<int> inOrder = {5, 6, 7, 8, 9, 10, 11}; TreeNode *head = NULL; Solution solution; head = solution.reConstructBinaryTree(preOrder, inOrder); solution.printPreOrderBinaryTree(head); solution.Mirror(head); cout<<"mirror"<<endl; solution.printPreOrderBinaryTree(head); }
[ "shu_nan2008@163.com" ]
shu_nan2008@163.com
2bd43ad6ad6c9c3d686df396e87b32b05134976a
ba02f978b8f5d5e98556d44679cb88425a9ca398
/src/main.cpp
ff69632614495eddf571733f5aa4ec145aa94092
[ "ISC" ]
permissive
aejsmith/swrast
12d698668bd25792de76f0d1f11b80596f742340
eac34f9eac97d2303a78e7cd08f07fe8481fffa5
refs/heads/master
2021-09-02T09:59:49.605560
2018-01-01T18:04:29
2018-01-01T18:04:29
115,617,109
1
0
null
null
null
null
UTF-8
C++
false
false
3,460
cpp
// // Copyright (C) 2017 Alex Smith // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // #include "CRasteriser.h" #include "CSurface.h" #include <algorithm> #include <cassert> #include <cmath> #include <cstdio> #include <SDL.h> static const uint32_t kWindowWidth = 512; static const uint32_t kWindowHeight = 512; static void Draw(CSurface& inSurface, CRasteriser& inRasteriser) { const SVertex vertices[3] = { {{-0.5f, -0.5f, 1.0f, 1.0f}, {1.0f, 0.0f, 0.0f, 1.0f}}, {{ 0.5f, -0.5f, 1.0f, 1.0f}, {0.0f, 1.0f, 0.0f, 1.0f}}, {{ 0.0f, 0.5f, 1.0f, 1.0f}, {0.0f, 0.0f, 1.0f, 1.0f}}, }; inRasteriser.DrawTriangle(inSurface, vertices); } int main(int argc, char** argv) { SDL_Init(SDL_INIT_VIDEO); SDL_Window* window = SDL_CreateWindow("swrast", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, kWindowWidth, kWindowHeight, 0); CSurface surface(kWindowWidth, kWindowHeight); SDL_Surface* sourceSDLSurface = surface.CreateSDLSurface(); SDL_Surface* destSDLSurface = SDL_GetWindowSurface(window); SDL_SetSurfaceBlendMode(destSDLSurface, SDL_BLENDMODE_NONE); double totalDrawTime = 0.0; double totalFrameTime = 0.0; uint32_t numFrames = 0; const uint64_t perfFreq = SDL_GetPerformanceFrequency(); CRasteriser rasteriser; while (true) { const uint64_t frameStart = SDL_GetPerformanceCounter(); SDL_Event event; if (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) break; } surface.Clear(); const uint64_t drawStart = SDL_GetPerformanceCounter(); Draw(surface, rasteriser); const uint64_t drawEnd = SDL_GetPerformanceCounter(); SDL_BlitSurface(sourceSDLSurface, nullptr, destSDLSurface, nullptr); SDL_UpdateWindowSurface(window); const uint64_t frameEnd = SDL_GetPerformanceCounter(); totalDrawTime += static_cast<double>((drawEnd - drawStart) * 1000) / perfFreq; totalFrameTime += static_cast<double>((frameEnd - frameStart) * 1000) / perfFreq; numFrames++; if (totalFrameTime >= 2000.0) { const double avgDrawTime = totalDrawTime / numFrames; const double avgFrameTime = totalFrameTime / numFrames; printf("Average: draw = %.4f ms, frame = %.4f ms\n", avgDrawTime, avgFrameTime); totalDrawTime = totalFrameTime = 0.0; numFrames = 0; } } return 0; }
[ "alex@alex-smith.me.uk" ]
alex@alex-smith.me.uk
fc888131391ad33b8b2ce179552c2dccba0e77c6
914a4d60f79b0b96a4440979e1fd6ded5f7bc668
/2DPatternSearch/main.cpp
c9e60c5acd25c701555592e0c892354aae9de8cf
[]
no_license
marcinwasowicz/Text-Algorithms
9772fddb924685772dceb5b87dab7b9ee1754ce8
66ade82efec434c78e09464236af2ec4d33202d2
refs/heads/master
2021-05-19T07:03:06.107565
2020-09-27T16:09:18
2020-09-27T16:09:18
251,577,146
1
0
null
null
null
null
UTF-8
C++
false
false
9,080
cpp
#include "PatternSearch.h" #include "FileParser.h" string ALPHABET = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM \n.,1234567890(){}[]|;':-\u0022"; vector<string> transpose(vector<string>& matrix){ vector<string> result(matrix[0].length(), string()); for(int i = 0; i<matrix.size(); i++){ for(int j = 0; j<matrix[0].length(); j++){ result[j] += matrix[i][j]; } } return result; } void raportPatternSearch(vector<pair<int, vector<int>>>& searchResult){ cout<<"lower right corners of pattern found at: "<<endl; for(auto pair : searchResult){ cout<<"line: "<< pair.first<<" positions: "; for(auto position : pair.second){ cout<<position<<" "; } cout<<endl; } } int main(){ FileParser fileParser; clock_t start; clock_t end; char* path = "haystack.txt"; vector<string> text = fileParser.parseFile(path); cout<<"Część pierwsza: Znajdź wszystkie wystąpienia: th w dwóch liniach pod rząd, t h w dwóch liniach pod rząd i wzorca p a t t e r n"<<endl; vector<string> pattern1 = { "th", "th" }; pattern1 = transpose(pattern1); vector<string> pattern2 = { "t h", "t h" }; pattern2 = transpose(pattern2); vector<string> pattern3 = { "p a t t e r n" }; pattern3 = transpose(pattern3); PatternSearch patternSearch1(pattern1, ALPHABET); PatternSearch patternSearch2(pattern2, ALPHABET); PatternSearch patternSearch3(pattern3, ALPHABET); vector<pair<int, vector<int>>> result1 = patternSearch1.findPattern(text); vector<pair<int, vector<int>>> result2 = patternSearch2.findPattern(text); vector<pair<int, vector<int>>> result3 = patternSearch3.findPattern(text); cout<<"th w dwóch liniach pod rząd"<<endl; raportPatternSearch(result1); cout<<"t h w dwóch liniach pod rząd"<<endl; raportPatternSearch(result2); cout<<"p a t t e r n"<<endl; raportPatternSearch(result3); cout<<"Część druga: Znajdź wszystkie sytuacje, gdy taka sama literka występuje w dwóch liniach po rząd na tej samej pozycji"<<endl; string letters = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"; for(auto letter : letters){ vector<string> pattern = { string(1, letter), string(1, letter) }; pattern = transpose(pattern); PatternSearch patternSearch(pattern, ALPHABET); auto result = patternSearch.findPattern(text); if(result.size()!=0){ cout<<"literka: "<<letter<<endl; raportPatternSearch(result); } } cout<<"Część trzecia: Wybierz 4 małe literki i znajdź wystąpienia każdej z nich w załączonym tekście"<<endl; letters = "sxop"; for(auto letter : letters){ vector<string> pattern = { string(1, letter) }; pattern = transpose(pattern); PatternSearch patternSearch(pattern, ALPHABET); auto result = patternSearch.findPattern(text); if(result.size()!=0){ cout<<"literka: "<<letter<<endl; raportPatternSearch(result); } } cout<<"Część czwarta: porównaj czas boduwania automatu i wyszukiwania dla różnych rozmiarów wzorca"<<endl; char* patternPath4 = "wzorzec4.txt"; char* patternPath5 = "wzorzec5.txt"; char* patternPath6 = "wzorzec6.txt"; vector<string> pattern4 = fileParser.parseFile(patternPath4); pattern4 = transpose(pattern4); vector<string> pattern5 = fileParser.parseFile(patternPath5); pattern4 = transpose(pattern4); vector<string> pattern6 = fileParser.parseFile(patternPath6); pattern4 = transpose(pattern4); start = clock(); PatternSearch patternSearch4(pattern4, ALPHABET); end = clock(); cout<<"Tworzenie automatu na wzorcu 4 zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; start = clock(); PatternSearch patternSearch5(pattern5, ALPHABET); end = clock(); cout<<"Tworzenie automatu na wzorcu 5 zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; start = clock(); PatternSearch patternSearch6(pattern6, ALPHABET); end = clock(); cout<<"Tworzenie automatu na wzorcu 6 zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; start = clock(); auto result4 = patternSearch4.findPattern(text); end = clock(); cout<<"Wyszukiwanie wzorca 4 w tekście zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; start = clock(); auto result5 = patternSearch5.findPattern(text); end = clock(); cout<<"Wyszukiwanie wzorca 5 w tekście zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; start = clock(); auto result6 = patternSearch6.findPattern(text); end = clock(); cout<<"Wyszukiwanie wzorca 6 w tekście zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; cout<<"Część piąta: podziel podany tekst na 2, 4, 8 fragmentów w poziomie i teraz porównaj czas wyszukiwania wzorców z poprzedniej części"<<endl; cout<<"Dla każdego wzorca (4 - 6), dla każdego typu podziału pliku (na 2, 4, 8) wypisane będą po kolei czasy poszukiwania danego wzorca w każdym fragmencie pliku," "z danego typu podziału"<<endl; int len = text.size(); vector<vector<string>> twoSplit = { vector<string> (text.begin(), text.begin()+len/2), vector<string>(text.begin()+len/2+1, text.end()) }; vector<vector<string>> fourSplit = { vector<string> (text.begin(), text.begin()+len/4), vector<string>(text.begin()+len/4+1, text.begin()+len/2), vector<string> (text.begin()+len/2+1, text.begin()+3*len/4), vector<string>(text.begin()+3*len/4+1, text.end()) }; vector<vector<string>> eightSplit ={ vector<string> (text.begin(), text.begin()+len/8), vector<string>(text.begin()+len/8+1, text.begin()+len/4), vector<string> (text.begin()+len/4+1, text.begin()+3*len/8), vector<string>(text.begin()+3*len/8+1, text.begin()+len/2), vector<string> (text.begin()+len/2+1, text.begin()+5*len/8), vector<string>(text.begin()+5*len/8+1, text.begin()+3*len/4), vector<string> (text.begin()+3*len/4+1, text.begin()+7*len/8), vector<string>(text.begin()+7*len/8+1, text.end()) }; cout<<"wzorzec 4"<<endl; cout<<"Podział na 2: "<<endl; for(auto it : twoSplit){ start = clock(); patternSearch4.findPattern(it); end = clock(); cout<<"Wyszukiwanie wzorca 4 w tekście zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; } cout<<"Podział na 4: "<<endl; for(auto it : fourSplit){ start = clock(); patternSearch4.findPattern(it); end = clock(); cout<<"Wyszukiwanie wzorca 4 w tekście zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; } cout<<"Podział na 8: "<<endl; for(auto it : eightSplit){ start = clock(); patternSearch4.findPattern(it); end = clock(); cout<<"Wyszukiwanie wzorca 4 w tekście zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; } cout<<"wzorzec 5"<<endl; cout<<"Podział na 2: "<<endl; for(auto it : twoSplit){ start = clock(); patternSearch5.findPattern(it); end = clock(); cout<<"Wyszukiwanie wzorca 5 w tekście zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; } cout<<"Podział na 4: "<<endl; for(auto it : fourSplit){ start = clock(); patternSearch5.findPattern(it); end = clock(); cout<<"Wyszukiwanie wzorca 5 w tekście zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; } cout<<"Podział na 8: "<<endl; for(auto it : eightSplit){ start = clock(); patternSearch5.findPattern(it); end = clock(); cout<<"Wyszukiwanie wzorca 5 w tekście zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; } cout<<"wzorzec 6"<<endl; cout<<"Podział na 2: "<<endl; for(auto it : twoSplit){ start = clock(); patternSearch6.findPattern(it); end = clock(); cout<<"Wyszukiwanie wzorca 6 w tekście zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; } cout<<"Podział na 4: "<<endl; for(auto it : fourSplit){ start = clock(); patternSearch6.findPattern(it); end = clock(); cout<<"Wyszukiwanie wzorca 6 w tekście zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; } cout<<"Podział na 8: "<<endl; for(auto it : eightSplit){ start = clock(); patternSearch6.findPattern(it); end = clock(); cout<<"Wyszukiwanie wzorca 6 w tekście zajęło: "<<(end-start)*1000000/CLOCKS_PER_SEC<<" mikrosekund"<<endl; } return 0; }
[ "noreply@github.com" ]
marcinwasowicz.noreply@github.com
f3211a6fced7bce0d8656514f4d06c79a6e1ca2e
82c64906356c05817cedff0af0ee98cb97280d01
/problems/pB/solutions/sol5.cc
ccabd1751f51e40b1dfce5f8ba40c22d1fe64815
[]
no_license
wangyenjen/icpc-xuzhou-2019
31fa1f64e803634047099bf1c9bffd7a43deda2a
328b3a05dec588620d6a7258802f720505d543d5
refs/heads/master
2022-07-20T07:24:56.653872
2019-10-28T12:13:09
2019-10-28T12:13:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,813
cc
#include <bits/stdc++.h> using namespace std; const int kN = 1e6 + 1; const int kMod = 998244353; constexpr int kState[4] = {0, 0, 12, 68}; constexpr int kRecurrence[4] = {0, 0, 70, 70}; int tab[kN][2], rec[500][500], tr[70][70]; string cache[500]; vector<int> suc[70]; map<string, int> z; int GetID(const string &s) { if (z.find(s) != z.end()) return z[s]; int res = z.size(); cache[res] = s; return z[s] = res; } template <int K> array<int, kState[K]> Perm() { vector<int> v(K); iota(v.begin(), v.end(), 0); array<int, kState[K]> res{}; do { string s = ""; for (int i = 0; i < K; ++i) s += (char)(v[i] + '0'); res[GetID(s)] = 1; } while (next_permutation(v.begin(), v.end())); return res; } template <int K> int Insert(const string &s, int r, int pos) { if (rec[r][pos] != -1) return rec[r][pos]; string res = ""; for (int i = 0; i < pos; ++i) { if (s[i] == 'x' || s[i] - '0' == K - 1) res += 'x'; else res += s[i] + 1; } res += '0'; for (int i = pos; i < (int)s.size(); ++i) { if (s[i] == 'x' || s[i] - '0' == K - 1) res += 'x'; else res += s[i] + 1; } string trim = ""; for (int i = 0, j; i < (int)res.size(); i = j) { if (res[i] != 'x') { trim += res[i]; j = i + 1; } else { for (j = i; j < (int)res.size() && res[j] == 'x'; ++j) ; trim += 'x'; } } return rec[r][pos] = GetID(trim); } int fpow(int a, int n, int p) { int res = 1; while (n > 0) { if (n & 1) res = 1LL * res * a % p; a = 1LL * a * a % p; n >>= 1; } return res; } template <int P> vector<int> BerlekampMassey(vector<int> x) { vector<int> cur, ls; int lf = 0, ld = 0; for (int i = 0; i < (int)x.size(); ++i) { int t = 0; for (int j = 0; j < (int)cur.size(); ++j) (t += 1LL * cur[j] * x[i - j - 1] % P) %= P; if (t == x[i]) continue; if (cur.empty()) { cur.resize(i + 1); lf = i, ld = (t + P - x[i]) % P; continue; } int k = 1LL * fpow(ld, P - 2, P) * (t + P - x[i]) % P; vector<int> c(i - lf - 1); c.push_back(k); for (int j = 0; j < (int)ls.size(); ++j) c.push_back(1LL * k * (P - ls[j]) % P); if (c.size() < cur.size()) c.resize(cur.size()); for (int j = 0; j < (int)cur.size(); ++j) c[j] = (c[j] + cur[j]) % P; if (i - lf + (int)ls.size() >= (int)cur.size()) { ls = cur, lf = i; ld = (t + P - x[i]) % P; } cur = c; } return cur; } template <int K> void Build() { z.clear(); memset(cache, 0, sizeof(cache)); memset(rec, -1, sizeof(rec)); memset(tr, 0, sizeof(tr)); array<int, kState[K]> dp = Perm<K>(); for (int i = K + 1; i <= kRecurrence[K]; ++i) { vector<pair<int, int>> tran; for (int p = 0; p < kState[K]; ++p) { string &s = cache[p]; if (s.empty()) continue; for (int j = 0; j <= (int)s.size(); ++j) { bool ok = (j == (int)s.size() || s[j] != 'x') && (j == 0 || s[j - 1] != 'x'); if (ok) { int o = Insert<K>(s, p, j); if (i == 10) tr[p][o]++; tran.emplace_back(o, dp[p]); } } } sort(tran.begin(), tran.end()); fill(dp.begin(), dp.end(), 0); int total = 0; for (int j = 0, k; j < (int)tran.size(); j = k) { int sum = 0; for (k = j; k < (int)tran.size() && tran[k].first == tran[j].first; ++k) (sum += tran[k].second) %= kMod; dp[tran[j].first] = sum; (total += sum) %= kMod; } if (K == 2) tab[i][0] = total; else tab[i][1] = total; } vector<int> s(kRecurrence[K]); for (int i = 0; i < K; ++i) { if (i == 0) s[i] = tab[i + 1][K - 2] = 1; if (i == 1) s[i] = tab[i + 1][K - 2] = 2; if (i == 3) s[i] = tab[i + 1][K - 2] = 6; } for (int i = K; i < kRecurrence[K]; ++i) s[i] = tab[i + 1][K - 2]; vector<int> rec = BerlekampMassey<kMod>(s); for (int i = kRecurrence[K] + 1; i < kN; ++i) { tab[i][K - 2] = 0; for (int j = 0; j < (int)rec.size(); ++j) (tab[i][K - 2] += 1LL * rec[j] * tab[i - j - 1][K - 2] % kMod) %= kMod; } } void Init() { Build<2>(); Build<3>(); } int main() { Init(); int t; scanf("%d", &t); while (t--) { int n, k; scanf("%d%d", &n, &k); if (k == 1) { if (n == 1) printf("1\n"); else printf("2\n"); } if (k == 2) { if (n == 1) printf("1\n"); else if (n == 2) printf("2\n"); else printf("%d\n", tab[n][0]); } if (k == 3) { if (n == 1) printf("1\n"); else if (n == 2) printf("2\n", 2); else if (n == 3) printf("6\n", 6); else printf("%d\n", tab[n][1]); } } return 0; }
[ "b06902093@ntu.edu.tw" ]
b06902093@ntu.edu.tw
a4b6bb60bd274be4862f11875cc080307f226977
685c151efb36ed60a8de318b2eca119de1372f87
/1/source/Violet/shoot.cpp
7d7cb446baf10bd226e9c451dfa3ebe6f9369a4d
[]
no_license
EAirPeter/wh2014
95cb9e7e2eb311900253ac5bfcba1ff31397b9bd
66e72f671f64012374f47be0cd86e0acef133de0
refs/heads/master
2020-05-09T12:03:57.146410
2014-02-21T11:11:12
2014-02-21T11:11:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,086
cpp
#include <algorithm> #include <cstdio> #include <queue> using namespace std; #ifdef NAVIO #define LLD "%lld" #else #define LLD "%I64d" #endif struct pnt { int x, y; } D[ 501 ], E[ 501 ]; inline bool operator < ( const pnt & a, const pnt & b ) { if( a.x != b.x ) return a.x < b.x; return a.y < b.y; } int gcd( const int a, const int b ) { return b ? gcd( b, a % b ) : a; } long long M, X, C; int N, d, e; int phi[ 4000001 ]; int pri[ 4000001 ], prc; bool vpr[ 4000001 ]; priority_queue< int > h; int ff( const pnt * f, const int l, int & p, const int g, const int o ) { while( p < l && f[ p ].x < g ) ++p; int t = p; while( p < l && f[ p ].x == g ) ++p; int k = phi[ g ]; for( int i = t; i < p; ) { int r = i; while( i < p && f[ i ].y == f[ r ].y ) ++i; --k; h.push( o + r - i ); } return k; } int main() { freopen( "shoot.in", "r", stdin ); freopen( "shoot.out", "w", stdout ); scanf( "%d" LLD, &N, &M ); for( int i = 2; i <= N; ++i ) { if( !vpr[ i ] ) { pri[ prc++ ] = i; phi[ i ] = i - 1; } for( int j = 0; j < prc && i * pri[ j ] <= N; ++j ) { vpr[ i * pri[ j ] ] = true; if( i % pri[ j ] ) phi[ i * pri[ j ] ] = phi[ i ] * ( pri[ j ] - 1 ); else { phi[ i * pri[ j ] ] = phi[ i ] * pri[ j ]; break; } } } --N; int a, b; int sx = N, sy = N, sz = N; while( scanf( "%d%d", &a, &b ) == 2 ) { int c = gcd( a, b ); a /= c; b /= c; if( a == 0 ) --sx; else if( b == 0 ) --sy; else if( a == b ) --sz; else if( a > b ) { D[ d ].x = a; D[ d++ ].y = b; } else { E[ e ].x = b; E[ e++ ].y = a; } } h.push( sx ); h.push( sy ); h.push( sz ); sort( D, D + d ); sort( E, E + e ); a = b = 0; for( int g = 2; g <= N && C < M; ++g ) { int um = N / g; while( !h.empty() && h.top() > um && C < M ) { ++C; X += h.top(); h.pop(); } long long k = ff( D, d, a, g, um ) + ff( E, e, b, g, um ); if( C + k > M ) k = M - C; C += k; X += k * um; } while( C < M && !h.empty() ) { ++C; X += h.top(); h.pop(); } printf( LLD "\n", X ); return 0; }
[ "thunderlz@vip.qq.com" ]
thunderlz@vip.qq.com
84a9c2887aec5f0f756701dcb506af2ce4d4a207
139dfee08bb7a9978388b97052a5329f9d368a35
/Exam1/ExampleImplementation/main.cpp
ae6727bf6bb859f7a2c22629bf3a415d7649e2ca
[]
no_license
JoeDumoulin/CS172
b40bb6c5d075066c97974a3f498a32b5dc0c02ef
e94ba41b163257969b2b12e548bce5012b0bf6d9
refs/heads/master
2021-01-18T13:08:51.680004
2017-05-15T00:57:24
2017-05-15T00:57:24
80,733,695
0
0
null
null
null
null
UTF-8
C++
false
false
1,813
cpp
// main.cpp // // compile with: g++ main.cpp Song.cpp Playlist.cpp -o test #include <string> #include <iostream> #include "Song.h" #include "Playlist.h" using namespace std; int main() { // make an array of songs static int numsongs = 9; Song songs[] = { Song("Human", "Rag'n'Bone Man", "ModernPop"), Song("Closer", "The Chainsmokers", "ModernPop"), Song("Chained To the Rhythm", "Katy Perry", "ModernPop"), Song("Smells Like Teen Spirit", "Nirvana", "Grunge"), Song("Black Hole Sun", "Soundgarden", "Grunge"), Song("Loser", "Beck", "Grunge"), Song("Elvis Presley Blues", "Gillian Welch", "Americana"), Song("Pirate's Gospel", "Alela Diane", "Americana"), Song("Come On Up To The House", "Sarah Jarosz", "Americana") }; // Make the playlist Playlist playlist("iRandomMusic"); for (int i = 0; i < numsongs; i++) playlist.addSong(songs[i]); int errors = 0; // Does the playlist have the correct number of songs? if (numsongs != playlist.numberOfSongs()) { errors++; cout << "error: not counting songs correctly\n"; } // Check the genre of one song if (playlist.playSong(2) == "") { errors++; cout << "error: genre of the third song is incorrect\n"; } // check if the playlist understands how many songs it contains. if (playlist.playSong(10) != "") { errors++; cout << "error: index out of range not handled correctly\n"; } // Check for a genre if (!playlist.hasGenre("Americana")) { errors++; cout << "error: search for genre is incorrect\n"; } if (errors == 0) cout << "Passed\n"; else cout << "Errors: " << errors << endl; return errors; }
[ "joe.dumoulin@gmail.com" ]
joe.dumoulin@gmail.com
4c2d376f7a4038164fef591d1fb5b994457b4bb9
d09945668f19bb4bc17087c0cb8ccbab2b2dd688
/codeforce/edu/081-120/116/e.cpp
65400d2b38ec56024d0c5942e39d2725b439cd4b
[]
no_license
kmjp/procon
27270f605f3ae5d80fbdb28708318a6557273a57
8083028ece4be1460150aa3f0e69bdb57e510b53
refs/heads/master
2023-09-04T11:01:09.452170
2023-09-03T15:25:21
2023-09-03T15:25:21
30,825,508
23
2
null
2023-08-18T14:02:07
2015-02-15T11:25:23
C++
UTF-8
C++
false
false
1,846
cpp
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define FORR2(x,y,arr) for(auto& [x,y]:arr) #define ALL(a) (a.begin()),(a.end()) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) template<class T> bool chmax(T &a, const T &b) { if(a<b){a=b;return 1;}return 0;} template<class T> bool chmin(T &a, const T &b) { if(a>b){a=b;return 1;}return 0;} //------------------------------------------------------- int N,X; const ll mo=998244353; ll comb(ll N_, ll C_) { const int NUM_=400001; static ll fact[NUM_+1],factr[NUM_+1],inv[NUM_+1]; if (fact[0]==0) { inv[1]=fact[0]=factr[0]=1; for (int i=2;i<=NUM_;++i) inv[i] = inv[mo % i] * (mo - mo / i) % mo; for (int i=1;i<=NUM_;++i) fact[i]=fact[i-1]*i%mo, factr[i]=factr[i-1]*inv[i]%mo; } if(C_<0 || C_>N_) return 0; return factr[C_]*fact[N_]%mo*factr[N_-C_]%mo; } ll modpow(ll a, ll n = mo-2) { if(a<0) return 0; ll r=1;a%=mo; while(n) r=r*((n%2)?a:1)%mo,a=a*a%mo,n>>=1; return r; } ll dp[505][505]; void solve() { int i,j,k,l,r,x,y; string s; cin>>N>>X; ll ret=0; for(i=2;i<=N;i++) { for(x=1;x<=i-1;x++) { dp[i][x]=(modpow(x,i)-modpow(x-1,i)+mo)%mo; } for(x=1;x<=X;x++) { for(int add=0;i+add<=N;add++) { if(x+(i+add-1)>X) continue; (dp[i+add][x+(i+add-1)]+=dp[i][x]*comb(i+add,i)%mo*modpow(i+add-1,add))%=mo; } if(i==N) { ret+=dp[N][x]; } } } cout<<ret%mo<<endl; } int main(int argc,char** argv){ string s;int i; if(argc==1) ios::sync_with_stdio(false), cin.tie(0); FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin); cout.tie(0); solve(); return 0; }
[ "kmjp@users.noreply.github.com" ]
kmjp@users.noreply.github.com
332d354f53d0057f0040d6c03fb695f10197a134
c7d4d31e26e4ee4a13f21050fc8a96005b1a2a24
/ABC099/D.cpp
3cce585b2f2885ead5a851e79c29a65904934803
[]
no_license
motacapla/ProgrammingContest-Atcoder-etc-
c26840bf435159ed46c44b3ec37f0ad6e4a722e5
a647b9656b1656ce7da73f8e66a54d353765717b
refs/heads/master
2021-10-28T06:25:40.276550
2021-10-23T11:29:37
2021-10-23T11:29:37
141,571,371
0
0
null
null
null
null
UTF-8
C++
false
false
1,888
cpp
//$g++ -std=c++11 Template.cpp //#include <bits/stdc++.h> #include <iostream> #include <complex> #include <sstream> #include <string> #include <algorithm> #include <deque> #include <list> #include <map> #include <numeric> #include <queue> #include <vector> #include <set> #include <limits> #include <cstdio> #include <cctype> #include <cmath> #include <cstring> #include <cstdlib> #include <ctime> #include <climits> #define REP(i, n) for(int i = 0; i < (int)(n); i++) #define FOR(i, j, k) for(int i = (int)(j); i < (int)(k); ++i) #define ROF(i, j, k) for(int i = (int)(j); i >= (int)(k); --i) #define FORLL(i, n, m) for(long long i = n; i < (long long)(m); i++) #define SORT(v, n) sort(v, v+n) #define REVERSE(v) reverse((v).begin(), (v).end()) using namespace std; using ll = long long; const ll MOD=1000000007LL; typedef pair<int, int> P; ll ADD(ll x, ll y) { return (x+y) % MOD; } ll SUB(ll x, ll y) { return (x-y+MOD) % MOD; } ll MUL(ll x, ll y) { return x*y % MOD; } ll POW(ll x, ll e) { ll v=1; for(; e; x=MUL(x,x), e>>=1) if (e&1) v = MUL(v,x); return v; } ll DIV(ll x, ll y) { /*assert(y%MOD!=0);*/ return MUL(x, POW(y, MOD-2)); } priority_queue<int> q_descending; priority_queue<int, vector<int>, greater<int> > q_ascending; int D[31][31]; int c[501][501]; int cnt[3][31]; int main(void){ ios_base::sync_with_stdio(false); int N, C; cin >> N >> C; REP(i, C) REP(j, C) cin >> D[i][j]; REP(i, N) REP(j, N) cin >> c[i][j]; REP(i, N) REP(j, N) cnt[(i+j+2)%3][c[i][j]-1]++; //cout << cnt[0] << " vs " << cnt[1] << " vs " << cnt[2] << endl; int ans = 1 << 30; REP(i, C) REP(j, C) if(i != j) REP(k, C) if(i != k && j != k) { int tmp = 0; REP(l, C) tmp += D[l][i] * cnt[0][l]; REP(l, C) tmp += D[l][j] * cnt[1][l]; REP(l, C) tmp += D[l][k] * cnt[2][l]; if(tmp < ans) ans=tmp; } cout << ans << endl; return 0; }
[ "tikeda@tikeda.local" ]
tikeda@tikeda.local
e33bb62511db18705c718f9b0713af16b57eb8f0
cb9fc08c5aa59e7ff556e48342832fa87bb487ac
/arduino_omni_wheel/ros_lib/voxblox_msgs/FilePath.h
5a150afaace9de791b874fd533e8f5e32bb3e0f0
[]
no_license
GigaFlopsis/Omni_robot_ROS
4b1ed0a22b1c5fc08952569ef23c385823ddb2af
80ebe6c306164a41964c55f956c5caf8eac1ecd1
refs/heads/main
2023-01-20T13:52:34.987613
2020-12-01T14:17:06
2020-12-01T14:17:06
313,404,594
1
0
null
2020-11-25T20:22:21
2020-11-16T19:22:41
C++
UTF-8
C++
false
false
2,035
h
#ifndef _ROS_SERVICE_FilePath_h #define _ROS_SERVICE_FilePath_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace voxblox_msgs { static const char FILEPATH[] = "voxblox_msgs/FilePath"; class FilePathRequest : public ros::Msg { public: typedef const char* _file_path_type; _file_path_type file_path; FilePathRequest(): file_path("") { } virtual int serialize(unsigned char *outbuffer) const override { int offset = 0; uint32_t length_file_path = strlen(this->file_path); varToArr(outbuffer + offset, length_file_path); offset += 4; memcpy(outbuffer + offset, this->file_path, length_file_path); offset += length_file_path; return offset; } virtual int deserialize(unsigned char *inbuffer) override { int offset = 0; uint32_t length_file_path; arrToVar(length_file_path, (inbuffer + offset)); offset += 4; for(unsigned int k= offset; k< offset+length_file_path; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_file_path-1]=0; this->file_path = (char *)(inbuffer + offset-1); offset += length_file_path; return offset; } virtual const char * getType() override { return FILEPATH; }; virtual const char * getMD5() override { return "a1f82596372c52a517e1fe32d1e998e8"; }; }; class FilePathResponse : public ros::Msg { public: FilePathResponse() { } virtual int serialize(unsigned char *outbuffer) const override { int offset = 0; return offset; } virtual int deserialize(unsigned char *inbuffer) override { int offset = 0; return offset; } virtual const char * getType() override { return FILEPATH; }; virtual const char * getMD5() override { return "d41d8cd98f00b204e9800998ecf8427e"; }; }; class FilePath { public: typedef FilePathRequest Request; typedef FilePathResponse Response; }; } #endif
[ "devittdv@gmail.com" ]
devittdv@gmail.com
7e6b60cb872b3b6cb9a162a4598d4577369af131
89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04
/third_party/WebKit/Source/core/dom/DocumentParserTiming.cpp
2909028cd25b30df0350d4b98c0c2a2ba80b0ad5
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
bino7/chromium
8d26f84a1b6e38a73d1b97fea6057c634eff68cb
4666a6bb6fdcb1114afecf77bdaa239d9787b752
refs/heads/master
2022-12-22T14:31:53.913081
2016-09-06T10:05:11
2016-09-06T10:05:11
67,410,510
1
3
BSD-3-Clause
2022-12-17T03:08:52
2016-09-05T10:11:59
null
UTF-8
C++
false
false
2,172
cpp
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "core/dom/DocumentParserTiming.h" #include "core/dom/Document.h" #include "core/loader/DocumentLoader.h" #include "platform/TraceEvent.h" namespace blink { static const char kSupplementName[] = "DocumentParserTiming"; DocumentParserTiming& DocumentParserTiming::from(Document& document) { DocumentParserTiming* timing = static_cast<DocumentParserTiming*>(Supplement<Document>::from(document, kSupplementName)); if (!timing) { timing = new DocumentParserTiming(document); Supplement<Document>::provideTo(document, kSupplementName, timing); } return *timing; } void DocumentParserTiming::markParserStart() { if (m_parserDetached || m_parserStart > 0.0) return; DCHECK_EQ(m_parserStop, 0.0); m_parserStart = monotonicallyIncreasingTime(); notifyDocumentParserTimingChanged(); } void DocumentParserTiming::markParserStop() { if (m_parserDetached || m_parserStart == 0.0 || m_parserStop > 0.0) return; m_parserStop = monotonicallyIncreasingTime(); notifyDocumentParserTimingChanged(); } void DocumentParserTiming::markParserDetached() { DCHECK_GT(m_parserStart, 0.0); m_parserDetached = true; } void DocumentParserTiming::recordParserBlockedOnScriptLoadDuration( double duration, bool scriptInsertedViaDocumentWrite) { if (m_parserDetached || m_parserStart == 0.0 || m_parserStop > 0.0) return; m_parserBlockedOnScriptLoadDuration += duration; if (scriptInsertedViaDocumentWrite) m_parserBlockedOnScriptLoadFromDocumentWriteDuration += duration; notifyDocumentParserTimingChanged(); } DEFINE_TRACE(DocumentParserTiming) { visitor->trace(m_document); Supplement<Document>::trace(visitor); } DocumentParserTiming::DocumentParserTiming(Document& document) : m_document(document) { } void DocumentParserTiming::notifyDocumentParserTimingChanged() { if (m_document->loader()) m_document->loader()->didChangePerformanceTiming(); } } // namespace blink
[ "bino.zh@gmail.com" ]
bino.zh@gmail.com
ccb954b08c942d9d7f5e2f1ded399f78dcbf313d
0e06506ea416777ea57a7429e19716267516b91f
/Laboration_2/src/Kladdkaka.cpp
8674694dbd92fbd6a9f2454e717e202038c7b0ce
[]
no_license
morganwallin/DesignPatterns
837047fde18148a14e21b9a49ca7d6a639d9a053
2884b78f89e90c69df2ca741e492d02d9f7102cd
refs/heads/master
2022-12-08T16:30:38.915773
2020-09-15T11:12:54
2020-09-15T11:12:54
295,693,061
0
0
null
null
null
null
UTF-8
C++
false
false
531
cpp
#include "Kladdkaka.h" Kladdkaka::Kladdkaka() : BakingRecepy("Kladdkaka") { neededIngredients = { Ingredient("egg"), Ingredient("sugar"), Ingredient("baking-powder"), Ingredient("wheat-flour"), Ingredient("salt"), Ingredient("marge"), Ingredient("cocoa-powder") }; } void Kladdkaka::bakeIt() { std::cout << "How to bake Kladdkaka: \n"; std::cout << "1. Preheat oven to 175 degrees.\n"; std::cout << "2. Mix the ingredients.\n"; std::cout << "3. Put in ovenware.\n"; std::cout << "4. Bake in oven for 15 minutes.\n\n\n"; }
[ "mova1701@student.miun.se" ]
mova1701@student.miun.se
4b7f041f9b4aab9383790c30c366208935d2c50c
9e15ab238833565cee000fe37f213e4fabceda1b
/hls/add_sdy/cpp_ap_fixed.cpp
821a1f4a026a70e4767517672d0fa77c276a110c
[]
no_license
Bounce00/fpga
1d40989b4fed96c04f0c9304f20ba504f221f4ec
6baf0ff8519cfa066978b68471d7a2f8d3270e17
refs/heads/master
2020-03-28T13:32:38.290566
2018-09-14T01:41:34
2018-09-14T01:41:34
148,403,665
0
0
null
2018-09-14T01:41:35
2018-09-12T01:35:38
C++
UTF-8
C++
false
false
5,653
cpp
/******************************************************************************* Vendor: Xilinx Associated Filename: cpp_ap_fixed.cpp Purpose:Vivado HLS Coding Style example Device: All Revision History: May 30, 2008 - initial release ******************************************************************************* #- (c) Copyright 2011-2016 Xilinx, Inc. All rights reserved. #- #- This file contains confidential and proprietary information #- of Xilinx, Inc. and is protected under U.S. and #- international copyright and other intellectual property #- laws. #- #- DISCLAIMER #- This disclaimer is not a license and does not grant any #- rights to the materials distributed herewith. Except as #- otherwise provided in a valid license issued to you by #- Xilinx, and to the maximum extent permitted by applicable #- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND #- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES #- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING #- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- #- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and #- (2) Xilinx shall not be liable (whether in contract or tort, #- including negligence, or under any other theory of #- liability) for any loss or damage of any kind or nature #- related to, arising under or in connection with these #- materials, including for any direct, or any indirect, #- special, incidental, or consequential loss or damage #- (including loss of data, profits, goodwill, or any type of #- loss or damage suffered as a result of any action brought #- by a third party) even if such damage or loss was #- reasonably foreseeable or Xilinx had been advised of the #- possibility of the same. #- #- CRITICAL APPLICATIONS #- Xilinx products are not designed or intended to be fail- #- safe, or for use in any application requiring fail-safe #- performance, such as life-support or safety devices or #- systems, Class III medical devices, nuclear facilities, #- applications related to the deployment of airbags, or any #- other applications that could lead to death, personal #- injury, or severe property or environmental damage #- (individually and collectively, "Critical #- Applications"). Customer assumes the sole risk and #- liability of any use of Xilinx products in Critical #- Applications, subject only to applicable laws and #- regulations governing limitations on product liability. #- #- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS #- PART OF THIS FILE AT ALL TIMES. #- ************************************************************************ This file contains confidential and proprietary information of Xilinx, Inc. and is protected under U.S. and international copyright and other intellectual property laws. DISCLAIMER This disclaimer is not a license and does not grant any rights to the materials distributed herewith. Except as otherwise provided in a valid license issued to you by Xilinx, and to the fibon_fimum extent permitted by applicable law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and (2) Xilinx shall not be liable (whether in contract or tort, including negligence, or under any other theory of liability) for any loss or damage of any kind or nature related to, arising under or in connection with these materials, including for any direct, or any indirect, special, incidental, or consequential loss or damage (including loss of data, profits, goodwill, or any type of loss or damage suffered as a result of any action brought by a third party) even if such damage or loss was reasonably foreseeable or Xilinx had been advised of the possibility of the same. CRITICAL APPLICATIONS Xilinx products are not designed or intended to be fail-safe, or for use in any application requiring fail-safe performance, such as life-support or safety devices or systems, Class III medical devices, nuclear facilities, applications related to the deployment of airbags, or any other applications that could lead to death, personal injury, or severe property or environmental damage (individually and collectively, "Critical Applications"). Customer assumes the sole risk and liability of any use of Xilinx products in Critical Applications, subject only to applicable laws and regulations governing limitations on product liability. THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS PART OF THIS FILE AT ALL TIMES. *******************************************************************************/ #include "cpp_ap_fixed.h" dout_t cpp_ap_fixed(din1_t d_in1, din2_t d_in2) { static dint_t sum; din1_t a = 6; const din1_t aa[3][2] = {{1,2},{3,4},{5,6}}; din1_t aaa[2] = aa[1]; int bbb = 1; bbb = bbb<<char(4); din4_t g1 = a * a + a * a; const char FFT_NFFT_MAX = 4; const int FFT_LENGTH = 1 << FFT_NFFT_MAX; din1_t g2 = a *a; ap_fixed<4,1> b; // b = 0.5; b(1,0) = ap_fixed<4,1>(a.range(1,0)); // test_t aaa = 1.25; Cdin1 c,cc; c.real()= 6; c.imag() = 6; cc.real() = c.real()>>1; cc.imag() = c.imag()>>1; Cdin2 d ; d.real() = 4; d.imag() = 5; Cdin2 bb; bb = Cdin2(c) * Cdin2(c); Cdin3 e,f; e = Cdin2(c)+d; f = Cdin2(c)*d; // int b = sizeof(din1_t); sum =+ d_in1; return d_in1 + d_in2; } // XSIP watermark, do not delete 67d7842dbbe25473c3c32b93c0da8047785f30d78e8a024de1b57352245f9689
[ "Haijun.zhang@sigtrum.com" ]
Haijun.zhang@sigtrum.com
1ee97183adbd4bb0db561ee47d546273b5c42756
7e48d392300fbc123396c6a517dfe8ed1ea7179f
/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/AIModule/BTDecorator_KeepInCone.gen.cpp
47595e7ce9f37fca81d54fdde215cc3cc7a5c6fa
[]
no_license
WestRyanK/Rodent-VR
f4920071b716df6a006b15c132bc72d3b0cba002
2033946f197a07b8c851b9a5075f0cb276033af6
refs/heads/master
2021-06-14T18:33:22.141793
2020-10-27T03:25:33
2020-10-27T03:25:33
154,956,842
1
1
null
2018-11-29T09:56:21
2018-10-27T11:23:11
C++
UTF-8
C++
false
false
11,398
cpp
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "AIModule/Classes/BehaviorTree/Decorators/BTDecorator_KeepInCone.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeBTDecorator_KeepInCone() {} // Cross Module References AIMODULE_API UClass* Z_Construct_UClass_UBTDecorator_KeepInCone_NoRegister(); AIMODULE_API UClass* Z_Construct_UClass_UBTDecorator_KeepInCone(); AIMODULE_API UClass* Z_Construct_UClass_UBTDecorator(); UPackage* Z_Construct_UPackage__Script_AIModule(); AIMODULE_API UScriptStruct* Z_Construct_UScriptStruct_FBlackboardKeySelector(); // End Cross Module References void UBTDecorator_KeepInCone::StaticRegisterNativesUBTDecorator_KeepInCone() { } UClass* Z_Construct_UClass_UBTDecorator_KeepInCone_NoRegister() { return UBTDecorator_KeepInCone::StaticClass(); } struct Z_Construct_UClass_UBTDecorator_KeepInCone_Statics { static UObject* (*const DependentSingletons[])(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bUseSelfAsObserved_MetaData[]; #endif static void NewProp_bUseSelfAsObserved_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bUseSelfAsObserved; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bUseSelfAsOrigin_MetaData[]; #endif static void NewProp_bUseSelfAsOrigin_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bUseSelfAsOrigin; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Observed_MetaData[]; #endif static const UE4CodeGen_Private::FStructPropertyParams NewProp_Observed; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ConeOrigin_MetaData[]; #endif static const UE4CodeGen_Private::FStructPropertyParams NewProp_ConeOrigin; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ConeHalfAngle_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_ConeHalfAngle; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_UBTDecorator, (UObject* (*)())Z_Construct_UPackage__Script_AIModule, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::Class_MetaDataParams[] = { { "Comment", "/**\n * Cooldown decorator node.\n * A decorator node that bases its condition on whether the observed position is still inside a cone. The cone's direction is calculated when the node first becomes relevant.\n */" }, { "HideCategories", "Condition" }, { "IncludePath", "BehaviorTree/Decorators/BTDecorator_KeepInCone.h" }, { "ModuleRelativePath", "Classes/BehaviorTree/Decorators/BTDecorator_KeepInCone.h" }, { "ToolTip", "Cooldown decorator node.\nA decorator node that bases its condition on whether the observed position is still inside a cone. The cone's direction is calculated when the node first becomes relevant." }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_bUseSelfAsObserved_MetaData[] = { { "Comment", "// deprecated, set value of Observed on initialization\n" }, { "ModuleRelativePath", "Classes/BehaviorTree/Decorators/BTDecorator_KeepInCone.h" }, { "ToolTip", "deprecated, set value of Observed on initialization" }, }; #endif void Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_bUseSelfAsObserved_SetBit(void* Obj) { ((UBTDecorator_KeepInCone*)Obj)->bUseSelfAsObserved = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_bUseSelfAsObserved = { "bUseSelfAsObserved", nullptr, (EPropertyFlags)0x0010000000000000, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(UBTDecorator_KeepInCone), &Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_bUseSelfAsObserved_SetBit, METADATA_PARAMS(Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_bUseSelfAsObserved_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_bUseSelfAsObserved_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_bUseSelfAsOrigin_MetaData[] = { { "Comment", "// deprecated, set value of ConeOrigin on initialization\n" }, { "ModuleRelativePath", "Classes/BehaviorTree/Decorators/BTDecorator_KeepInCone.h" }, { "ToolTip", "deprecated, set value of ConeOrigin on initialization" }, }; #endif void Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_bUseSelfAsOrigin_SetBit(void* Obj) { ((UBTDecorator_KeepInCone*)Obj)->bUseSelfAsOrigin = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_bUseSelfAsOrigin = { "bUseSelfAsOrigin", nullptr, (EPropertyFlags)0x0010000000000000, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(UBTDecorator_KeepInCone), &Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_bUseSelfAsOrigin_SetBit, METADATA_PARAMS(Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_bUseSelfAsOrigin_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_bUseSelfAsOrigin_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_Observed_MetaData[] = { { "Category", "Blackboard" }, { "Comment", "/** blackboard key selector */" }, { "ModuleRelativePath", "Classes/BehaviorTree/Decorators/BTDecorator_KeepInCone.h" }, { "ToolTip", "blackboard key selector" }, }; #endif const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_Observed = { "Observed", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UBTDecorator_KeepInCone, Observed), Z_Construct_UScriptStruct_FBlackboardKeySelector, METADATA_PARAMS(Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_Observed_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_Observed_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_ConeOrigin_MetaData[] = { { "Category", "Blackboard" }, { "Comment", "/** blackboard key selector */" }, { "ModuleRelativePath", "Classes/BehaviorTree/Decorators/BTDecorator_KeepInCone.h" }, { "ToolTip", "blackboard key selector" }, }; #endif const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_ConeOrigin = { "ConeOrigin", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UBTDecorator_KeepInCone, ConeOrigin), Z_Construct_UScriptStruct_FBlackboardKeySelector, METADATA_PARAMS(Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_ConeOrigin_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_ConeOrigin_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_ConeHalfAngle_MetaData[] = { { "Category", "Decorator" }, { "Comment", "/** max allowed time for execution of underlying node */" }, { "ModuleRelativePath", "Classes/BehaviorTree/Decorators/BTDecorator_KeepInCone.h" }, { "ToolTip", "max allowed time for execution of underlying node" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_ConeHalfAngle = { "ConeHalfAngle", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UBTDecorator_KeepInCone, ConeHalfAngle), METADATA_PARAMS(Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_ConeHalfAngle_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_ConeHalfAngle_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_bUseSelfAsObserved, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_bUseSelfAsOrigin, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_Observed, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_ConeOrigin, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::NewProp_ConeHalfAngle, }; const FCppClassTypeInfoStatic Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<UBTDecorator_KeepInCone>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::ClassParams = { &UBTDecorator_KeepInCone::StaticClass, nullptr, &StaticCppClassTypeInfo, DependentSingletons, nullptr, Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::PropPointers, nullptr, UE_ARRAY_COUNT(DependentSingletons), 0, UE_ARRAY_COUNT(Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::PropPointers), 0, 0x001000A0u, METADATA_PARAMS(Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_UBTDecorator_KeepInCone() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UBTDecorator_KeepInCone_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(UBTDecorator_KeepInCone, 3954309473); template<> AIMODULE_API UClass* StaticClass<UBTDecorator_KeepInCone>() { return UBTDecorator_KeepInCone::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_UBTDecorator_KeepInCone(Z_Construct_UClass_UBTDecorator_KeepInCone, &UBTDecorator_KeepInCone::StaticClass, TEXT("/Script/AIModule"), TEXT("UBTDecorator_KeepInCone"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(UBTDecorator_KeepInCone); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
[ "west.ryan.k@gmail.com" ]
west.ryan.k@gmail.com
dd64c66f6f9f5e32a43f052ca8d6099b098ab3d3
ed21303caf7ecbdb1f5c035e44a36b806a619d17
/BETD/stdafx.cpp
999d0081cbcdd5b26abbfb42249fd0045d56b532
[]
no_license
presscad/TDCP
58028ef978a247e9d5aac944b0583396c14b4747
e72e27fa8c1198c62e80dd7d2bcd0d3f4588c4cb
refs/heads/master
2022-04-08T16:09:44.037771
2020-03-19T10:34:31
2020-03-19T10:34:31
null
0
0
null
null
null
null
GB18030
C++
false
false
159
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // BETD.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h"
[ "wxc_sxy@163.com" ]
wxc_sxy@163.com
1aaf26491721207a74927c382ee7efe2781072be
2ba94892764a44d9c07f0f549f79f9f9dc272151
/Engine/Source/ThirdParty/CEF3/cef_binary_3.2272.2077_windows64/cefclient/performance_test_tests.cc
d906ebf9472180a82ea549c17b77438051e825e5
[ "BSD-3-Clause", "LicenseRef-scancode-unknown", "BSD-2-Clause", "LicenseRef-scancode-proprietary-license" ]
permissive
PopCap/GameIdea
934769eeb91f9637f5bf205d88b13ff1fc9ae8fd
201e1df50b2bc99afc079ce326aa0a44b178a391
refs/heads/master
2021-01-25T00:11:38.709772
2018-09-11T03:38:56
2018-09-11T03:38:56
37,818,708
0
0
BSD-2-Clause
2018-09-11T03:39:05
2015-06-21T17:36:44
null
UTF-8
C++
false
false
9,934
cc
// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "cefclient/performance_test.h" #include "cefclient/performance_test_setup.h" #include "include/cef_v8.h" namespace client { namespace performance_test { namespace { // Test function implementations. PERF_TEST_FUNC(V8NullCreate) { PERF_ITERATIONS_START() CefRefPtr<CefV8Value> value = CefV8Value::CreateNull(); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8BoolCreate) { PERF_ITERATIONS_START() CefRefPtr<CefV8Value> value = CefV8Value::CreateBool(true); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8IntCreate) { PERF_ITERATIONS_START() CefRefPtr<CefV8Value> value = CefV8Value::CreateInt(-5); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8UIntCreate) { PERF_ITERATIONS_START() CefRefPtr<CefV8Value> value = CefV8Value::CreateUInt(10); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8DoubleCreate) { PERF_ITERATIONS_START() CefRefPtr<CefV8Value> value = CefV8Value::CreateDouble(12.432); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8DateCreate) { static cef_time_t time = {2012, 1, 0, 1}; PERF_ITERATIONS_START() CefRefPtr<CefV8Value> value = CefV8Value::CreateDate(time); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8StringCreate) { CefString str = "test string"; PERF_ITERATIONS_START() CefRefPtr<CefV8Value> value = CefV8Value::CreateString(str); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8ArrayCreate) { PERF_ITERATIONS_START() CefRefPtr<CefV8Value> value = CefV8Value::CreateArray(1); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8ArraySetValue) { CefRefPtr<CefV8Value> val = CefV8Value::CreateBool(true); CefRefPtr<CefV8Value> array = CefV8Value::CreateArray(1); array->SetValue(0, val); PERF_ITERATIONS_START() array->SetValue(0, val); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8ArrayGetValue) { CefRefPtr<CefV8Value> val = CefV8Value::CreateBool(true); CefRefPtr<CefV8Value> array = CefV8Value::CreateArray(1); array->SetValue(0, val); PERF_ITERATIONS_START() CefRefPtr<CefV8Value> ret = array->GetValue(0); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8FunctionCreate) { class Handler : public CefV8Handler { public: Handler() {} virtual bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { return false; } IMPLEMENT_REFCOUNTING(Handler); }; CefString name = "name"; CefRefPtr<CefV8Handler> handler = new Handler(); PERF_ITERATIONS_START() CefRefPtr<CefV8Value> value = CefV8Value::CreateFunction(name, handler); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8FunctionExecute) { class Handler : public CefV8Handler { public: Handler() {} virtual bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { return true; } IMPLEMENT_REFCOUNTING(Handler); }; CefString name = "name"; CefRefPtr<CefV8Handler> handler = new Handler(); CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction(name, handler); CefRefPtr<CefV8Value> obj = CefV8Context::GetCurrentContext()->GetGlobal(); CefV8ValueList args; PERF_ITERATIONS_START() func->ExecuteFunction(obj, args); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8FunctionExecuteWithContext) { class Handler : public CefV8Handler { public: Handler() {} virtual bool Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { return true; } IMPLEMENT_REFCOUNTING(Handler); }; CefString name = "name"; CefRefPtr<CefV8Handler> handler = new Handler(); CefRefPtr<CefV8Value> func = CefV8Value::CreateFunction(name, handler); CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext(); CefRefPtr<CefV8Value> obj = context->GetGlobal(); CefV8ValueList args; PERF_ITERATIONS_START() func->ExecuteFunctionWithContext(context, obj, args); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8ObjectCreate) { PERF_ITERATIONS_START() CefRefPtr<CefV8Value> value = CefV8Value::CreateObject(NULL); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8ObjectCreateWithAccessor) { class Accessor : public CefV8Accessor { public: Accessor() {} virtual bool Get(const CefString& name, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { return true; } virtual bool Set(const CefString& name, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) OVERRIDE { return true; } IMPLEMENT_REFCOUNTING(Accessor); }; CefRefPtr<CefV8Accessor> accessor = new Accessor(); PERF_ITERATIONS_START() CefRefPtr<CefV8Value> value = CefV8Value::CreateObject(accessor); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8ObjectSetValue) { CefString name = "name"; CefRefPtr<CefV8Value> val = CefV8Value::CreateBool(true); CefRefPtr<CefV8Value> obj = CefV8Value::CreateObject(NULL); obj->SetValue(name, val, V8_PROPERTY_ATTRIBUTE_NONE); PERF_ITERATIONS_START() obj->SetValue(name, val, V8_PROPERTY_ATTRIBUTE_NONE); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8ObjectGetValue) { CefString name = "name"; CefRefPtr<CefV8Value> val = CefV8Value::CreateBool(true); CefRefPtr<CefV8Value> obj = CefV8Value::CreateObject(NULL); obj->SetValue(name, val, V8_PROPERTY_ATTRIBUTE_NONE); PERF_ITERATIONS_START() CefRefPtr<CefV8Value> ret = obj->GetValue(name); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8ObjectSetValueWithAccessor) { class Accessor : public CefV8Accessor { public: Accessor() {} virtual bool Get(const CefString& name, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { return true; } virtual bool Set(const CefString& name, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) OVERRIDE { val_ = value; return true; } CefRefPtr<CefV8Value> val_; IMPLEMENT_REFCOUNTING(Accessor); }; CefRefPtr<CefV8Accessor> accessor = new Accessor(); CefString name = "name"; CefRefPtr<CefV8Value> val = CefV8Value::CreateBool(true); CefRefPtr<CefV8Value> obj = CefV8Value::CreateObject(accessor); obj->SetValue(name, V8_ACCESS_CONTROL_DEFAULT, V8_PROPERTY_ATTRIBUTE_NONE); obj->SetValue(name, val, V8_PROPERTY_ATTRIBUTE_NONE); PERF_ITERATIONS_START() obj->SetValue(name, val, V8_PROPERTY_ATTRIBUTE_NONE); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8ObjectGetValueWithAccessor) { class Accessor : public CefV8Accessor { public: Accessor() : val_(CefV8Value::CreateBool(true)) {} virtual bool Get(const CefString& name, const CefRefPtr<CefV8Value> object, CefRefPtr<CefV8Value>& retval, CefString& exception) OVERRIDE { retval = val_; return true; } virtual bool Set(const CefString& name, const CefRefPtr<CefV8Value> object, const CefRefPtr<CefV8Value> value, CefString& exception) OVERRIDE { return true; } CefRefPtr<CefV8Value> val_; IMPLEMENT_REFCOUNTING(Accessor); }; CefRefPtr<CefV8Accessor> accessor = new Accessor(); CefString name = "name"; CefRefPtr<CefV8Value> val = CefV8Value::CreateBool(true); CefRefPtr<CefV8Value> obj = CefV8Value::CreateObject(accessor); obj->SetValue(name, V8_ACCESS_CONTROL_DEFAULT, V8_PROPERTY_ATTRIBUTE_NONE); obj->SetValue(name, val, V8_PROPERTY_ATTRIBUTE_NONE); PERF_ITERATIONS_START() CefRefPtr<CefV8Value> ret = obj->GetValue(name); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8ContextEnterExit) { CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext(); PERF_ITERATIONS_START() context->Enter(); context->Exit(); PERF_ITERATIONS_END() } PERF_TEST_FUNC(V8ContextEval) { CefRefPtr<CefV8Context> context = CefV8Context::GetCurrentContext(); CefString jsCode = "var i = 0;"; CefRefPtr<CefV8Value> retval; CefRefPtr<CefV8Exception> exception; PERF_ITERATIONS_START() context->Eval(jsCode, retval, exception); PERF_ITERATIONS_END() } } // namespace // Test function entries. const PerfTestEntry kPerfTests[] = { PERF_TEST_ENTRY(V8NullCreate), PERF_TEST_ENTRY(V8BoolCreate), PERF_TEST_ENTRY(V8IntCreate), PERF_TEST_ENTRY(V8UIntCreate), PERF_TEST_ENTRY(V8DoubleCreate), PERF_TEST_ENTRY(V8DateCreate), PERF_TEST_ENTRY(V8StringCreate), PERF_TEST_ENTRY(V8ArrayCreate), PERF_TEST_ENTRY(V8ArraySetValue), PERF_TEST_ENTRY(V8ArrayGetValue), PERF_TEST_ENTRY(V8FunctionCreate), PERF_TEST_ENTRY(V8FunctionExecute), PERF_TEST_ENTRY(V8FunctionExecuteWithContext), PERF_TEST_ENTRY(V8ObjectCreate), PERF_TEST_ENTRY(V8ObjectCreateWithAccessor), PERF_TEST_ENTRY(V8ObjectSetValue), PERF_TEST_ENTRY(V8ObjectGetValue), PERF_TEST_ENTRY(V8ObjectSetValueWithAccessor), PERF_TEST_ENTRY(V8ObjectGetValueWithAccessor), PERF_TEST_ENTRY(V8ContextEnterExit), PERF_TEST_ENTRY(V8ContextEval), }; const int kPerfTestsCount = (sizeof(kPerfTests) / sizeof(kPerfTests[0])); } // namespace performance_test } // namespace client
[ "dkroell@acm.org" ]
dkroell@acm.org
48fbe150a91110736dbac01cc62e781c9f0a559a
2832578defcbb8384b219a58428edfd822036a6c
/mm3dMapperEvent/osgFittingWallSpaceEvent.cpp
031cc6eac1ef73da3263c8b607b4ca48b4cebc3d
[]
no_license
aabin/mapmatrix3d-2.0
83cba485b041a9fc628c41beddbcadeadb4a1741
8eb22b3b849621df44809c1b6e16f7c208fb7406
refs/heads/master
2021-05-23T10:49:26.930463
2018-05-23T06:33:20
2018-05-23T06:33:20
null
0
0
null
null
null
null
GB18030
C++
false
false
5,944
cpp
// osgFittingWallSpaceEvent.cpp : 定义 DLL 应用程序的导出函数。 // #include "stdafx.h" #include "ThreadSafeUpdateCallback.h" #include "InterfaceBaseDrawer.h" #include "osgFittingWallSpaceEvent.h" #include "InterfaceOsgFinder.h" #include "Geometry.h" #include "cvLine.h" #define WALLCOLOR osg::Vec4d(0,1,1,0.4) //墙面颜色 void COsgFittingWallSpaceEvent::UpdateActivatedStatus(std::vector<OperatingState> vecOpState) { bool flag = false; if (isActivated == true) { flag = true; } isActivated = isActivate(vecOpState, OPS_FITTING_WALLSPACE); if (isActivated == false && flag == true) { ClearGroupResult(tempGroup); iSigEventCallBack->EmitSigShowOpsHint(""); } if (isActivated && flag == false) //刚激活 { InterfaceOsgExtractWallFactory IWallFactory; InterfaceOsgExtractWall* IWall = IWallFactory.create(); IWall->addDraggerToScene(mRoot, slotGroup, editWallGroup); //读取面数据 IWall->readWallDataFromSqlite3(planePara, iSqliteDatabase, "runData.db"); InterfaceBaseDrawerFactory IDrawerFactory; InterfaceBaseDrawer* IDrawer = IDrawerFactory.create(); ClearGroupResult(editWallGroup); IWall->getWorldMatrix(mRoot, worldMatrix); for (size_t i = 0; i < planePara.size(); ++i) { IDrawer->BaseDrawPolygon(planePara[i].coord, WALLCOLOR, editWallGroup, worldMatrix); } //读取点数据 IWall->readPointDataFromSqlite3(vecTotalTriangle,iSqliteDatabase,"Points"); if (vecTotalTriangle.size()>0) { std::vector<osg::Vec3d> vecNormal; IWall->readPointDataFromSqlite3(vecNormal, iSqliteDatabase, "Normal"); normal = vecNormal[0]; if (IWall->fittingWallSpace(vecTotalTriangle, planePara, normal, worldMatrix))//拟合平面 { InterfaceBaseDrawerFactory IDrawerFactory; InterfaceBaseDrawer* IDrawer = IDrawerFactory.create(); IDrawer->BaseDrawPolygon(planePara.back().coord, WALLCOLOR, editWallGroup, worldMatrix); vecTotalTriangle.clear(); IWall->clearPointDataInSqlite3(iSqliteDatabase,"Points"); char strMsg[299]; sprintf(strMsg, "提取墙面:墙面倾斜角:%f ° 墙面拟合误差:%lf", planePara.back().angle, planePara.back().err); iSigEventCallBack->EmitSigShowOpsHint(strMsg); IWall->saveWallDataToSqlite3(planePara, iSqliteDatabase, "runData.db"); } } else { iSigEventCallBack->EmitSigShowOpsHint("提取墙面:找不到采样信息"); } } } bool COsgFittingWallSpaceEvent::handle(const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa) { if (isActivated) { InterfaceBaseDrawerFactory IDrawerFactory; InterfaceBaseDrawer* IDrawer = IDrawerFactory.create(); InterfaceOsgExtractWallFactory IWallFactory; InterfaceOsgExtractWall* IWall = IWallFactory.create(); //执行拖动相关事件 if (IWall->draggerEvent(atWall, ea, aa, mViewer, _activeDragger, editWallGroup, tempGroup, partnerPoint, wallSelected, _pointer, endPoint, planePara, worldMatrix, WALLCOLOR)) { //保存墙面信息 IWall->saveWallDataToSqlite3(planePara, iSqliteDatabase, "runData.db"); } if (IsLeftClick(ea) && GetKeyState(VK_CONTROL) < 0)//单击事件 { CPickResult pickResult = PickResult(ea.getX(), ea.getY(), mViewer); worldPt = pickResult.worldPt; if (worldPt.x() == 0 && worldPt.y() == 0 && worldPt.z() == 0) { return false; } int _i = 0; for (std::vector<WallInfo>::iterator ite = (planePara).begin(); ite != (planePara).end(); ++ite) { if (CL::Point_In_Rectangle_3D(worldPt, partnerPoint, (*ite).coord))//点在墙面上 { //点在wall上激活单击事件 if (!pushEvent(ea, aa)) { return false; } atWall = true; editWallGroup->removeChild(_i); IDrawer->BaseDrawPolygon((*ite).coord, WALLCOLOR, tempGroup, worldMatrix); wallSelected = *ite; (planePara).erase(ite); IWall->saveWallDataToSqlite3(planePara, iSqliteDatabase, "runData.db"); return false; } ++_i; } return false; } else if(IsKeyPress(ea)) { if (ea.getKey() == osgGA::GUIEventAdapter::KEY_M) { char strMsg[99]; sprintf(strMsg, "节点数:%d", mRoot->getNumChildren()); iSigEventCallBack->EmitSigShowOpsHint(strMsg); } else if (ea.getKey() == osgGA::GUIEventAdapter::KEY_BackSpace) { int num = editWallGroup->getNumChildren(); if (num>0) { editWallGroup->removeChild(num - 1); planePara.pop_back(); //保存墙面信息 IWall->saveWallDataToSqlite3(planePara, iSqliteDatabase, "runData.db"); } } else if (ea.getKey() == osgGA::GUIEventAdapter::KEY_Z) { ClearGroupResult(editWallGroup); ClearGroupResult(tempGroup); planePara.clear(); //保存墙面信息 IWall->saveWallDataToSqlite3(planePara, iSqliteDatabase, "runData.db"); } } } return false; } bool COsgFittingWallSpaceEvent::pushEvent(const osgGA::GUIEventAdapter &ea, osgGA::GUIActionAdapter &aa) { osgUtil::LineSegmentIntersector::Intersections intersections; _pointer.reset(); if (mViewer->computeIntersections(ea.getX(), ea.getY(), intersections)) { _pointer.setCamera(mViewer->getCamera()); _pointer.setMousePosition(ea.getX(), ea.getY()); for (osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin(); hitr != intersections.end(); ++hitr) { _pointer.addIntersection(hitr->nodePath, hitr->getWorldIntersectPoint()); } for (osg::NodePath::iterator itr = _pointer._hitList.front().first.begin(); itr != _pointer._hitList.front().first.end(); ++itr) { CDraggerPoint* dragger = dynamic_cast<CDraggerPoint*>(*itr); if (dragger) { dragger->handle(_pointer, ea, aa); _activeDragger = dragger; return true; } } } return false; }
[ "noreply@github.com" ]
aabin.noreply@github.com
e679d4f410b193f48eb4690062c0f67fdb7ee313
a335057fbc9dc7637c1d7cf840a18d197ce5f0bf
/fastpath/router/message_wrapper.cpp
1a3c77a4bbc6d177d972d62a22efbf1f4e37fe20
[]
no_license
wannabegeek/Fastpath
d6d78e0318a389720ceaa814c53c723e1a2866f3
8cc0c0c846deca7a7e693678c53995d37a868aac
refs/heads/master
2021-06-01T01:07:37.627557
2016-06-15T08:33:43
2016-06-15T08:33:43
51,838,238
2
0
null
null
null
null
UTF-8
C++
false
false
2,231
cpp
/*************************************************************************** __FILE__ ------------------- copyright : Copyright (c) 2004-2016 Tom Fewster email : tom@wannabegeek.com date : 26/03/2016 ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ***************************************************************************/ #include "message_wrapper.h" namespace fp { message_wrapper::message_wrapper(const MessageBuffer::ByteStorageType &buffer) noexcept : m_byte_storage(buffer) { } message_wrapper::message_wrapper(const MessageBuffer::ByteStorageType &buffer, const SharedMemoryManager::shared_ptr_type &shared_ptr) noexcept : m_byte_storage(buffer), m_shared_ptr(shared_ptr) { } const SharedMemoryManager::shared_ptr_type &message_wrapper::getSharedPtrBuffer() const noexcept { if (m_shared_ptr) { return m_shared_ptr; } else { ERROR_LOG("We need to create a shared ptr buffer"); return m_shared_ptr; } } }
[ "tom@wannabegeek.com" ]
tom@wannabegeek.com
6c094e84997be01899efb83780aae98592b2c699
b7dc016762f67a038a9110bf6222e96deedaecc4
/src/port.h
2b073cc4f96c41fad1f7c6fe94a870aa7cdf87a3
[]
no_license
snavendu/Wifi_Switch
5f777cfc544b3c5b1c67f910a8bc23d5fed497ec
6c08ac61a31ea52746b56720e15e42a09d530e4a
refs/heads/master
2020-07-09T13:30:14.838289
2019-09-03T09:32:55
2019-09-03T09:32:55
203,981,220
0
0
null
null
null
null
UTF-8
C++
false
false
1,163
h
#ifndef PORT_H #define PORT_H #include "driver/i2c.h" #include "driver/gpio.h" #include <stdio.h> #define REG_IODIRA 0x00 #define REG_IODIRB 0x01 #define REG_IPOLA 0x02 #define REG_IPOLB 0x03 #define REG_GPINTENA 0x04 #define REG_GPINTENB 0x05 #define REG_DEFVALA 0x06 #define REG_DEFVALB 0x07 #define REG_INTCONA 0x08 #define REG_INTCONB 0x09 #define REG_IOCON 0x0A #define REG_GPPUA 0x0C #define REG_GPPUB 0x0D #define REG_INTFA 0x0E #define REG_INTFB 0x0F #define REG_INTCAPA 0x10 #define REG_INTCAPB 0x11 #define REG_GPIOA 0x12 #define REG_GPIOB 0x13 #define REG_OLATA 0x14 #define REG_OLATB 0x15 typedef enum{ OUT, IN }dir_t; class IO_2{ public: IO_2(); //it will set up all default values for corresponding direction //if the dir is for input then set pullup regster also void setMode(uint8_t,dir_t); void on(uint8_t); void off(uint8_t); void setInt(uint8_t); private: gpio_num_t scl = GPIO_NUM_2; gpio_num_t sda = GPIO_NUM_4; i2c_cmd_handle_t cmd; i2c_config_t conf; void set(uint8_t addr , uint8_t val); uint8_t* get(uint8_t addr); }; #endif
[ "snavendu0@gmail.com" ]
snavendu0@gmail.com
56fc63f3cf7b9abce31a914386172a63533ed94f
8db0e2d4b42987f8acb854fdb7813fd74fece445
/src/qt/dequantstrings.cpp
8ed6c51f48aa2a663070dc03ef8a9d9a908d36d9
[ "MIT" ]
permissive
sp1k31973/dequant-1
c6853df1b19d43d6def529364e209c76e9d21d50
8fdd17e4794abd307e43b2c624c2e706d86a6668
refs/heads/master
2020-05-14T18:07:47.097544
2019-03-23T18:38:39
2019-03-23T18:38:39
181,905,527
0
0
MIT
2019-04-17T14:11:49
2019-04-17T14:11:48
null
UTF-8
C++
false
false
29,049
cpp
#include <QtGlobal> // Automatically generated by extract_strings.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif static const char UNUSED *dequant_strings[] = { QT_TRANSLATE_NOOP("dequant-core", "" "(1 = keep tx meta data e.g. account owner and payment request information, 2 " "= drop tx meta data)"), QT_TRANSLATE_NOOP("dequant-core", "" "Allow JSON-RPC connections from specified source. Valid for <ip> are a " "single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or " "a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"), QT_TRANSLATE_NOOP("dequant-core", "" "An error occurred while setting up the RPC address %s port %u for listening: " "%s"), QT_TRANSLATE_NOOP("dequant-core", "" "Bind to given address and always listen on it. Use [host]:port notation for " "IPv6"), QT_TRANSLATE_NOOP("dequant-core", "" "Bind to given address and whitelist peers connecting to it. Use [host]:port " "notation for IPv6"), QT_TRANSLATE_NOOP("dequant-core", "" "Bind to given address to listen for JSON-RPC connections. Use [host]:port " "notation for IPv6. This option can be specified multiple times (default: " "bind to all interfaces)"), QT_TRANSLATE_NOOP("dequant-core", "" "Cannot obtain a lock on data directory %s. Dequant Core is probably already " "running."), QT_TRANSLATE_NOOP("dequant-core", "" "Change automatic finalized budget voting behavior. mode=auto: Vote for only " "exact finalized budget match to my generated budget. (string, default: auto)"), QT_TRANSLATE_NOOP("dequant-core", "" "Continuously rate-limit free transactions to <n>*1000 bytes per minute " "(default:%u)"), QT_TRANSLATE_NOOP("dequant-core", "" "Create new files with system default permissions, instead of umask 077 (only " "effective with disabled wallet functionality)"), QT_TRANSLATE_NOOP("dequant-core", "" "Delete all wallet transactions and only recover those parts of the " "blockchain through -rescan on startup"), QT_TRANSLATE_NOOP("dequant-core", "" "Disable all Dequant Core specific functionality (Masternodes, SwiftTX, " "Budgeting) (0-1, default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "" "Distributed under the MIT software license, see the accompanying file " "COPYING or <http://www.opensource.org/licenses/mit-license.php>."), QT_TRANSLATE_NOOP("dequant-core", "" "Enable SwiftTX, show confirmations for locked transactions (bool, default: %s)"), QT_TRANSLATE_NOOP("dequant-core", "" "Enable spork administration functionality with the appropriate private key."), QT_TRANSLATE_NOOP("dequant-core", "" "Enter regression test mode, which uses a special chain in which blocks can " "be solved instantly."), QT_TRANSLATE_NOOP("dequant-core", "" "Error: Listening for incoming connections failed (listen returned error %s)"), QT_TRANSLATE_NOOP("dequant-core", "" "Error: The transaction was rejected! This might happen if some of the coins " "in your wallet were already spent, such as if you used a copy of wallet.dat " "and coins were spent in the copy but not marked as spent here."), QT_TRANSLATE_NOOP("dequant-core", "" "Error: This transaction requires a transaction fee of at least %s because of " "its amount, complexity, or use of recently received funds!"), QT_TRANSLATE_NOOP("dequant-core", "" "Error: Unsupported argument -checklevel found. Checklevel must be level 4."), QT_TRANSLATE_NOOP("dequant-core", "" "Error: Unsupported argument -socks found. Setting SOCKS version isn't " "possible anymore, only SOCKS5 proxies are supported."), QT_TRANSLATE_NOOP("dequant-core", "" "Execute command when a relevant alert is received or we see a really long " "fork (%s in cmd is replaced by message)"), QT_TRANSLATE_NOOP("dequant-core", "" "Execute command when a wallet transaction changes (%s in cmd is replaced by " "TxID)"), QT_TRANSLATE_NOOP("dequant-core", "" "Execute command when the best block changes (%s in cmd is replaced by block " "hash)"), QT_TRANSLATE_NOOP("dequant-core", "" "Fees (in DEQ/Kb) smaller than this are considered zero fee for relaying " "(default: %s)"), QT_TRANSLATE_NOOP("dequant-core", "" "Fees (in DEQ/Kb) smaller than this are considered zero fee for transaction " "creation (default: %s)"), QT_TRANSLATE_NOOP("dequant-core", "" "Flush database activity from memory pool to disk log every <n> megabytes " "(default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "" "If paytxfee is not set, include enough fee so transactions begin " "confirmation on average within n blocks (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "" "In this mode -genproclimit controls how many blocks are generated " "immediately."), QT_TRANSLATE_NOOP("dequant-core", "" "Insufficient or insufficient confirmed funds, you might need to wait a few " "minutes and try again."), QT_TRANSLATE_NOOP("dequant-core", "" "Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay " "fee of %s to prevent stuck transactions)"), QT_TRANSLATE_NOOP("dequant-core", "" "Keep the specified amount available for spending at all times (default: 0)"), QT_TRANSLATE_NOOP("dequant-core", "" "Log transaction priority and fee per kB when mining blocks (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "" "Maintain a full transaction index, used by the getrawtransaction rpc call " "(default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "" "Maximum size of data in data carrier transactions we relay and mine " "(default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "" "Maximum total fees to use in a single wallet transaction, setting too low " "may abort large transactions (default: %s)"), QT_TRANSLATE_NOOP("dequant-core", "" "Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "" "Output debugging information (default: %u, supplying <category> is optional)"), QT_TRANSLATE_NOOP("dequant-core", "" "Query for peer addresses via DNS lookup, if low on addresses (default: 1 " "unless -connect)"), QT_TRANSLATE_NOOP("dequant-core", "" "Randomize credentials for every proxy connection. This enables Tor stream " "isolation (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "" "Require high priority for relaying free or low-fee transactions (default:%u)"), QT_TRANSLATE_NOOP("dequant-core", "" "Send trace/debug info to console instead of debug.log file (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "" "Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), QT_TRANSLATE_NOOP("dequant-core", "" "Set the number of script verification threads (%u to %d, 0 = auto, <0 = " "leave that many cores free, default: %d)"), QT_TRANSLATE_NOOP("dequant-core", "" "Set the number of threads for coin generation if enabled (-1 = all cores, " "default: %d)"), QT_TRANSLATE_NOOP("dequant-core", "" "Show N confirmations for a successfully locked transaction (0-9999, default: " "%u)"), QT_TRANSLATE_NOOP("dequant-core", "" "Support filtering of blocks and transaction with bloom filters (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "" "SwiftTX requires inputs with at least 6 confirmations, you might need to wait " "a few minutes and try again."), QT_TRANSLATE_NOOP("dequant-core", "" "This is a pre-release test build - use at your own risk - do not use for " "staking or merchant applications!"), QT_TRANSLATE_NOOP("dequant-core", "" "This product includes software developed by the OpenSSL Project for use in " "the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software " "written by Eric Young and UPnP software written by Thomas Bernard."), QT_TRANSLATE_NOOP("dequant-core", "" "To use dequantd, or the -server option to dequant-qt, you must set an rpcpassword " "in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=dequantrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file " "permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"Dequant Core Alert\" admin@foo.com\n"), QT_TRANSLATE_NOOP("dequant-core", "" "Unable to bind to %s on this computer. Dequant Core is probably already running."), QT_TRANSLATE_NOOP("dequant-core", "" "Unable to locate enough funds for this transaction that are not equal 1000 " "DEQ."), QT_TRANSLATE_NOOP("dequant-core", "" "Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: " "%s)"), QT_TRANSLATE_NOOP("dequant-core", "" "Warning: -maxtxfee is set very high! Fees this large could be paid on a " "single transaction."), QT_TRANSLATE_NOOP("dequant-core", "" "Warning: -paytxfee is set very high! This is the transaction fee you will " "pay if you send a transaction."), QT_TRANSLATE_NOOP("dequant-core", "" "Warning: Please check that your computer's date and time are correct! If " "your clock is wrong Dequant Core will not work properly."), QT_TRANSLATE_NOOP("dequant-core", "" "Warning: The network does not appear to fully agree! Some miners appear to " "be experiencing issues."), QT_TRANSLATE_NOOP("dequant-core", "" "Warning: We do not appear to fully agree with our peers! You may need to " "upgrade, or other nodes may need to upgrade."), QT_TRANSLATE_NOOP("dequant-core", "" "Warning: error reading wallet.dat! All keys read correctly, but transaction " "data or address book entries might be missing or incorrect."), QT_TRANSLATE_NOOP("dequant-core", "" "Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as " "wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect " "you should restore from a backup."), QT_TRANSLATE_NOOP("dequant-core", "" "Whitelist peers connecting from the given netmask or IP address. Can be " "specified multiple times."), QT_TRANSLATE_NOOP("dequant-core", "" "Whitelisted peers cannot be DoS banned and their transactions are always " "relayed, even if they are already in the mempool, useful e.g. for a gateway"), QT_TRANSLATE_NOOP("dequant-core", "" "You must specify a masternodeprivkey in the configuration. Please see " "documentation for help."), QT_TRANSLATE_NOOP("dequant-core", "(3133 could be used only on mainnet)"), QT_TRANSLATE_NOOP("dequant-core", "(default: %s)"), QT_TRANSLATE_NOOP("dequant-core", "(default: 1)"), QT_TRANSLATE_NOOP("dequant-core", "(must be 3133 for mainnet)"), QT_TRANSLATE_NOOP("dequant-core", "<category> can be:"), QT_TRANSLATE_NOOP("dequant-core", "Accept command line and JSON-RPC commands"), QT_TRANSLATE_NOOP("dequant-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"), QT_TRANSLATE_NOOP("dequant-core", "Accept public REST requests (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Acceptable ciphers (default: %s)"), QT_TRANSLATE_NOOP("dequant-core", "Add a node to connect to and attempt to keep the connection open"), QT_TRANSLATE_NOOP("dequant-core", "Allow DNS lookups for -addnode, -seednode and -connect"), QT_TRANSLATE_NOOP("dequant-core", "Already have that input."), QT_TRANSLATE_NOOP("dequant-core", "Always query for peer addresses via DNS lookup (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Attempt to force blockchain corruption recovery"), QT_TRANSLATE_NOOP("dequant-core", "Attempt to recover private keys from a corrupt wallet.dat"), QT_TRANSLATE_NOOP("dequant-core", "Automatically create Tor hidden service (default: %d)"), QT_TRANSLATE_NOOP("dequant-core", "Block creation options:"), QT_TRANSLATE_NOOP("dequant-core", "Can't find random Masternode."), QT_TRANSLATE_NOOP("dequant-core", "Cannot downgrade wallet"), QT_TRANSLATE_NOOP("dequant-core", "Cannot resolve -bind address: '%s'"), QT_TRANSLATE_NOOP("dequant-core", "Cannot resolve -externalip address: '%s'"), QT_TRANSLATE_NOOP("dequant-core", "Cannot resolve -whitebind address: '%s'"), QT_TRANSLATE_NOOP("dequant-core", "Cannot write default address"), QT_TRANSLATE_NOOP("dequant-core", "Collateral not valid."), QT_TRANSLATE_NOOP("dequant-core", "Connect only to the specified node(s)"), QT_TRANSLATE_NOOP("dequant-core", "Connect through SOCKS5 proxy"), QT_TRANSLATE_NOOP("dequant-core", "Connect to a node to retrieve peer addresses, and disconnect"), QT_TRANSLATE_NOOP("dequant-core", "Connection options:"), QT_TRANSLATE_NOOP("dequant-core", "Copyright (C) 2009-%i The Bitcoin Core Developers"), QT_TRANSLATE_NOOP("dequant-core", "Copyright (C) 2014-%i The Dash Core Developers"), QT_TRANSLATE_NOOP("dequant-core", "Copyright (C) 2015-%i The PIVX Core Developers"), QT_TRANSLATE_NOOP("dequant-core", "Copyright (C) 2017-%i The Dequant Core Developers"), QT_TRANSLATE_NOOP("dequant-core", "Corrupted block database detected"), QT_TRANSLATE_NOOP("dequant-core", "Could not parse -rpcbind value %s as network address"), QT_TRANSLATE_NOOP("dequant-core", "Could not parse masternode.conf"), QT_TRANSLATE_NOOP("dequant-core", "Debugging/Testing options:"), QT_TRANSLATE_NOOP("dequant-core", "Delete blockchain folders and resync from scratch"), QT_TRANSLATE_NOOP("dequant-core", "Disable OS notifications for incoming transactions (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Disable safemode, override a real safe mode event (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Discover own IP address (default: 1 when listening and no -externalip)"), QT_TRANSLATE_NOOP("dequant-core", "Display the stake modifier calculations in the debug.log file."), QT_TRANSLATE_NOOP("dequant-core", "Display verbose coin stake messages in the debug.log file."), QT_TRANSLATE_NOOP("dequant-core", "Do not load the wallet and disable wallet RPC calls"), QT_TRANSLATE_NOOP("dequant-core", "Do you want to rebuild the block database now?"), QT_TRANSLATE_NOOP("dequant-core", "Done loading"), QT_TRANSLATE_NOOP("dequant-core", "Enable publish hash block in <address>"), QT_TRANSLATE_NOOP("dequant-core", "Enable publish hash transaction (locked via SwiftTX) in <address>"), QT_TRANSLATE_NOOP("dequant-core", "Enable publish hash transaction in <address>"), QT_TRANSLATE_NOOP("dequant-core", "Enable publish raw block in <address>"), QT_TRANSLATE_NOOP("dequant-core", "Enable publish raw transaction (locked via SwiftTX) in <address>"), QT_TRANSLATE_NOOP("dequant-core", "Enable publish raw transaction in <address>"), QT_TRANSLATE_NOOP("dequant-core", "Enable staking functionality (0-1, default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Enable the client to act as a masternode (0-1, default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Entries are full."), QT_TRANSLATE_NOOP("dequant-core", "Error connecting to Masternode."), QT_TRANSLATE_NOOP("dequant-core", "Error initializing block database"), QT_TRANSLATE_NOOP("dequant-core", "Error initializing wallet database environment %s!"), QT_TRANSLATE_NOOP("dequant-core", "Error loading block database"), QT_TRANSLATE_NOOP("dequant-core", "Error loading wallet.dat"), QT_TRANSLATE_NOOP("dequant-core", "Error loading wallet.dat: Wallet corrupted"), QT_TRANSLATE_NOOP("dequant-core", "Error loading wallet.dat: Wallet requires newer version of Dequant Core"), QT_TRANSLATE_NOOP("dequant-core", "Error opening block database"), QT_TRANSLATE_NOOP("dequant-core", "Error reading from database, shutting down."), QT_TRANSLATE_NOOP("dequant-core", "Error recovering public key."), QT_TRANSLATE_NOOP("dequant-core", "Error"), QT_TRANSLATE_NOOP("dequant-core", "Error: A fatal internal error occured, see debug.log for details"), QT_TRANSLATE_NOOP("dequant-core", "Error: Disk space is low!"), QT_TRANSLATE_NOOP("dequant-core", "Error: Unsupported argument -tor found, use -onion."), QT_TRANSLATE_NOOP("dequant-core", "Error: Wallet locked, unable to create transaction!"), QT_TRANSLATE_NOOP("dequant-core", "Failed to listen on any port. Use -listen=0 if you want this."), QT_TRANSLATE_NOOP("dequant-core", "Failed to read block index"), QT_TRANSLATE_NOOP("dequant-core", "Failed to read block"), QT_TRANSLATE_NOOP("dequant-core", "Failed to write block index"), QT_TRANSLATE_NOOP("dequant-core", "Fee (in DEQ/kB) to add to transactions you send (default: %s)"), QT_TRANSLATE_NOOP("dequant-core", "Finalizing transaction."), QT_TRANSLATE_NOOP("dequant-core", "Force safe mode (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Found enough users, signing ( waiting %s )"), QT_TRANSLATE_NOOP("dequant-core", "Found enough users, signing ..."), QT_TRANSLATE_NOOP("dequant-core", "Generate coins (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "How many blocks to check at startup (default: %u, 0 = all)"), QT_TRANSLATE_NOOP("dequant-core", "If <category> is not supplied, output all debugging information."), QT_TRANSLATE_NOOP("dequant-core", "Importing..."), QT_TRANSLATE_NOOP("dequant-core", "Imports blocks from external blk000??.dat file"), QT_TRANSLATE_NOOP("dequant-core", "Include IP addresses in debug output (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Incompatible mode."), QT_TRANSLATE_NOOP("dequant-core", "Incompatible version."), QT_TRANSLATE_NOOP("dequant-core", "Incorrect or no genesis block found. Wrong datadir for network?"), QT_TRANSLATE_NOOP("dequant-core", "Information"), QT_TRANSLATE_NOOP("dequant-core", "Initialization sanity check failed. Dequant Core is shutting down."), QT_TRANSLATE_NOOP("dequant-core", "Input is not valid."), QT_TRANSLATE_NOOP("dequant-core", "Insufficient funds"), QT_TRANSLATE_NOOP("dequant-core", "Insufficient funds."), QT_TRANSLATE_NOOP("dequant-core", "Invalid -onion address or hostname: '%s'"), QT_TRANSLATE_NOOP("dequant-core", "Invalid -proxy address or hostname: '%s'"), QT_TRANSLATE_NOOP("dequant-core", "Invalid amount for -maxtxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("dequant-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("dequant-core", "Invalid amount for -mintxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("dequant-core", "Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"), QT_TRANSLATE_NOOP("dequant-core", "Invalid amount for -paytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("dequant-core", "Invalid amount for -reservebalance=<amount>"), QT_TRANSLATE_NOOP("dequant-core", "Invalid amount"), QT_TRANSLATE_NOOP("dequant-core", "Invalid masternodeprivkey. Please see documenation."), QT_TRANSLATE_NOOP("dequant-core", "Invalid netmask specified in -whitelist: '%s'"), QT_TRANSLATE_NOOP("dequant-core", "Invalid port detected in masternode.conf"), QT_TRANSLATE_NOOP("dequant-core", "Invalid private key."), QT_TRANSLATE_NOOP("dequant-core", "Invalid script detected."), QT_TRANSLATE_NOOP("dequant-core", "Keep at most <n> unconnectable transactions in memory (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Limit size of signature cache to <n> entries (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Line: %d"), QT_TRANSLATE_NOOP("dequant-core", "Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Listen for connections on <port> (default: %u or testnet: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Loading addresses..."), QT_TRANSLATE_NOOP("dequant-core", "Loading block index..."), QT_TRANSLATE_NOOP("dequant-core", "Loading budget cache..."), QT_TRANSLATE_NOOP("dequant-core", "Loading masternode cache..."), QT_TRANSLATE_NOOP("dequant-core", "Loading masternode payment cache..."), QT_TRANSLATE_NOOP("dequant-core", "Loading sporks..."), QT_TRANSLATE_NOOP("dequant-core", "Loading wallet... (%3.2f %%)"), QT_TRANSLATE_NOOP("dequant-core", "Loading wallet..."), QT_TRANSLATE_NOOP("dequant-core", "Lock is already in place."), QT_TRANSLATE_NOOP("dequant-core", "Lock masternodes from masternode configuration file (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Maintain at most <n> connections to peers (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Masternode options:"), QT_TRANSLATE_NOOP("dequant-core", "Masternode queue is full."), QT_TRANSLATE_NOOP("dequant-core", "Masternode:"), QT_TRANSLATE_NOOP("dequant-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Missing input transaction information."), QT_TRANSLATE_NOOP("dequant-core", "Need to specify a port with -whitebind: '%s'"), QT_TRANSLATE_NOOP("dequant-core", "No Masternodes detected."), QT_TRANSLATE_NOOP("dequant-core", "No compatible Masternode found."), QT_TRANSLATE_NOOP("dequant-core", "Node relay options:"), QT_TRANSLATE_NOOP("dequant-core", "Non-standard public key detected."), QT_TRANSLATE_NOOP("dequant-core", "Not compatible with existing transactions."), QT_TRANSLATE_NOOP("dequant-core", "Not enough file descriptors available."), QT_TRANSLATE_NOOP("dequant-core", "Not in the Masternode list."), QT_TRANSLATE_NOOP("dequant-core", "Number of automatic wallet backups (default: 10)"), QT_TRANSLATE_NOOP("dequant-core", "Only accept block chain matching built-in checkpoints (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Only connect to nodes in network <net> (ipv4, ipv6 or onion)"), QT_TRANSLATE_NOOP("dequant-core", "Options:"), QT_TRANSLATE_NOOP("dequant-core", "Password for JSON-RPC connections"), QT_TRANSLATE_NOOP("dequant-core", "Preparing for resync..."), QT_TRANSLATE_NOOP("dequant-core", "Prepend debug output with timestamp (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Print version and exit"), QT_TRANSLATE_NOOP("dequant-core", "RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)"), QT_TRANSLATE_NOOP("dequant-core", "RPC server options:"), QT_TRANSLATE_NOOP("dequant-core", "RPC support for HTTP persistent connections (default: %d)"), QT_TRANSLATE_NOOP("dequant-core", "Randomly drop 1 of every <n> network messages"), QT_TRANSLATE_NOOP("dequant-core", "Randomly fuzz 1 of every <n> network messages"), QT_TRANSLATE_NOOP("dequant-core", "Rebuild block chain index from current blk000??.dat files"), QT_TRANSLATE_NOOP("dequant-core", "Receive and display P2P network alerts (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Relay and mine data carrier transactions (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Relay non-P2SH multisig (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Rescan the block chain for missing wallet transactions"), QT_TRANSLATE_NOOP("dequant-core", "Rescanning..."), QT_TRANSLATE_NOOP("dequant-core", "Run a thread to flush wallet periodically (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Run in the background as a daemon and accept commands"), QT_TRANSLATE_NOOP("dequant-core", "Send transactions as zero-fee transactions if possible (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Server certificate file (default: %s)"), QT_TRANSLATE_NOOP("dequant-core", "Server private key (default: %s)"), QT_TRANSLATE_NOOP("dequant-core", "Session not complete!"), QT_TRANSLATE_NOOP("dequant-core", "Session timed out."), QT_TRANSLATE_NOOP("dequant-core", "Set database cache size in megabytes (%d to %d, default: %d)"), QT_TRANSLATE_NOOP("dequant-core", "Set external address:port to get to this masternode (example: %s)"), QT_TRANSLATE_NOOP("dequant-core", "Set key pool size to <n> (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Set maximum block size in bytes (default: %d)"), QT_TRANSLATE_NOOP("dequant-core", "Set minimum block size in bytes (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Set the Maximum reorg depth (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Set the masternode private key"), QT_TRANSLATE_NOOP("dequant-core", "Set the number of threads to service RPC calls (default: %d)"), QT_TRANSLATE_NOOP("dequant-core", "Sets the DB_PRIVATE flag in the wallet db environment (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Show all debugging options (usage: --help -help-debug)"), QT_TRANSLATE_NOOP("dequant-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"), QT_TRANSLATE_NOOP("dequant-core", "Signing failed."), QT_TRANSLATE_NOOP("dequant-core", "Signing timed out."), QT_TRANSLATE_NOOP("dequant-core", "Signing transaction failed"), QT_TRANSLATE_NOOP("dequant-core", "Specify configuration file (default: %s)"), QT_TRANSLATE_NOOP("dequant-core", "Specify connection timeout in milliseconds (minimum: 1, default: %d)"), QT_TRANSLATE_NOOP("dequant-core", "Specify data directory"), QT_TRANSLATE_NOOP("dequant-core", "Specify masternode configuration file (default: %s)"), QT_TRANSLATE_NOOP("dequant-core", "Specify pid file (default: %s)"), QT_TRANSLATE_NOOP("dequant-core", "Specify wallet file (within data directory)"), QT_TRANSLATE_NOOP("dequant-core", "Specify your own public address"), QT_TRANSLATE_NOOP("dequant-core", "Spend unconfirmed change when sending transactions (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Staking options:"), QT_TRANSLATE_NOOP("dequant-core", "Stop running after importing blocks from disk (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Submitted following entries to masternode: %u / %d"), QT_TRANSLATE_NOOP("dequant-core", "Submitted to masternode, waiting for more entries ( %u / %d ) %s"), QT_TRANSLATE_NOOP("dequant-core", "Submitted to masternode, waiting in queue %s"), QT_TRANSLATE_NOOP("dequant-core", "SwiftTX options:"), QT_TRANSLATE_NOOP("dequant-core", "Synchronization failed"), QT_TRANSLATE_NOOP("dequant-core", "Synchronization finished"), QT_TRANSLATE_NOOP("dequant-core", "Synchronization pending..."), QT_TRANSLATE_NOOP("dequant-core", "Synchronizing budgets..."), QT_TRANSLATE_NOOP("dequant-core", "Synchronizing masternode winners..."), QT_TRANSLATE_NOOP("dequant-core", "Synchronizing masternodes..."), QT_TRANSLATE_NOOP("dequant-core", "Synchronizing sporks..."), QT_TRANSLATE_NOOP("dequant-core", "This help message"), QT_TRANSLATE_NOOP("dequant-core", "This is experimental software."), QT_TRANSLATE_NOOP("dequant-core", "This is intended for regression testing tools and app development."), QT_TRANSLATE_NOOP("dequant-core", "This is not a Masternode."), QT_TRANSLATE_NOOP("dequant-core", "Threshold for disconnecting misbehaving peers (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Tor control port password (default: empty)"), QT_TRANSLATE_NOOP("dequant-core", "Tor control port to use if onion listening enabled (default: %s)"), QT_TRANSLATE_NOOP("dequant-core", "Transaction amount too small"), QT_TRANSLATE_NOOP("dequant-core", "Transaction amounts must be positive"), QT_TRANSLATE_NOOP("dequant-core", "Transaction created successfully."), QT_TRANSLATE_NOOP("dequant-core", "Transaction fees are too high."), QT_TRANSLATE_NOOP("dequant-core", "Transaction not valid."), QT_TRANSLATE_NOOP("dequant-core", "Transaction too large for fee policy"), QT_TRANSLATE_NOOP("dequant-core", "Transaction too large"), QT_TRANSLATE_NOOP("dequant-core", "Transmitting final transaction."), QT_TRANSLATE_NOOP("dequant-core", "Unable to bind to %s on this computer (bind returned error %s)"), QT_TRANSLATE_NOOP("dequant-core", "Unable to sign spork message, wrong key?"), QT_TRANSLATE_NOOP("dequant-core", "Unknown network specified in -onlynet: '%s'"), QT_TRANSLATE_NOOP("dequant-core", "Unknown state: id = %u"), QT_TRANSLATE_NOOP("dequant-core", "Upgrade wallet to latest format"), QT_TRANSLATE_NOOP("dequant-core", "Use OpenSSL (https) for JSON-RPC connections"), QT_TRANSLATE_NOOP("dequant-core", "Use UPnP to map the listening port (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Use UPnP to map the listening port (default: 1 when listening)"), QT_TRANSLATE_NOOP("dequant-core", "Use a custom max chain reorganization depth (default: %u)"), QT_TRANSLATE_NOOP("dequant-core", "Use the test network"), QT_TRANSLATE_NOOP("dequant-core", "Username for JSON-RPC connections"), QT_TRANSLATE_NOOP("dequant-core", "Verifying blocks..."), QT_TRANSLATE_NOOP("dequant-core", "Verifying wallet..."), QT_TRANSLATE_NOOP("dequant-core", "Wallet %s resides outside data directory %s"), QT_TRANSLATE_NOOP("dequant-core", "Wallet is locked."), QT_TRANSLATE_NOOP("dequant-core", "Wallet needed to be rewritten: restart Dequant Core to complete"), QT_TRANSLATE_NOOP("dequant-core", "Wallet options:"), QT_TRANSLATE_NOOP("dequant-core", "Wallet window title"), QT_TRANSLATE_NOOP("dequant-core", "Warning"), QT_TRANSLATE_NOOP("dequant-core", "Warning: This version is obsolete, upgrade required!"), QT_TRANSLATE_NOOP("dequant-core", "Warning: Unsupported argument -benchmark ignored, use -debug=bench."), QT_TRANSLATE_NOOP("dequant-core", "Warning: Unsupported argument -debugnet ignored, use -debug=net."), QT_TRANSLATE_NOOP("dequant-core", "Will retry..."), QT_TRANSLATE_NOOP("dequant-core", "You need to rebuild the database using -reindex to change -txindex"), QT_TRANSLATE_NOOP("dequant-core", "Your entries added successfully."), QT_TRANSLATE_NOOP("dequant-core", "Your transaction was accepted into the pool!"), QT_TRANSLATE_NOOP("dequant-core", "Zapping all transactions from wallet..."), QT_TRANSLATE_NOOP("dequant-core", "ZeroMQ notification options:"), QT_TRANSLATE_NOOP("dequant-core", "on startup"), QT_TRANSLATE_NOOP("dequant-core", "wallet.dat corrupt, salvage failed"), };
[ "dequant@users.noreply.github.com" ]
dequant@users.noreply.github.com
d4585d12ebc4e83a059e98efec6ff6879f34e129
e73e31c1acf01a124e628e95db48b8cb7e218e1c
/src/4txn/txn_cursor.h
a4e8f464039f5b5228fc8887ae3fb02c02c7770d
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-protobuf" ]
permissive
billon-pl/upscaledb
06f7fe5919a56c4794dc0a281cf5c5a2cce2e59a
da365e3504346b968b6d35de2185f12bba1c1ede
refs/heads/master
2020-03-20T01:56:34.322777
2018-06-20T11:00:04
2018-06-20T11:00:04
137,094,250
1
0
Apache-2.0
2018-06-20T11:00:05
2018-06-12T15:46:48
C++
UTF-8
C++
false
false
4,296
h
/* * Copyright (C) 2005-2017 Christoph Rupp (chris@crupp.de). * * 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. * * See the file COPYING for License information. */ /* * A cursor which can iterate over transaction nodes and operations * * A Txn Cursor can walk over Txn trees (TxnIndex). * * Txn Cursors are only used as part of the Cursor structure as defined * in cursor.h. Like all Txn operations it is in-memory only, * traversing the red-black tree that is implemented in txn.h, and * consolidating multiple operations in a node (i.e. if a Txn first * overwrites a record, and another transaction then erases the key). * * The Txn Cursor has two states: either it is coupled to a * Txn operation (TxnOperation) or it is unused. */ #ifndef UPS_TXN_CURSOR_H #define UPS_TXN_CURSOR_H #include "0root/root.h" // Always verify that a file of level N does not include headers > N! #include "4txn/txn_local.h" #ifndef UPS_ROOT_H # error "root.h was not included" #endif namespace upscaledb { struct LocalCursor; struct Context; struct TxnCursorState { // The parent cursor LocalCursor *parent; // A Cursor can either be coupled or nil ("not in list"). If it's // coupled, it directly points to a TxnOperation structure. // If it's nil then |m_coupled_op| is null. // // the txn operation to which we're pointing TxnOperation *coupled_op; // a double linked list with other cursors that are coupled // to the same Operation TxnCursor *coupled_next, *coupled_previous; }; // // An cursor which can iterate over Txn nodes // struct TxnCursor { // Constructor TxnCursor(LocalCursor *parent) { state_.parent = parent; state_.coupled_op = 0; state_.coupled_next = 0; state_.coupled_previous = 0; } // Destructor; sets the cursor to nil ~TxnCursor() { close(); } // Clones another TxnCursor void clone(const TxnCursor *other); // Returns true if the cursor is nil (does not point to any item) bool is_nil() const { return state_.coupled_op == 0; } // Sets the cursor to nil void set_to_nil(); // Couples this cursor to a TxnOperation structure void couple_to(TxnOperation *op); // Closes the cursor void close() { set_to_nil(); } // Returns the parent cursor LocalCursor *parent() { return state_.parent; } // Returns the pointer to the coupled TxnOperation TxnOperation *get_coupled_op() const { return state_.coupled_op; } // Retrieves the key from the current item; creates a shallow copy. ups_key_t *coupled_key() { TxnNode *node = state_.coupled_op->node; return node->key(); } // Retrieves the key from the current item; creates a deep copy. // // If the cursor is uncoupled, UPS_CURSOR_IS_NIL is returned. this // means that the item was already flushed to the btree, and the caller has // to use the btree lookup function to retrieve the key. void copy_coupled_key(ups_key_t *key); // Retrieves the record from the current item; creates a deep copy. // // If the cursor is uncoupled, UPS_CURSOR_IS_NIL will be returned. this // means that the item was already flushed to the btree, and the caller has // to use the btree lookup function to retrieve the record. void copy_coupled_record(ups_record_t *record); // Moves the cursor to first, last, previous or next ups_status_t move(uint32_t flags); // Looks up an item, places the cursor ups_status_t find(ups_key_t *key, uint32_t flags); // Retrieves the record size of the current item uint32_t record_size(); // Returns the pointer to the next cursor in the linked list of coupled // cursors TxnCursor *next() { return state_.coupled_next; } TxnCursorState state_; }; } // namespace upscaledb #endif /* UPS_TXN_CURSOR_H */
[ "zbigniew.romanowski@billongroup.com" ]
zbigniew.romanowski@billongroup.com
2560ac4312b63dccdff2d0e1fb6de5c26800ad20
50c74a5dd38180e26f0608cb0002585489445555
/Codeforces Solutions/231C.cpp
a7fe3ed86352cc49f210c4c8e30890f7069ddf73
[]
no_license
ShobhitBehl/Competitive-Programming
1518fe25001cc57095c1643cc8c904523b2ac2ef
7a05897ca0ef5565655350803327f7f23bcf82fe
refs/heads/master
2020-04-17T05:20:52.302129
2019-03-18T10:17:47
2019-03-18T10:17:47
166,265,289
0
0
null
null
null
null
UTF-8
C++
false
false
3,381
cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <stack> #include <string> #include <climits> #include <iomanip> #include <queue> #include <set> #include <list> #include <deque> using namespace std; typedef long long int lli; #include <bits/stdc++.h> struct comparator { bool operator()(lli i, lli j) { return i > j; } }; bool sortpair(pair <lli,lli> &a, pair <lli,lli> &b) { return (b.first-b.second) > (a.first - a.second); } lli gcd(lli a, lli b) { if(a == 0) { return b; } return gcd(b%a,a); } long long int min(long long int a, long long int b) { return a>b?b:a; } long long int min(long long int a, long long int b, lli c) { if(a<=b && a<=c) { return a; } else if(b<=a && b<=c) { return b; } else { return c; } } long long int max(long long int a, long long int b) { return a>b?a:b; } lli lcm(lli a, lli b) { return (a*b/gcd(a,b)); } bool check(lli x) { while(x%2 == 0) { x/=2; } while(x%3 == 0) { x/=3; } if(x != 1) { return false; } return true; } lli ans(int num, int n) { if(n == 1) { return num; } else if(n == 2) { return num+1; } else if(n == 3) { return num+2; } else if(n%3 == 0) { return ans(num+2,(n-1)/2); } else if(n%2 == 0) { return ans(num+1,n/2); } } vector<lli> getprimes() { vector <lli> pl(101,1); for(int i = 2; i<=100; i++) { if(pl[i] == 1) { for(int j = 2*i; j<=100; j+=i) { pl[j] = 0; } } } return pl; } lli ans(int n) { if(n == 0) { return 1; } else if(n == 1 || n == 2) { return 0; } else if(n<0) { return 0; } else { return (ans(n-7) | ans(n-3)); } } lli primefactorise(int n) { if(n == 1) { return 1; } lli ans = n; while (n%2 == 0) { n = n/2; if(n != 1) { ans += n; } } for (int i = 3; i <= sqrt(n); i = i+2) { while (n%i == 0) { n = n/i; if(n != 1) { ans += n; } } } ans += 1; return ans; } lli power(lli a,lli b) { lli ans = 1; while(b > 0) { if(b%2 == 1) { ans *= a; } b /=2; a*=a; } return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); lli n,k; cin >> n >> k; lli a[n+1]; lli b[n+1]; b[0] = 0; for(int i = 1; i<=n; i++) { cin >> a[i]; } sort(a+1,a+n+1); for(int i = 1; i<=n; i++) { b[i] = b[i-1] + a[i]; } int ans,num = -1; for(int i = 1; i<=n; i++) { int l = 1, r = i; while(l <= r) { int mid = (l+r)/2; if(mid*a[i] - (b[i] - b[i-mid]) <= k) { l = mid+1; } else { r = mid-1; } } if(r > num) { ans = a[i]; num = r; } } cout << num << " " << ans << endl; }
[ "shobhitbehl1@gmail.com" ]
shobhitbehl1@gmail.com
1d2c5d78b9083f834bc1e89906a41c8be1a3dc2a
2f882847bd6b339c4df531e63e78f1e7b4e775d4
/src/util/bytes.cpp
f1c25b3dbf9b354f3a6110a823ffcb2bd2a30c4b
[ "Apache-2.0" ]
permissive
J-Heinemann/faabric
8f44823f33b2ec1ba2a0442f6d41bfbfb74410af
ab360e392d5bd3d28c713aceceac99e007adc536
refs/heads/master
2022-12-19T01:06:59.305204
2020-10-03T20:44:18
2020-10-03T20:44:18
295,178,722
0
0
Apache-2.0
2020-09-13T15:21:16
2020-09-13T15:21:15
null
UTF-8
C++
false
false
1,793
cpp
#include "bytes.h" #include <vector> namespace faabric::util { std::vector<uint8_t> stringToBytes(const std::string &str) { if (str.empty()) { std::vector<uint8_t> empty; return empty; } // Get raw data as byte pointer const char *cstr = str.c_str(); auto *rawBytes = reinterpret_cast<const uint8_t *>(cstr); // Wrap in bytes vector std::vector<uint8_t> actual(rawBytes, rawBytes + str.length()); return actual; } void trimTrailingZeros(std::vector<uint8_t> &vectorIn) { long i = vectorIn.size() - 1; while (i >= 0 && vectorIn.at((unsigned long) i) == 0) { i--; } if (i < 0) { vectorIn.clear(); } else { vectorIn.resize((unsigned long) i + 1); } } int safeCopyToBuffer(const std::vector<uint8_t> &dataIn, uint8_t *buffer, int bufferLen) { int dataSize = (int) dataIn.size(); if (bufferLen <= 0) { return dataSize; } return safeCopyToBuffer(dataIn.data(), dataIn.size(), buffer, bufferLen); } int safeCopyToBuffer(const uint8_t *dataIn, int dataLen, uint8_t *buffer, int bufferLen) { if (dataLen == 0) { return 0; } // Truncate date being copied into a short buffer int copyLen = std::min(dataLen, bufferLen); std::copy(dataIn, dataIn + copyLen, buffer); return copyLen; } std::string bytesToString(const std::vector<uint8_t> &bytes) { unsigned long byteLen = bytes.size(); const char *charPtr = reinterpret_cast<const char *>(bytes.data()); const std::string result = std::string(charPtr, charPtr + byteLen); return result; } }
[ "mail@simonshillaker.com" ]
mail@simonshillaker.com
baedfe7729238125d5387425c0cfca6f0bb13652
4352b5c9e6719d762e6a80e7a7799630d819bca3
/tutorials/oldd/Basic-Dynamic-Mesh-Tutorial-OpenFoam/TUT16/1.06/uniform/time
7693e01610392dc6e796287412b8c31ee7ac2c22
[]
no_license
dashqua/epicProject
d6214b57c545110d08ad053e68bc095f1d4dc725
54afca50a61c20c541ef43e3d96408ef72f0bcbc
refs/heads/master
2022-02-28T17:20:20.291864
2019-10-28T13:33:16
2019-10-28T13:33:16
184,294,390
1
0
null
null
null
null
UTF-8
C++
false
false
835
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "1.06/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 1.06000000000000005; name "1.06"; index 510; deltaT 0.00222222; deltaT0 0.00222222; // ************************************************************************* //
[ "thomasdigiusto@me.com" ]
thomasdigiusto@me.com
7bd3cfb0af9ab8317d963895d5fbbe0e2385e384
2f9cae60845001bbe0983bfe40b9dfcb31f3f189
/interface.cpp
df390f3b083cdf1f3e6a5b1dc1ef0b9bd8973cdd
[]
no_license
a1406/test_so_python
601708711f4f27ea9b2bd8374f02c845f9500231
31d400f9037f49d742d2d60445ce55649fb4ccb8
refs/heads/master
2020-12-07T00:07:37.402584
2016-08-20T07:42:19
2016-08-20T07:42:19
66,121,926
0
0
null
null
null
null
UTF-8
C++
false
false
611
cpp
#include "comm_head.h" extern "C" { int test_interface() { printf("%s %s\n", __FILE__, __FUNCTION__); return (0); } int register_event(int event_id, on_event_func func) { assert(event_id >= 0 && event_id < 4); all_event_func[event_id] = func; return (0); } char *get_name(player *p) { return p->m_name; } void set_name(player *p, char *name) { p->set_name(name); } int get_age(player *p) { return p->m_age; } void set_age(player *p, int age) { p->set_age(age); } int get_id(player *p) { return p->m_id; } player *get_player(int id) { assert(id >= 0 && id < 100); return &all_players[id]; } };
[ "jack@company" ]
jack@company
4c26204ffab842602485f15ecc17f19eb529bb23
03fd7f7917fd9638ee020ecec06ac8f62dd3d1fa
/webbrowser/webbrowser.h
0e585a60613ca36a14f69cd266e4cf6ef47317f9
[]
no_license
brucehsu/PIMaiden
66f7bb57281fd696d369f999ff4d75b255b43e41
47e0fa5dbae561e93d234ac05689a2baf3f90e1a
refs/heads/master
2021-03-12T19:55:14.161319
2009-12-29T12:47:06
2009-12-29T12:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
942
h
#ifndef WEBBROWSER_H #define WEBBROWSER_H #include <QtGui/QWidget> #include <QtGui/QGridLayout> #include <QtGui/QPushButton> #include <QtWebKit/QWebView> #include <QtWebKit/QWebPage> #include <QtWebKit/QWebFrame> #include <QtGui/QToolBar> #include <QtGui/QStatusBar> #include <QNetworkReply> #include <QLineEdit> #include <omnibox.h> class WebBrowser : public QWidget { Q_OBJECT public: WebBrowser(); ~WebBrowser(); void showUrl(QString url); private: QGridLayout *layout; QToolBar *toolbar; QWebView *webview; QPushButton *prevBtn, *nextBtn, *refreshBtn,*closeSearchBarBtn,*shortenerBtn; OmniBox *omnibox; QLineEdit *searchBar; public slots: void setWebUrl(); void setBtnStat(); void handleWebPageError(QNetworkReply*); void keyPressEvent(QKeyEvent *); void showSearchBar(); void hideSearchBar(); void findTextInPage(); void shortenUrl(); }; #endif // WEBBROWSER
[ "Administrator@.(none)" ]
Administrator@.(none)
7c2658133d50031f9faac56ed2f5ddea3fe6ad73
fbdc153778176641733260d71dd7cf9308d9484b
/battle-ships/board.cpp
f64a975912525cc482509d09940041c477336a3c
[]
no_license
hubertoszywa/battle-ships
dc2f64dc32afcfabf5566a5b54d3372af558810d
b513da11b1fdca9c12321be7f01d931bfb486f8d
refs/heads/master
2023-02-16T04:36:37.020231
2021-01-13T21:12:02
2021-01-13T21:12:02
312,797,161
0
0
null
null
null
null
UTF-8
C++
false
false
3,187
cpp
/*! *@file board.cpp *@brief Funkcje z tej biblioteki realizaują operacje tworzenia widoku plansz ze statkami oraz dodawania statków na planszach przy zachowaniu losowego ułożenia i obowiązujących zasad gry w statki. */ #include "board.h" //------------ PUBLIC ------------ Board::Board(int x, int y, QTableWidget *z, bool ut) { boardWidth = x; boardHeight = y; myTable = z; userTable = ut; } Board::~Board() { } void Board::createBoard() { myTable->setRowCount(boardWidth); myTable->setColumnCount(boardHeight); myTable->setFocusPolicy(Qt::NoFocus); myTable->setSelectionMode(QAbstractItemView::NoSelection); myTable->setEditTriggers(QAbstractItemView::NoEditTriggers); QHeaderView *headerView = myTable->horizontalHeader(); headerView->setSectionResizeMode(QHeaderView::Stretch); headerView = myTable->verticalHeader(); headerView->setSectionResizeMode(QHeaderView::Stretch); makeWater(); } void Board::addShipsToBoard(QColor c1) { colorNormal = c1; for(int i=0; i < NUMBEROFSHIPS; ++i) while(!addShip(SHIPS[i])); } //------------ PRIVATE ------------ void Board::makeWater() { for(int i=0; i < boardWidth; i++) for(int j=0; j < boardHeight; j++) myTable->setItem(i,j,new QTableWidgetItem(QString::number(-1))); } bool Board::addShip(int shipLength) { //losowanie kierunku, w którą ma być układany statek bool direction = rand()%2; //0 = poziomo, 1 = pionowo //losowanie współrzędnych pola, od którego ma zacząć się dodawanie statku //z jednoczesnym ograniczeniem planszy (tak, żeby statek nie wyszedł "po za" int x = rand()%(direction ? boardWidth : (1+boardWidth-shipLength)); int y = rand()%(direction ? (1+boardHeight-shipLength) : boardHeight); //sprawdzanie czy pola które ma zająć statek są dozwolone (czyli czy nie są 1 lub 2) for(int i = 0; i<shipLength; ++i) { int val; QTableWidgetItem *a = myTable->item(x+(direction ? 0 : i), y+(direction ? i : 0)); val = a->text().toInt(); if(val >= 0) return false; } //dodanie statku do planszy i oznaczenie pól wokół jako nieaktywne int ship; QTableWidgetItem *b; for(int i = 0; i<shipLength; i++) { myTable->setItem((direction ? x : x+i), (direction ? y+i : y), new QTableWidgetItem(QString::number(shipLength))); if(userTable == false) myTable->item((direction ? x : x+i), (direction ? y+i : y))->setBackground(colorNormal); for(int k = (direction ? x-1 : x+i-1); k <= (direction ? x+1 : x+i+1); k++) { if(k < 0) k++; if(k > boardWidth-1) break; for(int l = (direction ? y+i-1 : y-1); l <= (direction ? y+i+1 : y+1); l++) { if(l < 0) l++; if(l > boardHeight-1) break; b = myTable->item(k, l); ship = b->text().toInt(); if(ship != shipLength && ship != 0) myTable->setItem(k, l, new QTableWidgetItem(QString::number(0))); } } } return true; }
[ "hubertoszywa@gmail.com" ]
hubertoszywa@gmail.com
d870a30d3bca4921cdb2a844e9a45d7ff6845e37
193d62070a9330f994ae24c180f097997c4fdf33
/27. Object Oriented Programming/Vector_class.cpp
48fcde7f6bf02a84d9df71c1da2526bb17be2bd3
[]
no_license
sudo0809/Data-Structure-and-algo
06654ce0ddf295afc8910fc79d89adf42f2ea792
054740875d211fc4ed12fe978333b73d6c8bdcec
refs/heads/main
2023-02-14T03:46:55.825440
2021-01-14T20:02:52
2021-01-14T20:02:52
329,621,225
1
0
null
null
null
null
UTF-8
C++
false
false
1,988
cpp
#include<iostream> #include<cstring> using namespace std; //Let us define a vector class class Vector{ //Data Members and some functions int *arr; int cs; int maxSize; public: Vector(int defaultSize=4){ maxSize = defaultSize; cs = 0; arr = new int[maxSize]; } //overloading round bracktes will make it functional objects void operator()(string s){ cout<<s<<" Yeah!!!"<<endl; } void push_back(int data){ if(cs==maxSize){ //doubling operation int *oldarr = arr; arr = new int[maxSize*2]; maxSize *= 2; for(int i=0; i<cs; i++){ arr[i] = oldarr[i]; } //Delete the old array delete [] oldarr; } arr[cs] = data; cs++; } bool empty(){ return cs==0; } void pop_back(int data){ if(!empty()){ cs--; } } void print(){ for(int i=0; i<cs; i++){ cout<<arr[i]<<" "; } cout<<endl; } int at(int i){ return arr[i]; } int getSize(){ return cs; } int getMaxSize(){ return maxSize; } int& operator[](int i){ return arr[i]; } }; ostream& operator << (ostream &os, Vector &v){ cout<<"In << operator"<<endl; v.print(); return os; } istream& operator >> (istream &is, Vector &v){ //Input a vector return is; } int main(){ Vector v(20); v("inside my round brackets"); for(int i=0;i<=6; i++){ v.push_back(i*i); } // cout<<v.getSize()<<endl; // cout<<v.getMaxSize()<<endl; Vector fun; fun = v; //copy assignment operator cout<<fun; v.print(); // cout<<v[2]<<endl; v[2] = 5; v[2] += 5; cout<<"Final value "<<v[2]<<endl; }
[ "noreply@github.com" ]
sudo0809.noreply@github.com
5c71fe859a0a96bc18036b243040bb2314b3df47
f84f2a08b82bd06eab4d4972a7101bd3f4ca98c8
/atcoder/AtCoderProblems/Easy/easy83.cpp
78be174c66442f0a40326429d5eb6d781f7b9023
[]
no_license
hal0taso/WriteUp
acf9721d4fe78f101483273a9cbb1c14743831d1
fc0384da36dc5da0f27ee1ad79c16cb9fcbe2536
refs/heads/master
2021-07-12T11:08:39.631348
2021-03-23T16:54:51
2021-03-23T16:54:51
61,340,902
0
0
null
null
null
null
UTF-8
C++
false
false
602
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; #define FOR(i, a, b) for (int i = a; i < b; ++i) #define REP(i, n) for (ll i = 0; i < n; ++i) int main() { int n, ui, li, usum = 0, lsum = 0, ans = 0; cin >> n; vector<int> u(n); vector<int> l(n); REP(i, n) { cin >> ui; usum += ui; u[i] = usum; } REP(i, n) { cin >> l[i]; } REP(i, n) { lsum += l[n - 1 - i]; l[n - 1 - i] = lsum; } REP(i, n) { if (u[i] + l[i] > ans) ans = u[i] + l[i]; } cout << ans << endl; return 0; }
[ "11371960+hal0taso@users.noreply.github.com" ]
11371960+hal0taso@users.noreply.github.com
bd59ee536ed95b2f01a64d867220a1bf874186ab
b2739a22b2f16ac09f889244ee5ca5f8a33ae9d5
/Classes/SelectLevelLayer.cpp
7993aec4fe0c749cdae687d0015270b588826a6d
[]
no_license
chen3286822/Snake_for_v3.2
663b0a868cb9218614f6c06fa9c64f352e2de4b7
45a89b9e239803564c4c442fd950c89e7f0062b1
refs/heads/master
2021-01-02T22:50:03.231428
2014-10-08T15:51:43
2014-10-08T15:51:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,516
cpp
#include "SelectLevelLayer.h" #include "GameDefine.h" #include "MainLayer.h" #include "ScrollMenu.h" #include "TouchTableView.h" USING_NS_CC; USING_NS_CC_EXT; Scene* SelectLevelLayer::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = SelectLevelLayer::create(); // add layer as a child to scene scene->addChild(layer, 1, eID_SelectLevelLayer); // return the scene return scene; } bool SelectLevelLayer::init() { if (!Layer::init()) { return false; } auto bgSprite = Sprite::create("sky.png"); this->addChild(bgSprite, 1, eID_SelectLevelBg); bgSprite->setPosition(VisibleRect::center()); auto backItem = MenuItemImage::create("back.png", "back.png", CC_CALLBACK_1(SelectLevelLayer::backToMainLayer, this)); backItem->setAnchorPoint(Vec2(0, 1)); backItem->setScale(0.8f); backItem->setPosition(VisibleRect::leftTop() + Vec2(-5, 5)); auto menu = Menu::create(backItem, nullptr); this->addChild(menu, 1); menu->setPosition(Vec2::ZERO); // add up and down hint arrows auto upSprite = Sprite::create("up.png"); upSprite->setScale(0.6f); upSprite->setPosition(VisibleRect::top() - Vec2(0, 50)); this->addChild(upSprite, 1); auto downSprite = Sprite::create("down.png"); downSprite->setScale(0.6f); downSprite->setPosition(VisibleRect::bottom() + Vec2(0, 25)); this->addChild(downSprite, 1); for (int i = 0; i < m_snCellNum; ++i) { m_bAppearBefore[i] = false; } return true; } void SelectLevelLayer::onEnterTransitionDidFinish() { Layer::onEnterTransitionDidFinish(); // read level numbers std::vector<std::string> vLevelFiles; std::string indexFullPath = FileUtils::getInstance()->fullPathForFilename("map/index"); std::string filePath = indexFullPath.substr(0, indexFullPath.size() - 6); traversalFolder(vLevelFiles, filePath.c_str(), "json"); m_nLevelNums = vLevelFiles.size(); if (m_nLevelNums == 0) m_nTableCells = 0; else m_nTableCells = (m_nLevelNums - 1) / 3 + 1; // create the level table view m_iTableViewLeftDownPos = Vec2(30, 40); m_iTableViewSize = VisibleRect::getVisibleRect().size - Size(60.0f, 128.0f); auto levelView = TouchTableView::createWithSize(this, m_iTableViewSize); levelView->setDirection(ScrollView::Direction::VERTICAL); levelView->setPosition(m_iTableViewLeftDownPos); levelView->setDelegate(this); this->addChild(levelView, 1, eID_LevelView); //levelView->reloadData(); } void SelectLevelLayer::tableCellTouched(TableView* table, TableViewCell* cell) { log("cell touched at index: %ld", cell->getIdx()); } Size SelectLevelLayer::tableCellSizeForIndex(TableView *table, ssize_t idx) { return Size(900, 400); } TableViewCell* SelectLevelLayer::tableCellAtIndex(TableView *table, ssize_t idx) { TableViewCell *cell = table->dequeueCell(); if (!cell) { cell = LevelTableViewCell::createWithTableViewRect(m_iTableViewLeftDownPos, m_iTableViewSize); // the cell appears m_bAppearBefore[idx] = true; } else { // reset the LevelTableViewCell's variable m_bMoved if the idx cell never appears before if (idx < m_snCellNum && !m_bAppearBefore[idx]) { auto levelTableViewCell = dynamic_cast<LevelTableViewCell*>(cell); if (levelTableViewCell) { levelTableViewCell->resetAppeared(); } m_bAppearBefore[idx] = true; } } return cell; } ssize_t SelectLevelLayer::numberOfCellsInTableView(TableView *table) { return m_nTableCells; } void SelectLevelLayer::backToMainLayer(cocos2d::Ref* pSender) { auto scene = TransitionSlideInL::create(0.8f, MainLayer::createScene()); Director::getInstance()->replaceScene(scene); } LevelTableViewCell* LevelTableViewCell::createWithTableViewRect(Vec2 leftDownPos, Size rectSize) { auto ret = new LevelTableViewCell(); if (ret && ret->initWithTableViewRect(leftDownPos, rectSize)) { ret->autorelease(); } else { CC_SAFE_DELETE(ret); } return ret; } bool LevelTableViewCell::initWithTableViewRect(Vec2 leftDownPos, Size rectSize) { if (! TableViewCell::init()) return false; m_pMenu = ScrollMenu::createWithEffectiveRange(leftDownPos, rectSize); for (int i = 0; i < m_snItemNum; ++i) { m_pItems[i] = MenuItemImage::create("border.png", "border.png", CC_CALLBACK_1(LevelTableViewCell::chooseLevel, this, i)); m_pItems[i]->setAnchorPoint(Vec2::ZERO); m_pItems[i]->setPosition(Vec2(975 + 300*i, 20)); m_pMenu->addChild(m_pItems[i], 1); m_bAppeared[i] = false; } m_pMenu->setPosition(Vec2::ZERO); this->addChild(m_pMenu, 1); return true; } void LevelTableViewCell::resetAppeared() { for (int i = 0; i < m_snItemNum; ++i) { m_bAppeared[i] = false; } } void LevelTableViewCell::onEnter() { TableViewCell::onEnter(); for (int i = 0; i < m_snItemNum; ++i) { if (m_pItems[i]) { auto moveAction = m_pItems[i]->getActionByTag(eID_LevelViewItemAction1 + i); if ((moveAction && !moveAction->isDone()) || m_bAppeared[i]) { //reset the position if the action didn't "done" because the cell scrolls too fast m_pItems[i]->setPosition(Vec2(15 + 300 * i, 20)); continue;; } m_pItems[i]->setPosition(Vec2(975 + 300*i, 20)); ActionInterval* newAction = MoveBy::create(0.8f + 0.2*i, Vec2(-960, 0)); ActionInterval *easeElasticOut = CCEaseExponentialOut::create(newAction); easeElasticOut->setTag(eID_LevelViewItemAction1 + i); m_pItems[i]->runAction(easeElasticOut); m_bAppeared[i] = true; } } } void LevelTableViewCell::chooseLevel(cocos2d::Ref* pSender, int index) { log("%d\n", index); }
[ "chen3286822@yeah.net" ]
chen3286822@yeah.net
2c3ff6ec5713c93063a0c92dff05ad460848a8e6
6d1509cf545e956ce2f7f1271949b771c72e0702
/Two Pointers/p18-4sum.cpp
175883cd0791366340fb29300a4085e52a27d19c
[]
no_license
sizzle0121/leetcode
a2f5999283a7e715411199c312d7b93eb38a89cc
1aab55af306f8afd715faff095a807ec7620114a
refs/heads/master
2022-11-11T23:04:11.489466
2020-06-29T11:18:04
2020-06-29T11:18:04
255,982,803
0
0
null
null
null
null
UTF-8
C++
false
false
1,660
cpp
/* * Like 3Sum, sort the array first (in order to use two pointers) * Enumerate all possible starting points (here is two points)\ * Then use two pointer s to find the last two points which sum to (target - first two points)\ * The key point is to avoid duplicate quadruplets\ * This can be done by preventing from duplicate starting points(same nums[i], or same nums[j])\ * as well as when we found the last two points by two pointers, we should move both pointers to different points * * Time complexity: O(n^3) * * */ #include <iostream> #include <vector> #include <algorithm> using namespace std; vector<vector<int> > Solution(vector<int> &nums, int target){ if(nums.size() < 4) return vector<vector<int> >(); sort(nums.begin(), nums.end()); vector<vector<int> > ans; for(int i=0; i<nums.size(); i++){ if(i-1 >= 0 && nums[i] == nums[i-1]) continue; for(int j=i+1; j<nums.size(); j++){ if(j-1 != i && nums[j] == nums[j-1]) continue; int k = target - (nums[i] + nums[j]); int l = j+1, r = nums.size()-1; while(l < r){ if(k == nums[l] + nums[r]){ ans.push_back(vector<int>{nums[i], nums[j], nums[l++], nums[r--]}); while(l < nums.size() && nums[l] == nums[l-1]) l++; while(r >= 0 && nums[r] == nums[r+1]) r--; }else if(k > nums[l] + nums[r]){ l++; }else{ r--; } } } } return ans; } int main(){ int T, target; cin >> T; vector<int> nums(T); for(int i=0; i<T; i++) cin >> nums[i]; cin >> target; vector<vector<int> > ans = Solution(nums, target); for(int i=0; i<ans.size(); i++){ for(int j=0; j<ans[i].size(); j++) cout << ans[i][j] << " "; cout << endl; } }
[ "sizzle0121.cs04@nctu.edu.tw" ]
sizzle0121.cs04@nctu.edu.tw
a40bd8e37a4a0b90c728cfc2fb602d41759f0758
2104522851caee4c5f11b124c7bfb039669d9bc4
/Codeforces/Previous/Div II/230B_142.cpp
6d7b69d587910659db9b6b3e39df1fa394d84b40
[]
no_license
runngezhang/Algorithm
242d0753271bd06121387cca5c6c9939319cfd27
729aa6cbeea095aaa1ef319495270b70b9c6d824
refs/heads/master
2021-01-12T09:11:13.508664
2013-10-10T21:53:41
2013-10-10T21:53:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
695
cpp
#include <iostream> #include <vector> #include <queue> #include <string> #include <list> #include <set> #include <map> #include <sstream> #include <algorithm> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <ctime> using namespace std; const int N = 1000010; bool p[N]; int main () { int i, j, k; memset (p, true, sizeof (p)); for (i = 2; i <= 1000; ++i) { if (p[i]) for (j = i * i; j <= 1000000; p[j] = false, j += i); } for (cin >> k; k; --k) { long long x, y; cin >> y; x = (int) sqrt (1.0 * y); if (y != 1 && y == x * x && p[x]) printf ("YES\n"); else printf ("NO\n"); } return 0; }
[ "shuoxiangpub@gmail.com" ]
shuoxiangpub@gmail.com