blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
431418aec7f3411113cd7d8c1ea4b3831a24cefc
b56c6e4fe34ec4cb105a2675de9039a064d09e6a
/QTOpenGL/MyGLWidget.h
d15314e8a93adadce7939c396af15224188b121d
[]
no_license
angelamyu/2DAnimator
9ee973ec7a4e1bb3e23f4f58361383295cdca2e1
e723b8c90211e92a1bdf28403b1e1bc4837e7976
refs/heads/master
2016-08-05T05:31:34.727776
2012-10-25T21:24:29
2012-10-25T21:24:29
6,394,757
1
0
null
null
null
null
UTF-8
C++
false
false
2,414
h
MyGLWidget.h
#ifndef MYGLWIDGET #define MYGLWIDGET #include "glew.h" #include "gMatrix3.h" #include "gVector3.h" #include "rPolygon.h" #include "Square.h" #include "Circle.h" #include "Character.h" #include <sstream> #include <QGLWidget> #include <qmessagebox.h> class MyGLWidget : public QGLWidget { Q_OBJECT protected: void initializeGL(void); void paintGL(void); void resizeGL(int, int); void createSquare(gMatrix3 model); void createPolygon(gMatrix3 model, int sides, rPolygon& p); void traverse(sceneNode* root, gMatrix3 t); sceneNode* currentNode; QString name; int sides; bool nameChanged; bool sidesChanged; void addNode(); public: MyGLWidget(QWidget*); ~MyGLWidget(void); public slots: void translateX(int); void translateY(int); void rotation(int); void scaleX(int); void scaleY(int); void red(int); void green(int); void blue(int); void resetCharacter(); void setCurrentNode(QTreeWidgetItem* i ,int z); void deleteNode(); void addNodeName(QString s); void addNodeSides(QString s); void addQTFrame(); void makeQTFrameBehind(); void makeQTFrameBefore(); void editRepaint(sceneNode*); void makeInterpolatedQImage(sceneNode*,sceneNode*,int); void makeEditSpecificQImage(int,sceneNode*); signals: void makeRoot(sceneNode*); void makeChild(sceneNode*, sceneNode*); void makeFrame(QImage,sceneNode*); void editFrame(QImage,sceneNode*); void makeFrameBehind(QImage,sceneNode*); void makeFrameBefore(QImage,sceneNode*); void sendInterpolatedQImage(QImage,sceneNode*,int); void sendAddedNodeToFrames(int,QString,QString); void sendEditSpecificQImage(QImage,int,sceneNode*); void printWidget(QString); void addOneKeyFrame(QImage,sceneNode*); void setFrameText(QString); private: Character* cat; //vertex arrays needed for drawing unsigned int vbo; unsigned int cbo; unsigned int ibo; //attributes unsigned int positionLocation; unsigned int colorLocation; // uniforms unsigned int u_scr_widthLocation; unsigned int u_scr_heightLocation; unsigned int u_modelMatrixLocation; //needed to compile and link and use the shaders unsigned int vertexShader; unsigned int fragmentShader; unsigned int shaderProgram; //helper function to read shader source and put it in a char array //thanks to Swiftless char* textFileRead(const char*); //some other helper functions from CIS 565 void printLinkInfoLog(int); void printShaderInfoLog(int); }; #endif
1e4465a05ae00d67ba35577d2932d6a42788e639
57d123a5f68b1e8095d5239eb7c3af28784e0799
/OJ——work/work_nine/长方形排序.cpp
e7af82026aeffdb9ae65e31df60093b39bc34c50
[]
no_license
Floweryu/DataStructuresAlgorithms
dda159afe3b8327deecfa3a8f72a62cf16d1d538
e61a424dcca1913c0e5ef4fae15b5945dbd04d9b
refs/heads/master
2022-03-26T04:22:07.849883
2019-12-18T07:52:11
2019-12-18T07:52:11
null
0
0
null
null
null
null
GB18030
C++
false
false
1,132
cpp
长方形排序.cpp
#include <iostream> #include <algorithm> using namespace std; #define MAX_NUM 10001 struct SqList { int number; int length; int wide; }; bool cmp(SqList a, SqList b) //把小的放前面排序 { if (a.number != b.number) return a.number < b.number; else if(a.length != b.length) return a.length < b.length; else if(a.wide != b.wide) return a.wide < b.wide; } int main() { int t; cin>>t; while(t--) { int n; cin>>n; struct SqList rect[n]; int i; for (i = 0; i < n; i++) { cin>>rect[i].number>>rect[i].length>>rect[i].wide; if (rect[i].length < rect[i].wide) swap(rect[i].length, rect[i].wide); } sort(rect, rect+n, cmp); for (i = 0; i < n; i++) { if (!(rect[i].number == rect[i+1].number && rect[i].length == rect[i+1].length && rect[i].wide == rect[i+1].wide)) //遇到重复的不用输出直接跳过 cout<<rect[i].number<<" "<<rect[i].length<<" "<<rect[i].wide<<endl; } } }
a1957d578890ec617bc6b06144f18ffdca6ec84e
f770e781b429478abc301893d8557b8b519bf110
/hindsight/WriterDebuggerEventHandler.hpp
2eafad4a06ca1e77b48940f9a95e8acc6aa9ee1f
[ "MIT" ]
permissive
Imagine-Programming/hindsight
f0a9b9a715ce7ed4c61c0f24fabfae1488ccdb7e
720813cd3598378662d5798cf7a5036703a148b3
refs/heads/master
2023-03-18T04:40:08.431750
2021-03-15T11:14:41
2021-03-15T11:14:41
274,485,905
0
0
null
null
null
null
UTF-8
C++
false
false
17,819
hpp
WriterDebuggerEventHandler.hpp
#pragma once #ifndef writer_debugger_event_handler_h #define writer_debugger_event_handler_h #include "IDebuggerEventHandler.hpp" #include "BinaryLogFile.hpp" #include <fstream> #include <type_traits> namespace Hindsight { namespace Debugger { namespace EventHandler { /// <summary> /// An implementation of <see cref="::Hindsight::Debugger::EventHandler::IDebuggerEventHandler"/> that writes /// all relevant details of each debug event to a binary log file, which can later be converted to a textual /// log file or be replayed to simulate the same order of events and produce output like a regular debug /// session. /// </summary> class WriterDebuggerEventHandler : public IDebuggerEventHandler { private: std::ofstream m_Stream; /* The binary output stream */ Hindsight::BinaryLog::FileHeader m_Header; /* The file header, the instance is kept to update the checksum at the end */ public: /// <summary> /// Construct a new WriterDebuggerEventHandler, which will create and write to <paramref name="filepath"/>. /// </summary> /// <param name="filepath">The path to the file which will contain the logged events.</param> WriterDebuggerEventHandler(const std::string& filepath); /// <summary> /// Write the initial data to the binary log file, such as the file header. It will also write /// the debugged process path, working directory (if available) and program parameters (if available). /// </summary> /// <param name="time">The time of the event.</param> /// <param name="p">The process being debugged.</param> void OnInitialization( time_t time, const std::shared_ptr<const Hindsight::Process::Process> pi) override; /// <summary> /// Write details about a breakpoint exception event, including a thread context and stack trace. /// </summary> /// <param name="time">The time of the event.</param> /// <param name="info">A const reference to the <see cref="EXCEPTION_DEBUG_INFO"/> struct instance with event information.</param> /// <param name="pi">A const reference to the <see cref="PROCESS_INFORMATION"/> struct of the process and thread triggering the event.</param> /// <param name="context">A shared pointer to a const <see cref="::Hindsight::Debugger::DebugContext"/> instance.</param> /// <param name="trace">A shared pointer to a const <see cref="::Hindsight::Debugger::DebugStackTrace"/> instance.</param> /// <param name="collection">A const reference to the <see cref="::Hindsight::Debugger::ModuleCollection"/> of currently loaded modules at the time of the event.</param> void OnBreakpointHit( time_t time, const EXCEPTION_DEBUG_INFO& info, const PROCESS_INFORMATION& pi, std::shared_ptr<const DebugContext> context, std::shared_ptr<const DebugStackTrace> trace, const ModuleCollection& collection) override; /// <summary> /// Write details about an exception event, including a thread context and stack trace. /// stack trace and context of the exception address. /// </summary> /// <param name="time">The time of the event.</param> /// <param name="info">A const reference to the <see cref="EXCEPTION_DEBUG_INFO"/> struct instance with event information.</param> /// <param name="pi">A const reference to the <see cref="PROCESS_INFORMATION"/> struct of the process and thread triggering the event.</param> /// <param name="firstChance">A boolean indicating that this is the first encounter with this specific exception instance, or not.</param> /// <param name="name">A name of a known exception, or an empty string.</param> /// <param name="context">A shared pointer to a const <see cref="::Hindsight::Debugger::DebugContext"/> instance.</param> /// <param name="trace">A shared pointer to a const <see cref="::Hindsight::Debugger::DebugStackTrace"/> instance.</param> /// <param name="collection">A const reference to the <see cref="::Hindsight::Debugger::ModuleCollection"/> of currently loaded modules at the time of the event.</param> /// <param name="ertti">A shared pointer to a const <see cref="::Hindsight::Debugger::CxxExceptions::ExceptionRtti"/> instance.</param> void OnException( time_t time, const EXCEPTION_DEBUG_INFO& info, const PROCESS_INFORMATION& pi, bool firstChance, const std::wstring& name, std::shared_ptr<const DebugContext> context, std::shared_ptr<const DebugStackTrace> trace, const ModuleCollection& collection, std::shared_ptr<const CxxExceptions::ExceptionRunTimeTypeInformation> ertti) override; /// <summary> /// Write the event that denotes the creation of a process. /// </summary> /// <param name="time">The time of the event.</param> /// <param name="info">A const reference to the <see cref="CREATE_PROCESS_DEBUG_INFO"/> struct instance with event information.</param> /// <param name="pi">A const reference to the <see cref="PROCESS_INFORMATION"/> struct of the process and thread triggering the event.</param> /// <param name="path">The full path to the loaded module on file system.</param> /// <param name="collection">A const reference to the <see cref="::Hindsight::Debugger::ModuleCollection"/> of currently loaded modules at the time of the event.</param> void OnCreateProcess( time_t time, const CREATE_PROCESS_DEBUG_INFO& info, const PROCESS_INFORMATION& pi, const std::wstring& path, const ModuleCollection& collection) override; /// <summary> /// Write the event that denotes the creation of a thread. /// </summary> /// <param name="time">The time of the event.</param> /// <param name="info">A const reference to the <see cref="CREATE_THREAD_DEBUG_INFO"/> struct instance with event information.</param> /// <param name="pi">A const reference to the <see cref="PROCESS_INFORMATION"/> struct of the process and thread triggering the event.</param> /// <param name="collection">A const reference to the <see cref="::Hindsight::Debugger::ModuleCollection"/> of currently loaded modules at the time of the event.</param> void OnCreateThread( time_t time, const CREATE_THREAD_DEBUG_INFO& info, const PROCESS_INFORMATION& pi, const ModuleCollection& collection) override; /// <summary> /// Write the EXIT_PROCESS event. /// </summary> /// <param name="time">The time of the event.</param> /// <param name="info">A const reference to the <see cref="EXIT_PROCESS_DEBUG_INFO"/> struct instance with event information.</param> /// <param name="pi">A const reference to the <see cref="PROCESS_INFORMATION"/> struct of the process and thread triggering the event.</param> /// <param name="collection">A const reference to the <see cref="::Hindsight::Debugger::ModuleCollection"/> of currently loaded modules at the time of the event.</param> void OnExitProcess( time_t time, const EXIT_PROCESS_DEBUG_INFO& info, const PROCESS_INFORMATION& pi, const ModuleCollection& collection) override; /// <summary> /// Write the EXIT_THREAD event. /// </summary> /// <param name="time">The time of the event.</param> /// <param name="info">A const reference to the <see cref="EXIT_THREAD_DEBUG_INFO"/> struct instance with event information.</param> /// <param name="pi">A const reference to the <see cref="PROCESS_INFORMATION"/> struct of the process and thread triggering the event.</param> /// <param name="collection">A const reference to the <see cref="::Hindsight::Debugger::ModuleCollection"/> of currently loaded modules at the time of the event.</param> void OnExitThread( time_t time, const EXIT_THREAD_DEBUG_INFO& info, const PROCESS_INFORMATION& pi, const ModuleCollection& collection) override; /// <summary> /// Write the LOAD_DLL event, accompanied by information about the loaded module. /// </summary> /// <param name="time">The time of the event.</param> /// <param name="info">A const reference to the <see cref="EXIT_THREAD_DEBUG_INFO"/> struct instance with event information.</param> /// <param name="pi">A const reference to the <see cref="PROCESS_INFORMATION"/> struct of the process and thread triggering the event.</param> /// <param name="path">The full unicode path to the DLL that was loaded.</param> /// <param name="moduleIndex">The index in the module collection of this module, it might have been loaded before.</param> /// <param name="collection">A const reference to the <see cref="::Hindsight::Debugger::ModuleCollection"/> of currently loaded modules at the time of the event.</param> void OnDllLoad( time_t time, const LOAD_DLL_DEBUG_INFO& info, const PROCESS_INFORMATION& pi, const std::wstring& path, int moduleIndex, const ModuleCollection& collection) override; /// <summary> /// Write an ANSI (or might be UTF-8) debug string sent by the debugged process. /// </summary> /// <param name="time">The time of the event.</param> /// <param name="info">A const reference to the <see cref="OUTPUT_DEBUG_STRING_INFO"/> struct instance with event information.</param> /// <param name="pi">A const reference to the <see cref="PROCESS_INFORMATION"/> struct of the process and thread triggering the event.</param> /// <param name="string">The ANSI debug string.</param> void OnDebugString( time_t time, const OUTPUT_DEBUG_STRING_INFO& info, const PROCESS_INFORMATION& pi, const std::string& string) override; /// <summary> /// Write a unicode (wchar_t) debug string sent by the debugged process. /// </summary> /// <param name="time">The time of the event.</param> /// <param name="info">A const reference to the <see cref="OUTPUT_DEBUG_STRING_INFO"/> struct instance with event information.</param> /// <param name="pi">A const reference to the <see cref="PROCESS_INFORMATION"/> struct of the process and thread triggering the event.</param> /// <param name="string">The Unicode debug string.</param> void OnDebugStringW( time_t time, const OUTPUT_DEBUG_STRING_INFO& info, const PROCESS_INFORMATION& pi, const std::wstring& string) override; /// <summary> /// Write a RIP error event. /// </summary> /// <param name="time">The time of the event.</param> /// <param name="info">A const reference to the <see cref="RIP_INFO"/> struct instance with event information.</param> /// <param name="pi">A const reference to the <see cref="PROCESS_INFORMATION"/> struct of the process and thread triggering the event.</param> /// <param name="errorMessage">A string describing the <see cref="RIP_INFO::dwError"/> member, or an empty string if no description is available.</param> void OnRip( time_t time, const RIP_INFO& info, const PROCESS_INFORMATION& pi, const std::wstring& errorMessage) override; /// <summary> /// Write an UNLOAD_DLL event. Binary log files don't keep a complete list of loaded modules, instead they /// keep the LOAD and UNLOAD events. Like that, it is known when a module was in memory and when it was not. /// /// One could do an extra pass on the file extracting all of these events and build a list. /// </summary> /// <param name="time">The time of the event.</param> /// <param name="info">A const reference to the <see cref="RIP_INFO"/> struct instance with event information.</param> /// <param name="pi">A const reference to the <see cref="PROCESS_INFORMATION"/> struct of the process and thread triggering the event.</param> /// <param name="path">The full unicode path to the DLL that is being unloaded.</param> /// <param name="moduleIndex">The index in the module collection of this module.</param> /// <param name="collection">A const reference to the <see cref="::Hindsight::Debugger::ModuleCollection"/> of currently loaded modules at the time of the event.</param> /// <remarks> /// Note: At the time of invoking this event, the module still exists in <paramref name="collection"/> so that you can still work with it. /// It is unloaded immediately after all event handlers have been invoked. /// </remarks> void OnDllUnload( time_t time, const UNLOAD_DLL_DEBUG_INFO& info, const PROCESS_INFORMATION& pi, const std::wstring& path, int moduleIndex, const ModuleCollection& collection) override; /// <summary> /// Finalize the binary logging, which will seek back to the header and overwrite it with the updated Crc32 checksum. /// </summary> /// <param name="time">The time of the event.</param> /// <param name="collection">A const reference to the <see cref="::Hindsight::Debugger::ModuleCollection"/> of currently loaded modules at the time of the event.</param> void OnModuleCollectionComplete( time_t time, const ModuleCollection& collection) override; private: /// <summary> /// Write a class or struct instance to the output stream. /// </summary> /// <param name="s">A reference to the class or struct instance to write, of type <typeparamref name="T"/>.</param> /// <typeparam name="T">The type of value to write, which must be a class.</typeparam> template <typename T, std::enable_if_t<std::is_class<T>::value, int> = 0> void Write(T s); /// <summary> /// Write a <see cref="::std::wstring"/> to the output stream, optionally preceeded by its length. /// </summary> /// <param name="s">A reference to the string to write.</param> /// <param name="writeLength">When set to true, the length of the string will be written as a <see cref="uint32_t"/> before the string.</param> void Write(const std::wstring& s, bool writeLength = false); /// <summary> /// Write a <see cref="::std::string"/> to the output stream, optionally preceeded by its length. /// </summary> /// <param name="s">A reference to the string to write.</param> /// <param name="writeLength">When set to true, the length of the string will be written as a <see cref="uint32_t"/> before the string.</param> void Write(const std::string& s, bool writeLength = false); /// <summary> /// Write an arbitrarily sized block of data to the output stream and optionally update the internal checksum of /// all the written data. /// </summary> /// <param name="data">A pointer to <paramref name="size"/> bytes of memory to write.</param> /// <param name="size">The amount of bytes to write.</param> /// <param name="updateChecksum">When set to true, the internal checksum will be updated.</param> void Write(const char* data, size_t size, bool updateChecksum = true); /// <summary> /// Write an exception event, this function is defined because both breakpoints and exceptions are written in the /// exact same format in binary log files. They are, essentially, the same debug event with only an exception code /// indicating whether it is a breakpoint or not. /// </summary> /// <param name="info">A const reference to the <see cref="EXCEPTION_DEBUG_INFO"/> instance of this event.</param> /// <param name="pi">A const reference to the <see cref="PROCESS_INFORMATION"/> instance of the thread causing the event.</param> /// <param name="context">A shared pointer to a <see cref="::Hindsight::Debugger::DebugContext"/> instance.</param> /// <param name="trace">A shared pointer to a <see cref="::Hindsight::Debugger::DebugStackTrace"/> instance.</param> /// <param name="collection">A const reference to a <see cref="Hindsight::Debugger::ModuleCollection"/> instance containing information about loaded modules.</param> /// <param name="ertti">Run-time type information about the exception.</param> /// <param name="isBreak">True when breakpoint, false when exception.</param> void Write( const EXCEPTION_DEBUG_INFO& info, const PROCESS_INFORMATION& pi, std::shared_ptr<const DebugContext> context, std::shared_ptr<const DebugStackTrace> trace, const ModuleCollection& collection, std::shared_ptr<const CxxExceptions::ExceptionRunTimeTypeInformation> ertti, bool isBreak); /// <summary> /// Write a thread context to the output stream, which will be either a <see cref="CONTEXT"/> struct or /// a <see cref="WOW64_CONTEXT"/> struct depending on the debugged process. /// </summary> /// <param name="context">A shared pointer to a <see cref="::Hindsight::Debugger::DebugContext"/> instance.</param> void Write(std::shared_ptr<const DebugContext> context); /// <summary> /// Write a stack trace to the output stream, starting from an exception address. /// </summary> /// <param name="trace">A shared pointer to a <see cref="::Hindsight::Debugger::DebugStackTrace"/> instance.</param> /// <param name="collection">A const reference to a <see cref="Hindsight::Debugger::ModuleCollection"/> instance containing information about loaded modules.</param> void Write( std::shared_ptr<const DebugStackTrace> trace, const ModuleCollection& collection); }; } } } #endif
ffa7236ee44f0ffe1d455844c70d7b381774ba58
1f70194130fe378a1e3d88181bac705caffdd9a6
/Editor/MainFrame.h
19813e8d5e34ebe5f3241444cd65cfb2958293ac
[]
no_license
pthiben/Helium
3ac988ef47d896f727fd9d96a27d03b217f1e109
45cc99296634429eb69b213e1826ad9a5731f187
refs/heads/master
2021-01-18T08:41:52.078150
2010-08-19T20:57:21
2010-08-19T20:57:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,257
h
MainFrame.h
#pragma once #include "Editor/EditorGenerated.h" #include "DirectoryPanel.h" #include "HelpPanel.h" #include "ProjectPanel.h" #include "LayersPanel.h" #include "PropertiesPanel.h" #include "ToolbarPanel.h" #include "TypesPanel.h" #include "ViewPanel.h" #include "Core/Scene/PropertiesManager.h" #include "Core/Scene/Scene.h" #include "Core/Scene/SceneManager.h" #include "Application/Inspect/DragDrop/DropTarget.h" #include "Editor/MRU/MenuMRU.h" #include "Editor/TreeMonitor.h" #include "Editor/MessageDisplayer.h" #include "Editor/FileDialogDisplayer.h" #include "Core/Project.h" namespace Helium { namespace Editor { typedef std::map< i32, i32 > M_IDToColorMode; // Maps wx ID for menu items to our ViewColorMode enum class MainFrame : public MainFrameGenerated { protected: enum { ID_MenuOpened = wxID_HIGHEST + 1, }; private: struct OutlinerStates { SceneOutlinerState m_Hierarchy; SceneOutlinerState m_Entities; SceneOutlinerState m_Types; }; typedef std::map< Core::Scene*, OutlinerStates > M_OutlinerStates; public: MainFrame( wxWindow* parent = NULL, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 1280,1024 ), long style = wxDEFAULT_FRAME_STYLE|wxTAB_TRAVERSAL ); virtual ~MainFrame(); void SetHelpText( const tchar* text ); bool OpenProject( const Helium::Path& path ); void SyncPropertyThread(); private: // Stores information about the state of each outliner for each scene // that is open. Restores the state when switching between scenes. M_OutlinerStates m_OutlinerStates; HelpPanel* m_HelpPanel; ProjectPanel* m_ProjectPanel; LayersPanel* m_LayersPanel; TypesPanel* m_TypesPanel; ViewPanel* m_ViewPanel; ToolbarPanel* m_ToolbarPanel; DirectoryPanel* m_DirectoryPanel; PropertiesPanel* m_PropertiesPanel; Core::ProjectPtr m_Project; MessageDisplayer m_MessageDisplayer; FileDialogDisplayer m_FileDialogDisplayer; Core::SceneManager m_SceneManager; // the attributes for the current selection Core::EnumeratorPtr m_SelectionEnumerator; Core::PropertiesManagerPtr m_SelectionPropertiesManager; Inspect::Canvas m_SelectionProperties; // the attributes for the current tool Core::EnumeratorPtr m_ToolEnumerator; Core::PropertiesManagerPtr m_ToolPropertiesManager; Inspect::Canvas m_ToolProperties; MenuMRUPtr m_MRU; M_IDToColorMode m_ColorModeLookup; //context items ordered by name Core::V_HierarchyNodeDumbPtr m_OrderedContextItems; TreeMonitor m_TreeMonitor; private: bool ValidateDrag( const Inspect::DragArgs& args ); wxDragResult DragOver( const Inspect::DragArgs& args ); wxDragResult Drop( const Inspect::DragArgs& args ); void SceneAdded( const Core::SceneChangeArgs& args ); void SceneRemoving( const Core::SceneChangeArgs& args ); void SceneLoadFinished( const Core::LoadArgs& args ); bool DoOpen( const tstring& path ); private: void OnMRUOpen( const MRUArgs& args ); // frame events void OnEraseBackground( wxEraseEvent& event ); void OnSize( wxSizeEvent& event ); void OnChar( wxKeyEvent& event ); void OnShow( wxShowEvent& event ); void OnMenuOpen( wxMenuEvent& event ); void OnNewScene( wxCommandEvent& event ); void OnNewEntity( wxCommandEvent& event ); void OnNewProject( wxCommandEvent& event ); void OnOpen( wxCommandEvent& event ); void OnClose( wxCommandEvent& event ); void OnSaveAll( wxCommandEvent& event ); void OnViewChange( wxCommandEvent& event ); void OnViewCameraChange( wxCommandEvent& event ); void OnViewVisibleChange( wxCommandEvent& event ); void OnViewColorModeChange( wxCommandEvent& event ); void OnImport( wxCommandEvent& event ); void OnExport( wxCommandEvent& event ); void OnUndo( wxCommandEvent& event ); void OnRedo( wxCommandEvent& event ); void OnCut( wxCommandEvent& event ); void OnCopy( wxCommandEvent& event ); void OnPaste( wxCommandEvent& event ); void OnDelete( wxCommandEvent& event ); void OnSelectAll( wxCommandEvent& event ); void OnInvertSelection( wxCommandEvent& event ); void OnParent( wxCommandEvent& event ); void OnUnparent( wxCommandEvent& event ); void OnGroup( wxCommandEvent& event ); void OnUngroup( wxCommandEvent& event ); void OnCenter( wxCommandEvent& event ); void OnDuplicate( wxCommandEvent& event ); void OnSmartDuplicate( wxCommandEvent& event ); void OnCopyTransform( wxCommandEvent& event ); void OnPasteTransform( wxCommandEvent& event ); void OnSnapToCamera( wxCommandEvent& event ); void OnSnapCameraTo( wxCommandEvent& event ); void OnPickWalk( wxCommandEvent& event ); void Executed( const Core::ExecuteArgs& args ); void SelectionChanged( const Core::OS_SelectableDumbPtr& selection ); void CurrentSceneChanged( const Core::SceneChangeArgs& args ); void CurrentSceneChanging( const Core::SceneChangeArgs& args ); void OnPropertiesCreated( const Core::PropertiesCreatedArgs& args ); void OnToolSelected(wxCommandEvent& event); void PickWorld( Core::PickArgs& args ); void DocumentModified( const Application::DocumentChangedArgs& args ); void DocumentClosed( const Application::DocumentChangedArgs& args ); void ViewToolChanged( const Core::ToolChangeArgs& args ); void SceneStatusChanged( const Core::SceneStatusChangeArgs& args ); void SceneContextChanged( const Core::SceneContextChangeArgs& args ); void OnExit( wxCommandEvent& event ); void OnExiting( wxCloseEvent& args ); void OnAbout( wxCommandEvent& event ); void OnSettings( wxCommandEvent& event ); void OnManifestContextMenu(wxCommandEvent& event); void OnTypeContextMenu(wxCommandEvent& event); private: bool Copy( Core::Scene* scene ); bool Paste( Core::Scene* scene ); void Render( Core::RenderVisitor* render ); void Select( const Core::SelectArgs& args ); void SetHighlight( const Core::SetHighlightArgs& args ); void ClearHighlight( const Core::ClearHighlightArgs& args ); private: void SelectItemInScene( wxCommandEvent& event ); void SelectSimilarItemsInScene( wxCommandEvent& event ); void OpenManifestContextMenu( const Core::SelectArgs& args ); void OpenTypeContextMenu( const Core::SelectArgs& args ); void SetupTypeContextMenu( const Core::HM_StrToSceneNodeTypeSmartPtr& sceneNodeTypes,wxMenu& contextMenu, u32& numMenuItems ); void SetupEntityTypeMenus( const Core::EntityType* entity, wxMenu* entityMenu, u32& numMenuItems ); static bool SortContextItemsByName( Core::SceneNode* lhs, Core::SceneNode* rhs ); static bool SortTypeItemsByName( Core::SceneNodeType* lhs, Core::SceneNodeType* rhs ); }; } }
4b711ace299525029c6b8a5c5d99d0838dd601ec
42e6b2003c19a4152a27370e0eeb1014b27ed8b3
/src/nexmark_hot_items_fw/GroupbyAuction.cpp
bbfca0c68ce7e4cd4c79fd98c8a880a792906dac
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
DonTassettitos/AIR
71510f43a4fbaf1ccf4f2a1fa843ca64c4a79d6e
92c93f05d6f15095d403dcbbe7ebe16563198697
refs/heads/master
2022-12-18T11:15:59.051265
2020-09-16T11:43:20
2020-09-16T11:43:20
296,014,950
0
0
null
null
null
null
UTF-8
C++
false
false
4,904
cpp
GroupbyAuction.cpp
/** * Copyright (c) 2020 University of Luxembourg. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF LUXEMBOURG AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE UNIVERSITY OF LUXEMBOURG OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ /* * GroupbyAuction.cpp * * Created on: April 23, 2020 * Author: damien.tassetti */ #include "GroupbyAuction.hpp" #include "../nexmark_gen/PODTypes.hpp" #include "../usecases/NQ5FW.hpp" #include "../serialization/Serialization.hpp" #include <mpi.h> #include <unistd.h> #include <stdio.h> #include <string.h> #include <algorithm> using nexmark_hot_items_fw::GroupbyAuction; using nexmark_gen::Bid; using std::min; GroupbyAuction::GroupbyAuction(int tag, int rank, int worldSize) : Vertex(tag, rank, worldSize) { pthread_mutex_init(&mutex, NULL); } GroupbyAuction::~GroupbyAuction() { } void GroupbyAuction::batchProcess() { } void GroupbyAuction::streamProcess(int channel) { Message* inMessage; list<Message*>* tmpMessages = new list<Message*>(); const int window_duration = nexmark::NQ5FW::window_duration; while (ALIVE) { pthread_mutex_lock(&listenerMutexes[channel]); while (inMessages[channel].empty()) pthread_cond_wait(&listenerCondVars[channel], &listenerMutexes[channel]); while (!inMessages[channel].empty()) { inMessage = inMessages[channel].front(); inMessages[channel].pop_front(); tmpMessages->push_back(inMessage); } pthread_mutex_unlock(&listenerMutexes[channel]); while (!tmpMessages->empty()) { inMessage = tmpMessages->front(); tmpMessages->pop_front(); WrapperUnit wu = Serialization::unwrap<WrapperUnit>(inMessage); int wid = wu.window_start_time; // TODO : check numeric limits pthread_mutex_lock(&mutex); // do not update structure and read it at the same time update(wid, inMessage); completeness[wid] += wu.completeness_tag_numerator; // every rank will send an is_complete message once // the first windows will never be complete if (completeness[wid] == wu.completeness_tag_denominator){ send(wid); windows.erase(wid); window_ends.erase(wid); completeness.erase(wid); } pthread_mutex_unlock(&mutex); delete inMessage; // delete message from incoming queue } tmpMessages->clear(); } delete tmpMessages; } void GroupbyAuction::update(int wid, Message*const inMessage){ size_t nof_bids = inMessage->size / sizeof(Bid); for(size_t i = 0; i < nof_bids; i++){ const Bid& bid = Serialization::read_front<Bid>(inMessage, sizeof(Bid) * i); windows[wid][bid.auction_id]++; if (bid.event_time > window_ends[wid]) window_ends[wid] = bid.event_time; } } void GroupbyAuction::send(int wid){ Message* outMessage = new Message(windows[wid].size() * (sizeof(int) + sizeof(size_t)) + sizeof(WrapperUnit)); for(auto it = windows[wid].begin(); it != windows[wid].end(); ++it){ Serialization::wrap<int>((*it).first, outMessage); // auction_id Serialization::wrap<size_t>((*it).second, outMessage); // nof bids for the given auction } WrapperUnit wu; wu.window_start_time = wid; // the rest doesn't matter Serialization::wrap<WrapperUnit>(wu, outMessage); int channel = 0; // send to the global aggregator on rank 0 pthread_mutex_lock(&senderMutexes[channel]); outMessages[channel].push_back(outMessage); pthread_cond_signal(&senderCondVars[channel]); pthread_mutex_unlock(&senderMutexes[channel]); }
9bb8a8e04bb0dea5178acc5772c05b0fdf112c36
190cfe853208fa287aa2539f1dd4e729f5235091
/HospitalFee/FMOutpatientInsuranceCost80A.cpp
d2fd0dde4e26c275ecc7ea90f0d427c4841445cf
[]
no_license
smithgold53/HMSReportForms
d8cacb7de1509995b46be16bc5a99ca9104dbea1
7f426de1a3f8b7bad956c62ba61306a3969accf2
refs/heads/master
2020-05-18T09:24:39.420731
2015-05-06T09:47:03
2015-05-06T09:47:03
34,946,969
0
0
null
null
null
null
UTF-8
C++
false
false
61,078
cpp
FMOutpatientInsuranceCost80A.cpp
#include "stdafx.h" #include "FMOutpatientInsuranceCost80A.h" #include "HMSMainFrame.h" #include "ReportDocument.h" #include "Excel.h" /*static void _OnYearChangeFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnYearChange(); } */ /*static void _OnYearSetfocusFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnYearSetfocus();} */ /*static void _OnYearKillfocusFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnYearKillfocus(); } */ static int _OnYearCheckValueFnc(CWnd *pWnd){ return ((CFMOutpatientInsuranceCost80A *)pWnd)->OnYearCheckValue(); } static void _OnReportPeriodSelectChangeFnc(CWnd *pWnd, int nOldItemSel, int nNewItemSel){ ((CFMOutpatientInsuranceCost80A* )pWnd)->OnReportPeriodSelectChange(nOldItemSel, nNewItemSel); } static void _OnReportPeriodSelendokFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnReportPeriodSelendok(); } /*static void _OnReportPeriodSetfocusFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnReportPeriodKillfocus(); }*/ /*static void _OnReportPeriodKillfocusFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnReportPeriodKillfocus(); }*/ static long _OnReportPeriodLoadDataFnc(CWnd *pWnd){ return ((CFMOutpatientInsuranceCost80A *)pWnd)->OnReportPeriodLoadData(); } /*static void _OnReportPeriodAddNewFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnReportPeriodAddNew(); }*/ /*static void _OnFromDateChangeFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnFromDateChange(); } */ /*static void _OnFromDateSetfocusFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnFromDateSetfocus();} */ /*static void _OnFromDateKillfocusFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnFromDateKillfocus(); } */ static int _OnFromDateCheckValueFnc(CWnd *pWnd){ return ((CFMOutpatientInsuranceCost80A *)pWnd)->OnFromDateCheckValue(); } /*static void _OnToDateChangeFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnToDateChange(); } */ /*static void _OnToDateSetfocusFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnToDateSetfocus();} */ /*static void _OnToDateKillfocusFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnToDateKillfocus(); } */ static int _OnToDateCheckValueFnc(CWnd *pWnd){ return ((CFMOutpatientInsuranceCost80A *)pWnd)->OnToDateCheckValue(); } static void _OnClerkSelectChangeFnc(CWnd *pWnd, int nOldItemSel, int nNewItemSel){ ((CFMOutpatientInsuranceCost80A* )pWnd)->OnClerkSelectChange(nOldItemSel, nNewItemSel); } static void _OnClerkSelendokFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnClerkSelendok(); } /*static void _OnClerkSetfocusFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnClerkKillfocus(); }*/ /*static void _OnClerkKillfocusFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnClerkKillfocus(); }*/ static long _OnClerkLoadDataFnc(CWnd *pWnd){ return ((CFMOutpatientInsuranceCost80A *)pWnd)->OnClerkLoadData(); } /*static void _OnClerkAddNewFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A *)pWnd)->OnClerkAddNew(); }*/ static void _OnByDischargedDateSelectFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A*)pWnd)->OnByDischargedDateSelect(); } static void _OnUnapprovedSelectFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A*)pWnd)->OnUnapprovedSelect(); } static void _OnPrintSelectFnc(CWnd *pWnd){ CFMOutpatientInsuranceCost80A *pVw = (CFMOutpatientInsuranceCost80A *)pWnd; pVw->OnPrintSelect(); } static void _OnExportSelectFnc(CWnd *pWnd){ CFMOutpatientInsuranceCost80A *pVw = (CFMOutpatientInsuranceCost80A *)pWnd; pVw->OnExportSelect(); } static void _OnExportForInsSelectFnc(CWnd *pWnd){ CFMOutpatientInsuranceCost80A *pVw = (CFMOutpatientInsuranceCost80A *)pWnd; pVw->OnExportForInsSelect(); } static long _OnCardListLoadDataFnc(CWnd *pWnd){ return ((CFMOutpatientInsuranceCost80A*)pWnd)->OnCardListLoadData(); } static void _OnCardListDblClickFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A*)pWnd)->OnCardListDblClick(); } static void _OnCardListSelectChangeFnc(CWnd *pWnd, int nOldItem, int nNewItem){ ((CFMOutpatientInsuranceCost80A*)pWnd)->OnCardListSelectChange(nOldItem, nNewItem); } static int _OnCardListCheckAllFnc(CWnd *pWnd){ return ((CFMOutpatientInsuranceCost80A*)pWnd)->OnCardListCheckAll(); } static int _OnCardListUnCheckAllFnc(CWnd *pWnd){ return ((CFMOutpatientInsuranceCost80A*)pWnd)->OnCardListUnCheckAll(); } static long _OnDeptListLoadDataFnc(CWnd *pWnd){ return ((CFMOutpatientInsuranceCost80A*)pWnd)->OnDeptListLoadData(); } static void _OnDeptListDblClickFnc(CWnd *pWnd){ ((CFMOutpatientInsuranceCost80A*)pWnd)->OnDeptListDblClick(); } static void _OnDeptListSelectChangeFnc(CWnd *pWnd, int nOldItem, int nNewItem){ ((CFMOutpatientInsuranceCost80A*)pWnd)->OnDeptListSelectChange(nOldItem, nNewItem); } static int _OnDeptListCheckAllFnc(CWnd *pWnd){ return ((CFMOutpatientInsuranceCost80A*)pWnd)->OnDeptListCheckAll(); } static int _OnDeptListUnCheckAllFnc(CWnd *pWnd){ return ((CFMOutpatientInsuranceCost80A*)pWnd)->OnDeptListUnCheckAll(); } CFMOutpatientInsuranceCost80A::CFMOutpatientInsuranceCost80A(CWnd *pParent){ m_nDlgWidth = 1029; m_nDlgHeight = 773; SetDefaultValues(); } CFMOutpatientInsuranceCost80A::~CFMOutpatientInsuranceCost80A(){ } void CFMOutpatientInsuranceCost80A::OnCreateComponents(){ m_wndReportCondition.Create(this, _T("Report Condtion"), 5, 5, 440, 520); m_wndInsuranceCardInfo.Create(this, _T("Insurance Card Information"), 10, 120, 435, 255); m_wndDeptInfo.Create(this, _T("Dept"), 10, 260, 435, 515); m_wndYearLabel.Create(this, _T("Year"), 10, 30, 90, 55); m_wndYear.Create(this,95, 30, 215, 55); m_wndReportPeriodLabel.Create(this, _T("Report Period"), 220, 30, 310, 55); m_wndReportPeriod.Create(this,315, 30, 435, 55); m_wndFromDateLabel.Create(this, _T("From Date"), 10, 60, 90, 85); m_wndFromDate.Create(this,95, 60, 215, 85); m_wndToDateLabel.Create(this, _T("To Date"), 220, 60, 310, 85); m_wndToDate.Create(this,315, 60, 435, 85); m_wndClerkLabel.Create(this, _T("Clerk"), 10, 90, 90, 115); m_wndClerk.Create(this,95, 90, 435, 115); m_wndByDischargedDate.Create(this, _T("By Discharged Date"), 5, 525, 145, 550); m_wndUnapproved.Create(this, _T("Unapproved"), 150, 525, 290, 550); m_wndOnlyCommander.Create(this, _T("Only Commander"), 295, 525, 440, 550); m_wndPrint.Create(this, _T("&Print"), 150, 555, 250, 580); m_wndExport.Create(this, _T("&Export"), 255, 555, 355, 580); m_wndExportForIns.Create(this, _T("Export for Ins"), 360, 555, 440, 580); m_wndCardList.Create(this,15, 145, 430, 250); m_wndDeptList.Create(this,15, 285, 430, 510); } void CFMOutpatientInsuranceCost80A::OnInitializeComponents(){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); m_wndYear.SetLimitText(16); //m_wndYear.SetCheckValue(true); //m_wndReportPeriod.SetCheckValue(true); m_wndReportPeriod.LimitText(35); //m_wndFromDate.SetMax(CDateTime(pMF->GetSysDateTime())); m_wndFromDate.SetCheckValue(true); //m_wndToDate.SetMax(CDateTime(pMF->GetSysDateTime())); m_wndToDate.SetCheckValue(true); //m_wndClerk.SetCheckValue(true); m_wndClerk.LimitText(75); m_wndReportPeriod.InsertColumn(0, _T("ID"), CFMT_TEXT, 50); m_wndReportPeriod.InsertColumn(1, _T("Description"), CFMT_TEXT, 150); m_wndClerk.InsertColumn(0, _T("ID"), CFMT_TEXT, 80); m_wndClerk.InsertColumn(1, _T("Name"), CFMT_TEXT, 240); m_wndCardList.InsertColumn(0, _T("ID"), CFMT_TEXT, 90); m_wndCardList.InsertColumn(1, _T("Desc"), CFMT_TEXT, 300); m_wndCardList.SetCheckBox(TRUE); m_wndDeptList.InsertColumn(0, _T("ID"), CFMT_TEXT, 90); m_wndDeptList.InsertColumn(1, _T("Name"), CFMT_TEXT, 300); m_wndDeptList.SetCheckBox(TRUE); } void CFMOutpatientInsuranceCost80A::OnSetWindowEvents(){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); //m_wndYear.SetEvent(WE_CHANGE, _OnYearChangeFnc); //m_wndYear.SetEvent(WE_SETFOCUS, _OnYearSetfocusFnc); //m_wndYear.SetEvent(WE_KILLFOCUS, _OnYearKillfocusFnc); m_wndYear.SetEvent(WE_CHECKVALUE, _OnYearCheckValueFnc); m_wndReportPeriod.SetEvent(WE_SELENDOK, _OnReportPeriodSelendokFnc); //m_wndReportPeriod.SetEvent(WE_SETFOCUS, _OnReportPeriodSetfocusFnc); //m_wndReportPeriod.SetEvent(WE_KILLFOCUS, _OnReportPeriodKillfocusFnc); m_wndReportPeriod.SetEvent(WE_SELCHANGE, _OnReportPeriodSelectChangeFnc); m_wndReportPeriod.SetEvent(WE_LOADDATA, _OnReportPeriodLoadDataFnc); //m_wndReportPeriod.SetEvent(WE_ADDNEW, _OnReportPeriodAddNewFnc); //m_wndFromDate.SetEvent(WE_CHANGE, _OnFromDateChangeFnc); //m_wndFromDate.SetEvent(WE_SETFOCUS, _OnFromDateSetfocusFnc); //m_wndFromDate.SetEvent(WE_KILLFOCUS, _OnFromDateKillfocusFnc); m_wndFromDate.SetEvent(WE_CHECKVALUE, _OnFromDateCheckValueFnc); //m_wndToDate.SetEvent(WE_CHANGE, _OnToDateChangeFnc); //m_wndToDate.SetEvent(WE_SETFOCUS, _OnToDateSetfocusFnc); //m_wndToDate.SetEvent(WE_KILLFOCUS, _OnToDateKillfocusFnc); m_wndToDate.SetEvent(WE_CHECKVALUE, _OnToDateCheckValueFnc); m_wndClerk.SetEvent(WE_SELENDOK, _OnClerkSelendokFnc); //m_wndClerk.SetEvent(WE_SETFOCUS, _OnClerkSetfocusFnc); //m_wndClerk.SetEvent(WE_KILLFOCUS, _OnClerkKillfocusFnc); m_wndClerk.SetEvent(WE_SELCHANGE, _OnClerkSelectChangeFnc); m_wndClerk.SetEvent(WE_LOADDATA, _OnClerkLoadDataFnc); //m_wndClerk.SetEvent(WE_ADDNEW, _OnClerkAddNewFnc); m_wndByDischargedDate.SetEvent(WE_CLICK, _OnByDischargedDateSelectFnc); m_wndUnapproved.SetEvent(WE_CLICK, _OnUnapprovedSelectFnc); m_wndPrint.SetEvent(WE_CLICK, _OnPrintSelectFnc); m_wndExport.SetEvent(WE_CLICK, _OnExportSelectFnc); m_wndExportForIns.SetEvent(WE_CLICK, _OnExportForInsSelectFnc); m_wndCardList.SetEvent(WE_SELCHANGE, _OnCardListSelectChangeFnc); m_wndCardList.SetEvent(WE_LOADDATA, _OnCardListLoadDataFnc); m_wndCardList.SetEvent(WE_DBLCLICK, _OnCardListDblClickFnc); m_wndCardList.AddEvent(1, _T("Check All"), _OnCardListCheckAllFnc); m_wndCardList.AddEvent(2, _T("Uncheck All"), _OnCardListUnCheckAllFnc); m_wndDeptList.SetEvent(WE_SELCHANGE, _OnDeptListSelectChangeFnc); m_wndDeptList.SetEvent(WE_LOADDATA, _OnDeptListLoadDataFnc); m_wndDeptList.SetEvent(WE_DBLCLICK, _OnDeptListDblClickFnc); m_wndDeptList.AddEvent(1, _T("Check All"), _OnDeptListCheckAllFnc); m_wndDeptList.AddEvent(2, _T("Uncheck All"), _OnDeptListUnCheckAllFnc); CString szSQL; CString szSysDate = pMF->GetSysDate(); m_nYear = ToInt(szSysDate.Left(4)); m_szReportPeriodKey.Format(_T("%d"), ToInt(szSysDate.Mid(5, 2))); m_szFromDate = m_szToDate = pMF->GetSysDate(); m_szFromDate += _T("00:00"); m_szToDate += _T("23:59"); UpdateData(false); OnDeptListLoadData(); OnCardListLoadData(); } void CFMOutpatientInsuranceCost80A::OnDoDataExchange(CDataExchange* pDX){ DDX_Text(pDX, m_wndYear.GetDlgCtrlID(), m_nYear); DDX_TextEx(pDX, m_wndReportPeriod.GetDlgCtrlID(), m_szReportPeriodKey); DDX_TextEx(pDX, m_wndFromDate.GetDlgCtrlID(), m_szFromDate); DDX_TextEx(pDX, m_wndToDate.GetDlgCtrlID(), m_szToDate); DDX_TextEx(pDX, m_wndClerk.GetDlgCtrlID(), m_szClerkKey); DDX_Check(pDX, m_wndByDischargedDate.GetDlgCtrlID(), m_bByDischargedDate); DDX_Check(pDX, m_wndUnapproved.GetDlgCtrlID(), m_bUnapproved); DDX_Check(pDX, m_wndOnlyCommander.GetDlgCtrlID(), m_bOnlyCommander); } void CFMOutpatientInsuranceCost80A::SetDefaultValues(){ m_nYear=0; m_szReportPeriodKey.Empty(); m_szFromDate.Empty(); m_szToDate.Empty(); m_szClerkKey.Empty(); m_bIsInsPurpose = FALSE; m_bByDischargedDate = FALSE; m_bUnapproved = FALSE; m_bOnlyCommander = FALSE; m_bShowDiff = FALSE; } int CFMOutpatientInsuranceCost80A::SetMode(int nMode){ int nOldMode = GetMode(); CGuiView::SetMode(nMode); CHMSMainFrame *pMF = (CHMSMainFrame *) AfxGetMainWnd(); CString szSQL; CRecord rs(&pMF->m_db); switch(nMode){ case VM_ADD: EnableControls(TRUE); EnableButtons(TRUE, 3, 4, -1); SetDefaultValues(); break; case VM_EDIT: EnableControls(TRUE); EnableButtons(TRUE, 3, 4, -1); break; case VM_VIEW: EnableControls(FALSE); EnableButtons(FALSE, 3, 4, -1); break; case VM_NONE: EnableControls(FALSE); EnableButtons(TRUE, 0, 6, -1); SetDefaultValues(); break; }; UpdateData(FALSE); return nOldMode; } /*void CFMOutpatientInsuranceCost80A::OnYearChange(){ } */ /*void CFMOutpatientInsuranceCost80A::OnYearSetfocus(){ } */ /*void CFMOutpatientInsuranceCost80A::OnYearKillfocus(){ } */ int CFMOutpatientInsuranceCost80A::OnYearCheckValue(){ UpdateData(TRUE); if (m_nYear > 0) { CDateTime dt; CDate date; CString szTemp; dt.ParseDateTime(m_szFromDate); date = dt.GetDate(); if (date.GetYear() != 1752) { dt.SetDate(m_nYear, date.GetMonth(), date.GetDay()); m_szFromDate = dt.GetDateTime(); szTemp.Format(_T("%.2d/.2d/.4d %.2d:%.2d"), dt.GetDate().GetDay(), dt.GetDate().GetMonth(), dt.GetDate().GetYear(), dt.GetTime().GetHour(), dt.GetTime().GetMinute()); m_wndFromDate.SetWindowText(szTemp); } dt.ParseDateTime(m_szToDate); date = dt.GetDate(); if (date.GetYear() != 1752) { dt.SetDate(m_nYear, date.GetMonth(), date.GetDay()); m_szToDate = dt.GetDateTime(); szTemp.Format(_T("%.2d/.2d/.4d %.2d:%.2d"), dt.GetDate().GetDay(), dt.GetDate().GetMonth(), dt.GetDate().GetYear(), dt.GetTime().GetHour(), dt.GetTime().GetMinute()); m_wndToDate.SetWindowText(szTemp); } } UpdateData(FALSE); return 0; } void CFMOutpatientInsuranceCost80A::OnReportPeriodSelectChange(int nOldItemSel, int nNewItemSel){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); } void CFMOutpatientInsuranceCost80A::OnReportPeriodSelendok(){ CHMSMainFrame *pMF = (CHMSMainFrame *) AfxGetMainWnd(); CString tmpStr; CDate dte, date; UpdateData(true); date.ParseDate(pMF->GetSysDate()); int nYear = date.GetYear(); int nMonth = ToInt(m_szReportPeriodKey); if (nMonth > 0 && nMonth <= 12) { m_szFromDate.Format(_T("%.4d/%.2d/1 00:00"), nYear, nMonth); dte.ParseDate(m_szFromDate); m_szToDate.Format(_T("%.4d/%.2d/%.2d 23:59"), nYear, nMonth, dte.GetMonthLastDay()); } if (nMonth == 13) { m_szFromDate.Format(_T("%.4d/1/1 00:00"), nYear); tmpStr.Format(_T("%.4d/3/1"), nYear); dte.ParseDate(tmpStr); m_szToDate.Format(_T("%.4d/3/%.2d 23:59"), nYear, dte.GetMonthLastDay()); } if (nMonth == 14) { m_szFromDate.Format(_T("%.4d/4/1 00:00"), nYear); tmpStr.Format(_T("%.4d/6/1"), nYear); dte.ParseDate(tmpStr); m_szToDate.Format(_T("%.4d/6/%.2d 23:59"), nYear, dte.GetMonthLastDay()); } if (nMonth == 15) { m_szFromDate.Format(_T("%.4d/7/1 00:00"), nYear); tmpStr.Format(_T("%.4d/9/1"), nYear); dte.ParseDate(tmpStr); m_szToDate.Format(_T("%.4d/9/%.2d 23:59"), nYear, dte.GetMonthLastDay()); } if (nMonth == 16) { m_szFromDate.Format(_T("%.4d/10/1 00:00"), nYear); tmpStr.Format(_T("%.4d/12/1"), nYear); dte.ParseDate(tmpStr); m_szToDate.Format(_T("%.4d/12/%.2d 23:59"), nYear, dte.GetMonthLastDay()); } if (nMonth == 17) { m_szFromDate.Format(_T("%.4d/1/1 00:00"), nYear); tmpStr.Format(_T("%.4d/12/1"), nYear); dte.ParseDate(tmpStr); m_szToDate.Format(_T("%.4d/12/%.2d 23:59"), nYear, dte.GetMonthLastDay()); } UpdateData(false); } /*void CFMOutpatientInsuranceCost80A::OnReportPeriodSetfocus(){ }*/ /*void CFMOutpatientInsuranceCost80A::OnReportPeriodKillfocus(){ }*/ long CFMOutpatientInsuranceCost80A::OnReportPeriodLoadData(){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); CRecord rs(&pMF->m_db); CString szSQL, szWhere; szWhere.Empty(); if(m_wndReportPeriod.IsSearchKey() && ToInt(m_szReportPeriodKey) > 0) { szWhere.Format(_T(" WHERE hpr_idx=%d "), ToInt(m_szReportPeriodKey)); } m_wndReportPeriod.DeleteAllItems(); int nCount = 0; szSQL.Format(_T("SELECT * FROM hms_period_report %s ORDER BY hpr_idx "), szWhere); nCount = rs.ExecSQL(szSQL); while(!rs.IsEOF()){ m_wndReportPeriod.AddItems( rs.GetValue(_T("hpr_idx")), rs.GetValue(_T("hpr_name")), NULL); rs.MoveNext(); } return nCount; } /*void CFMOutpatientInsuranceCost80A::OnReportPeriodAddNew(){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); } */ /*void CFMOutpatientInsuranceCost80A::OnFromDateChange(){ } */ /*void CFMOutpatientInsuranceCost80A::OnFromDateSetfocus(){ } */ /*void CFMOutpatientInsuranceCost80A::OnFromDateKillfocus(){ } */ int CFMOutpatientInsuranceCost80A::OnFromDateCheckValue(){ return 0; } /*void CFMOutpatientInsuranceCost80A::OnToDateChange(){ } */ /*void CFMOutpatientInsuranceCost80A::OnToDateSetfocus(){ } */ /*void CFMOutpatientInsuranceCost80A::OnToDateKillfocus(){ } */ int CFMOutpatientInsuranceCost80A::OnToDateCheckValue(){ return 0; } void CFMOutpatientInsuranceCost80A::OnClerkSelectChange(int nOldItemSel, int nNewItemSel){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); } void CFMOutpatientInsuranceCost80A::OnClerkSelendok(){ } /*void CFMOutpatientInsuranceCost80A::OnClerkSetfocus(){ }*/ /*void CFMOutpatientInsuranceCost80A::OnClerkKillfocus(){ }*/ long CFMOutpatientInsuranceCost80A::OnClerkLoadData(){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); CRecord rs(&pMF->m_db); CString szSQL, szWhere; szWhere.Empty(); if(m_wndClerk.IsSearchKey() && !m_szClerkKey.IsEmpty()) { szWhere.Format(_T(" and lower(su_userid)=lower('%s') "), m_szClerkKey); } m_wndClerk.DeleteAllItems(); int nCount = 0; szSQL.Format(_T("SELECT su_userid as id, su_name as name FROM sys_user WHERE su_groupid in('A','F') %s ORDER BY su_userid"), szWhere); nCount = rs.ExecSQL(szSQL); while(!rs.IsEOF()){ m_wndClerk.AddItems( rs.GetValue(_T("id")), rs.GetValue(_T("name")), NULL); rs.MoveNext(); } return nCount; } /*void CFMOutpatientInsuranceCost80A::OnClerkAddNew(){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); } */ void CFMOutpatientInsuranceCost80A::OnByDischargedDateSelect(){ UpdateData(true); if (m_bUnapproved) m_wndUnapproved.SetCheck(false); } void CFMOutpatientInsuranceCost80A::OnUnapprovedSelect(){ UpdateData(true); if (m_bByDischargedDate) m_wndByDischargedDate.SetCheck(false); } void CFMOutpatientInsuranceCost80A::OnPrintSelect(){ CHMSMainFrame *pMF = (CHMSMainFrame *)AfxGetMainWnd(); UpdateData(true); CReport rpt; CRecord rs(&pMF->m_db); CString szSQL, tmpStr; TCHAR *lszLine[] ={_T("a) \x42\x1EC7nh nh\xE2n \x111\xFAng tuy\x1EBFn."), _T("b) \x42\x1EC7nh nh\xE2n tr\xE1i tuy\x1EBFn.")}; szSQL = GetQueryString(); BeginWaitCursor(); int nCount = rs.ExecSQL(szSQL); if (nCount <= 0) { ShowMessage(150, MB_ICONSTOP); return; } if (!rpt.Init(_T("Reports/HMS/HF_BANGKETHANHTOAN_MAU80A.RPT"))) return; StringUpper(pMF->m_CompanyInfo.sc_pname, tmpStr); rpt.GetReportHeader()->SetValue(_T("HEALTHSERVICE"), tmpStr); StringUpper(pMF->m_CompanyInfo.sc_name, tmpStr); rpt.GetReportHeader()->SetValue(_T("HOSPITALNAME"), tmpStr); rpt.GetReportHeader()->SetValue(_T("ObjectGroup"), _T("")); rpt.GetReportHeader()->SetValue(_T("ReportPeriod"), m_szClerkKey); rs.GetValue(_T("invoiceno"), tmpStr); rpt.GetReportHeader()->SetValue(_T("InvoiceNo"), tmpStr); tmpStr.Format(rpt.GetReportHeader()->GetValue(_T("ReportDate")), CDateTime::Convert(m_szFromDate, yyyymmdd | hhmm, ddmmyyyy | hhmm), CDateTime::Convert(m_szToDate, yyyymmdd | hhmm, ddmmyyyy | hhmm)); rpt.GetReportHeader()->SetValue(_T("ReportDate"), tmpStr); int nIndex = 1; CString szOldLine, szNewLine, szOldGroup, szNewGroup, szLineName; CString szNewOfLine, szOldOfLine, szSumOfline; CReportSection* rptDetail; long double grpCost[26], grpLine[26], ttlCost[26], grpOfLine[26]; double cost = 0; for (int i = 0; i < 26; i++) { grpCost[i] = 0; grpLine[i] = 0; ttlCost[i] = 0; grpOfLine[i] =0; } while(!rs.IsEOF()) { rs.GetValue(_T("insline"), szNewLine); if (szNewLine != szOldLine && !szNewLine.IsEmpty()) { CString szField, szAmount; /*if (grpOfLine[20] > 0) { TranslateString(_T("\x43\x1ED9ng"), szAmount); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetFaceSize(9); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetBold(true); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetItalic(true); rptDetail = rpt.AddDetail(rpt.GetGroupFooter(1)); tmpStr.Format(_T("%s (%s) "), szAmount, szSumOfline); rptDetail->SetValue(_T("TotalGroup"), tmpStr); for (int i = 10; i < 24; i++) { szField.Format(_T("S%d"), i); FormatCurrency(grpOfLine[i], tmpStr); rptDetail->SetValue(szField, tmpStr); grpOfLine[i] = 0; } }*/ if (grpCost[11] > 0) { TranslateString(_T("Total Group"), szAmount); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetFaceSize(11); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetBold(true); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetItalic(true); rptDetail = rpt.AddDetail(rpt.GetGroupFooter(1)); tmpStr.Format(_T("%s (%s)"), szAmount, szOldGroup); rptDetail->SetValue(_T("TotalGroup"), tmpStr); for (int i = 11; i < 26; i++) { szField.Format(_T("S%d"), i); FormatCurrency(grpCost[i], tmpStr); //_msg(_T("%s"), tmpStr); rptDetail->SetValue(szField, tmpStr); //grpLine[i] = 0; grpCost[i] = 0; } } if (grpLine[11] > 0) { TranslateString(_T("Total Line"), szAmount); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetFaceSize(10); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetBold(true); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetItalic(false); rptDetail = rpt.AddDetail(rpt.GetGroupFooter(1)); tmpStr.Format(_T("%s (%s)"), szAmount, szLineName); rptDetail->SetValue(_T("TotalGroup"), tmpStr); for (int i = 11; i < 26; i++) { szField.Format(_T("S%d"), i); FormatCurrency(grpLine[i], tmpStr); rptDetail->SetValue(szField, tmpStr); ttlCost[i] += grpLine[i]; grpLine[i] = 0; } } rpt.GetGroupHeader(1)->GetItem(_T("GroupName"))->SetFaceSize(11); rpt.GetGroupHeader(1)->GetItem(_T("GroupName"))->SetBold(true); rpt.GetGroupHeader(1)->GetItem(_T("GroupName"))->SetItalic(false); rptDetail = rpt.AddDetail(rpt.GetGroupHeader(1)); rs.GetValue(_T("linename"), szLineName); rptDetail->SetValue(_T("GroupName"), szLineName + _T(". ") + pMF->GetSelectionString(_T("hms_insline"), szNewLine)); szOldLine = szNewLine; szOldOfLine.Empty(); szOldGroup.Empty(); nIndex = 1; } rs.GetValue(_T("insgroup"), szNewGroup); if (szNewGroup != szOldGroup && !szNewGroup.IsEmpty()) { CString szField, szAmount; /*if (grpOfLine[8] > 0) { TranslateString(_T("\x43\x1ED9ng"), szAmount); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetFaceSize(9); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetBold(true); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetItalic(true); rptDetail = rpt.AddDetail(rpt.GetGroupFooter(1)); tmpStr.Format(_T("%s (%s) "),szAmount , szSumOfline); rptDetail->SetValue(_T("TotalGroup"), tmpStr ); for (int i =10; i < 24; i++) { szField.Format(_T("S%d"), i); FormatCurrency(grpOfLine[i], tmpStr); rptDetail->SetValue(szField, tmpStr); grpOfLine[i] = 0; } }*/ if (grpCost[11] > 0) { TranslateString(_T("Total Group"), szAmount); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetFaceSize(10); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetBold(true); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetItalic(true); rptDetail = rpt.AddDetail(rpt.GetGroupFooter(1)); tmpStr.Format(_T("%s (%s)"), szAmount, szOldGroup); rptDetail->SetValue(_T("TotalGroup"), tmpStr); for (int i = 11; i < 26; i++) { szField.Format(_T("S%d"), i); FormatCurrency(grpCost[i], tmpStr); rptDetail->SetValue(szField, tmpStr); grpCost[i] = 0; } } rpt.GetGroupHeader(1)->GetItem(_T("GroupName"))->SetFaceSize(10); rpt.GetGroupHeader(1)->GetItem(_T("GroupName"))->SetItalic(true); rpt.GetGroupHeader(1)->GetItem(_T("GroupName"))->SetBold(true); rptDetail = rpt.AddDetail(rpt.GetGroupHeader(1)); rptDetail->SetValue(_T("GroupName"), szNewGroup + _T(". ") + pMF->GetSelectionString(_T("hms_insurance_group"), szNewGroup)); szOldGroup = szNewGroup; szOldOfLine.Empty(); nIndex = 1; } /*rs.GetValue(_T("hdline"), szNewOfLine); if(szNewOfLine != szOldOfLine && !szNewOfLine.IsEmpty()) { CString szField, szAmount; if (grpOfLine[9] > 0) { TranslateString(_T("\x43\x1ED9ng"), szAmount); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetFaceSize(9); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetBold(true); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetItalic(true); rptDetail = rpt.AddDetail(rpt.GetGroupFooter(1)); tmpStr.Format(_T("%s (%s) "),szAmount , szSumOfline); rptDetail->SetValue(_T("TotalGroup"), tmpStr ); for (int i = 9; i < 24; i++) { szField.Format(_T("S%d"), i); FormatCurrency(grpOfLine[i], tmpStr); rptDetail->SetValue(szField, tmpStr); grpOfLine[i] = 0; } } if (szNewOfLine == _T("0") ) { tmpStr.Format(_T("%s"), lszLine[0]); szSumOfline = _T("a"); } else { tmpStr.Format(_T("%s"), lszLine[1]); szSumOfline = _T("b"); } rpt.GetGroupHeader(1)->GetItem(_T("InsuranceLine"))->SetFaceSize(9); rpt.GetGroupHeader(1)->GetItem(_T("InsuranceLine"))->SetItalic(true); rpt.GetGroupHeader(1)->GetItem(_T("InsuranceLine"))->SetBold(true); rptDetail = rpt.AddDetail(rpt.GetGroupHeader(1)); rptDetail->SetValue(_T("InsuranceLine"),tmpStr); szOldOfLine = szNewOfLine; nIndex = 1; }*/ rptDetail = rpt.AddDetail(); tmpStr.Format(_T("%d"), nIndex++); rptDetail->SetValue(_T("1"), tmpStr); rs.GetValue(_T("pname"), tmpStr); rptDetail->SetValue(_T("2"), tmpStr); rs.GetValue(_T("mbirthyear"), tmpStr); rptDetail->SetValue(_T("3"), tmpStr); rs.GetValue(_T("fbirthyear"), tmpStr); rptDetail->SetValue(_T("4"), tmpStr); /*rs.GetValue(_T("sex"), tmpStr); rptDetail->SetValue(_T("4"), tmpStr);*/ rs.GetValue(_T("cardno"), tmpStr); rptDetail->SetValue(_T("5"), tmpStr); rs.GetValue(_T("regplace"), tmpStr); tmpStr.Insert(2, _T("-")); rptDetail->SetValue(_T("6"), tmpStr); rs.GetValue(_T("icd10"), tmpStr); rptDetail->SetValue(_T("7"), tmpStr); rs.GetValue(_T("admitdate"), tmpStr); //tmpStr = CDate::Convert(rs.GetValue(_T("admitdate")), yyyymmdd, ddmmyyyy); rptDetail->SetValue(_T("8"), tmpStr); rs.GetValue(_T("dischargedate"), tmpStr); //tmpStr = CDate::Convert(rs.GetValue(_T("dischargedate")), yyyymmdd, ddmmyyyy); rptDetail->SetValue(_T("9"), tmpStr); rs.GetValue(_T("totaltreat"), tmpStr); rptDetail->SetValue(_T("10"), tmpStr); rs.GetValue(_T("cost"), cost); grpCost[11] += cost; grpLine[11] += cost; //grpOfLine[9] += cost; FormatCurrency(cost, tmpStr); rptDetail->SetValue(_T("11"), tmpStr); rs.GetValue(_T("testfee"), cost); grpCost[12] += cost; grpLine[12] += cost; //grpOfLine[10] += cost; FormatCurrency(cost, tmpStr); rptDetail->SetValue(_T("12"), tmpStr); rs.GetValue(_T("pacsfee"), cost); grpCost[13] += cost; grpLine[13] += cost; //grpOfLine[11] += cost; FormatCurrency(cost, tmpStr); rptDetail->SetValue(_T("13"), tmpStr); rs.GetValue(_T("drugfee"), cost); grpCost[14] += cost; grpLine[14] += cost; //grpOfLine[12] += cost; FormatCurrency(cost, tmpStr); rptDetail->SetValue(_T("14"), tmpStr); rs.GetValue(_T("bloodfee"), cost); grpCost[15] += cost; grpLine[15] += cost; //grpOfLine[13] += cost; FormatCurrency(cost, tmpStr); rptDetail->SetValue(_T("15"), tmpStr); rs.GetValue(_T("normtechfee"), cost); grpCost[16] += cost; grpLine[16] += cost; //grpOfLine[14] += cost; FormatCurrency(cost, tmpStr); rptDetail->SetValue(_T("16"), tmpStr); rs.GetValue(_T("materialfee"), cost); grpCost[17] += cost; grpLine[17] += cost; //grpOfLine[15] += cost; FormatCurrency(cost, tmpStr); rptDetail->SetValue(_T("17"), tmpStr); rs.GetValue(_T("replace_materialfee"), cost); grpCost[18] += cost; grpLine[18] += cost; //grpOfLine[15] += cost; FormatCurrency(cost, tmpStr); rptDetail->SetValue(_T("18"), tmpStr); rs.GetValue(_T("hitechfee"), cost); grpCost[19] += cost; grpLine[19] += cost; //grpOfLine[17] += cost; FormatCurrency(cost, tmpStr); rptDetail->SetValue(_T("19"), tmpStr); rs.GetValue(_T("drugfeek"), cost); grpCost[20] += cost; grpLine[20] += cost; //grpOfLine[18] += cost; FormatCurrency(cost, tmpStr); rptDetail->SetValue(_T("20"), tmpStr); rs.GetValue(_T("bedfee"), cost); grpCost[21] += cost; grpLine[21] += cost; //grpOfLine[19] += cost; FormatCurrency(cost, tmpStr); rptDetail->SetValue(_T("21"), tmpStr); rs.GetValue(_T("transportfee"), cost);; grpCost[22] += cost; grpLine[22] += cost; //grpOfLine[19] += cost; FormatCurrency(cost, tmpStr); rptDetail->SetValue(_T("22"), tmpStr); rs.GetValue(_T("patpaid"), cost); grpCost[23] += cost; grpLine[23] += cost; //grpOfLine[21] += cost; FormatCurrency(cost, tmpStr); rptDetail->SetValue(_T("23"), tmpStr); rs.GetValue(_T("inspaid"), cost); grpCost[24] += cost; grpLine[24] += cost; //grpOfLine[22] += cost; FormatCurrency(cost, tmpStr); rptDetail->SetValue(_T("24"), tmpStr); rs.MoveNext(); } for (int i = 11; i < 26; i++) { ttlCost[i] += grpLine[i]; } /*if (grpOfLine[20] > 0) { CString szField,szAmount; TranslateString(_T("\x43\x1ED9ng"), szAmount); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetFaceSize(9); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetBold(true); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetItalic(true); rptDetail = rpt.AddDetail(rpt.GetGroupFooter(1)); tmpStr.Format(_T("%s (%s)"),szAmount , szSumOfline); rptDetail->SetValue(_T("TotalGroup"), tmpStr ); for (int i =10; i < 24; i++) { szField.Format(_T("S%d"), i); FormatCurrency(grpLine[i], tmpStr); rptDetail->SetValue(szField, tmpStr); } }*/ if (grpCost[11] > 0) { CString szField,szAmount; TranslateString(_T("Total Group"), szAmount); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetFaceSize(10); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetBold(true); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetItalic(true); rptDetail = rpt.AddDetail(rpt.GetGroupFooter(1)); tmpStr.Format(_T("%s (%s)"), szAmount, szOldGroup); rptDetail->SetValue(_T("TotalGroup"), tmpStr); for (int i = 11; i < 26; i++) { szField.Format(_T("S%d"), i); FormatCurrency(grpCost[i], tmpStr); rptDetail->SetValue(szField, tmpStr); } } if (grpLine[11] > 0) { CString szField, szAmount; TranslateString(_T("Total Line"), szAmount); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetFaceSize(11); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetBold(true); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetItalic(false); rptDetail = rpt.AddDetail(rpt.GetGroupFooter(1)); tmpStr.Format(_T("%s (%s)"), szAmount, szLineName); rptDetail->SetValue(_T("TotalGroup"), tmpStr); for (int i = 11; i < 26; i++) { szField.Format(_T("S%d"), i); FormatCurrency(grpCost[i], tmpStr); rptDetail->SetValue(szField, tmpStr); } } if (ttlCost[11] > 0) { CString szField, szAmount; TranslateString(_T("Total Amount:"), szAmount); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetFaceSize(12); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetBold(true); rpt.GetGroupFooter(1)->GetItem(_T("TotalGroup"))->SetItalic(false); rptDetail = rpt.AddDetail(rpt.GetGroupFooter(1)); rptDetail->SetValue(_T("TotalGroup"), szAmount); for (int i = 11; i < 26; i++) { szField.Format(_T("S%d"), i); FormatCurrency(ttlCost[i], tmpStr); rptDetail->SetValue(szField, tmpStr); } } CString szDate; tmpStr = pMF->GetSysDate(); szDate.Format(rpt.GetReportFooter()->GetValue(_T("PrintDate")), tmpStr.Mid(8, 2), tmpStr.Mid(5, 2), tmpStr.Left(4)); rpt.GetReportFooter()->SetValue(_T("PrintDate"), szDate); EndWaitCursor(); rpt.PrintPreview(); } void CFMOutpatientInsuranceCost80A::OnExportSelect(){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); CRecord rs(&pMF->m_db); CString szSQL; CString tmpStr, szTemp, szFromDateToDate; CString szDate; CString szMonth, szYear; int nIncrement = 0; BeginWaitCursor(); UpdateData(TRUE); szSQL = GetQueryString(); _fmsg(_T("%s"), szSQL); int nRes = rs.ExecSQL(szSQL); if (rs.IsEOF()) { if (nRes < 0) _msg(_T("%s"), szSQL); else _fmsg(_T("%s"), szSQL); ShowMessageBox(_T("No Data"), MB_OK | MB_ICONERROR); return; } CDate dt1, dt2; dt1.ParseDate(m_szFromDate); dt2.ParseDate(m_szToDate); if (dt1.GetYear() == dt2.GetYear()) szYear.Format(_T("%d"), dt1.GetYear()); else szYear.Format(_T("%d"), dt2.GetYear()); if (dt1.GetMonth() == dt2.GetMonth()) szMonth.Format(_T("%d"), dt1.GetMonth()); else szMonth.Format(_T("%d"), dt2.GetMonth()); CExcel xls; xls.CreateSheet(1); xls.SetWorksheet(0); xls.SetColumnWidth(0, 4); xls.SetColumnWidth(1, 17); xls.SetColumnWidth(2, 7); xls.SetColumnWidth(3, 5); xls.SetColumnWidth(4, 16); xls.SetColumnWidth(5, 8); xls.SetColumnWidth(6, 24); xls.SetColumnWidth(7, 10); xls.SetColumnWidth(8, 10); xls.SetColumnWidth(9, 6); xls.SetColumnWidth(10, 8); xls.SetColumnWidth(11, 8); xls.SetColumnWidth(12, 8); xls.SetColumnWidth(13, 8); xls.SetColumnWidth(14, 8); xls.SetColumnWidth(15, 8); xls.SetColumnWidth(16, 8); xls.SetColumnWidth(17, 8); xls.SetColumnWidth(18, 8); xls.SetColumnWidth(19, 8); xls.SetColumnWidth(20, 8); xls.SetColumnWidth(21, 8); xls.SetColumnWidth(22, 8); xls.SetColumnWidth(23, 8); xls.SetColumnWidth(24, 8); xls.SetColumnWidth(25, 6); xls.SetColumnWidth(26, 9); xls.SetColumnWidth(27, 6); xls.SetColumnWidth(28, 5); xls.SetColumnWidth(29, 6); xls.SetColumnWidth(30, 7); xls.SetColumnWidth(31, 10); xls.SetColumnWidth(32, 10); xls.SetColumnWidth(33, 44); xls.SetColumnWidth(34, 8); xls.SetColumnWidth(35, 9); xls.SetColumnWidth(36, 6); xls.SetColumnWidth(37, 8); xls.SetColumnWidth(38, 8); xls.SetColumnWidth(39, 6); xls.SetColumnWidth(40, 8); xls.SetColumnWidth(41, 8); xls.SetColumnWidth(42, 7); xls.SetColumnWidth(43, 5); xls.SetColumnWidth(46, 20); xls.SetCellMergedColumns(0, 1, 5); xls.SetCellMergedColumns(0, 2, 5); xls.SetCellMergedColumns(37, 1, 7); xls.SetCellMergedColumns(37, 2, 7); xls.SetCellMergedColumns(0, 3, 44); xls.SetCellMergedColumns(0, 4, 44); xls.SetCellText(0, 1, pMF->m_CompanyInfo.sc_pname, FMT_TEXT | FMT_CENTER, true); xls.SetCellText(0, 2, pMF->m_CompanyInfo.sc_name, FMT_TEXT | FMT_CENTER, true); xls.SetCellText(37, 1, _T("\x43\x1ED8NG H\xD2\x41 \x58\xC3 H\x1ED8I \x43H\x1EE6 NGH\x128\x41 VI\x1EC6T N\x41M"), FMT_TEXT | FMT_CENTER, true); xls.SetCellText(37, 2, _T("\x110\x1ED8\x43 L\x1EACP - T\x1EF0 \x44O - H\x1EA0NH PH\xDA\x43"), FMT_TEXT | FMT_CENTER, true); xls.SetCellText(0, 3, _T("\x44\x41NH S\xC1\x43H \x110\x1EC0 NGH\x1ECA TH\x41NH TO\xC1N \x43HI PH\xCD KH\xC1M \x43H\x1EEE\x41 \x42\x1EC6NH N\x1ED8I TR\xDA"), FMT_TEXT|FMT_CENTER, true, 18); TranslateString(_T("From Date"), tmpStr); szFromDateToDate.Format(_T("%s: %s"), tmpStr, CDateTime::Convert(m_szFromDate, yyyymmdd | hhmm, ddmmyyyy | hhmm)); TranslateString(_T("To Date"), tmpStr); szFromDateToDate.AppendFormat(_T(" %s: %s"), tmpStr, CDateTime::Convert(m_szToDate, yyyymmdd | hhmm, ddmmyyyy | hhmm)); xls.SetCellText(0, 4, szFromDateToDate, FMT_TEXT | FMT_CENTER, true, 12); int nRow = 6, nCol = 0; xls.SetCellText(0, nRow, _T("stt"), FMT_TEXT); xls.SetCellText(1, nRow, _T("hoten"), FMT_TEXT); xls.SetCellText(2, nRow, _T("namsinh"), FMT_TEXT); xls.SetCellText(3, nRow, _T("gioitinh"), FMT_TEXT); xls.SetCellText(4, nRow, _T("mathe"), FMT_TEXT); xls.SetCellText(5, nRow, _T("ma_dkbd"), FMT_TEXT); xls.SetCellText(6, nRow, _T("mabenh"), FMT_TEXT); xls.SetCellText(7, nRow, _T("ngay_vao"), FMT_TEXT); xls.SetCellText(8, nRow, _T("ngay_ra"), FMT_TEXT); xls.SetCellText(9, nRow, _T("ngay_dtr"), FMT_TEXT); xls.SetCellText(10, nRow, _T("t_tongchi"), FMT_TEXT); xls.SetCellText(11, nRow, _T("t_xn"), FMT_TEXT); xls.SetCellText(12, nRow, _T("t_cdha"), FMT_TEXT); xls.SetCellText(13, nRow, _T("t_thuoc"), FMT_TEXT); xls.SetCellText(14, nRow, _T("t_mau"), FMT_TEXT); xls.SetCellText(15, nRow, _T("t_pttt"), FMT_TEXT); xls.SetCellText(16, nRow, _T("t_vtytth"), FMT_TEXT); xls.SetCellText(17, nRow, _T("t_vtyttt"), FMT_TEXT); xls.SetCellText(18, nRow, _T("t_dvktc"), FMT_TEXT); xls.SetCellText(19, nRow, _T("t_ktg"), FMT_TEXT); xls.SetCellText(20, nRow, _T("t_kham"), FMT_TEXT); xls.SetCellText(21, nRow, _T("t_vchuyen"), FMT_TEXT); xls.SetCellText(22, nRow, _T("t_bnct"), FMT_TEXT); xls.SetCellText(23, nRow, _T("t_bhtt"), FMT_TEXT); xls.SetCellText(24, nRow, _T("t_ngoaids"), FMT_TEXT); xls.SetCellText(25, nRow, _T("lydo_vv"), FMT_TEXT); xls.SetCellText(26, nRow, _T("benhkhac"), FMT_TEXT); xls.SetCellText(27, nRow, _T("noikcb"), FMT_TEXT); xls.SetCellText(28, nRow, _T("khoa"), FMT_TEXT); xls.SetCellText(29, nRow, _T("nam_qt"), FMT_TEXT); xls.SetCellText(30, nRow, _T("thang_qt"), FMT_TEXT); xls.SetCellText(31, nRow, _T("gt_tu"), FMT_TEXT); xls.SetCellText(32, nRow, _T("gt_den"), FMT_TEXT); xls.SetCellText(33, nRow, _T("diachi"), FMT_TEXT); xls.SetCellText(34, nRow, _T("giamdinh"), FMT_TEXT); xls.SetCellText(35, nRow, _T("t_xuattoan"), FMT_TEXT); xls.SetCellText(36, nRow, _T("lydo_xt"), FMT_TEXT); xls.SetCellText(37, nRow, _T("t_datuyen"), FMT_TEXT); xls.SetCellText(38, nRow, _T("t_vuottran"), FMT_TEXT); xls.SetCellText(39, nRow, _T("loaikcb"), FMT_TEXT); xls.SetCellText(40, nRow, _T("noi_ttoan"), FMT_TEXT); xls.SetCellText(41, nRow, _T("sophieu"), FMT_TEXT); xls.SetCellText(42, nRow, _T("maicd10"), FMT_TEXT); xls.SetCellText(43, nRow, _T("tuyen"), FMT_TEXT); nCol = 44; if (m_bIsInsPurpose) { xls.SetCellText(nCol++, nRow, _T("nhom"), FMT_TEXT); xls.SetCellText(nCol++, nRow, _T("ngay_tt"), FMT_TEXT); xls.SetCellText(nCol++, nRow, _T("tt_vtyttt"), FMT_TEXT); } if (m_bShowDiff) xls.SetCellText(nCol++, nRow, _T("chenh"), FMT_TEXT); nCol = 0; int nIndex = 1, nTemp = 0; double nCost = 0; CellFormat xlsFormat(&xls); xlsFormat.SetCellStyle(FMT_INTEGER); CDate date; CString szNewLine, szOldLine; CString szNewGroup, szOldGroup; while (!rs.IsEOF()) { if (!m_bIsInsPurpose) rs.GetValue(_T("insline"), szNewLine); if (szOldLine != szNewLine && !szNewLine.IsEmpty()) { nRow++; xls.SetCellMergedColumns(nCol + 1, nRow, 9); rs.GetValue(_T("linename"), tmpStr); xls.SetCellText(nCol, nRow, tmpStr, FMT_TEXT, true); szTemp.Format(_T("%s"), pMF->GetSelectionString(_T("hms_insline"), szNewLine)); xls.SetCellText(nCol + 1, nRow, szTemp, FMT_TEXT, true); szOldLine = szNewLine; szOldGroup.Empty(); } if (!m_bIsInsPurpose) rs.GetValue(_T("insgroup"), szNewGroup); if (szOldGroup != szNewGroup && !szNewGroup.IsEmpty()) { nRow++; xls.SetCellText(nCol, nRow, szNewGroup, FMT_TEXT, true); xls.SetCellMergedColumns(nCol + 1, nRow, 9); tmpStr.Format(_T("%s"), pMF->GetSelectionString(_T("hms_insurance_group"), szNewGroup)); xls.SetCellText(nCol + 1, nRow, tmpStr, FMT_TEXT, true); szOldGroup = szNewGroup; nIndex = 1; } nRow++; tmpStr.Format(_T("%d"), nIndex++); xls.SetCellText(nCol, nRow, tmpStr, FMT_INTEGER); rs.GetValue(_T("pname"), tmpStr); xls.SetCellText(nCol + 1, nRow, tmpStr, FMT_TEXT); rs.GetValue(_T("sex"), tmpStr); if (tmpStr == _T("F")) { rs.GetValue(_T("fbirthyear"), tmpStr); xls.SetCellText(nCol + 2, nRow, tmpStr, FMT_INTEGER); xls.WriteNumber(nRow, nCol + 3, 2, &xlsFormat); } else { rs.GetValue(_T("mbirthyear"), tmpStr); xls.SetCellText(nCol + 2, nRow, tmpStr, FMT_INTEGER); xls.WriteNumber(nRow, nCol + 3, 1, &xlsFormat); } rs.GetValue(_T("cardno"), tmpStr); xls.SetCellText(nCol + 4, nRow, tmpStr, FMT_TEXT); rs.GetValue(_T("regplace"), tmpStr); xls.SetCellText(nCol + 5, nRow, tmpStr, FMT_TEXT); rs.GetValue(_T("icd10"), tmpStr); xls.SetCellText(nCol + 6, nRow, tmpStr, FMT_TEXT); rs.GetValue(_T("admitdate"), tmpStr); //szDate = CDate::Convert(tmpStr, yyyymmdd, ddmmyyyy); xls.SetCellText(nCol + 7, nRow, tmpStr, FMT_TEXT); rs.GetValue(_T("dischargedate"), tmpStr); //szDate = CDate::Convert(tmpStr, yyyymmdd, ddmmyyyy); xls.SetCellText(nCol + 8, nRow, tmpStr, FMT_TEXT); rs.GetValue(_T("totaltreat"), tmpStr); xls.SetCellText(nCol + 9, nRow, tmpStr, FMT_INTEGER); rs.GetValue(_T("cost"), nCost); xls.WriteNumber(nRow, nCol + 10, nCost, &xlsFormat); rs.GetValue(_T("testfee"), nCost); xls.WriteNumber(nRow, nCol + 11, nCost, &xlsFormat); rs.GetValue(_T("pacsfee"), nCost); xls.WriteNumber(nRow, nCol + 12, nCost, &xlsFormat); rs.GetValue(_T("drugfee"), nCost); xls.WriteNumber(nRow, nCol + 13, nCost, &xlsFormat); rs.GetValue(_T("bloodfee"), nCost); xls.WriteNumber(nRow, nCol + 14, nCost, &xlsFormat); rs.GetValue(_T("normtechfee"), nCost); xls.WriteNumber(nRow, nCol + 15, nCost, &xlsFormat); rs.GetValue(_T("materialfee"), nCost); xls.WriteNumber(nRow, nCol + 16, nCost, &xlsFormat); rs.GetValue(_T("replace_materialfee"), nCost); xls.WriteNumber(nRow, nCol + 17, nCost, &xlsFormat); rs.GetValue(_T("hitechfee"), nCost); xls.WriteNumber(nRow, nCol + 18, nCost, &xlsFormat); rs.GetValue(_T("drugfeek"), nCost); xls.WriteNumber(nRow, nCol + 19, nCost, &xlsFormat); rs.GetValue(_T("bedfee"), nCost); xls.WriteNumber(nRow, nCol + 20, nCost, &xlsFormat); /*rs.GetValue(_T("transportfee"), nCost); xls.WriteNumber(nRow, nCol + 19, nCost, &xlsFormat);*/ rs.GetValue(_T("patpaid"), nCost); xls.WriteNumber(nRow, nCol + 22, nCost, &xlsFormat); rs.GetValue(_T("inspaid"), nCost); xls.WriteNumber(nRow, nCol + 23, nCost, &xlsFormat); /*rs.GetValue(_T("ratefee"), nCost); xls.WriteNumber(nRow, nCol + 23, nCost, &xlsFormat);*/ rs.GetValue(_T("emergency"), tmpStr); if (tmpStr == _T("Y")) nTemp = 2; else { rs.GetValue(_T("hdline"), tmpStr); if (tmpStr == _T("1")) { nTemp = 0; } else { nTemp = 1; } } xls.WriteNumber(nRow, nCol + 25, nTemp, &xlsFormat); rs.GetValue(_T("reldisease"), tmpStr); xls.SetCellText(nCol + 26, nRow, tmpStr, FMT_TEXT); tmpStr.Format(_T("%s"), pMF->m_CompanyInfo.sc_id); xls.SetCellText(nCol + 27, nRow, tmpStr, FMT_TEXT); rs.GetValue(_T("deptid"), tmpStr); xls.SetCellText(nCol + 28, nRow, tmpStr, FMT_TEXT); nCost = ToDouble(szYear); xls.WriteNumber(nRow, nCol + 29, nCost, &xlsFormat); nCost = ToDouble(szMonth); xls.WriteNumber(nRow, nCol + 30, nCost, &xlsFormat); rs.GetValue(_T("regdate"), tmpStr); szDate = CDate::Convert(tmpStr, yyyymmdd, ddmmyyyy); xls.SetCellText(nCol + 31, nRow, szDate, FMT_DATE); rs.GetValue(_T("expdate"), tmpStr); szDate = CDate::Convert(tmpStr, yyyymmdd, ddmmyyyy); xls.SetCellText(nCol + 32, nRow, szDate, FMT_DATE); rs.GetValue(_T("address"), tmpStr); xls.SetCellText(nCol + 33, nRow, tmpStr, FMT_TEXT); xls.WriteNumber(nRow, nCol + 35, 0, &xlsFormat); xls.WriteNumber(nRow, nCol + 37, 0, &xlsFormat); xls.WriteNumber(nRow, nCol + 38, 0, &xlsFormat); xls.SetCellText(nCol + 39, nRow, _T("NOI"), FMT_TEXT); xls.SetCellText(nCol + 40, nRow, _T("\x43SK\x43\x42"), FMT_TEXT); rs.GetValue(_T("docno"), tmpStr); xls.SetCellText(nCol + 41, nRow, tmpStr, FMT_INTEGER); rs.GetValue(_T("hcr_mainicd"), tmpStr); xls.SetCellText(nCol + 42, nRow, tmpStr, FMT_TEXT); rs.GetValue(_T("insline"), tmpStr); xls.SetCellText(nCol + 43, nRow, tmpStr, FMT_INTEGER); //xls.SetCellText(nCol + 40, nRow, _T("\x30\x31"), FMT_TEXT); nIncrement = 0; if (m_bIsInsPurpose) { xls.SetCellText(nCol +44 + nIncrement, nRow, rs.GetValue(_T("insgroup")), FMT_TEXT); nIncrement++; xls.SetCellText(nCol +45 + nIncrement, nRow, rs.GetValue(_T("invoice_date")), FMT_TEXT); nIncrement++; xls.SetCellText(nCol +46 + nIncrement, nRow, rs.GetValue(_T("ref_materialfee")), FMT_NUMBER1); nIncrement++; } if (m_bShowDiff) xls.SetCellText(nCol +44 + nIncrement, nRow, rs.GetValue(_T("diffpaid")), FMT_NUMBER1); rs.MoveNext(); } xls.Save(_T("Exports\\ChiphikhambenhBHYT_80a.xls")); EndWaitCursor(); } void CFMOutpatientInsuranceCost80A::OnExportForInsSelect(){ m_bIsInsPurpose = true; OnExportSelect(); m_bIsInsPurpose = false; } void CFMOutpatientInsuranceCost80A::OnCardListDblClick(){ } void CFMOutpatientInsuranceCost80A::OnCardListSelectChange(int nOldItem, int nNewItem){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); } int CFMOutpatientInsuranceCost80A::OnCardListDeleteItem(){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); return 0; } long CFMOutpatientInsuranceCost80A::OnCardListLoadData(){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); CRecord rs(&pMF->m_db); CString szSQL; CString tmpStr, szTemp; m_wndCardList.BeginLoad(); int nCount = 0; szSQL.Format(_T(" select hig_note as itemid, hig_name as itemname") \ _T(" from hms_insurance_group") \ _T(" order by hig_group, hig_idx")); nCount = rs.ExecSQL(szSQL); while (!rs.IsEOF()) { m_wndCardList.AddItems( rs.GetValue(_T("itemid")), rs.GetValue(_T("itemname")), NULL); rs.MoveNext(); } m_wndCardList.EndLoad(); return nCount; } void CFMOutpatientInsuranceCost80A::OnDeptListDblClick(){ } void CFMOutpatientInsuranceCost80A::OnDeptListSelectChange(int nOldItem, int nNewItem){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); } int CFMOutpatientInsuranceCost80A::OnDeptListDeleteItem(){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); return 0; } long CFMOutpatientInsuranceCost80A::OnDeptListLoadData(){ CHMSMainFrame *pMF = (CHMSMainFrame*) AfxGetMainWnd(); CRecord rs(&pMF->m_db); CString szSQL; m_wndDeptList.BeginLoad(); int nCount = 0; szSQL.Format(_T("SELECT sd_id as id, sd_name as name ") \ _T("FROM sys_dept ") \ _T("WHERE 1=1 AND sd_type='DT' ORDER BY id ")); nCount = rs.ExecSQL(szSQL); while(!rs.IsEOF()){ m_wndDeptList.AddItems( rs.GetValue(_T("id")), rs.GetValue(_T("name")), NULL); rs.MoveNext(); } m_wndDeptList.EndLoad(); return nCount; } int CFMOutpatientInsuranceCost80A::OnCardListCheckAll(){ for (int i = 0; i < m_wndCardList.GetItemCount(); i++) { if (!m_wndCardList.GetCheck(i)) { m_wndCardList.SetCheck(i, TRUE); } } return 0; } int CFMOutpatientInsuranceCost80A::OnCardListUnCheckAll(){ for (int i = 0; i < m_wndCardList.GetItemCount(); i++) { if (m_wndCardList.GetCheck(i)) { m_wndCardList.SetCheck(i, FALSE); } } return 0; } int CFMOutpatientInsuranceCost80A::OnDeptListCheckAll(){ for (int i = 0; i < m_wndDeptList.GetItemCount(); i++) { if (!m_wndDeptList.GetCheck(i)) { m_wndDeptList.SetCheck(i, TRUE); } } return 0; } int CFMOutpatientInsuranceCost80A::OnDeptListUnCheckAll(){ for (int i = 0; i < m_wndDeptList.GetItemCount(); i++) { if (m_wndDeptList.GetCheck(i)) { m_wndDeptList.SetCheck(i, FALSE); } } return 0; } CString CFMOutpatientInsuranceCost80A::GetQueryString(){ CHMSMainFrame *pMF = (CHMSMainFrame*)AfxGetMainWnd(); CRecord rs(&pMF->m_db); CString szSQL, szWhere, szSubWhere, szSubSQL, szOrderBy, szTable, szGroup; CString szDepts, szCards, szMaterialID; CString tmpStr, szTemp; int nIndex = 0; szWhere.Empty(); szSubWhere.Empty(); szDepts.Empty(); szCards.Empty(); if (!m_szClerkKey.IsEmpty()) szWhere.AppendFormat(_T(" AND fi.hfe_staff='%s' "), m_szClerkKey); for (int i = 0; i < m_wndDeptList.GetItemCount(); i++) { if (m_wndDeptList.GetCheck(i)) { if (!szDepts.IsEmpty()) szDepts += _T(","); szDepts.AppendFormat(_T("'%s'"), m_wndDeptList.GetItemText(i, 0)); } } if (!szDepts.IsEmpty()) { szWhere.AppendFormat(_T(" AND fi.hfe_deptid IN(%s) "), szDepts); } for (int i = 0; i < m_wndCardList.GetItemCount(); i++) { if (m_wndCardList.GetCheck(i)) { tmpStr = m_wndCardList.GetItemText(i, 0); nIndex = 0; if (tmpStr.Find(_T(',')) > -1) { for (int i = 0; i < tmpStr.GetLength(); i++) { if (tmpStr[i] == _T(',')) { szTemp = tmpStr.Mid(nIndex, i - nIndex); nIndex = i + 1; if (!szCards.IsEmpty()) szCards += _T(","); szCards.AppendFormat(_T("'%s'"), szTemp); } } szTemp = tmpStr.Right(tmpStr.GetLength() - nIndex); } else { szTemp = tmpStr; } if (!szCards.IsEmpty()) szCards += _T(","); szCards.AppendFormat(_T("'%s'"), szTemp); } } if (!szCards.IsEmpty()) { szSubWhere.AppendFormat(_T(" AND substr(hd_cardno,1,2) IN(%s) "), szCards); //MessageBox(szCards); } szSQL.Format(_T("SELECT hsd_id id FROM hms_surgery_drugtype WHERE hsd_type = 'M'")); rs.ExecSQL(szSQL); while (!rs.IsEOF()) { if (!szMaterialID.IsEmpty()) szMaterialID += _T(", "); szMaterialID.AppendFormat(_T("'%s'"),rs.GetValue(_T("id"))); rs.MoveNext(); } if (!szMaterialID.IsEmpty()) szMaterialID += _T(", "); szMaterialID += _T("'A1500', 'A1600'"); szOrderBy = _T(" insline, insgroup, hdline, admitdate, docno, cardno"); if (m_bIsInsPurpose) szOrderBy = _T(" to_date(dischargedate, 'dd/mm/yyyy') , deptid, hp_surname, hp_midname, hp_firstname"); if (m_bByDischargedDate) szWhere.AppendFormat(_T(" AND htr_dischargedate BETWEEN cast_string2timestamp('%s') AND cast_string2timestamp('%s') ") \ _T(" AND htrf_acceptedfee IN ('P', 'Y')"), m_szFromDate, m_szToDate); else if (m_bUnapproved) szWhere.AppendFormat(_T(" AND htr_dischargedate BETWEEN cast_string2timestamp('%s') AND cast_string2timestamp('%s') ") \ _T(" AND NVL(htrf_acceptedfee, 'N') = 'N'"), m_szFromDate, m_szToDate); else szWhere.AppendFormat(_T(" AND fi.hfe_date BETWEEN cast_string2timestamp('%s') AND cast_string2timestamp('%s') ") \ _T(" AND fi.hfe_status = 'P'"), m_szFromDate, m_szToDate); szWhere.AppendFormat(_T(" AND NVL(htr_outpatient, 'X') = 'Y'")); szGroup = _T("D0000"); if (m_bOnlyCommander) szSubWhere.AppendFormat(_T(" AND hd_rank IN (15, 16, 17, 18, 21, 22, 23, 24)")); if (m_bOnlyCommander || (szCards == _T("'QN'"))) m_bShowDiff = true; else m_bShowDiff = false; szSubSQL.Format(_T(" UNION ALL SELECT fi.hfe_deptid as deptid,") \ _T(" fi.hfe_class,") \ _T(" fe.hfe_docno as docno,") \ _T(" fe.hfe_invoiceno as invoiceno,") \ _T(" fe.hfe_group AS groupid,") \ _T(" hcr_reldisease, htr_admitdate, htr_dischargedate, ") \ _T(" hcr_sumtreat, hcr_mainicd, hcr_maindisease, fi.hfe_date invoice_date,") \ _T(" 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,") \ _T(" CASE WHEN fe.hfe_feegroup NOT IN ('HITECH_L', 'OPT_L') ") \ _T(" THEN DECODE('P', fe.hfe_status, fe.hfe_patpaid, fe.hfe_patdebt)") \ _T(" ELSE 0 END AS diffpaid") \ _T(" FROM hms_clinical_record ") \ _T(" LEFT JOIN hms_treatment_record ON (hcr_docno = htr_docno)") \ _T(" LEFT JOIN hms_fee_invoice fi ON (hcr_docno = fi.hfe_docno AND htr_treattime = fi.hfe_treattime)") \ _T(" LEFT JOIN hms_fee_view fe ON(fe.hfe_invoiceno=fi.hfe_invoiceno AND fe.hfe_docno=fi.hfe_docno)") \ _T(" LEFT JOIN hms_fee_list ON (fe.hfe_itemid = hfl_feeid)") \ _T(" WHERE fi.hfe_class IN('A', 'I') AND fe.hfe_discount = 0 AND fe.hfe_category <> 'Y' AND htr_status='T'") \ _T(" AND fe.hfe_type <> 'V' ") \ _T(" %s") \ _T(" UNION ALL") \ _T(" SELECT fi.hfe_deptid as deptid,") \ _T(" fi.hfe_class,") \ _T(" fe.hfe_docno as docno,") \ _T(" fe.hfe_invoiceno as invoiceno,") \ _T(" fe.hfe_group AS groupid,") \ _T(" hcr_reldisease, htr_admitdate, htr_dischargedate, ") \ _T(" hcr_sumtreat, hcr_mainicd, hcr_maindisease, fi.hfe_date invoice_date,") \ _T(" 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,") \ _T(" CASE WHEN fe.hfe_feegroup IN ('HITECH_L', 'OPT_L') ") \ _T(" THEN DECODE('P', fe.hfe_status, fe.hfe_patpaid, fe.hfe_patdebt)") \ _T(" ELSE 0 END AS diffpaid") \ _T(" FROM hms_clinical_record ") \ _T(" LEFT JOIN hms_treatment_record ON (hcr_docno = htr_docno)") \ _T(" LEFT JOIN hms_fee_invoice fi ON (hcr_docno = fi.hfe_docno AND htr_treattime = fi.hfe_treattime)") \ _T(" LEFT JOIN hms_fee_view fe ON(fe.hfe_invoiceno=fi.hfe_invoiceno AND fe.hfe_docno=fi.hfe_docno)") \ _T(" WHERE fi.hfe_class IN('A', 'I') AND fe.hfe_discount = 0 AND fe.hfe_category <> 'Y' AND htr_status='T'") \ _T(" AND fe.hfe_type = 'V' ") \ _T(" %s"), szWhere, szWhere); szSQL.Format(_T(" SELECT hd_docno AS docno,") \ _T(" max(invoiceno) AS invoiceno,") \ _T(" trim(hp_surname||' '||hp_midname||' '||hp_firstname) AS pname,") \ _T(" case when hp_sex='M' then extract(year from hp_birthdate) else 0 end AS mbirthyear,") \ _T(" case when hp_sex='F' then extract(year from hp_birthdate) else 0 end AS fbirthyear,") \ _T(" hp_sex AS sex,") \ _T(" hms_getaddress(hp_provid, hp_distid, hp_villid) as address,") \ _T(" hcr_reldisease as reldisease,") \ _T(" CASE WHEN LENGTH(hd_cardno) > 15 THEN SUBSTR(hd_cardno,1,15) ELSE hd_cardno END AS cardno,") \ _T(" hd_insregdate AS regdate,") \ _T(" hd_Insexpdate AS expdate,") \ _T(" CASE WHEN hd_insline='Y' THEN 1 ELSE 0 END AS hdline,") \ _T(" hc_regcode AS regplace,") \ _T(" hc_line AS insline,") \ _T(" (SELECT distinct ss_default FROM sys_sel WHERE ss_id='hms_insline' ") \ _T(" AND ss_code=CAST(hc_line AS NVARCHAR2(15))) AS linename,") \ _T(" (SELECT distinct hig_group FROM hms_insurance_group WHERE hig_idx= hc_groupid) AS insgroup,") \ _T(" TO_CHAR(htr_admitdate, 'DD/MM/YYYY') AS admitdate,") \ _T(" TO_CHAR(htr_dischargedate, 'DD/MM/YYYY') AS dischargedate,") \ _T(" hcr_sumtreat AS totaltreat,") \ _T(" hcr_mainicd,") \ _T(" hcr_maindisease AS icd10,") \ _T(" case when hd_admitdept='C1.3' then 'Y' else 'N' end AS emergency,") \ _T(" lower(deptid) AS deptid,") \ _T(" TO_CHAR(invoice_date, 'DD/MM/YYYY') invoice_date,") \ _T(" round(SUM(drugfee)) AS drugfee,") \ _T(" round(SUM(drugfeek)) AS drugfeek,") \ _T(" round(SUM(bloodfee)) AS bloodfee,") \ _T(" round(SUM(testfee)) AS testfee,") \ _T(" round(SUM(pacsfee)) AS pacsfee,") \ _T(" round(SUM(normtechfee)) AS normtechfee,") \ _T(" round(SUM(hitechfee)) AS hitechfee,") \ _T(" round(SUM(materialfee)) AS materialfee,") \ _T(" round(SUM(replace_materialfee)) AS replace_materialfee,") \ _T(" round(SUM(ref_materialfee)) AS ref_materialfee,") \ _T(" round(SUM(bedfee)) AS bedfee,") \ _T(" round(SUM(transportfee)) AS transportfee,") \ _T(" round(SUM(inspaid)) AS cost,") \ _T(" round(SUM(otherfee)) AS otherfee,") \ _T(" round(SUM(discount)) AS inspaid,") \ _T(" round(SUM(inspaid-discount)) AS patpaid,") \ _T(" round(SUM(diffpaid)) AS diffpaid") \ _T(" FROM") \ _T(" (") \ _T(" SELECT fi.hfe_deptid as deptid,") \ _T(" fi.hfe_class,") \ _T(" fe.hfe_docno as docno,") \ _T(" fe.hfe_invoiceno as invoiceno,") \ _T(" fe.hfe_group AS groupid,") \ _T(" hcr_reldisease, htr_admitdate, htr_dischargedate, ") \ _T(" hcr_sumtreat, hcr_mainicd, hcr_maindisease, fi.hfe_date invoice_date,") \ _T(" CASE WHEN SUBSTR(fe.hfe_group,1,2) IN('A1','A6') AND fe.hfe_group NOT IN ('A1400', 'A1500', 'A1600') THEN fe.hfe_inspaid ELSE 0 END AS drugfee,") \ _T(" CASE WHEN fe.hfe_group='A1400' THEN fe.hfe_inspaid ELSE 0 END AS drugfeek,") \ _T(" CASE WHEN NVL(hfl_bloodfee, 'X') = 'Y' THEN fe.hfe_inspaid ELSE 0 END AS bloodfee,") \ _T(" CASE WHEN SUBSTR(fe.hfe_group, 1, 2)='B1' AND NVL(hfl_bloodfee, 'X') <> 'Y' ") \ _T(" AND fe.hfe_hitech ='N' THEN fe.hfe_inspaid ELSE 0 END AS testfee,") \ _T(" CASE WHEN SUBSTR(fe.hfe_group, 1, 2) IN('B2','B3') AND fe.hfe_hitech ='N' THEN fe.hfe_inspaid ELSE 0 END AS pacsfee,") \ _T(" CASE WHEN SUBSTR(fe.hfe_group, 1, 2) IN('B4','B5') AND fe.hfe_hitech ='N' THEN fe.hfe_inspaid ELSE 0 END AS normtechfee,") \ _T(" CASE WHEN fe.hfe_hitech='Y' THEN fe.hfe_inspaid ELSE 0 END AS hitechfee,") \ _T(" CASE WHEN fe.hfe_group IN (%s) AND fe.hfe_feegroup NOT IN ('OPT_L', 'OPT') THEN fe.hfe_inspaid ELSE 0 END AS materialfee,") \ _T(" CASE WHEN fe.hfe_group IN (%s) AND fe.hfe_feegroup IN ('OPT_L', 'OPT') THEN fe.hfe_inspaid ELSE 0 END AS replace_materialfee,") \ _T(" CASE WHEN fe.hfe_group IN (%s) AND fe.hfe_feegroup IN ('OPT_L', 'OPT') THEN fe.hfe_cost ELSE 0 END AS ref_materialfee,") \ _T(" CASE WHEN fe.hfe_group='%s' THEN fe.hfe_inspaid ELSE 0 END AS bedfee,") \ _T(" CASE WHEN fe.hfe_group='E0000' THEN fe.hfe_inspaid ELSE 0 END AS transportfee,") \ _T(" CASE WHEN fe.hfe_group='F0000' THEN fe.hfe_inspaid ELSE 0 END AS otherfee,") \ _T(" fe.hfe_cost AS cost,") \ _T(" CASE WHEN fe.hfe_feegroup NOT IN ('HITECH_L', 'OPT_L') THEN fe.hfe_inspaid ELSE 0 END AS inspaid,") \ _T(" CASE WHEN fe.hfe_feegroup NOT IN ('HITECH_L', 'OPT_L') THEN fe.hfe_discount ELSE 0 END AS discount,") \ _T(" fe.hfe_patpaid AS patpaid,") \ _T(" CASE WHEN fe.hfe_feegroup NOT IN ('HITECH_L', 'OPT_L') THEN fe.hfe_diffpaid ELSE 0 END AS diffpaid") \ _T(" FROM hms_clinical_record ") \ _T(" LEFT JOIN hms_treatment_record ON (hcr_docno = htr_docno)") \ _T(" LEFT JOIN hms_fee_invoice fi ON (hcr_docno = fi.hfe_docno AND htr_treattime = fi.hfe_treattime)") \ _T(" LEFT JOIN hms_fee_view fe ON(fe.hfe_invoiceno=fi.hfe_invoiceno AND fe.hfe_docno=fi.hfe_docno)") \ _T(" LEFT JOIN hms_fee_list ON (fe.hfe_itemid = hfl_feeid)") \ _T(" WHERE fi.hfe_class IN('A', 'I') AND fe.hfe_discount > 0 AND fe.hfe_category <> 'Y' AND htr_status='T'") \ _T(" AND fe.hfe_type <> 'V' ") \ _T(" %s") \ _T(" UNION ALL") \ _T(" SELECT fi.hfe_deptid as deptid,") \ _T(" fi.hfe_class,") \ _T(" fe.hfe_docno as docno,") \ _T(" fe.hfe_invoiceno as invoiceno,") \ _T(" fe.hfe_group AS groupid,") \ _T(" hcr_reldisease, htr_admitdate, htr_dischargedate, ") \ _T(" hcr_sumtreat, hcr_mainicd, hcr_maindisease, fi.hfe_date invoice_date,") \ _T(" 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,") \ _T(" fe.hfe_cost AS cost,") \ _T(" CASE WHEN fe.hfe_feegroup IN ('HITECH_L', 'OPT_L') THEN fe.hfe_inspaid ELSE 0 END AS inspaid,") \ _T(" CASE WHEN fe.hfe_feegroup IN ('HITECH_L', 'OPT_L') THEN fe.hfe_discount ELSE 0 END AS discount,") \ _T(" fe.hfe_patpaid AS patpaid,") \ _T(" CASE WHEN fe.hfe_feegroup IN ('HITECH_L', 'OPT_L') THEN fe.hfe_diffpaid ELSE 0 END AS diffpaid") \ _T(" FROM hms_clinical_record ") \ _T(" LEFT JOIN hms_treatment_record ON (hcr_docno = htr_docno)") \ _T(" LEFT JOIN hms_fee_invoice fi ON (hcr_docno = fi.hfe_docno AND htr_treattime = fi.hfe_treattime)") \ _T(" LEFT JOIN hms_fee_view fe ON(fe.hfe_invoiceno=fi.hfe_invoiceno AND fe.hfe_docno=fi.hfe_docno)") \ _T(" WHERE fi.hfe_class IN('A', 'I') AND fe.hfe_discount > 0 AND fe.hfe_category <> 'Y' AND htr_status='T'") \ _T(" AND fe.hfe_type = 'V' ") \ _T(" %s") \ _T(" %s) tbl") \ _T(" LEFT JOIN hms_doc ON(docno=hd_docno)") \ _T(" LEFT JOIN hms_patient ON(hd_patientno=hp_patientno)") \ _T(" LEFT JOIN hms_card ON(hc_patientno=hp_patientno AND hc_idx=hd_cardidx)") \ _T(" LEFT JOIN hms_object ON(ho_id=hd_object)") \ _T(" LEFT JOIN hms_icd ON(hcr_mainicd=hi_icd)") \ _T(" WHERE ho_type IN('I','C') AND LENGTH(hd_cardno) > 1 ") \ _T(" %s") \ _T(" GROUP BY hd_docno, hp_surname, hp_midname, hp_firstname, hp_birthdate, hp_sex, hd_cardno, hd_insline, ") \ _T(" hc_groupid, hc_line, hd_insline, hc_regcode, hcr_mainicd, hcr_maindisease, htr_admitdate, htr_dischargedate, ") \ _T(" hcr_sumtreat, hp_provid, hp_distid, hp_villid, hd_insregdate, hd_Insexpdate, hcr_reldisease, hi_name, ") \ _T(" hd_emergency, deptid, hd_admitdept, invoice_date") \ _T(" HAVING SUM(cost) > 0") \ _T(" ORDER BY ") \ _T(" %s"), szMaterialID, szMaterialID, szMaterialID, szGroup, szWhere, szWhere, szSubSQL, szSubWhere, szOrderBy); _fmsg(_T("%s"), szSQL); return szSQL; }
9914af0a3d4e2df50ee71e29feb93c7c998add8d
a051be3b44d59ad841acdc8c2d641d7027694a5b
/src/util/file/mapped_file.cpp
019fd5d371b2d318192b8060e81f9da4c767ecc4
[]
no_license
chpatton013/crash
66663b3f4284c6f44a1de9063a47d6be45f29955
9825e0a90b1aefd26300a1cba5adb8c63f670a07
refs/heads/master
2021-01-22T23:26:16.311322
2015-06-26T17:16:28
2015-06-26T17:16:28
23,650,959
0
0
null
null
null
null
UTF-8
C++
false
false
2,866
cpp
mapped_file.cpp
#include <crash/util/file/mapped_file.hpp> #include <fcntl.h> #include <unistd.h> #include <sys/mman.h> #include <sys/stat.h> #include <algorithm> #include <cmath> #include <boost/filesystem.hpp> #include <boost/system/error_code.hpp> using namespace crash::util; MappedFile::MappedFile(const std::string& path) : File(path) { struct stat fileStat; if (::fstat(this->_handle, &fileStat) == -1) { this->_valid = false; return; } std::size_t size = MappedFile::bufferCeil(fileStat.st_size); ::ftruncate(this->_handle, size); void* data = ::mmap(nullptr, size, MappedFile::_protFlags, MappedFile::_mapFlags, this->_handle, 0); if (data == MAP_FAILED) { this->_valid = false; return; } this->_size = size; this->_data = data; this->_adviseMethod = MADV_NORMAL; this->_valid = true; } /* virtual */ MappedFile::~MappedFile() { this->flush(); ::munmap(this->_data, this->_size); } std::size_t MappedFile::size() const { return this->_size; } int MappedFile::adviseMethod() const { return this->_adviseMethod; } void* MappedFile::data() const { return this->_data; } std::size_t MappedFile::resize(std::size_t size) { if (size <= this->_size) { return this->_size; } size = MappedFile::bufferCeil(size); ::munmap(this->_data, this->_size); ::ftruncate(this->_handle, size); this->_data = ::mmap(nullptr, size, MappedFile::_protFlags, MappedFile::_mapFlags, this->_handle, 0); if (this->_data == MAP_FAILED) { this->_valid = false; return 0; } return this->_size = size; } bool MappedFile::advise(int method) { bool successful = ::madvise(this->_data, this->_size, method) == 0; if (successful) { this->_adviseMethod = method; } return successful; } bool MappedFile::flush() { return ::msync(this->_data, this->_size, MS_SYNC) == 0; } /* static */ boost::optional< std::shared_ptr< MappedFile > > MappedFile::New(const std::string& fileName) { std::lock_guard<std::mutex> lock(MappedFile::_instanceMutex); return File::New< MappedFile >(fileName, MappedFile::_instances); } /* static */ bool MappedFile::Delete(std::shared_ptr< MappedFile > file) { std::lock_guard<std::mutex> lock(MappedFile::_instanceMutex); return File::Delete< MappedFile >(file, MappedFile::_instances); } /* static */ std::size_t MappedFile::bufferCeil(std::size_t size) { static const std::size_t bufferSize = ::getpagesize(); int buffers = std::max((int)std::ceil(size / (float)bufferSize), 1); return buffers * bufferSize; } /* static */ std::unordered_map< std::string, std::shared_ptr< MappedFile > > MappedFile::_instances; /* static */ std::mutex MappedFile::_instanceMutex; /* static */ const int MappedFile::_protFlags = PROT_READ | PROT_WRITE; /* static */ const int MappedFile::_mapFlags = MAP_SHARED;
6675a735502668ed07d221c2b8269c01906479f6
7d56928145d415ff3e50bd14e66cbc44906201bc
/ScareBearPi/ScareBearPi/WebServer.cpp
e0f144d8a2df97c043cd4ab89673335bdad5c95d
[]
no_license
mrmarss/ScareBear
0b87e1bcb00db786802fe812d7aaa2464f7d2b2c
054402fd326133cf60d0aa1e340cee3175a8c0cd
refs/heads/master
2021-01-10T06:11:30.588622
2015-11-01T18:48:09
2015-11-01T18:48:09
45,269,176
0
0
null
null
null
null
UTF-8
C++
false
false
14,438
cpp
WebServer.cpp
// // WebServer.cpp // ScareBearPi // // Created by Doug on 11/1/15. // Copyright (c) 2015 Doug Roeper. All rights reserved. // #include "WebServer.h" #include "WebSession.h" #include "WebPage.h" #include <iostream> /** * Invalid method page. */ #define METHOD_ERROR "<html><head><title>Illegal request</title></head><body>Go away.</body></html>" /** * Name of our cookie. */ #define COOKIE_NAME "session" /** * Data kept per request. */ struct Request { /** * Associated session. */ WebSession *session; /** * Post processor handling form data (IF this is * a POST request). */ struct MHD_PostProcessor *pp; /** * URL to serve in response to this POST (if this request * was a 'POST') */ const char *post_url; }; /** * Return the session handle for this connection, or * create one if this is a new user. */ WebSession * WebServer::getSession (struct MHD_Connection *connection) { WebSession *result = NULL; const char *cookie; cookie = MHD_lookup_connection_value (connection, MHD_COOKIE_KIND, COOKIE_NAME); if (cookie != NULL) { for (auto it = _sessions.begin(); it != _sessions.end(); it++) { WebSession *current = *it; if (strcmp (cookie, current->getSID().c_str())) { result = current; break; } } } if (result == NULL) { /* not a super-secure way to generate a random session ID, but should do for a simple example... */ std::string sid; sid += (unsigned int) rand (); sid += (unsigned int) rand (); sid += (unsigned int) rand (); sid += (unsigned int) rand (); WebSession *newSession = new WebSession(sid, 1, time(NULL)); _sessions.push_back(newSession); result = newSession; } return result; } /** * Iterator over key-value pairs where the value * maybe made available in increments and/or may * not be zero-terminated. Used for processing * POST data. * * @param cls user-specified closure * @param kind type of the value * @param key 0-terminated key for the value * @param filename name of the uploaded file, NULL if not known * @param content_type mime-type of the data, NULL if not known * @param transfer_encoding encoding of the data, NULL if not known * @param data pointer to size bytes of data at the * specified offset * @param off offset of data in the overall value * @param size number of bytes in data available * @return MHD_YES to continue iterating, * MHD_NO to abort the iteration */ static int post_iterator (void *cls, enum MHD_ValueKind kind, const char *key, const char *filename, const char *content_type, const char *transfer_encoding, const char *data, uint64_t off, size_t size) { struct Request *request = (struct Request *)cls; WebSession *session = request->session; if (0 == strcmp ("DONE", key)) { fprintf (stdout, "Session `%s' submitted something", session->getSID().c_str()); return MHD_YES; } /* if (0 == strcmp ("v1", key)) { if (size + off >= sizeof(session->value_1)) size = sizeof (session->value_1) - off - 1; memcpy (&session->value_1[off], data, size); session->value_1[size+off] = '\0'; return MHD_YES; } */ fprintf (stderr, "Unsupported form value `%s'\n", key); return MHD_YES; } /** * Callback called upon completion of a request. * Decrements session reference counter. * * @param cls not used * @param connection connection that completed * @param con_cls session handle * @param toe status code */ static void request_completed_callback (void *cls, struct MHD_Connection *connection, void **con_cls, enum MHD_RequestTerminationCode toe) { struct Request *request = (struct Request *)*con_cls; if (NULL == request) return; if (NULL != request->session) request->session->rc--; if (NULL != request->pp) MHD_destroy_post_processor (request->pp); free (request); } /** * Clean up handles of sessions that have been idle for * too long. */ void WebServer::expireSessions() { /* struct Session *pos; struct Session *prev; struct Session *next; time_t now; now = time (NULL); prev = NULL; pos = sessions; while (NULL != pos) { next = pos->next; if (now - pos->start > 60 * 60) { // expire sessions after 1h if (NULL == prev) sessions = pos->next; else prev->next = next; free (pos); } else prev = pos; pos = next; } */ std::cout << "Need to expire sessions" <<std::endl; } /** * Main MHD callback for handling requests. * * @param cls argument given together with the function * pointer when the handler was registered with MHD * @param connection handle identifying the incoming connection * @param url the requested url * @param method the HTTP method used ("GET", "PUT", etc.) * @param version the HTTP version string (i.e. "HTTP/1.1") * @param upload_data the data being uploaded (excluding HEADERS, * for a POST that fits into memory and that is encoded * with a supported encoding, the POST data will NOT be * given in upload_data and is instead available as * part of MHD_get_connection_values; very large POST * data *will* be made available incrementally in * upload_data) * @param upload_data_size set initially to the size of the * upload_data provided; the method must update this * value to the number of bytes NOT processed; * @param ptr pointer that the callback can set to some * address and that will be preserved by MHD for future * calls for this request; since the access handler may * be called many times (i.e., for a PUT/POST operation * with plenty of upload data) this allows the application * to easily associate some request-specific state. * If necessary, this state can be cleaned up in the * global "MHD_RequestCompleted" callback (which * can be set with the MHD_OPTION_NOTIFY_COMPLETED). * Initially, <tt>*con_cls</tt> will be NULL. * @return MHS_YES if the connection was handled successfully, * MHS_NO if the socket must be closed due to a serios * error while handling the request */ static int create_response (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **ptr) { if (cls != NULL) { WebServer *server = (WebServer *)cls; return server->createResponse(connection, url, method, version, upload_data, upload_data_size, ptr); } return MHD_NO; } WebServer::WebServer(int aPort) { _port = aPort; _notFoundPage = new WebPage(); } void WebServer::addPage(WebPage * aPage) { _pages.push_back(aPage); } void WebServer::start() { /* initialize PRNG */ srand ((unsigned int) time (NULL)); d = MHD_start_daemon (MHD_USE_DEBUG, _port, NULL, NULL, &create_response, this, MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 15, MHD_OPTION_NOTIFY_COMPLETED, &request_completed_callback, NULL, MHD_OPTION_END); if (d == NULL) { std::cout << "Unable to start daemon!" << std::endl; } } void WebServer::run() { expireSessions (); max = 0; FD_ZERO (&rs); FD_ZERO (&ws); FD_ZERO (&es); if (MHD_YES != MHD_get_fdset (d, &rs, &ws, &es, &max)) return; /* fatal internal error */ if (MHD_get_timeout (d, &mhd_timeout) == MHD_YES) { tv.tv_sec = mhd_timeout / 1000; tv.tv_usec = (mhd_timeout - (tv.tv_sec * 1000)) * 1000; tvp = &tv; } else tvp = NULL; select (max + 1, &rs, &ws, &es, tvp); MHD_run (d); } int WebServer::createResponse (struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **ptr) { struct MHD_Response *response; struct Request *request; WebSession *session; int ret = MHD_NO; unsigned int i; request = (struct Request *)*ptr; if (NULL == request) { request = (struct Request *)calloc (1, sizeof (struct Request)); if (NULL == request) { fprintf (stderr, "calloc error: %s\n", strerror (errno)); return MHD_NO; } *ptr = request; if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { request->pp = MHD_create_post_processor (connection, 1024, &post_iterator, request); if (NULL == request->pp) { fprintf (stderr, "Failed to setup post processor for `%s'\n", url); return MHD_NO; /* internal error */ } } return MHD_YES; } if (NULL == request->session) { request->session = getSession(connection); if (NULL == request->session) { fprintf (stderr, "Failed to setup session for `%s'\n", url); return MHD_NO; /* internal error */ } } session = request->session; session->start = time (NULL); if (0 == strcmp (method, MHD_HTTP_METHOD_POST)) { /* evaluate POST data */ MHD_post_process (request->pp, upload_data, *upload_data_size); /* if (0 != *upload_data_size) { *upload_data_size = 0; return MHD_YES; } */ /* done with POST data, serve response */ MHD_destroy_post_processor (request->pp); request->pp = NULL; method = MHD_HTTP_METHOD_GET; /* fake 'GET' */ if (NULL != request->post_url) url = request->post_url; //handle data /* find out which page to serve */ WebPage * page = NULL; for (auto it = _pages.begin(); it != _pages.end(); it++) { WebPage *current = *it; if (strcmp (current->getURL().c_str(), url) == 0) { page = current; break; } } if (page != NULL) { page->handlePost(session, upload_data, *upload_data_size); } } if ( (0 == strcmp (method, MHD_HTTP_METHOD_GET)) || (0 == strcmp (method, MHD_HTTP_METHOD_HEAD)) ) { /* find out which page to serve */ WebPage * page = NULL; for (auto it = _pages.begin(); it != _pages.end(); it++) { WebPage *current = *it; if (strcmp (current->getURL().c_str(), url) == 0) { page = current; break; } } if (page == NULL) { page = _notFoundPage; } std::cout << "Serving page" << std::endl; struct MHD_Response *response; std::string replyString = page->fillRequest(session); // return static form response = MHD_create_response_from_buffer (strlen (replyString.c_str()), (void *) replyString.c_str(), MHD_RESPMEM_MUST_COPY); if (NULL != response) { addSessionCookie(session, response); MHD_add_response_header (response, MHD_HTTP_HEADER_CONTENT_ENCODING, page->getMime().c_str()); ret = MHD_queue_response (connection, MHD_HTTP_OK, response); MHD_destroy_response (response); } /* i=0; while ( (pages[i].url != NULL) && (0 != strcmp (pages[i].url, url)) ) i++; ret = pages[i].handler (pages[i].handler_cls, pages[i].mime, session, connection); */ if (ret != MHD_YES) fprintf (stderr, "Failed to create page for `%s'\n", url); return ret; } /* unsupported HTTP method */ response = MHD_create_response_from_buffer (strlen (METHOD_ERROR), (void *) METHOD_ERROR, MHD_RESPMEM_PERSISTENT); ret = MHD_queue_response (connection, MHD_HTTP_NOT_ACCEPTABLE, response); MHD_destroy_response (response); return ret; } /** * Add header to response to set a session cookie. * * @param session session to use * @param response response to modify */ void WebServer::addSessionCookie (WebSession *session, struct MHD_Response *response) { char cstr[256]; snprintf (cstr, sizeof (cstr), "%s=%s", COOKIE_NAME, session->getSID().c_str()); if (MHD_NO == MHD_add_response_header (response, MHD_HTTP_HEADER_SET_COOKIE, cstr)) { fprintf (stderr, "Failed to set session cookie header!\n"); } } void WebServer::stop() { MHD_stop_daemon (d); }
3becadd66c8d178bbec5a100636e1e1e6f4674b6
b932134deff2e82f984c267c26b47ce74c521ef5
/leetcode/908. Smallest Range I.cpp
aee185ef6497066f13fa884dcba240002c83eb21
[ "MIT" ]
permissive
chamow97/Interview-Prep
db234e0df0bfa6b3358d73ac187d6a132fa14595
9ce13afef6090b1604f72bf5f80a6e1df65be24f
refs/heads/master
2022-11-06T07:06:54.705258
2020-06-21T07:29:14
2020-06-21T07:29:14
112,472,858
1
0
null
null
null
null
UTF-8
C++
false
false
296
cpp
908. Smallest Range I.cpp
class Solution { public: int smallestRangeI(vector<int>& A, int k) { sort(A.begin(), A.end()); int n = A.size(); A[0] += k; A[n - 1] -= k; int ans = A[n - 1] - A[0]; if(ans < 0) { ans = 0; } return ans; } };
93c5f61e236f5f2f312c0a3f9b87bcfce0cbf311
557b60baadca1744a761b61a2dcd44f083f4f77d
/src/raii.cpp
c1fe56646de348486f2bd2186849e0cf15995a6b
[]
no_license
slashdotted/corsocpp_tp_2021
c7705e5945f7c487ab128e30e143034a07299784
11160fbf0b98aae231a1805c2b95c2cff287e47f
refs/heads/master
2023-05-22T14:40:52.838768
2021-06-07T12:04:39
2021-06-07T12:04:39
342,510,462
0
0
null
null
null
null
UTF-8
C++
false
false
1,748
cpp
raii.cpp
#include "raii.h" #include <iostream> #include <string> struct A { A() { std::cout << "Costruzione di A\n"; } ~A() { std::cout << "Distruzione di A\n"; } }; struct B { B(const std::string &n) : nome{n}, a{new A} { // RAII Resource Acquisition Is Initialization // (acquisisco nel costruttore) std::cout << "Costruzione di B " << nome << '\n'; } // Costruttore di copia B(const B &o) : nome{o.nome}, a{new A{*o.a}} { // Copio il valore dei campi da o std::cout << "Costruzione di una copia B " << nome << '\n'; } // Operatore di assegnamento di copia B &operator=(const B &o) { nome = o.nome; // copio il valore *a = *o.a; // copio il valore std::cout << "Assegnamento di una copia B " << nome << '\n'; return *this; } ~B() { std::cout << "Distruzione di B " << nome << '\n'; delete a; // RAII Resource Acquisition Is Initialization (dealloco nel // distruttore) } private: A *a; std::string nome; }; struct C { C(const std::string &n) : nome{n} { std::cout << "Costruzione di C " << nome << '\n'; } A a; std::string nome; }; struct D { D(C &c) : ex_c{c} {} C &ex_c; }; void foo(B b) {} void raii_run() { B aldo{"Aldo"}; B giovanni{"Giovanni"}; aldo = giovanni; // crea copia! (operatore di assegnamento di copia) foo(aldo); // crea copia! (Costruttore di copia) B giacomo{aldo}; // crea copia! (Costruttore di copia) // Senza costruttore / operatore di assegnamento di copia: // 1. aldo e giovanni e giacomo condividono la stessa allocazione (A) sullo // heap --> double // 2. free la memoria allocata da aldo / giacomo sullo heap non è più // raggiungibile / deallocabile }
253c77620bf2749de975b57332643753d844914a
4bcc9806152542ab43fc2cf47c499424f200896c
/tensorflow/tools/graph_transforms/sparsify_gather.cc
de13abbefe26dd56fbda981cf567d48741c34d79
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
tensorflow/tensorflow
906276dbafcc70a941026aa5dc50425ef71ee282
a7f3934a67900720af3d3b15389551483bee50b8
refs/heads/master
2023-08-25T04:24:41.611870
2023-08-25T04:06:24
2023-08-25T04:14:08
45,717,250
208,740
109,943
Apache-2.0
2023-09-14T20:55:50
2015-11-07T01:19:20
C++
UTF-8
C++
false
false
23,510
cc
sparsify_gather.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. ==============================================================================*/ #include <cmath> #include <memory> #include <unordered_map> #include "tensorflow/c/checkpoint_reader.h" #include "tensorflow/core/common_runtime/graph_constructor.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/graph/node_builder.h" #include "tensorflow/core/graph/subgraph.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/platform/init_main.h" #include "tensorflow/core/public/session.h" #include "tensorflow/core/util/tensor_bundle/tensor_bundle.h" #include "tensorflow/tools/graph_transforms/transform_utils.h" namespace tensorflow { using str_util::Split; using str_util::StringReplace; using strings::StrCat; namespace graph_transforms { // Sparsify Tensor of shape [N, 1]. Return the indices and values vectors for // non-zero tensor content. Status SparsifyWeights(const Tensor& tensor, Tensor* indices_tensor, Tensor* values_tensor) { if (tensor.dims() != 2 || tensor.dim_size(1) != 1) { return tensorflow::errors::FailedPrecondition( "Transform only applicable to subgraph with 'Const' with " "tensor of shape [N, 1]. But instead get shape ", tensor.shape().DebugString(), "."); } auto flat = tensor.flat<float>(); std::vector<int64_t> indices; std::vector<float> values; for (int64_t i = 0; i < flat.size(); i++) { float val = flat(i); if (std::abs(val) >= 1.0e-5) { indices.push_back(i); values.push_back(val); } } // During model initialization, InitializeTableOp makes use of // KeyValueTensorIterator, which does not accept empty keys or values. // Consequently, adding a dummy pair of indices and values as a walkaround. if (indices.empty() || values.empty()) { indices.push_back(0); values.push_back(0); } *indices_tensor = Tensor(DataTypeToEnum<int64_t>::value, {static_cast<int64_t>(indices.size())}); std::copy_n(indices.begin(), indices.size(), indices_tensor->flat<int64_t>().data()); *values_tensor = Tensor(DataTypeToEnum<float>::value, {static_cast<int64_t>(values.size())}); std::copy_n(values.begin(), values.size(), values_tensor->flat<float>().data()); return OkStatus(); } void CreateConstNode(const Tensor& tensor, const string& name, NodeDef* node_def) { node_def->set_op("Const"); node_def->set_name(name); SetNodeTensorAttr<float>("value", tensor, node_def); } string GetMonolithicTensorKey(const string& tensor_slice_name) { std::vector<string> names = Split(tensor_slice_name, "/"); if (absl::StartsWith(names[names.size() - 1], "part_")) { CHECK_GE(names.size(), 2); names.pop_back(); } return absl::StrJoin(names, "/"); } Status ObtainTensorSlice(const GraphDef& input_graph_def, const string& target_name, string* shape_slice_string) { string restore_node_name; for (const auto& node : input_graph_def.node()) { std::vector<string> node_name_parts = Split(node.name(), "/"); if (node_name_parts.size() == 2 && absl::StartsWith(node_name_parts[0], "save") && absl::StartsWith(node_name_parts[1], "Assign") && node.input(0) == target_name) { restore_node_name = node.input(1); break; } } std::vector<string> restore_node_parts = Split(restore_node_name, ":"); CHECK_LE(restore_node_parts.size(), 2); string tensor_names_node; string shape_and_slices_node; for (const auto& node : input_graph_def.node()) { if ((node.name() == restore_node_parts[0]) && (node.op() == "RestoreV2")) { tensor_names_node = node.input(1); shape_and_slices_node = node.input(2); break; } } int offset = -1; for (const auto& node : input_graph_def.node()) { if (node.name() == tensor_names_node) { Tensor tensor_names_tensor; TF_RETURN_IF_ERROR(GetNodeAttr(node, "value", &tensor_names_tensor)); const auto& tensor_names_value = tensor_names_tensor.flat<tstring>(); for (int i = 0; i < tensor_names_value.size(); i++) { if (tensor_names_value(i) == GetMonolithicTensorKey(target_name)) { offset = i; break; } } } } if (offset == -1) { return errors::Internal("Unable to find RestoreV2 entry for variable: ", target_name); } for (const auto& node : input_graph_def.node()) { if (node.name() == shape_and_slices_node) { Tensor shape_and_slices_tensor; TF_RETURN_IF_ERROR(GetNodeAttr(node, "value", &shape_and_slices_tensor)); const auto& shape_and_slices_value = shape_and_slices_tensor.flat<tstring>(); *shape_slice_string = shape_and_slices_value(offset); return OkStatus(); } } return errors::Internal("Unable to find slice for variable: ", target_name); } Status ReadTensorFromCheckpoint( const string& tensor_name, const std::unique_ptr<BundleReader>& ckpt_reader, const string& shape_and_slice, Tensor* tensor) { if (ckpt_reader) { TensorShape parsed_full_shape; TensorSlice parsed_slice; TensorShape parsed_slice_shape; bool get_slice = false; if (!shape_and_slice.empty()) { TF_RETURN_IF_ERROR( checkpoint::ParseShapeAndSlice(shape_and_slice, &parsed_full_shape, &parsed_slice, &parsed_slice_shape)); get_slice = (parsed_full_shape != parsed_slice_shape); } if (get_slice) { TF_RETURN_IF_ERROR(ckpt_reader->LookupSlice( GetMonolithicTensorKey(tensor_name), parsed_slice, tensor)); } else { TF_RETURN_IF_ERROR( ckpt_reader->Lookup(GetMonolithicTensorKey(tensor_name), tensor)); } return OkStatus(); } return errors::Internal("Checkpoint reader was not initialized. "); } Status InitializeCheckpointReader(const TransformFuncContext& context, std::unique_ptr<BundleReader>* ckpt_reader) { if (context.params.count("input_checkpoint")) { const string input_checkpoint = context.params.at("input_checkpoint")[0]; ckpt_reader->reset(new BundleReader(Env::Default(), input_checkpoint)); TF_RETURN_IF_ERROR((*ckpt_reader)->status()); } return OkStatus(); } Status ObtainVariableInfo( const GraphDef& input_graph_def, std::unique_ptr<std::unordered_map<string, string> >* shapes_and_slices) { shapes_and_slices->reset(new std::unordered_map<string, string>()); for (const auto& node : input_graph_def.node()) { if ((node.op() == "Variable") || (node.op() == "VariableV2")) { string s; TF_RETURN_IF_ERROR(ObtainTensorSlice(input_graph_def, node.name(), &s)); (**shapes_and_slices)[node.name()] = s; } } return OkStatus(); } Status RemoveInputAtIndex(NodeDef* n, int index) { for (int i = index; i < n->input_size() - 1; i++) { n->mutable_input()->SwapElements(i, i + 1); } n->mutable_input()->RemoveLast(); return OkStatus(); } Status RemoveNodeAtIndex(GraphDef* g, int index) { for (int i = index; i < g->node_size() - 1; i++) { g->mutable_node()->SwapElements(i, i + 1); } g->mutable_node()->RemoveLast(); return OkStatus(); } Status SparsifyGatherInternal( const GraphDef& input_graph_def, const std::unique_ptr<std::unordered_map<string, string> >& shapes_and_slices, const TransformFuncContext& context, const OpTypePattern& pattern, const std::unique_ptr<BundleReader>& ckpt_reader, GraphDef* output_graph_def) { string group_init_node = "group_deps"; if (context.params.count("group_init_node")) { group_init_node = context.params.at("group_init_node")[0]; } GraphDef current_graph_def = input_graph_def; bool any_match_found = false; // Populate references. std::unordered_map<string, int> refs; for (const auto& node : current_graph_def.node()) { for (const auto& input : node.input()) { auto parsed_input = StringReplace(input, "^", "", true); refs[parsed_input] += 1; } } // The subgraphs may have overlapping components, therefore GraphMatcher // doesn't return all subgraphs in one round -- this has to be multi-round // update. do { any_match_found = false; GraphDef replaced_graph_def = current_graph_def; std::vector<string> init_table_node_names; std::vector<string> removed_node_names; TF_RETURN_IF_ERROR(ReplaceMatchingOpTypes( current_graph_def, pattern, [&ckpt_reader, &any_match_found, &init_table_node_names, &shapes_and_slices, &removed_node_names, &refs](const NodeMatch& match, const std::set<string>& input_nodes, const std::set<string>& output_nodes, std::vector<NodeDef>* new_nodes) { any_match_found = true; // The captured subgraph should be of the following pattern: // Const --> Identity --> Gather --> ... // ^ // | // (ids) // // After transform, it becomes: // --> NoOp(group_deps) // | // Const --> InitializeTable --> HashTable // ^ | // | | // Const ------------- | // v // (ids) ---> LookupTableFind <--- Const(default) // | // v // ... // clang-format off // For each subgraph, do the following // 1. Sparsify the `Const`, creating two `Const`, for hashtable // key/val. // 2. Create a `InitializeTable` op connecting to the above 2 `Const`. // 3. Create a `HashTable` op connecting to `InitializeTable` op. // 4. Replace the `Gather` with a `LookupTableFind` op. // 5. Connect the `LookupTableFind` with // a. `HashTable` // b. `Gather`'s ids input // c. a `default_val` arg, valued at 0 // clang-format on const NodeDef& gather_node = match.node; // GatherV2 adds an "axis" parameter. sparsify_gather only supports // axis 0 gathers. if (gather_node.op() == "GatherV2") { // Per the OpTypePattern, the 3rd input to Gather must be a Const. const NodeDef& axis_node = match.inputs[2].node; Tensor axis_t; TF_RETURN_IF_ERROR(GetNodeAttr(axis_node, "value", &axis_t)); int64_t axis = 0; if (axis_t.dtype() == DT_INT32) { axis = axis_t.scalar<int32>()(); } else if (axis_t.dtype() == DT_INT64) { axis = axis_t.scalar<int64_t>()(); } else { return tensorflow::errors::FailedPrecondition( "Gather axis was not int32 or int64."); } if (axis != 0) { return tensorflow::errors::FailedPrecondition( "Transform only applicable to subgraph with GatherV2 over " "axis 0. Found axis ", axis, "."); } } const NodeDef& weights_node = match.inputs[0].inputs[0].node; DataType data_type; TF_RETURN_IF_ERROR(GetNodeAttr(weights_node, "dtype", &data_type)); if (data_type != DT_FLOAT) { return tensorflow::errors::FailedPrecondition( "Transform only applicable to subgraph with 'Const'," "'Variable', or 'VariableV2' of dtype " "'DT_FLOAT'. Found '" + weights_node.op() + "' with name '", weights_node.name(), "' and dtype '", data_type, "'."); } Tensor weight; if (weights_node.op() == "Const") { weight = GetNodeTensorAttr(weights_node, "value"); } else { TF_RETURN_IF_ERROR(ReadTensorFromCheckpoint( weights_node.name(), ckpt_reader, (*shapes_and_slices)[weights_node.name()], &weight)); } // Add both weight and identity node names. removed_node_names.push_back(weights_node.name()); removed_node_names.push_back(match.inputs[0].node.name()); for (auto input_node : match.inputs[0].node.input()) { auto parsed_input = StringReplace(input_node, "^", "", true); refs[parsed_input]--; } Tensor indices_tensor; Tensor values_tensor; TF_RETURN_IF_ERROR( SparsifyWeights(weight, &indices_tensor, &values_tensor)); // indices and values of sparsified `Const` DataType key_dtype = DT_INT64; NodeDef indices_node; CreateConstNode(indices_tensor, StrCat(weights_node.name(), "/indices"), &indices_node); SetNodeAttr("dtype", key_dtype, &indices_node); NodeDef values_node; CreateConstNode(values_tensor, StrCat(weights_node.name(), "/values"), &values_node); SetNodeAttr("dtype", data_type, &values_node); // HashTable node NodeDef hashtable_node; hashtable_node.set_op("HashTable"); hashtable_node.set_name(StrCat(weights_node.name(), "/HashTable")); SetNodeAttr("key_dtype", key_dtype, &hashtable_node); SetNodeAttr("value_dtype", data_type, &hashtable_node); // InitializeTable node NodeDef init_table_node; init_table_node.set_op("InitializeTable"); init_table_node.set_name( StrCat(weights_node.name(), "/InitializeTable")); SetNodeAttr("Tkey", key_dtype, &init_table_node); SetNodeAttr("Tval", data_type, &init_table_node); init_table_node_names.push_back(init_table_node.name()); // LookupTableFind node NodeDef lookup_node; lookup_node.set_op("LookupTableFind"); lookup_node.set_name(StrCat(gather_node.name(), "/LookupTableFind")); SetNodeAttr("Tin", key_dtype, &lookup_node); SetNodeAttr("Tout", data_type, &lookup_node); // Default return value of hashtable lookup Tensor zero_tensor(data_type, TensorShape({})); zero_tensor.flat<float>()(0) = 0.0; NodeDef default_value_node; CreateConstNode(zero_tensor, StrCat(gather_node.name(), "/Const"), &default_value_node); SetNodeAttr("dtype", data_type, &default_value_node); // ExpandDims argument Tensor dim_idx(DT_INT32, TensorShape({})); dim_idx.flat<int32>()(0) = -1; NodeDef dim_idx_node; dim_idx_node.set_op("Const"); dim_idx_node.set_name( StrCat(gather_node.name(), "/ExpandDims/Const")); SetNodeAttr("value", dim_idx, &dim_idx_node); SetNodeAttr("dtype", DT_INT32, &dim_idx_node); // ExpandDims node NodeDef expand_dims_node; expand_dims_node.set_op("ExpandDims"); // Reuse gather_node's name so not to change dependent's inputs expand_dims_node.set_name(gather_node.name()); SetNodeAttr("T", data_type, &expand_dims_node); // Connect nodes AddNodeInput(hashtable_node.name(), &init_table_node); refs[hashtable_node.name()]++; AddNodeInput(indices_node.name(), &init_table_node); refs[indices_node.name()]++; AddNodeInput(values_node.name(), &init_table_node); refs[values_node.name()]++; AddNodeInput(hashtable_node.name(), &lookup_node); refs[hashtable_node.name()]++; AddNodeInput(gather_node.input(1), &lookup_node); refs[gather_node.input(1)]++; AddNodeInput(default_value_node.name(), &lookup_node); refs[default_value_node.name()]++; AddNodeInput(lookup_node.name(), &expand_dims_node); refs[lookup_node.name()]++; AddNodeInput(dim_idx_node.name(), &expand_dims_node); refs[dim_idx_node.name()]++; // Copy 'ids' input of original 'Gather' new_nodes->push_back(match.inputs[1].node); new_nodes->push_back(indices_node); new_nodes->push_back(values_node); new_nodes->push_back(hashtable_node); new_nodes->push_back(init_table_node); new_nodes->push_back(lookup_node); new_nodes->push_back(default_value_node); new_nodes->push_back(dim_idx_node); new_nodes->push_back(expand_dims_node); return OkStatus(); }, {true}, &replaced_graph_def)); NodeDef* init_op = nullptr; for (int i = 0; i < replaced_graph_def.node_size(); i++) { if (replaced_graph_def.node(i).name() == group_init_node && replaced_graph_def.node(i).op() == "NoOp") { init_op = replaced_graph_def.mutable_node(i); break; } } if (!init_op) { // Init node init_op = replaced_graph_def.mutable_node()->Add(); init_op->set_op("NoOp"); init_op->set_name(group_init_node); } for (const string& name : init_table_node_names) { // Add control dependence from init_table_node to group_deps_node AddNodeInput(StrCat("^", name), init_op); refs[name]++; } // Erase inputs and outputs as they are not considered for deletion. for (const auto& output : context.output_names) { refs.erase(output); } for (const auto& input : context.input_names) { refs.erase(input); } // Add nodes with a reference count of 0 for deletion. for (const auto& entry : refs) { if (entry.second == 0) { removed_node_names.push_back(entry.first); } } while (!removed_node_names.empty()) { auto name = removed_node_names.back(); removed_node_names.pop_back(); int i = 0; while (i < replaced_graph_def.node_size()) { // Revisit this to see if we can safely remove RestoreV2 nodes. if ((replaced_graph_def.node(i).name() == name) && (replaced_graph_def.node(i).op() != "RestoreV2")) { for (const auto& input : replaced_graph_def.node(i).input()) { auto parsed_input = StringReplace(input, "^", "", true); refs[parsed_input] -= 1; if (refs[parsed_input] == 0) { removed_node_names.push_back(parsed_input); } } TF_RETURN_IF_ERROR(RemoveNodeAtIndex(&replaced_graph_def, i)); continue; } int j = 0; bool deleted_inputs = false; while (j < replaced_graph_def.node(i).input_size()) { if (replaced_graph_def.node(i).input(j) == name || replaced_graph_def.node(i).input(j) == ("^" + name)) { TF_RETURN_IF_ERROR( RemoveInputAtIndex(replaced_graph_def.mutable_node(i), j)); deleted_inputs = true; continue; } j++; } if (deleted_inputs) { if (replaced_graph_def.node(i).op() == "ConcatV2") { if (replaced_graph_def.node(i).input_size() > 2) { SetNodeAttr("N", replaced_graph_def.node(i).input_size() - 1, replaced_graph_def.mutable_node(i)); } else if (replaced_graph_def.node(i).input_size() == 2) { if (refs[replaced_graph_def.node(i).input(1)] != 1) { return errors::Internal( "Expect axis tensor of ConcatV2 node to only be referenced " "once."); } refs[replaced_graph_def.node(i).input(1)] -= 1; removed_node_names.push_back(replaced_graph_def.node(i).input(1)); replaced_graph_def.mutable_node(i)->mutable_input()->RemoveLast(); replaced_graph_def.mutable_node(i)->mutable_attr()->erase("N"); replaced_graph_def.mutable_node(i)->set_op("Identity"); } else { return errors::Internal( "ConcatV2 should have at least two elements"); } } if ((replaced_graph_def.node(i).op() == "Assign" || replaced_graph_def.node(i).op() == "Reshape" || replaced_graph_def.node(i).op() == "Equal" || replaced_graph_def.node(i).op() == "Mean" || replaced_graph_def.node(i).op() == "ScalarSummary") && replaced_graph_def.node(i).input_size() == 1) { removed_node_names.push_back(replaced_graph_def.node(i).name()); } if (!replaced_graph_def.node(i).input_size()) { removed_node_names.push_back(replaced_graph_def.node(i).name()); } } i++; } } current_graph_def = replaced_graph_def; } while (any_match_found); *output_graph_def = current_graph_def; return OkStatus(); } Status SparsifyGather(const GraphDef& input_graph_def, const TransformFuncContext& context, GraphDef* output_graph_def) { // clang-format off const OpTypePattern gather_pattern = {"Gather", { {"Identity", { {"Const|Variable|VariableV2"} } }, {"*"}, } }; const OpTypePattern gather_v2_pattern = {"GatherV2", { {"Identity", { {"Const|Variable|VariableV2"} } }, {"*"}, // GatherV2's axis must be constant. {"Const"}, } }; // clang-format on GraphDef cleaned_input_graph_def; RemoveAttributes(input_graph_def, {"_output_shapes"}, &cleaned_input_graph_def); GraphDef temp_output; std::unique_ptr<BundleReader> ckpt_reader; TF_RETURN_IF_ERROR(InitializeCheckpointReader(context, &ckpt_reader)); std::unique_ptr<std::unordered_map<string, string> > shapes_and_slices; TF_RETURN_IF_ERROR( ObtainVariableInfo(cleaned_input_graph_def, &shapes_and_slices)); TF_RETURN_IF_ERROR(SparsifyGatherInternal( cleaned_input_graph_def, shapes_and_slices, context, gather_pattern, ckpt_reader, &temp_output)); TF_RETURN_IF_ERROR(SparsifyGatherInternal(temp_output, shapes_and_slices, context, gather_v2_pattern, ckpt_reader, output_graph_def)); return OkStatus(); } REGISTER_GRAPH_TRANSFORM("sparsify_gather", SparsifyGather); } // namespace graph_transforms } // namespace tensorflow
9c0e6cf701847fe1f1771d64cadebb3e1e4ab777
f6f8cfcd6c4f09772f99e4a6fe6a244e3499dac5
/Validation.h
49daa1f22c7070afeffd192367b5768c438619a7
[ "Apache-2.0" ]
permissive
trackreco/mkFit
eedceb76639fce2cd6893a332e27fe43c7aed36b
ba37025247ff72c8edd2baea02b5b4ac335bdede
refs/heads/devel
2022-02-11T01:07:33.040657
2021-12-14T18:07:59
2021-12-14T18:07:59
17,191,259
11
12
Apache-2.0
2022-04-09T01:39:47
2014-02-25T22:59:21
C++
UTF-8
C++
false
false
1,825
h
Validation.h
#ifndef _validation_ #define _validation_ #include "Track.h" namespace mkfit { class Event; // Fit Validation objects -- mplex only struct FitVal { public: FitVal() {} FitVal(float ppz, float eppz, float ppphi, float eppphi, float upt, float eupt, float umphi, float eumphi, float umeta, float eumeta) : ppz(ppz), eppz(eppz), ppphi(ppphi), eppphi(eppphi), upt(upt), eupt(eupt), umphi(umphi), eumphi(eumphi), umeta(umeta), eumeta(eumeta) {} // first p or u = propagated or updated // middle: p or m/nothing = position or momentum // begining: e = error (already sqrt) float ppz, eppz, ppphi, eppphi; float upt, eupt, umphi, eumphi, umeta, eumeta; }; class Validation { public: virtual ~Validation() {} virtual void alignTracks(TrackVec&, TrackExtraVec&, bool) {} virtual void resetValidationMaps() {} virtual void resetDebugVectors() {} virtual void collectFitInfo(const FitVal&, int, int) {} virtual void setTrackExtras(Event& ev) {} virtual void makeSimTkToRecoTksMaps(Event&) {} virtual void makeSeedTkToRecoTkMaps(Event&) {} virtual void makeRecoTkToRecoTkMaps(Event&) {} virtual void makeCMSSWTkToRecoTksMaps(Event&) {} virtual void makeSeedTkToCMSSWTkMap(Event&) {} virtual void makeCMSSWTkToSeedTkMap(Event&) {} virtual void makeRecoTkToSeedTkMapsDumbCMSSW(Event&) {} virtual void setTrackScoresDumbCMSSW(Event &) {} virtual void fillEfficiencyTree(const Event&) {} virtual void fillFakeRateTree(const Event&) {} virtual void fillConfigTree() {} virtual void fillCMSSWEfficiencyTree(const Event&) {} virtual void fillCMSSWFakeRateTree(const Event&) {} virtual void fillFitTree(const Event&) {} virtual void saveTTrees() {} static Validation* make_validation(const std::string&); protected: Validation(); }; } // end namespace mkfit #endif
8edba380464018b518d9b2414f2a0a379f2b8440
ae35ab4d2ce60e0efc72d4d3a6eb76bfacd7eef0
/adult/scripts/08_history.swap.inc
c342a34618003bd5a5989492457761990e6cb983
[]
no_license
qq674684107/hdp_ims
a72594e9ffa1019541eb1adfd842f1f386017a5e
f060203b5eef99295d86682c35be599c6cc42d31
refs/heads/master
2020-05-15T18:20:00.969739
2017-01-09T05:38:02
2017-01-09T05:38:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
39
inc
08_history.swap.inc
../../video/scripts/08_history.swap.inc
ebbc172cc3b2b007b7f60c35dc1bb13470e4e5fc
ab4c33df512a280756b611291fa8e74f23801d2f
/ex02-01/Rational.h
b776ee84f3a1af187e78140ee31048aad964019c
[]
no_license
meirl1/cpluspluslab
a496b05c602b896a4a6c979acefd22630571c6ea
8c7a15cab9763eb2b3ccd91ead5398f7aa196bbb
refs/heads/master
2023-04-22T03:50:32.466918
2021-05-18T13:27:11
2021-05-18T13:27:11
343,748,724
1
1
null
2021-03-04T19:13:13
2021-03-02T11:20:44
C++
UTF-8
C++
false
false
255
h
Rational.h
#pragma once class Rational { int numerator; int denominator; public: Rational(int _numerator = 0, int _denominator = 1); void setNumerator(int _numerator); void setDenominator(int _denominator); int getNumerator() const; int getDenominator(); };
12c6a28829572d2bdf9f329e43de4917b9a49574
836560ade457e4ae270aadbcee4761474eeacb30
/include/model.h
cedf4c4deacf4905d1e3b917298f585d4ed50b36
[]
no_license
weigert/MicroClimate
830ec0598da809f495e0c0f794510d19c9b15838
8fa73f2a43bd5b7537a0b113b1c441f6e08ea6bc
refs/heads/master
2022-11-27T22:36:07.127469
2020-08-05T06:54:48
2020-08-05T06:54:48
284,885,032
28
1
null
null
null
null
UTF-8
C++
false
false
2,974
h
model.h
//Model Stuff int SEED = 10; double scale = 15.0; glm::vec2 dim = glm::vec2(100); noise::module::Perlin perlin; //View Stuff const int WIDTH = 1200; const int HEIGHT = 800; glm::vec3 viewPos = glm::vec3(50, 0, 50); float zoom = 0.1; float zoomInc = 0.001; float rotation = 0.0f; glm::vec3 cameraPos = glm::vec3(50, 60, 50); glm::vec3 lookPos = glm::vec3(0, 10, 0); glm::mat4 camera = glm::lookAt(cameraPos, lookPos, glm::vec3(0,1,0)); glm::mat4 projection = glm::ortho(-(float)WIDTH*zoom, (float)WIDTH*zoom, -(float)HEIGHT*zoom, (float)HEIGHT*zoom, -800.0f, 500.0f); glm::vec3 lightPos = glm::vec3(-100.0f, 100.0f, -150.0f); glm::mat4 depthModelMatrix = glm::mat4(1.0); glm::mat4 depthProjection = glm::ortho<float>(-300, 300, -300, 300, 0, 800); glm::mat4 depthCamera = glm::lookAt(lightPos, glm::vec3(0), glm::vec3(0,1,0)); glm::mat4 biasMatrix = glm::mat4( 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0 ); std::function<void(Model*, double* )> constructor = [&](Model* m, double* D){ //Clear the Containers m->indices.clear(); m->positions.clear(); m->normals.clear(); m->colors.clear(); int w = dim.y; //Loop over all positions and add the triangles! for(int i = 0; i < dim.x-1; i++){ for(int j = 0; j < dim.y-1; j++){ //Add to Position Vector glm::vec3 b = glm::vec3(i, scale*D[i*w+j], j); glm::vec3 a = glm::vec3(i+1, scale*D[(i+1)*w+j], j); glm::vec3 d = glm::vec3(i, scale*D[i*w+j+1], j+1); glm::vec3 c = glm::vec3(i+1, scale*D[(i+1)*w+j+1], j+1); //Add Indices m->indices.push_back(m->positions.size()/3+0); m->indices.push_back(m->positions.size()/3+1); m->indices.push_back(m->positions.size()/3+2); m->positions.push_back(a.x); m->positions.push_back(a.y); m->positions.push_back(a.z); m->positions.push_back(b.x); m->positions.push_back(b.y); m->positions.push_back(b.z); m->positions.push_back(c.x); m->positions.push_back(c.y); m->positions.push_back(c.z); glm::vec3 n1 = -glm::normalize(glm::cross(a-b, c-b)); for(int i = 0; i < 3; i++){ m->normals.push_back(n1.x); m->normals.push_back(n1.y); m->normals.push_back(n1.z); } m->indices.push_back(m->positions.size()/3+0); m->indices.push_back(m->positions.size()/3+1); m->indices.push_back(m->positions.size()/3+2); m->positions.push_back(d.x); m->positions.push_back(d.y); m->positions.push_back(d.z); m->positions.push_back(c.x); m->positions.push_back(c.y); m->positions.push_back(c.z); m->positions.push_back(b.x); m->positions.push_back(b.y); m->positions.push_back(b.z); glm::vec3 n2 = -glm::normalize(glm::cross(d-c, b-c)); for(int i = 0; i < 3; i++){ m->normals.push_back(n2.x); m->normals.push_back(n2.y); m->normals.push_back(n2.z); } } } };
e057447a71ecdb8c391634a3553bc8454f777bd3
98f9f977a39843e5f7719062f43011ebfd169e42
/Plugins/org.commontk.configadmin/ctkCMEventDispatcher.cpp
7ff58297f1bcebd6ed02d8e5c2c98a29bd6c36da
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
txdy077345/CTK
71cab2d77193d09340afe7a50e5dddc3ea66a06d
7cd253376139ea73f0450e1bad75bab41aa1b507
refs/heads/master
2023-05-27T19:20:21.825916
2023-04-29T16:35:03
2023-04-29T16:35:03
276,658,777
1
0
Apache-2.0
2020-07-02T13:50:30
2020-07-02T13:50:29
null
UTF-8
C++
false
false
3,156
cpp
ctkCMEventDispatcher.cpp
/*============================================================================= Library: CTK Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "ctkCMEventDispatcher_p.h" #include <service/log/ctkLogService.h> #include <service/cm/ctkConfigurationListener.h> #include <QRunnable> class _DispatchEventRunnable : public QRunnable { public: _DispatchEventRunnable(ctkServiceTracker<ctkConfigurationListener*>* tracker, ctkLogService* log, const ctkConfigurationEvent& event, const ctkServiceReference& ref) : tracker(tracker), log(log), event(event), ref(ref) { } void run() { ctkConfigurationListener* listener = tracker->getService(ref); if (listener == 0) { return; } try { listener->configurationEvent(event); } catch (const std::exception& e) { log->log(ctkLogService::LOG_ERROR, e.what()); } catch (...) { log->log(ctkLogService::LOG_ERROR, "Unspecified exception"); } } private: ctkServiceTracker<ctkConfigurationListener*>* tracker; ctkLogService* log; ctkConfigurationEvent event; ctkServiceReference ref; }; ctkCMEventDispatcher::ctkCMEventDispatcher(ctkPluginContext* context, ctkLogService* log) : tracker(context), queue("ctkConfigurationListener Event Queue"), log(log) { } void ctkCMEventDispatcher::start() { tracker.open(); } void ctkCMEventDispatcher::stop() { tracker.close(); { QMutexLocker lock(&mutex); configAdminReference = 0; } } void ctkCMEventDispatcher::setServiceReference(const ctkServiceReference& reference) { QMutexLocker lock(&mutex); if (!configAdminReference) { configAdminReference = reference; } } void ctkCMEventDispatcher::dispatchEvent(ctkConfigurationEvent::Type type, const QString& factoryPid, const QString& pid) { const ctkConfigurationEvent event = createConfigurationEvent(type, factoryPid, pid); if (event.isNull()) return; QList<ctkServiceReference> refs = tracker.getServiceReferences(); foreach (ctkServiceReference ref, refs) { queue.put(new _DispatchEventRunnable(&tracker, log, event, ref)); } } ctkConfigurationEvent ctkCMEventDispatcher::createConfigurationEvent(ctkConfigurationEvent::Type type, const QString& factoryPid, const QString& pid) { if (!configAdminReference) { return ctkConfigurationEvent(); } return ctkConfigurationEvent(configAdminReference, type, factoryPid, pid); }
3c9a85e8eb77dac814618396696668c8a6a475e7
f51ef9e7249f42bb339996e9e024f1cd7433049a
/Chapter1/prob_04.cpp
e0f3ed71512bd0e66525c1251fd0de86a441f2e6
[]
no_license
kstar/CtCI-Testcases
8c414c9ba0136ea40cd331e8d7e482e14131f3e5
c8e16e725bccad64d11d978316d4d1ecb3ce90f1
refs/heads/master
2021-01-13T12:17:38.445104
2017-01-07T12:47:28
2017-01-07T12:47:28
78,273,685
0
0
null
null
null
null
UTF-8
C++
false
false
1,349
cpp
prob_04.cpp
/*************************************************************************** prob_04.cpp - ------------------- begin : Mon 10 Oct 2016 03:30:45 CDT copyright : (c) 2016 by Akarsh Simha email : akarsh.simha@kdemail.net ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ /* Project Includes */ /* STL Includes */ #include <vector> #include <string> #include <iostream> bool isPalindromePermutation( const std::string &s ) { } int main() { std::string s; std::getline( std::cin, s ); std::cout << std::string( isPalindromePermutation( s ) ? "true" : "false" ) << std::endl; }
1433d6b40c8859a1b65e3b67b4e841e91ecc8ac7
dcc4cf1b34bbe254d976447ae957388d7507a70f
/games-generated/Crash Course Game/Export/mac64/cpp/obj/include/openfl/events/JoystickEvent.h
92ddb2a015785a7d60ac343874835ecd5491908c
[ "MIT" ]
permissive
dylanmarcus/stencylworks
fe2bfd4e0bf16915bc9a7babcb681d7de5365dd5
06bc44e5d04101f61c70cabd64b23c69ef043c43
refs/heads/master
2020-12-25T23:47:22.985344
2015-04-22T02:21:18
2015-04-22T02:21:18
34,361,979
1
0
null
2015-04-22T02:21:18
2015-04-22T01:40:02
C++
UTF-8
C++
false
false
1,698
h
JoystickEvent.h
#ifndef INCLUDED_openfl_events_JoystickEvent #define INCLUDED_openfl_events_JoystickEvent #ifndef HXCPP_H #include <hxcpp.h> #endif #include <flash/events/Event.h> HX_DECLARE_CLASS2(flash,events,Event) HX_DECLARE_CLASS2(openfl,events,JoystickEvent) namespace openfl{ namespace events{ class HXCPP_CLASS_ATTRIBUTES JoystickEvent_obj : public ::flash::events::Event_obj{ public: typedef ::flash::events::Event_obj super; typedef JoystickEvent_obj OBJ_; JoystickEvent_obj(); Void __construct(::String type,hx::Null< bool > __o_bubbles,hx::Null< bool > __o_cancelable,hx::Null< int > __o_device,hx::Null< int > __o_id,hx::Null< Float > __o_x,hx::Null< Float > __o_y,hx::Null< Float > __o_z); public: static hx::ObjectPtr< JoystickEvent_obj > __new(::String type,hx::Null< bool > __o_bubbles,hx::Null< bool > __o_cancelable,hx::Null< int > __o_device,hx::Null< int > __o_id,hx::Null< Float > __o_x,hx::Null< Float > __o_y,hx::Null< Float > __o_z); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); ~JoystickEvent_obj(); HX_DO_RTTI; static void __boot(); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); ::String __ToString() const { return HX_CSTRING("JoystickEvent"); } virtual ::String toString( ); virtual ::flash::events::Event clone( ); Float z; Float y; Float x; int id; int device; Array< Float > axis; static ::String AXIS_MOVE; static ::String BALL_MOVE; static ::String BUTTON_DOWN; static ::String BUTTON_UP; static ::String HAT_MOVE; }; } // end namespace openfl } // end namespace events #endif /* INCLUDED_openfl_events_JoystickEvent */
3603d29d264417a3d32edcb95451387669e3d79f
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/net/filter/source_stream.cc
f31a83863f8f7923ed89098c2350e5bf546a798b
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
388
cc
source_stream.cc
// Copyright 2016 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/filter/source_stream.h" namespace net { SourceStream::SourceStream(SourceType type) : type_(type) {} SourceStream::~SourceStream() = default; std::string SourceStream::Description() const { return ""; } } // namespace net
7ac47b7f7ceb6513cae18fe9824ba21cf512e6db
11130633fe59b222da0696dc05e72ac30871a573
/Problem_Solving/baekjoon/BFS/1018_repaint_chess_board/repaintBoard.cpp
c1e7bce597248baf620e9ad9679f3b1787d762bc
[]
no_license
Jin-SukKim/Algorithm
024aa77c6bf63666910a1eb03407e808a05307ec
5f2a14fe1f64032126df55b1eadc1580a32735f3
refs/heads/master
2023-09-01T20:50:13.150780
2023-09-01T07:54:32
2023-09-01T07:54:32
263,555,962
4
0
null
2023-02-14T14:36:38
2020-05-13T07:24:51
C++
UTF-8
C++
false
false
1,008
cpp
repaintBoard.cpp
#include <iostream> #include <vector> #include <string> #include <algorithm> int fixLine(std::string& s, std::vector<char> &pattern, int j) { int count = 0; for (int m = j; m < j + 8; m++) { if (s[m] != pattern[m % 2]) count++; } return count; } int countBoard(std::vector<std::string>& board, int i, int j) { int countW = 0, countB = 0; std::vector<char> WB = {'W', 'B'}; std::vector<char> BW = {'B', 'W'}; for (int n = i; n < i + 8; n++) { countW += fixLine(board[n], n % 2 ? WB : BW, j); countB += fixLine(board[n], n % 2 ? BW : WB, j); } return std::min(countW, countB); } int main() { std::ios_base::sync_with_stdio(0); std::cin.tie(0); int n, m; std::cin >> n >> m; std::vector<std::string> board(n); for (int i = 0; i < n; i++) { std::string s; std::cin >> s; board[i] = s; } int res = INT_MAX; for (int i = 0; i + 8 <= n; i++) { for (int j = 0; j + 8 <= m; j++) { res = std::min(res, countBoard(board, i ,j)); } } std::cout << res; return 0; }
b11c6853bd51d8f822584f959c8c534519eb7021
c4be633d1d95cfce6b94669bc59352efc75d18fc
/BuilderBlackJack/Game.h
46a4d437700f5fff176ed35b92ef1ae78de87a27
[]
no_license
dmkrch/Blackjack
8a3b03b50f9dccd143bf09523629e202ef9e3037
ff647f9fa25ec486c09729f8ba89b394bbd1f1e6
refs/heads/master
2022-11-07T06:31:26.572741
2020-06-17T17:46:40
2020-06-17T17:46:40
273,040,919
0
0
null
null
null
null
UTF-8
C++
false
false
1,431
h
Game.h
#include <vector> #include "Player.h" #include <string> #include <vcl.h> #include "Main.h" #ifndef GameH #define GameH class Game { private: int rounds; double bet_money; // ammount of money that player must bet std::vector<Player> players; public: Game(); /* Function makes preparationos to the game */ void Make_Preparations_For_Game(int bots, String name, int money, int percents); /* Function adds players to the game */ void Add_Player(Player player); /* Functions returns true if at least one player still plays and false if noone plays */ bool Is_Playing(int i); /* Resets all player information for next round */ void Reset(); /* Functions retuens true if at least one bot still plays and false if noone plays */ bool Is_Bots_Playing(); /* Returns true if player is still playing and false if he passed */ bool Is_Player_Playing(); /* Player takes a card */ Card Player_Take(Deck* deck, TLabel* Label13, TButton* Button1, TButton* Button2); /* Player passes */ void Player_Pass(TLabel* Label13, TButton* Button1, TButton* Button2); int Amount_Of_Cards(int i); int Amount_Of_Bots(); Card Bot_Take(int i, Deck* deck, TLabel* Label13, int&, int&); int Get_Money(int i); int Get_Points(int i); String Get_Name(int i); std::vector<int> Find_Winners(); void Change_Money(std::vector<int> winners_id); void Bot_Pass(int i); void End_Of_Round(Game* game, Deck* deck); }; #endif
7853b4573fc04494f19fd58497234c79e32126c2
bf343216edcf9fb689cd2ef38d1ddf23138559b0
/dstSIMDMatrix.h
3f8835e129e58732445335d158de60bf32170c2f
[ "ISC" ]
permissive
hglm/DataSetTurbo
17a5a54b44c09941f237fe39ab1602e2ecf31a69
37d901cbfbeeaa52230d34b20adaac27a2f3432b
refs/heads/master
2021-01-01T05:41:23.829160
2015-05-02T09:08:48
2015-05-02T09:08:48
27,776,710
3
0
null
null
null
null
UTF-8
C++
false
false
32,888
h
dstSIMDMatrix.h
/* Copyright (c) 2014 Harm Hanemaaijer <fgenfb@yahoo.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef __DST_SIMD_MATRIX_H__ #define __DST_SIMD_MATRIX_H__ // This file is included by dstSIMD.h. When including that file directly, DST_SIMD_MODE // must be set to the SIMD type, which will be appended to exported function names. // The following SIMD functions for matrix multiplication have been implemented. // // SIMD 4x4 float matrix multiplication for matrices in column-major order. // Requires 16-byte alignment of the matrices. // void simd_matrix_multiply_4x4CM_float(const float * __restrict m1, // const float * __restrict__ m2, float * __restrict m3); // inline void simd_inline_matrix_multiply_4x4CM_float(const float * __restrict m1, // const float * __restrict__ m2, float * __restrict m3); // // Multiply 4x3 (4 rows, 3 rows) matrices in row-major order. The fourth // row is implicitly defined as (0.0f, 0.0f, 0.0f, 1.0f). // // void simd_matrix_multiply_4x3RM_float(const float * __restrict m1, // const float * __restrict__ m2, float * __restrict m3); // inline void simd_inline_matrix_multiply_4x3RM_float(const float * __restrict m1, // const float * __restrict__ m2, float * __restrict m3); // // Multiply 4x4 (column-major) and 4x3 (4 rows, 3 rows, row-major order) matrices. // The fourth row of the 4x3 matrix is implicitly defined as (0.0f, 0.0f, 0.0f, 1.0f). // // void simd_matrix_multiply_4x4CM_4x3RM_float(const float * __restrict m1, // const float * __restrict__ m2, float * __restrict m3); // inline void simd_inline_matrix_multiply_4x4CM_4x3RM_float(const float * __restrict m1, // const float * __restrict__ m2, float * __restrict m3); // // Classes have been defined for using SIMD to multiply a specific matrix with one or more // vertices. // // The following class is for a 4x4 matrix and can be initialized with matrices // (float arrays) in both row-major or column-major format. It can subsequently be used to // multiply the matrix with one or more vertices. // // class SIMDMatrix4x4; // // The following class is for a 4x3 matrix and can be initialized with matrices // (float arrays) in both row-major or column-major format. It requires // simd128_transpose4to3_float and simd_transpose3to4_float. // // class SIMDMatrix4x3; // // The following more elaborate functions, for matrix multiplication and // dot products, are provided both as an inline functions and as regular functions // that are implemented with the inline function. // // In some cases, using the inline version may allow the compiler to simplify // code (e.g. eliminate loads or stores) at the expense of greater overall code size // of the application; in many other cases, there is not much benefit from using // using the inline version while code size and CPU instruction cache utilization // may significantly benefit from using a regular function call. // SIMD 4x4 float matrix multiplication for matrices in column-major order. // Requires 16-byte alignment of the matrices. DST_API void SIMD_FUNC(dstMatrixMultiply4x4CM)(const float * DST_RESTRICT m1, const float * DST_RESTRICT m2, float * DST_RESTRICT m3); static DST_INLINE_ONLY void dstInlineMatrixMultiply4x4CM(const float * DST_RESTRICT m1, const float * DST_RESTRICT m2, float * DST_RESTRICT m3) { // m.n[column][row] // First value (row = 0, column = 0): // m1.n[0][0] * m2.n[0][0] + m1.n[1][0] * m2.n[0][1] + // m1.n[2][0] * m2.n[0][2] + m1.n[3][0] * m2.n[0][3] // Second value (row = 0, column = 1): // m1.n[0][0] * m2.n[1][0] + m1.n[1][0] * m2.n[1][1] + // m1.n[2][0] * m2.n[1][2] + m1.n[3][0] * m2.n[1][3] // Second row: // m1.n[0][1] * m2.n[0][0] + m1.n[1][1] * m2.n[0][1] + // m1.n[2][1] * m2.n[0][2] + m1.n[3][1] * m2.n[0][3], // Third row: // m1.n[0][2] * m2.n[0][0] + m1.n[1][2] * m2.n[0][1] + // m1.n[2][2] * m2.n[0][2] + m1.n[3][2] * m2.n[0][3], __simd128_float col0_m1 = simd128_load_float(&m1[0]); __simd128_float col1_m1 = simd128_load_float(&m1[4]); __simd128_float col2_m1 = simd128_load_float(&m1[8]); __simd128_float col3_m1 = simd128_load_float(&m1[12]); // For each result column. for (int i = 0; i < 4; i++) { __simd128_float col_m2 = simd128_load_float(&m2[i * 4]); __simd128_float v0 = simd128_replicate_float(col_m2, 0); __simd128_float v1 = simd128_replicate_float(col_m2, 1); __simd128_float v2 = simd128_replicate_float(col_m2, 2); __simd128_float v3 = simd128_replicate_float(col_m2, 3); // v0 = m1.n[0][i], v1 = m1.n[1][i], v2 = m1.n[2][i], ... __simd128_float result_col = simd128_add_float( simd128_add_float( simd128_mul_float(v0, col0_m1), simd128_mul_float(v1, col1_m1)), simd128_add_float( simd128_mul_float(v2, col2_m1), simd128_mul_float(v3, col3_m1)) ); simd128_store_float(&m3[i * 4], result_col); } } // Multiply 4x3 (3 rows, 4 columns) matrices in row-major order. The fourth // row is implicitly defined as (0.0f, 0.0f, 0.0f, 1.0f). void SIMD_FUNC(dstMatrixMultiply4x3RM)(const float * DST_RESTRICT m1, const float * DST_RESTRICT m2, float * DST_RESTRICT m3); static DST_INLINE_ONLY void dstInlineMatrixMultiply4x3RM(const float * DST_RESTRICT m1, const float * DST_RESTRICT m2, float * DST_RESTRICT m3) { __simd128_float row0 = simd128_load_float(&m2[0]); __simd128_float row1 = simd128_load_float(&m2[4]); __simd128_float row2 = simd128_load_float(&m2[8]); __simd128_float zeros = _mm_setzero_ps(); // For each row in m1. for (int i = 0; i < 3; i++) { // Get each column from row i in m1. __simd128_float row = simd128_load_float(&m1[i * 4]); __simd128_float v0 = simd128_replicate_float(row, 0); __simd128_float v1 = simd128_replicate_float(row, 1); __simd128_float v2 = simd128_replicate_float(row, 2); __simd128_float v3_mult = simd128_select_float( simd128_merge1_float(zeros, row), 0, 0, 0, 3); __simd128_float result_row = simd128_add_float( simd128_add_float( simd128_mul_float(v0, row0), simd128_mul_float(v1, row1)), simd128_add_float( simd128_mul_float(v2, row2), v3_mult) ); simd128_store_float(&m3[i * 4], result_row); } } // Multiply 4x4 (column-major) and 4x3 (4 rows, 3 rows, row-major order) matrices. // The fourth row of the 4x3 matrix is implicitly defined as (0.0f, 0.0f, 0.0f, 1.0f). DST_API void SIMD_FUNC(dstMatrixMultiplyVectors4x4CM4x3RM)(const float * DST_RESTRICT m1, const float * DST_RESTRICT m2, float * DST_RESTRICT m3); static DST_INLINE_ONLY void dstInlineMatrixMultiply4x4CM4x3RM( const float * DST_RESTRICT m1, const float * DST_RESTRICT m2, float * DST_RESTRICT m3) { __simd128_float col0 = simd128_load_float(&m1[0]); __simd128_float col1 = simd128_load_float(&m1[4]); __simd128_float col2 = simd128_load_float(&m1[8]); __simd128_float col3 = simd128_load_float(&m1[12]); __simd128_float m2_row0 = simd128_load_float(&m2[0]); __simd128_float m2_row1 = simd128_load_float(&m2[4]); __simd128_float m2_row2 = simd128_load_float(&m2[8]); for (int i = 0; i < 3; i++) { // Get column i from each row of m2. __simd128_float m2_coli_row0 = simd128_replicate_float(m2_row0, 0); __simd128_float m2_coli_row1 = simd128_replicate_float(m2_row1, 0); __simd128_float m2_coli_row2 = simd128_replicate_float(m2_row2, 0); m2_row0 = simd128_shift_right_float(m2_row0, 1); m2_row1 = simd128_shift_right_float(m2_row1, 1); m2_row2 = simd128_shift_right_float(m2_row2, 1); __simd128_float result_col = simd128_add_float( simd128_add_float( simd128_mul_float(m2_coli_row0, col0), simd128_mul_float(m2_coli_row1, col1)), simd128_mul_float(m2_coli_row2, col2) ); simd128_store_float(&m3[i * 4], result_col); } // Element 0 of m2_coli_row0/1/2 now contains column 3 of each row. __simd128_float m2_col3_row0 = simd128_replicate_float(m2_row0, 0); __simd128_float m2_col3_row1 = simd128_replicate_float(m2_row1, 0); __simd128_float m2_col3_row2 = simd128_replicate_float(m2_row2, 0); __simd128_float result_col3 = simd128_add_float( simd128_add_float( simd128_mul_float(m2_col3_row0, col0), simd128_mul_float(m2_col3_row1, col1)), simd128_add_float( simd128_mul_float(m2_col3_row2, col2), col3) ); simd128_store_float(&m3[3 * 4], result_col3); } // Multiply a single matrix with an array of vertices. DST_API void SIMD_FUNC(dstMatrixMultiplyVectors1xNM4x4CMV4)(int n, const float * DST_RESTRICT m, float * DST_RESTRICT v, float * DST_RESTRICT v_result); DST_API void SIMD_FUNC(dstMatrixMultiplyVectors1x4M4x4CMV4)(const float * DST_RESTRICT m, float * DST_RESTRICT v, float * DST_RESTRICT v_result); static DST_INLINE_ONLY void dstInlineMatrixMultiplyVectors1x4M4x4CMV4( __simd128_float m_column0, __simd128_float m_column1, __simd128_float m_column2, __simd128_float m_column3, const float *v, __simd128_float& m_result_0, __simd128_float& m_result_1, __simd128_float& m_result_2, __simd128_float& m_result_3) { // Load four vectors and transpose so that all similar coordinates are // stored in a single vector. __simd128_float m_v_x = simd128_load_float(&v[0]); __simd128_float m_v_y = simd128_load_float(&v[4]); __simd128_float m_v_z = simd128_load_float(&v[8]); __simd128_float m_v_w = simd128_load_float(&v[12]); simd128_transpose4_float(m_v_x, m_v_y, m_v_z, m_v_w); __simd128_float m_mul0, m_mul1, m_mul2, m_mul3; // Process the x coordinates. // m_column0 contains column 0 of the matrix. m_mul0 = simd128_mul_float(simd128_replicate_float(m_column0, 0), m_v_x); // m[0][0] * Vx[i] m_mul1 = simd128_mul_float(simd128_replicate_float(m_column1, 0), m_v_y); // + m[1][0] * Vy[i] m_mul2 = simd128_mul_float(simd128_replicate_float(m_column2, 0), m_v_z); // + m[2][0] * Vz[i] m_mul3 = simd128_mul_float(simd128_replicate_float(m_column3, 0), m_v_w); // + m[3][0] * Vw[i] __simd128_float m_result_x = simd128_add_float( simd128_add_float(m_mul0, m_mul1), simd128_add_float(m_mul2, m_mul3)); // Process the y coordinates. m_mul0 = simd128_mul_float(simd128_replicate_float(m_column0, 1), m_v_x); m_mul1 = simd128_mul_float(simd128_replicate_float(m_column1, 1), m_v_y); m_mul2 = simd128_mul_float(simd128_replicate_float(m_column2, 1), m_v_z); m_mul3 = simd128_mul_float(simd128_replicate_float(m_column3, 1), m_v_w); __simd128_float m_result_y = simd128_add_float( simd128_add_float(m_mul0, m_mul1), simd128_add_float(m_mul2, m_mul3)); // Process the z coordinates. m_mul0 = simd128_mul_float(simd128_replicate_float(m_column0, 2), m_v_x); m_mul1 = simd128_mul_float(simd128_replicate_float(m_column1, 2), m_v_y); m_mul2 = simd128_mul_float(simd128_replicate_float(m_column2, 2), m_v_z); m_mul3 = simd128_mul_float(simd128_replicate_float(m_column3, 2), m_v_w); __simd128_float m_result_z = simd128_add_float( simd128_add_float(m_mul0, m_mul1), simd128_add_float(m_mul2, m_mul3)); // Process the w coordinates. m_mul0 = simd128_mul_float(simd128_replicate_float(m_column0, 3), m_v_x); m_mul1 = simd128_mul_float(simd128_replicate_float(m_column1, 3), m_v_y); m_mul2 = simd128_mul_float(simd128_replicate_float(m_column2, 3), m_v_z); m_mul3 = simd128_mul_float(simd128_replicate_float(m_column3, 3), m_v_w); __simd128_float m_result_w = simd128_add_float( simd128_add_float(m_mul0, m_mul1), simd128_add_float(m_mul2, m_mul3)); // Transpose results so that each vector holds multiplication product. simd128_transpose4to4_float(m_result_x, m_result_y, m_result_z, m_result_w, m_result_0, m_result_1, m_result_2, m_result_3); } static DST_INLINE_ONLY void dstInlineMatrixMultiplyVectors1x4M4x4CMV4( __simd128_float m_column0, __simd128_float m_column1, __simd128_float m_column2, __simd128_float m_column3, const float * DST_RESTRICT v, float * DST_RESTRICT v_result) { __simd128_float m_result_0, m_result_1, m_result_2, m_result_3; dstInlineMatrixMultiplyVectors1x4M4x4CMV4(m_column0, m_column1, m_column2, m_column3, v, m_result_0, m_result_1, m_result_2, m_result_3); // Store the results. simd128_store_float(&v_result[0], m_result_0); simd128_store_float(&v_result[4], m_result_1); simd128_store_float(&v_result[8], m_result_2); simd128_store_float(&v_result[12], m_result_3); } static DST_INLINE_ONLY void dstInlineMatrixMultiplyVectors1x4M4x4CMV4( const float * DST_RESTRICT m, const float * DST_RESTRICT v, float * DST_RESTRICT v_result) { __simd128_float m_column0, m_column1, m_column2, m_column3; m_column0 = simd128_load_float(&m[0]); m_column1 = simd128_load_float(&m[4]); m_column2 = simd128_load_float(&m[8]); m_column3 = simd128_load_float(&m[12]); dstInlineMatrixMultiplyVectors1x4M4x4CMV4(m_column0, m_column1, m_column2, m_column3, v, v_result); } static DST_INLINE_ONLY void dstInlineMatrixMultiplyVectors1xNM4x4CMV4(int n, const float * DST_RESTRICT m, const float * DST_RESTRICT v, float * DST_RESTRICT v_result) { __simd128_float m_column0, m_column1, m_column2, m_column3; m_column0 = simd128_load_float(&m[0]); m_column1 = simd128_load_float(&m[4]); m_column2 = simd128_load_float(&m[8]); m_column3 = simd128_load_float(&m[12]); int i = 0; for (; i + 3 < n; i += 4) dstInlineMatrixMultiplyVectors1x4M4x4CMV4(m_column0, m_column1, m_column2, m_column3, &v[i * 4], &v_result[i * 4]); if (i < n) { __simd128_float m_row0, m_row1, m_row2, m_row3; simd128_transpose4to4_float(m_column0, m_column1, m_column2, m_column3, m_row0, m_row1, m_row2, m_row3); for (; i < n; i++) { __simd128_float m_v = simd128_load_float(&v[i * 4]); __simd128_float m_result = simd128_multiply_matrix4x4_vector4( m_row0, m_row1, m_row2, m_row3, m_v); simd128_store_float(&v_result[i * 4], m_result); } } } // Multiply a 4x4 matrix with an array of points (Point3DPadded). DST_API void SIMD_FUNC(dstMatrixMultiplyVectors1xNM4x4CMP3P)(int n, const float * DST_RESTRICT m, float * DST_RESTRICT v, float * DST_RESTRICT v_result); DST_API void SIMD_FUNC(dstMatrixMultiplyVectors1x4M4x4CMP3P)(const float * DST_RESTRICT m, float * DST_RESTRICT v, float * DST_RESTRICT v_result); static DST_INLINE_ONLY void dstInlineMatrixMultiplyVectors1x4M4x4CMP3P( __simd128_float m_column0, __simd128_float m_column1, __simd128_float m_column2, __simd128_float m_column3, const float *v, __simd128_float& m_result_0, __simd128_float& m_result_1, __simd128_float& m_result_2, __simd128_float& m_result_3) { // Load four vectors and transpose so that all similar coordinates are // stored in a single vector. __simd128_float m_v_x = simd128_load_float(&v[0]); __simd128_float m_v_y = simd128_load_float(&v[4]); __simd128_float m_v_z = simd128_load_float(&v[8]); __simd128_float m_v_w = simd128_load_float(&v[12]); simd128_transpose4_float(m_v_x, m_v_y, m_v_z, m_v_w); // Set m_v_w to (1.0, 1.0, 1.0, 1.0). m_v_w = simd128_replicate_float(simd128_set_first_and_clear_float(1.0f), 0); __simd128_float m_mul0, m_mul1, m_mul2, m_mul3; // Process the x coordinates. // m_column0 contains column 0 of the matrix. m_mul0 = simd128_mul_float(simd128_replicate_float(m_column0, 0), m_v_x); // m[0][0] * Vx[i] m_mul1 = simd128_mul_float(simd128_replicate_float(m_column1, 0), m_v_y); // + m[1][0] * Vy[i] m_mul2 = simd128_mul_float(simd128_replicate_float(m_column2, 0), m_v_z); // + m[2][0] * Vz[i] m_mul3 = simd128_mul_float(simd128_replicate_float(m_column3, 0), m_v_w); // + m[3][0] * Vw[i] __simd128_float m_result_x = simd128_add_float( simd128_add_float(m_mul0, m_mul1), simd128_add_float(m_mul2, m_mul3)); // Process the y coordinates. m_mul0 = simd128_mul_float(simd128_replicate_float(m_column0, 1), m_v_x); m_mul1 = simd128_mul_float(simd128_replicate_float(m_column1, 1), m_v_y); m_mul2 = simd128_mul_float(simd128_replicate_float(m_column2, 1), m_v_z); m_mul3 = simd128_mul_float(simd128_replicate_float(m_column3, 1), m_v_w); __simd128_float m_result_y = simd128_add_float( simd128_add_float(m_mul0, m_mul1), simd128_add_float(m_mul2, m_mul3)); // Process the z coordinates. m_mul0 = simd128_mul_float(simd128_replicate_float(m_column0, 2), m_v_x); m_mul1 = simd128_mul_float(simd128_replicate_float(m_column1, 2), m_v_y); m_mul2 = simd128_mul_float(simd128_replicate_float(m_column2, 2), m_v_z); m_mul3 = simd128_mul_float(simd128_replicate_float(m_column3, 2), m_v_w); __simd128_float m_result_z = simd128_add_float( simd128_add_float(m_mul0, m_mul1), simd128_add_float(m_mul2, m_mul3)); // Process the w coordinates. m_mul0 = simd128_mul_float(simd128_replicate_float(m_column0, 3), m_v_x); m_mul1 = simd128_mul_float(simd128_replicate_float(m_column1, 3), m_v_y); m_mul2 = simd128_mul_float(simd128_replicate_float(m_column2, 3), m_v_z); m_mul3 = simd128_mul_float(simd128_replicate_float(m_column3, 3), m_v_w); __simd128_float m_result_w = simd128_add_float( simd128_add_float(m_mul0, m_mul1), simd128_add_float(m_mul2, m_mul3)); // Transpose results so that each vector holds multiplication product. simd128_transpose4to4_float(m_result_x, m_result_y, m_result_z, m_result_w, m_result_0, m_result_1, m_result_2, m_result_3); } static DST_INLINE_ONLY void dstInlineMatrixMultiplyVectors1x4M4x4CMP3P( __simd128_float m_column0, __simd128_float m_column1, __simd128_float m_column2, __simd128_float m_column3, const float * DST_RESTRICT v, float * DST_RESTRICT v_result) { __simd128_float m_result_0, m_result_1, m_result_2, m_result_3; dstInlineMatrixMultiplyVectors1x4M4x4CMP3P(m_column0, m_column1, m_column2, m_column3, v, m_result_0, m_result_1, m_result_2, m_result_3); // Store the results. simd128_store_float(&v_result[0], m_result_0); simd128_store_float(&v_result[4], m_result_1); simd128_store_float(&v_result[8], m_result_2); simd128_store_float(&v_result[12], m_result_3); } static DST_INLINE_ONLY void dstInlineMatrixMultiplyVectors1x4M4x4CMP3P( const float * DST_RESTRICT m, const float * DST_RESTRICT v, float * DST_RESTRICT v_result) { __simd128_float m_column0, m_column1, m_column2, m_column3; m_column0 = simd128_load_float(&m[0]); m_column1 = simd128_load_float(&m[4]); m_column2 = simd128_load_float(&m[8]); m_column3 = simd128_load_float(&m[12]); dstInlineMatrixMultiplyVectors1x4M4x4CMP3P(m_column0, m_column1, m_column2, m_column3, v, v_result); } static DST_INLINE_ONLY void dstInlineMatrixMultiplyVectors1xNM4x4CMP3P(int n, const float * DST_RESTRICT m, const float * DST_RESTRICT v, float * DST_RESTRICT v_result) { __simd128_float m_column0, m_column1, m_column2, m_column3; m_column0 = simd128_load_float(&m[0]); m_column1 = simd128_load_float(&m[4]); m_column2 = simd128_load_float(&m[8]); m_column3 = simd128_load_float(&m[12]); int i = 0; for (; i + 3 < n; i += 4) dstInlineMatrixMultiplyVectors1x4M4x4CMP3P(m_column0, m_column1, m_column2, m_column3, &v[i * 4], &v_result[i * 4]); if (i < n) { __simd128_float m_row0, m_row1, m_row2, m_row3; simd128_transpose4to4_float(m_column0, m_column1, m_column2, m_column3, m_row0, m_row1, m_row2, m_row3); for (; i < n; i++) { // Load the point vector and make sure the w component is 1.0f. __simd128_float m_v = simd128_set_last_float( simd128_load_float(&v[i * 4]), 1.0f); __simd128_float m_result = simd128_multiply_matrix4x4_vector4( m_row0, m_row1, m_row2, m_row3, m_v); simd128_store_float(&v_result[i * 4], m_result); } } } // Classes for using SIMD to multiply a specific matrix with one or more vertices. // Because these classes are inline and not exported, there is no problem when the // library code is compiled multiple times for different SIMD implementations. // The following class is for a 4x4 matrix and can be initialized with matrices // (float arrays) in both row-major or column-major format. class SIMDMatrix4x4 { public : __simd128_float m_row0; __simd128_float m_row1; __simd128_float m_row2; __simd128_float m_row3; // Set row-major matrix data. DST_INLINE_ONLY void SetRM(const float *f) { // Load rows. m_row0 = simd128_load_float(&f[0]); m_row1 = simd128_load_float(&f[4]); m_row2 = simd128_load_float(&f[8]); m_row3 = simd128_load_float(&f[12]); } // Set column-major matrix data. DST_INLINE_ONLY void SetCM(const float *f) { // Load columns, then transpose to rows. SetRM(f); simd128_transpose4_float(m_row0, m_row1, m_row2, m_row3); } // Multiply with a four-float SIMD vector. // Note: This uses the inefficient horizontal addition primitive. DST_INLINE_ONLY void MultiplyVector4(const __simd128_float m_v, __simd128_float& m_result) const { __simd128_float m_mul0 = simd128_mul_float(m_row0, m_v); __simd128_float m_mul1 = simd128_mul_float(m_row1, m_v); __simd128_float m_mul2 = simd128_mul_float(m_row2, m_v); __simd128_float m_mul3 = simd128_mul_float(m_row3, m_v); m_result = simd128_horizontal_add2_float( simd128_horizontal_add2_float(m_mul0, m_mul1), simd128_horizontal_add2_float(m_mul2, m_mul3)); } DST_INLINE_ONLY void MultiplyVector4(const __simd128_float m_v, float &result_x, float &result_y, float &result_z, float& result_w) const { __simd128_float m_result; MultiplyVector4(m_v, m_result); result_x = simd128_get_float(m_result); result_y = simd128_get_float(simd128_shift_right_float(m_result, 1)); result_z = simd128_get_float(simd128_shift_right_float(m_result, 2)); result_w = simd128_get_float(simd128_shift_right_float(m_result, 3)); } DST_INLINE_ONLY void MultiplyVector4(const __simd128_float m_v, float *result) const { __simd128_float m_result; MultiplyVector4(m_v, m_result); simd128_store_float(result, m_result); } DST_INLINE_ONLY void MultiplyVector4(const float *v, __simd128_float m_result) const { __simd128_float m_v = simd128_load_float(&v[0]); MultiplyVector4(m_v, m_result); } DST_INLINE_ONLY void MultiplyVector4(const float *v, float &result_x, float &result_y, float &result_z, float& result_w) const { __simd128_float m_v = simd128_load_float(&v[0]); MultiplyVector4(m_v, result_x, result_y, result_z, result_w); } DST_INLINE_ONLY void MultiplyVector4(const float *v, float *result) const { __simd128_float m_v = simd128_load_float(&v[0]); MultiplyVector4(m_v, result); } }; #ifdef SIMD_HAVE_MATRIX4X3_VECTOR_MULTIPLICATION // The following class is for a 4x3 matrix and can be initialized with matrices // (float arrays) in both row-major or column-major format. // // Requires simd128_transpose4to3_float and simd_transpose3to4_float. class SIMDMatrix4x3 { public : __simd128_float m_row0; __simd128_float m_row1; __simd128_float m_row2; // Set row-major matrix data. DST_INLINE_ONLY void SetRM(const float *f) { // Load rows. m_row0 = simd128_load_float(&f[0]); m_row1 = simd128_load_float(&f[4]); m_row2 = simd128_load_float(&f[8]); } // Set column-major matrix data. DST_INLINE_ONLY void SetCM(const float *f) { // Load columns, then transpose to rows. __simd128_float m_col0 = simd128_load3_float(&f[0]); __simd128_float m_col1 = simd128_load3_float(&f[3]); __simd128_float m_col2 = simd128_load3_float(&f[6]); __simd128_float m_col3 = simd128_load3_float(&f[9]); simd128_transpose4to3_float(m_col0, m_col1, m_col2, m_col3, m_row0, m_row1, m_row2); } // Multiply with a three-float SIMD vector. // Note: This uses the inefficient horizontal addition primitive. // The fourth component of m_v (0.0f or 1.0f) makes a difference. DST_INLINE_ONLY void MultiplyVector3(const __simd128_float m_v, __simd128_float& m_result) const { __simd128_float m_mul0 = simd128_mul_float(m_row0, m_v); __simd128_float m_mul1 = simd128_mul_float(m_row1, m_v); __simd128_float m_mul2 = simd128_mul_float(m_row2, m_v); __simd128_float m_zeros = simd128_set_zero_float(); m_result = simd128_horizontal_add2_float( simd128_horizontal_add2_float(m_mul0, m_mul1), simd128_horizontal_add2_float(m_mul2, m_zeros)); } // The fourth component of m_v (0.0f or 1.0f) makes a difference. DST_INLINE_ONLY void MultiplyVector3(const __simd128_float m_v, float &result_x, float &result_y, float &result_z) const { __simd128_float m_result; MultiplyVector3(m_v, m_result); result_x = simd128_get_float(m_result); result_y = simd128_get_float(simd128_shift_right_float(m_result, 1)); result_z = simd128_get_float(simd128_shift_right_float(m_result, 2)); } // Unpacked three-float result vector (16-byte aligned, with four bytes padding). // The fourth component of source vector m_v (0.0f or 1.0f) makes a difference. DST_INLINE_ONLY void MultiplyVector3(const __simd128_float m_v, float *result) const { __simd128_float m_result; MultiplyVector3(m_v, m_result); simd128_store_float(result, m_result); } // Unpacked three-float source vector (16-byte aligned, with four bytes padding). DST_INLINE_ONLY void MultiplyVector3(const float *v, __simd128_float m_result) const { // Make sure the fourth element is zero after loading. __simd128_float m_v = simd128_set_last_zero_float(simd128_load_float(&v[0])); MultiplyVector3(m_v, m_result); } // Unpacked three-float source vector (16-byte aligned, with four bytes padding). DST_INLINE_ONLY void MultiplyVector3(const float *v, float &result_x, float &result_y, float &result_z) const { __simd128_float m_v = simd128_load_float(&v[0]); MultiplyVector3(m_v, result_x, result_y, result_z); } // Unpacked three-float source and result vectors (16-byte aligned, with four bytes padding). DST_INLINE_ONLY void MultiplyVector3(const float *v, float *result) const { __simd128_float m_v = simd128_set_last_zero_float(simd128_load_float(&v[0])); MultiplyVector3(m_v, result); } // Packed three-float result vector (unaligned). // The fourth component of source vector m_v (0.0f or 1.0f) makes a difference. DST_INLINE_ONLY void MultiplyVector3Packed(const __simd128_float m_v, float *result) const { __simd128_float m_result; MultiplyVector3(m_v, m_result); simd128_store3_float(result, m_result); } // Packed three-float source vector (unaligned). DST_INLINE_ONLY void MultiplyVector3Packed(const float *v, __simd128_float m_result) const { __simd128_float m_v = simd128_load3_float(&v[0]); MultiplyVector3(m_v, m_result); } // Packed three-float source vector (unaligned). DST_INLINE_ONLY void MultiplyVector3Packed(const float *v, float &result_x, float &result_y, float &result_z) const { __simd128_float m_v = simd128_load3_float(&v[0]); MultiplyVector3(m_v, result_x, result_y, result_z); } // Packed three-float source and result vectors (unaligned). DST_INLINE_ONLY void MultiplyVector3Packed(const float *v, float *result) const { __simd128_float m_v = simd128_load3_float(&v[0]); MultiplyVector3Packed(m_v, result); } // Four-float vectors including (fourth) w component. DST_INLINE_ONLY void MultiplyVector4(const __simd128_float m_v, __simd128_float& m_result) const { __simd128_float m_mul0 = simd128_mul_float(m_row0, m_v); __simd128_float m_mul1 = simd128_mul_float(m_row1, m_v); __simd128_float m_mul2 = simd128_mul_float(m_row2, m_v); // Set m_mul3 to (0.0f, 0.0f, 0.0f, m_v.w) __simd128_float m_mul3 = simd128_select_float( simd128_merge_float(simd128_set_zero_float(), m_v, 0, 0, 3, 3), 0, 0, 0, 3); m_result = simd128_horizontal_add2_float( simd128_horizontal_add2_float(m_mul0, m_mul1), simd128_horizontal_add2_float(m_mul2, m_mul3)); } // Result is stored in three seperate floats. DST_INLINE_ONLY void MultiplyVector4(const __simd128_float m_v, float &result_x, float &result_y, float &result_z) const { __simd128_float m_result; MultiplyVector4(m_v, m_result); result_x = simd128_get_float(m_result); result_y = simd128_get_float(simd128_shift_right_float(m_result, 1)); result_z = simd128_get_float(simd128_shift_right_float(m_result, 2)); } // Result is stored in four seperate floats. DST_INLINE_ONLY void MultiplyVector4(const __simd128_float m_v, float &result_x, float &result_y, float &result_z, float& result_w) const { __simd128_float m_result; MultiplyVector4(m_v, m_result); result_x = simd128_get_float(m_result); result_y = simd128_get_float(simd128_shift_right_float(m_result, 1)); result_z = simd128_get_float(simd128_shift_right_float(m_result, 2)); result_w = simd128_get_float(simd128_shift_right_float(m_result, 3)); } // Four-float result vector. DST_INLINE_ONLY void MultiplyVector4(const __simd128_float m_v, float *result) const { __simd128_float m_result; MultiplyVector4(m_v, m_result); simd128_store_float(result, m_result); } DST_INLINE_ONLY void MultiplyVector4(const float *v, __simd128_float m_result) const { __simd128_float m_v = simd128_load_float(&v[0]); MultiplyVector4(m_v, m_result); } DST_INLINE_ONLY void MultiplyVector4(const float *v, float &result_x, float &result_y, float &result_z, float& result_w) const { __simd128_float m_v = simd128_load_float(&v[0]); MultiplyVector4(m_v, result_x, result_y, result_z, result_w); } // Four-float result vector. DST_INLINE_ONLY void MultiplyVector4(const float *v, float *result) const { __simd128_float m_v = simd128_load_float(&v[0]); MultiplyVector4(m_v, result); } // Unpacked three-float source point vector (16-byte aligned, with four bytes padding). // Point vector has implicit w component of 1.0f. DST_INLINE_ONLY void MultiplyPoint3(const float *v, __simd128_float m_result) const { // Make sure the fourth element is 1.0f after loading. __simd128_float m_v = simd128_set_last_float(simd128_load_float(&v[0]), 1.0f); MultiplyVector3(m_v, m_result); } // Unpacked three-float source vector (16-byte aligned, with four bytes padding). DST_INLINE_ONLY void MultiplyPoint3(const float *v, float &result_x, float &result_y, float &result_z) const { __simd128_float m_v = simd128_set_last_float(simd128_load_float(&v[0]), 1.0f); MultiplyVector3(m_v, result_x, result_y, result_z); } // Unpacked three-float source and result vectors (16-byte aligned, with four bytes padding). DST_INLINE_ONLY void MultiplyPoint3(const float *v, float *result) const { __simd128_float m_v = simd128_set_last_float(simd128_load_float(&v[0]), 1.0f); MultiplyVector3(m_v, result); } }; #endif // defined(SIMD_HAVE_MATRIX4X3_VECTOR_MULTIPLICATION) #endif // defined(__DST_SIMD_MATRIX_H__)
576582eef3159ca6476cc1c807b66287182bce59
fd3f046382bc78baf573d164d0911ae7ab71571c
/sources/Pawn.cpp
7e8c5d6b56065939203c3ad17272655cd2713e57
[]
no_license
Minik7k2/Chinczyk
e7d7c6c799b65702312455c9f0b797e0bdbd5879
99ae7e0bf075c700f7e2100ac52c49155359e3d2
refs/heads/main
2023-02-24T02:35:48.377607
2021-01-28T20:09:12
2021-01-28T20:09:12
330,653,787
0
0
null
null
null
null
UTF-8
C++
false
false
1,274
cpp
Pawn.cpp
#include <iostream> #include <SFML/Graphics.hpp> #include "Pawn.hpp" #include <string> using namespace std; using namespace sf; Pawn::Pawn() { } void Pawn::draw(RenderWindow &window) { window.draw(pawnFigure); } void Pawn::set_color(int color) { pawnColor = color; loadTexture(); } void Pawn::loadTexture() { if(!pawnTexture.loadFromFile("../textures/pawns.png")) { } pawnFigure.setTexture(pawnTexture); pawnFigure.setTextureRect(IntRect(0, pawnColor*50, 50, 50)); } void Pawn::setOnStart() { pawnFigure.setPosition(startingPosition); fieldGroup = 0; } void Pawn::highlightOn() { pawnFigure.setTextureRect(IntRect(50, pawnColor*50, 50, 50)); pawnFigure.move(0,-5); } void Pawn::highlightOff() { pawnFigure.setTextureRect(IntRect(0, pawnColor*50, 50, 50)); pawnFigure.move(0,5); } void Pawn::changeFieldGroup(int x) { fieldGroup = x; } void Pawn::move(int cubeOutput, Board &board) { if(fieldGroup == 0) { changeFieldGroup(1); pawnFigure.setPosition(startingPoint); pathPosition = 0; // zeby sprawdzic ktory to -> pathElements[(playerID*14)+pathPosition] }else if(fieldGroup == 1) { pathPosition = pathPosition + cubeOutput; pawnFigure.setPosition(board.getPosition(board.pathElements[pathPosition])); } } Pawn::~Pawn() { }
b1519631dd8e6e4d411484eb3c0cd0f446c0129b
88cc420e751989fe8811851aa74e067d57360740
/Skyrim/src/FormComponents/Condition.cpp
306dd67e7cff038d6bdca155bb5a237df08100e7
[]
no_license
clayne/SKSEPlugins-powerof3
3085a213b07df78f4d915d9e53637a40a8245116
2d55e7f0966bfd23c330ef05a692213965554eda
refs/heads/master
2022-05-21T00:10:29.886599
2019-11-03T19:37:32
2019-11-03T19:37:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
664
cpp
Condition.cpp
#include "Skyrim/FormComponents/Condition.h" Condition::ComparisonFlags::ComparisonFlags() : isOR(false), usesAliases(false), global(false), usePackData(false), swapTarget(false), opCode(Opcode::kOpcode_Equal) {} Condition::Node::Node() : next(nullptr), comparisonValue(0.0), handle(0), unk0C(0), functionID(static_cast<FunctionID>(-1)), unk12(0), unk13(0), param1(nullptr), param2(nullptr), comparisonType(), referenceType(ReferenceTypes::kReferenceType_Subject) {} Condition::Condition() : head(nullptr) {} Condition::~Condition() { auto cur = head; while (cur) { auto next = cur->next; delete cur; cur = next; } head = nullptr; }
9b34e69ef3477078febdc76c7cb0c58d7d781c8d
230dc58a7f0a82cd11e3bef4a0ba56e3a341c5ad
/Timer.cpp
18a681fbc536f7bd9f8e29dfd4c2c7182e10bd93
[]
no_license
Zantiki/NetProg
6ea026c7d6f8239c7c45fffd307d7c57eca73272
0641292603871259b2da2eb75083cfee4c9acdcc
refs/heads/master
2021-01-01T00:53:26.273406
2020-03-05T09:44:27
2020-03-05T09:44:27
239,106,203
0
0
null
null
null
null
UTF-8
C++
false
false
534
cpp
Timer.cpp
// // Created by Jakob on unknown date. // #pragma once #include <chrono> using namespace std; class Timer { private: chrono::high_resolution_clock::time_point start; chrono::high_resolution_clock::time_point end; public: void set() { start = chrono::high_resolution_clock::now(); return; } double stop(int scale = 1) { end = chrono::high_resolution_clock::now(); chrono::duration<double, milli> duration = end - start; return duration.count()*scale; } };
a883f8cbf28a957c3316752921c019890a8d643d
6f04702ec9347d69feacb0a7f4d9fd21beaae387
/bit manipulation/power^2.cpp
c6e29202b67b0558fefdddf5c4485318670aab43
[]
no_license
MohdOwais22/DSA-cpp
b45889e80bab9462a17e9f39a7c205792b05edb0
22662241a1fffdad52722d579276df25ab473761
refs/heads/main
2023-09-01T23:05:16.966131
2021-10-26T15:59:28
2021-10-26T15:59:28
413,727,365
0
0
null
null
null
null
UTF-8
C++
false
false
203
cpp
power^2.cpp
//wap to check if given no. is power of 2 #include <iostream> using namespace std; bool isPower2(int n){ return (n && !(n & (n-1))); } int main(){ cout<<isPower2(11)<<endl; return 0; }
7b7d8d68cf0adb100273fad3933e0e5cb1e39567
78297bc868d588dd7a16cfea059ef7365ba18622
/lib/administration/zone/src/zone_administration.cpp
8430ffaae0eaae8f1ab539f51f7075733711b18b
[ "BSD-3-Clause" ]
permissive
irods/irods
ab72a41fdf05a4a905c3e3a97bb7ba3c2a6ae52d
f3ccaa842218e477395ebcf553639134433b63ee
refs/heads/main
2023-09-01T20:12:33.322002
2023-08-23T18:22:59
2023-08-31T13:41:31
14,724,975
381
167
NOASSERTION
2023-09-11T18:18:14
2013-11-26T18:10:18
C++
UTF-8
C++
false
false
4,009
cpp
zone_administration.cpp
#include "irods/zone_administration.hpp" #ifdef IRODS_ZONE_ADMINISTRATION_ENABLE_SERVER_SIDE_API // The server maintains a list of the zones known to the system. // The library takes advantage of this information where possible to avoid // unnecessary network and database operations. extern zoneInfo* ZoneInfoHead; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) #endif // IRODS_ZONE_ADMINISTRATION_ENABLE_SERVER_SIDE_API namespace irods::experimental::administration::NAMESPACE_IMPL { auto add_zone(RxComm& _comm, const std::string_view _zone_name, const zone_options& _opts) -> void { if (_zone_name.empty()) { // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay) THROW(SYS_INVALID_INPUT_PARAM, "Invalid zone name: cannot be empty"); } generalAdminInp_t input{}; input.arg0 = "add"; input.arg1 = "zone"; input.arg2 = _zone_name.data(); input.arg3 = "remote"; input.arg4 = _opts.connection_info.data(); input.arg5 = _opts.comment.data(); if (const auto ec = rxGeneralAdmin(&_comm, &input); ec < 0) { // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay) THROW(ec, fmt::format("Failed to add zone [{}].", _zone_name)); } } // add_zone auto remove_zone(RxComm& _comm, const std::string_view _zone_name) -> void { if (_zone_name.empty()) { // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay) THROW(SYS_INVALID_INPUT_PARAM, "Invalid zone name: cannot be empty"); } generalAdminInp_t input{}; input.arg0 = "rm"; input.arg1 = "zone"; input.arg2 = _zone_name.data(); if (const auto ec = rxGeneralAdmin(&_comm, &input); ec < 0) { // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay) THROW(ec, fmt::format("Failed to remove zone [{}].", _zone_name)); } } // remove_zone auto zone_exists([[maybe_unused]] RxComm& _comm, const std::string_view _zone_name) -> bool { if (_zone_name.empty()) { // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay) THROW(SYS_INVALID_INPUT_PARAM, "Invalid zone name: cannot be empty"); } #ifdef IRODS_ZONE_ADMINISTRATION_ENABLE_SERVER_SIDE_API for (const auto* p = ZoneInfoHead; p; p = p->next) { // NOLINT(readability-implicit-bool-conversion) if (_zone_name == p->zoneName) { // NOLINT(cppcoreguidelines-pro-bounds-array-to-pointer-decay) return true; } } #else const auto gql = fmt::format("select ZONE_NAME where ZONE_NAME = '{}'", _zone_name); for ([[maybe_unused]] auto&& row : irods::query{&_comm, gql}) { return true; } #endif // IRODS_ZONE_ADMINISTRATION_ENABLE_SERVER_SIDE_API return false; } // zone_exists auto zone_info(RxComm& _comm, const std::string_view _zone_name) -> std::optional<struct zone_info> { if (_zone_name.empty()) { // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay) THROW(SYS_INVALID_INPUT_PARAM, "Invalid zone name: cannot be empty"); } const auto gql = fmt::format("select ZONE_ID, ZONE_TYPE, ZONE_CONNECTION, ZONE_COMMENT where ZONE_NAME = '{}'", _zone_name); for (auto&& row : irods::query{&_comm, gql}) { // clang-format off return administration::zone_info{ .name{_zone_name}, .connection_info = std::move(row[2]), .comment = std::move(row[3]), .id = std::stoi(row[0]), .type = (row[1] == "local") ? zone_type::local : zone_type::remote }; // clang-format on } return std::nullopt; } // zone_info } // namespace irods::experimental::administration::NAMESPACE_IMPL
b95f2f1e4c5eb58110c0f92ec68db2131efce380
9d8e31db923601fa448871aa439aca7fb1bfca87
/StepWay/source/Platform/OpenGL/GLShader.cpp
09f69567fe36017971b5af98cc0b85c8bf89289f
[]
no_license
sashabusse/StepWay
19b6fad6bf02e3bf2f03ca34ea87f9d07bc388a8
c3746f5b54a68a9f1026bb538ed4da510d8225af
refs/heads/master
2021-06-28T08:50:55.859426
2020-10-09T14:25:27
2020-10-09T14:25:27
167,834,981
0
0
null
null
null
null
UTF-8
C++
false
false
5,268
cpp
GLShader.cpp
#include "StepWayPCH.h" #include "GLShader.h" #include "ErrorHandling.h" #include "glm/gtc/type_ptr.hpp" //remove #include <iostream> #include <fstream> namespace StepWay { namespace Graphics { namespace OpenGL { GLShader::GLShader(): m_Program(NULL) { } void GLShader::SetUpFromSource(const std::string& vertexSource, const std::string& fragmentSource) { m_Program = glCreateProgram(); uint vertexShader = ProcessShaderSource(GL_VERTEX_SHADER, vertexSource); uint fragmentShader = ProcessShaderSource(GL_FRAGMENT_SHADER, fragmentSource); glAttachShader(m_Program, vertexShader); glAttachShader(m_Program, fragmentShader); GL_CHECK_ERRORS(); glLinkProgram(m_Program); glValidateProgram(m_Program); GL_CHECK_ERRORS(); glDetachShader(m_Program, vertexShader); glDetachShader(m_Program, fragmentShader); GL_CHECK_ERRORS(); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); GL_CHECK_ERRORS(); } void GLShader::SetUpFromFile(const std::string & vertexPath, const std::string & fragmentPath) { std::string vertexSource = ReadFile(vertexPath); std::string fragmentSource = ReadFile(fragmentPath); SetUpFromSource(vertexSource, fragmentSource); } GLint GLShader::GetUniformLocation(const std::string& name) { auto iter = m_UniformLocations.find(name); if (iter != m_UniformLocations.end()) return iter->second; GLint location = glGetUniformLocation(m_Program, name.c_str()); GL_CHECK_ERRORS(); m_UniformLocations[name] = location; return location; } void GLShader::Compile(uint shader) { glCompileShader(shader); GLint result; glGetShaderiv(shader, GL_COMPILE_STATUS, &result); if (result == GL_FALSE) { GLint length; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); char* error = new char[length + 1]; glGetShaderInfoLog(shader, length, &length, &error[0]); glDeleteShader(shader); SW_CORE_ASSERT(false, error); } GL_CHECK_ERRORS(); } uint GLShader::ProcessShaderSource(GLenum shader_type, const std::string& source) { uint shader = glCreateShader(shader_type); GL_CHECK_ERRORS(); const char* tmpS = source.c_str(); glShaderSource(shader, 1, &(tmpS), NULL); GL_CHECK_ERRORS(); SW_CORE_TRACE("Compiling vertex shader. Source:\n" + source); Compile(shader); return shader; } std::string GLShader::ReadFile(const std::string& filePath) { std::ifstream file_stream(filePath); std::string nextLine; std::string text; while (std::getline(file_stream, nextLine)) { text += nextLine + "\n"; } return text; } void GLShader::ShutDown() { glDeleteProgram(m_Program); GL_CHECK_ERRORS(); } void GLShader::SetUpAsComputeShader(const std::string& filePath) { std::string source = ReadFile(filePath); SetUpAsComputeShaderFromSource(source); } void GLShader::SetUpAsComputeShaderFromSource(const std::string& source) { m_Program = glCreateProgram(); uint shader_id = ProcessShaderSource(GL_COMPUTE_SHADER, source); glAttachShader(m_Program, shader_id); GL_CHECK_ERRORS(); glLinkProgram(m_Program); glValidateProgram(m_Program); GL_CHECK_ERRORS(); glDetachShader(m_Program, shader_id); GL_CHECK_ERRORS(); glDeleteShader(shader_id); GL_CHECK_ERRORS(); } //now it's needed to bind before set uniform may be later do it some other way void GLShader::SetUniform(const std::string & name, const int val) { Bind(); glUniform1i(GetUniformLocation(name), val); GL_CHECK_ERRORS() } void GLShader::SetUniform(const std::string & name, const float val) { Bind(); glUniform1f(GetUniformLocation(name), val); GL_CHECK_ERRORS(); } void GLShader::SetUniform(const std::string & name, const glm::fvec2 & val) { Bind(); glUniform2f(GetUniformLocation(name), val.x, val.y); GL_CHECK_ERRORS(); } void GLShader::SetUniform(const std::string & name, const glm::fvec3 & val) { Bind(); glUniform3f(GetUniformLocation(name), val.x, val.y, val.z); GL_CHECK_ERRORS(); } void GLShader::SetUniform(const std::string & name, const glm::fvec4 & val) { Bind(); glUniform4f(GetUniformLocation(name), val.x, val.y, val.z, val.w); GL_CHECK_ERRORS(); } void GLShader::SetUniform(const std::string & name, const glm::fmat2 & val) { Bind(); glUniformMatrix2fv(GetUniformLocation(name), 1, false, glm::value_ptr(val)); GL_CHECK_ERRORS(); } void GLShader::SetUniform(const std::string & name, const glm::fmat3 & val) { Bind(); glUniformMatrix3fv(GetUniformLocation(name), 1, false, glm::value_ptr(val)); GL_CHECK_ERRORS(); } void GLShader::SetUniform(const std::string & name, const glm::fmat4 & val) { Bind(); GLint res = GetUniformLocation(name); GL_CHECK_ERRORS(); glUniformMatrix4fv(res, 1, false, glm::value_ptr(val)); GL_CHECK_ERRORS(); } void GLShader::Bind() { glUseProgram(m_Program); GL_CHECK_ERRORS() } void GLShader::Unbind() { glUseProgram(NULL); GL_CHECK_ERRORS() } } } }
818588ce023ad90efc3de5be3a08d85e1d25c114
639aa908a9cfc8cd7b969e328e092d3e847187ee
/src/using_markers_rviz/src/MarkerBasicControls.cpp
cfe7cec60cef66b44ba4bd007dda3258bba1473b
[]
no_license
pengboyemo/Ros
4f34eea65d8154bd2eb248bf62712deb1b059864
a2ca990fff76414d83ca5c3a622f53493e2deb9b
refs/heads/master
2022-05-01T10:53:34.194307
2022-04-01T07:44:03
2022-04-01T07:44:03
228,379,978
0
0
null
2019-12-16T12:14:14
2019-12-16T12:14:13
null
UTF-8
C++
false
false
21,148
cpp
MarkerBasicControls.cpp
#include <ros/ros.h> //系统文件 #include <interactive_markers/interactive_marker_server.h> //// 可视化交互 物体 interactive marker类型 visualization_msgs::InteractiveMarker #include <interactive_markers/menu_handler.h> //鼠标下拉菜单库 #include <tf/transform_broadcaster.h>//坐标变换库 #include <tf/tf.h> #include <math.h> //数学函数库 using namespace visualization_msgs; //使用可视化消息命名空间 调用变量时 省去visualization_msgs:: // 交互式marker服务器类型的 共享指针 服务器 多个() boost::shared_ptr<interactive_markers::InteractiveMarkerServer> server; //visualization_msgs类下 interactive_markers::MenuHandler 鼠标下拉菜单变量 interactive_markers::MenuHandler menu_handler; // // 创建 灰色 正方体 盒子 marker 函数 Marker makeBox( InteractiveMarker &msg ) { //msg 为 visualization_msgs::InteractiveMarker msg //visualization_msgs类下::Marker Marker marker; marker.type = Marker::CUBE; marker.scale.x = msg.scale * 0.45; marker.scale.y = msg.scale * 0.45; marker.scale.z = msg.scale * 0.45; marker.color.r = 0.5; marker.color.g = 0.5; marker.color.b = 0.5; marker.color.a = 1.0; return marker; } // // 创建 可视化 相关控制 InteractiveMarkerControl& makeBoxControl( InteractiveMarker &msg ) { //msg 为 visualization_msgs::InteractiveMarker msg //visualization_msgs类下::InteractiveMarkerControl InteractiveMarkerControl control; control.always_visible = true; //可见 control.markers.push_back( makeBox(msg) ); //先创建盒子 再创建控制 msg.controls.push_back( control ); //控制附着交互式marker return msg.controls.back(); } // %EndTag(Box)% //坐标系的回调函数 // %Tag(frameCallback)% void frameCallback(const ros::TimerEvent&) { static uint32_t counter = 0; //计数器 static tf::TransformBroadcaster br; //创建坐标广播 tf::Transform tf; //创建坐标转换变量 ros::Time time = ros::Time::now(); //时间戳 tf.setOrigin(tf::Vector3(0.0, 0.0, sin(float(counter)/140.0) * 2.0)); //与参考坐标系的相对位置 tf.setRotation(tf::Quaternion(0.0, 0.0, 0.0, 1.0)); //四元素 //发送坐标变换 变换内容 时间戳 父坐标系(参考坐标系) 子坐标系 br.sendTransform(tf::StampedTransform(tf, time, "base_link", "moving_frame"));//广播转换 tf.setOrigin(tf::Vector3(0.0, 0.0, 0.0)); tf.setRotation(tf::createQuaternionFromRPY(0.0, float(counter)/140.0, 0.0)); br.sendTransform(tf::StampedTransform(tf, time, "base_link", "rotating_frame")); counter++; } // %EndTag(frameCallback)% //鼠标操作等交互操作 回调函数 向控制台反馈 位置信息 void processFeedback( const visualization_msgs::InteractiveMarkerFeedbackConstPtr &feedback ) { std::ostringstream s; //创建总信息反馈 s << "Feedback from marker '" << feedback->marker_name << "' " << " / control '" << feedback->control_name << "'"; std::ostringstream mouse_point_ss; //创建鼠标位置反馈信息 if( feedback->mouse_point_valid ) //鼠标位置有效 { mouse_point_ss << " at " << feedback->mouse_point.x << ", " << feedback->mouse_point.y << ", " << feedback->mouse_point.z << " in frame " << feedback->header.frame_id; } switch ( feedback->event_type ) { case visualization_msgs::InteractiveMarkerFeedback::BUTTON_CLICK: //点击 ROS_INFO_STREAM( s.str() << ": button click" << mouse_point_ss.str() << "." ); break; case visualization_msgs::InteractiveMarkerFeedback::MENU_SELECT: //菜单 ROS_INFO_STREAM( s.str() << ": menu item " << feedback->menu_entry_id << " clicked" << mouse_point_ss.str() << "." ); break; case visualization_msgs::InteractiveMarkerFeedback::POSE_UPDATE: //更新位置 ROS_INFO_STREAM( s.str() << ": pose changed" << "\nposition = " << feedback->pose.position.x << ", " << feedback->pose.position.y << ", " << feedback->pose.position.z << "\norientation = " << feedback->pose.orientation.w << ", " << feedback->pose.orientation.x << ", " << feedback->pose.orientation.y << ", " << feedback->pose.orientation.z << "\nframe: " << feedback->header.frame_id << " time: " << feedback->header.stamp.sec << "sec, " << feedback->header.stamp.nsec << " nsec" ); break; case visualization_msgs::InteractiveMarkerFeedback::MOUSE_DOWN: //鼠标按下 确定 ROS_INFO_STREAM( s.str() << ": mouse down" << mouse_point_ss.str() << "." ); break; case visualization_msgs::InteractiveMarkerFeedback::MOUSE_UP: //鼠标松开 弹起 ROS_INFO_STREAM( s.str() << ": mouse up" << mouse_point_ss.str() << "." ); break; } server->applyChanges(); //可交互marker服务器 根据鼠标选择 更新(应用)变换(位置、方向等) } // %EndTag(processFeedback)% // 排列 marker void alignMarker( const visualization_msgs::InteractiveMarkerFeedbackConstPtr &feedback ) { geometry_msgs::Pose pose = feedback->pose; //姿态 位置 x y z 方向 w x y z pose.position.x = round(pose.position.x-0.5)+0.5; //位置标准化 取为最近 的整数位置点 pose.position.y = round(pose.position.y-0.5)+0.5; // //从之前的位置 排列 到现在的位置 ROS_INFO_STREAM( feedback->marker_name << ":" << " aligning position = " << feedback->pose.position.x << ", " << feedback->pose.position.y << ", " << feedback->pose.position.z << " to " << pose.position.x << ", " << pose.position.y << ", " << pose.position.z ); server->setPose( feedback->marker_name, pose ); //更新姿态信息 server->applyChanges(); //应用改变 } // %EndTag(alignMarker)% //产生 min ~ max 随机数 函数 double rand( double min, double max ) { //确保 max >= min double temp; if(min>max) {temp=max; max=min; min=temp; } //产生0~1随机数 double t = (double)rand() / (double)RAND_MAX; //产生min~max随机数 return min + t*(max-min); } // void saveMarker( InteractiveMarker int_marker ) { server->insert(int_marker);//保存 server->setCallback(int_marker.name, &processFeedback);//调用改变 反馈信息 } // 六自由度 void make6DofMarker( bool fixed, unsigned int interaction_mode, const tf::Vector3& position, bool show_6dof ) { //visualization_msgs类下::InteractiveMarker InteractiveMarker int_marker; int_marker.header.frame_id = "base_link"; //参考坐标系 tf::pointTFToMsg(position, int_marker.pose.position);//与左边变换相关联 可变换int_marker.header.frame_id int_marker.scale = 1; //尺寸 int_marker.name = "simple_6dof";//名字 int_marker.description = "Simple 6-DOF Control";// 描述 // insert a box makeBoxControl(int_marker);//// 创建 可视化 相关控制 盒子 marker int_marker.controls[0].interaction_mode = interaction_mode; //交互模式 //交互模式 visualization_msgs::InteractiveMarkerControl::MOVE_AXIS; //visualization_msgs类下::InteractiveMarkerControl InteractiveMarkerControl control; if ( fixed ) //坐标系是否固定 { int_marker.name += "_fixed"; int_marker.description += "\n(fixed orientation)"; control.orientation_mode = InteractiveMarkerControl::FIXED;//方向固定 } //确定交互模式 MOVE_AXIS(沿轴移动 )MOVE_3D (任意方向移动,方向不变) ROTATE_3D(任意方向旋转,位置不可动) MOVE_ROTATE_3D(任意移动+方向可变) //show_6dof 的模式没有 要自己搭建 if (interaction_mode != visualization_msgs::InteractiveMarkerControl::NONE)//交互模式非空 { std::string mode_text; if( interaction_mode == visualization_msgs::InteractiveMarkerControl::MOVE_3D ) mode_text = "MOVE_3D"; if( interaction_mode == visualization_msgs::InteractiveMarkerControl::ROTATE_3D ) mode_text = "ROTATE_3D"; if( interaction_mode == visualization_msgs::InteractiveMarkerControl::MOVE_ROTATE_3D ) mode_text = "MOVE_ROTATE_3D"; int_marker.name += "_" + mode_text; // int_marker.description = std::string("3D Control") + (show_6dof ? " + 6-DOF controls" : "") + "\n" + mode_text; } //show_6dof 的模式没有 要自己搭建 仅仅x y z三个方向的移动和x y z三个轴的旋转 if(show_6dof) { //方向 x轴旋转 x 轴移动 control.orientation.w = 1; control.orientation.x = 1; control.orientation.y = 0; control.orientation.z = 0; control.name = "rotate_x"; control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS;//旋转 int_marker.controls.push_back(control); control.name = "move_x"; control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS;//移动 int_marker.controls.push_back(control); //方向 z轴旋转 control.orientation.w = 1; control.orientation.x = 0; control.orientation.y = 1; control.orientation.z = 0; control.name = "rotate_z"; control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS;//旋转 int_marker.controls.push_back(control); control.name = "move_z"; control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS;//移动 int_marker.controls.push_back(control); //方向 x轴旋转 control.orientation.w = 1; control.orientation.x = 0; control.orientation.y = 0; control.orientation.z = 1; control.name = "rotate_y"; control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS;//旋转 int_marker.controls.push_back(control); control.name = "move_y"; control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS;//移动 int_marker.controls.push_back(control); } server->insert(int_marker);//保存 server->setCallback(int_marker.name, &processFeedback);//调用改变 反馈信息 if (interaction_mode != visualization_msgs::InteractiveMarkerControl::NONE) menu_handler.apply( *server, int_marker.name ); } // %EndTag(6DOF)% // 创建随机六轴模式的交互式marker void makeRandomDofMarker( const tf::Vector3& position ) { //visualization_msgs类下::InteractiveMarker InteractiveMarker int_marker; int_marker.header.frame_id = "base_link"; //参考坐标系 tf::pointTFToMsg(position, int_marker.pose.position);//与左边变换相关联 可变换int_marker.header.frame_id int_marker.scale = 1;//尺寸 int_marker.name = "6dof_random_axes";// 名字 int_marker.description = "6-DOF\n(Arbitrary Axes)";// 描述 makeBoxControl(int_marker); // 创建 可视化 相关控制 盒子 marker InteractiveMarkerControl control; //创建 可视化 相关控制 for ( int i=0; i<3; i++ ) //随机六轴 { control.orientation.w = rand(-1,1);//随机 control.orientation.x = rand(-1,1); control.orientation.y = rand(-1,1); control.orientation.z = rand(-1,1); control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS; int_marker.controls.push_back(control); control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS; int_marker.controls.push_back(control); } server->insert(int_marker);//保存 server->setCallback(int_marker.name, &processFeedback); //调用改变 反馈信息 } // %EndTag(RandomDof)% // 任意方向移动 + 面对使用者方向的 旋转 void makeViewFacingMarker( const tf::Vector3& position ) { //visualization_msgs类下::InteractiveMarker InteractiveMarker int_marker; int_marker.header.frame_id = "base_link"; //参考坐标系 tf::pointTFToMsg(position, int_marker.pose.position);//与左边变换相关联 可变换int_marker.header.frame_id int_marker.scale = 1;//尺寸 int_marker.name = "view_facing";// 名字 int_marker.description = "View Facing 6-DOF";// 描述 InteractiveMarkerControl control; //创建 可视化 相关控制 // make a control that rotates around the view axis 旋转 control.orientation_mode = InteractiveMarkerControl::VIEW_FACING; control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS; control.orientation.w = 1; control.name = "rotate"; int_marker.controls.push_back(control); // create a box in the center which should not be view facing, // but move in the camera plane. 移动 control.orientation_mode = InteractiveMarkerControl::VIEW_FACING; control.interaction_mode = InteractiveMarkerControl::MOVE_PLANE; control.independent_marker_orientation = true; control.name = "move"; control.markers.push_back( makeBox(int_marker) ); control.always_visible = true; int_marker.controls.push_back(control); server->insert(int_marker); server->setCallback(int_marker.name, &processFeedback); } // %EndTag(ViewFacing)% // 直升机 maker //xoy平面旋转+平移+ z轴上下移动 void makeQuadrocopterMarker( const tf::Vector3& position ) { //visualization_msgs类下::InteractiveMarker InteractiveMarker int_marker; int_marker.header.frame_id = "base_link"; //参考坐标系 tf::pointTFToMsg(position, int_marker.pose.position);//与左边变换相关联 可变换int_marker.header.frame_id int_marker.scale = 1;//尺寸 int_marker.name = "quadrocopter";//名字 int_marker.description = "Quadrocopter";//描述 makeBoxControl(int_marker);//创建盒子 InteractiveMarkerControl control;//创建控制 control.orientation.w = 1; control.orientation.x = 0; control.orientation.y = 1;//轴旋转 ? Y->Z Z->Y?? control.orientation.z = 0; control.interaction_mode = InteractiveMarkerControl::MOVE_ROTATE; //xoy平面旋转+平移 int_marker.controls.push_back(control); control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS; //z轴上下移动 int_marker.controls.push_back(control); server->insert(int_marker); server->setCallback(int_marker.name, &processFeedback); } // %EndTag(Quadrocopter)% // %Tag(ChessPiece)% xoy平面移动 void makeChessPieceMarker( const tf::Vector3& position ) { InteractiveMarker int_marker; int_marker.header.frame_id = "base_link"; tf::pointTFToMsg(position, int_marker.pose.position); int_marker.scale = 1; int_marker.name = "chess_piece"; int_marker.description = "Chess Piece\n(2D Move + Alignment)"; InteractiveMarkerControl control; control.orientation.w = 1; control.orientation.x = 0; control.orientation.y = 1; control.orientation.z = 0; control.interaction_mode = InteractiveMarkerControl::MOVE_PLANE; int_marker.controls.push_back(control); // make a box which also moves in the plane control.markers.push_back( makeBox(int_marker) ); control.always_visible = true; int_marker.controls.push_back(control); // we want to use our special callback function server->insert(int_marker); server->setCallback(int_marker.name, &processFeedback); // set different callback for POSE_UPDATE feedback server->setCallback(int_marker.name, &alignMarker, visualization_msgs::InteractiveMarkerFeedback::POSE_UPDATE ); } // %EndTag(ChessPiece)% // %Tag(PanTilt)% 两个方向的旋转 void makePanTiltMarker( const tf::Vector3& position ) { InteractiveMarker int_marker; int_marker.header.frame_id = "base_link"; tf::pointTFToMsg(position, int_marker.pose.position); int_marker.scale = 1; int_marker.name = "pan_tilt"; int_marker.description = "Pan / Tilt"; makeBoxControl(int_marker); InteractiveMarkerControl control; control.orientation.w = 1; control.orientation.x = 0; control.orientation.y = 1; control.orientation.z = 0; control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS; control.orientation_mode = InteractiveMarkerControl::FIXED; int_marker.controls.push_back(control); control.orientation.w = 1; control.orientation.x = 0; control.orientation.y = 0; control.orientation.z = 1; control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS; control.orientation_mode = InteractiveMarkerControl::INHERIT; int_marker.controls.push_back(control); server->insert(int_marker); server->setCallback(int_marker.name, &processFeedback); } // %EndTag(PanTilt)% // %Tag(Menu)% 创建带有 鼠标菜单 的marker void makeMenuMarker( const tf::Vector3& position ) { InteractiveMarker int_marker; int_marker.header.frame_id = "base_link"; tf::pointTFToMsg(position, int_marker.pose.position); int_marker.scale = 1; int_marker.name = "context_menu";//名字 int_marker.description = "Context Menu\n(Right Click)";//描述 InteractiveMarkerControl control;//控制 control.interaction_mode = InteractiveMarkerControl::MENU;//控制模式 control.name = "menu_only_control";//控制名字 Marker marker = makeBox( int_marker );//创建盒子 control.markers.push_back( marker );//应用控制模式 control.always_visible = true; //永久可视化 int_marker.controls.push_back(control); server->insert(int_marker); server->setCallback(int_marker.name, &processFeedback); menu_handler.apply( *server, int_marker.name ); } // %EndTag(Menu)% // %Tag(Button)% 创建带有 鼠标点击的marker void makeButtonMarker( const tf::Vector3& position ) { InteractiveMarker int_marker; int_marker.header.frame_id = "base_link"; tf::pointTFToMsg(position, int_marker.pose.position); int_marker.scale = 1; int_marker.name = "button"; int_marker.description = "Button\n(Left Click)"; InteractiveMarkerControl control; control.interaction_mode = InteractiveMarkerControl::BUTTON; control.name = "button_control"; Marker marker = makeBox( int_marker ); control.markers.push_back( marker ); control.always_visible = true; int_marker.controls.push_back(control); server->insert(int_marker); server->setCallback(int_marker.name, &processFeedback); } // %EndTag(Button)% // 移动的marker void makeMovingMarker( const tf::Vector3& position ) { InteractiveMarker int_marker; int_marker.header.frame_id = "moving_frame"; tf::pointTFToMsg(position, int_marker.pose.position); int_marker.scale = 1; int_marker.name = "moving"; int_marker.description = "Marker Attached to a\nMoving Frame"; InteractiveMarkerControl control; control.orientation.w = 1; control.orientation.x = 1; control.orientation.y = 0; control.orientation.z = 0; control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS; //x轴方向旋转 control.orientation.x = 1 int_marker.controls.push_back(control); control.interaction_mode = InteractiveMarkerControl::MOVE_PLANE; //任意方向移动 control.always_visible = true; control.markers.push_back( makeBox(int_marker) ); int_marker.controls.push_back(control); server->insert(int_marker); server->setCallback(int_marker.name, &processFeedback); } // %EndTag(Moving)% // %Tag(main)% int main(int argc, char** argv) { ros::init(argc, argv, "basic_controls"); //初始化ros系统 注册节点 节点名字为 basic_controls ros::NodeHandle nh; // create a timer to update the published transforms 参考系更新frameCallback ros::Timer frame_timer = nh.createTimer(ros::Duration(0.01), frameCallback); server.reset( new interactive_markers::InteractiveMarkerServer("basic_controls","",false) ); ros::Duration(0.1).sleep(); menu_handler.insert( "First Entry", &processFeedback ); menu_handler.insert( "Second Entry", &processFeedback ); //子菜单句柄sub_menu_handle interactive_markers::MenuHandler::EntryHandle sub_menu_handle = menu_handler.insert( "Submenu" ); menu_handler.insert( sub_menu_handle, "First Entry", &processFeedback ); menu_handler.insert( sub_menu_handle, "Second Entry", &processFeedback ); tf::Vector3 position; position = tf::Vector3(-3, 3, 0); //位置 make6DofMarker( false, visualization_msgs::InteractiveMarkerControl::NONE, position, true ); position = tf::Vector3( 0, 3, 0); make6DofMarker( true, visualization_msgs::InteractiveMarkerControl::NONE, position, true ); position = tf::Vector3( 3, 3, 0); makeRandomDofMarker( position ); position = tf::Vector3(-3, 0, 0); make6DofMarker( false, visualization_msgs::InteractiveMarkerControl::ROTATE_3D, position, false ); position = tf::Vector3( 0, 0, 0); make6DofMarker( false, visualization_msgs::InteractiveMarkerControl::MOVE_ROTATE_3D, position, true ); position = tf::Vector3( 3, 0, 0); make6DofMarker( false, visualization_msgs::InteractiveMarkerControl::MOVE_3D, position, false ); position = tf::Vector3(-3,-3, 0); makeViewFacingMarker( position ); position = tf::Vector3( 0,-3, 0); makeQuadrocopterMarker( position ); position = tf::Vector3( 3,-3, 0); makeChessPieceMarker( position ); position = tf::Vector3(-3,-6, 0); makePanTiltMarker( position ); position = tf::Vector3( 0,-6, 0); makeMovingMarker( position ); position = tf::Vector3( 3,-6, 0); makeMenuMarker( position ); position = tf::Vector3( 0,-9, 0); makeButtonMarker( position ); server->applyChanges(); //应用改变 ros::spin(); //给ros控制权 server.reset(); } // %EndTag(main)%
406901cf42442f0746de3e26a30714162d820872
23c88b6e0d21a68689dbef1cf89ef284947c2497
/BattleTank/Source/BattleTank/Private/TankMovementComponent.cpp
6684889c1ec45fb28778a29428f6245a76e7acb0
[]
no_license
mikeohl/Battle-Tank
2137be209b09206585e6222d94fdeeefa1645057
4cc1a8cfa7027642559e98551078472b7d6a2be8
refs/heads/master
2020-03-15T23:17:02.943413
2019-08-06T15:08:53
2019-08-06T15:08:53
132,387,359
0
0
null
null
null
null
UTF-8
C++
false
false
2,311
cpp
TankMovementComponent.cpp
// Copyright Michael Ohl 2018-2019 #include "TankMovementComponent.h" #include "TankTrack.h" void UTankMovementComponent::InitializeTracks(UTankTrack* LeftTrackToSet, UTankTrack* RightTrackToSet) { LeftTrack = LeftTrackToSet; RightTrack = RightTrackToSet; } void UTankMovementComponent::Move(float Intensity) { auto Name = GetOwner()->GetName(); //UE_LOG(LogTemp, Warning, TEXT("%s throttle set to %f"), *Name, Intensity); if (!ensure(LeftTrack && RightTrack)) { UE_LOG(LogTemp, Warning, TEXT("Track(s) missing from tank")); return; } // Cap backwards throttle at 1/2 maximum //FMath::Clamp<float>(Intensity, -0.5f, 1.0f); if (abs(Intensity) > .5f) //UE_LOG(LogTemp, Warning, TEXT("%s: Stick Intensity: %f"), *Name, Intensity); RightTrack->SetThrottle(Intensity); LeftTrack->SetThrottle(Intensity); } // TODO: Find a better way to mix intensities. Not a fan of this implementation void UTankMovementComponent::Turn(float Intensity) { //auto Name = GetName(); //UE_LOG(LogTemp, Warning, TEXT("%s throttle set to %f"), *Name, Intensity); if (!ensure(LeftTrack && RightTrack)) { UE_LOG(LogTemp, Warning, TEXT("Track(s) missing from tank")); return; } // Cap backwards throttle at 1/2 maximum //Intensity = Intensity / 2; auto Name = GetOwner()->GetName(); if (abs(Intensity) > .5f) //UE_LOG(LogTemp, Warning, TEXT("%s: Stick Intensity: %f"), *Name, Intensity); RightTrack->SetThrottle(-Intensity); LeftTrack->SetThrottle(Intensity); } void UTankMovementComponent::RequestDirectMove(const FVector& MoveVelocity, bool bForceMaxSpeed) { // UE_LOG(LogTemp, Warning, TEXT("%s: RequestDirectMove Called"), *GetOwner()->GetName()) auto TankForwardDirection = GetOwner()->GetActorForwardVector().GetSafeNormal(); auto AIMoveIntention = MoveVelocity.GetSafeNormal(); auto MoveIntensity = FVector::DotProduct(AIMoveIntention, TankForwardDirection); Move(MoveIntensity); auto TurnIntensity = FVector::CrossProduct(TankForwardDirection, AIMoveIntention).Z; Turn(TurnIntensity); // UE_LOG(LogTemp, Warning, TEXT("%s: Move Intensity = %f, Turn Intensity = %f"), *GetOwner()->GetName(), MoveIntensity, TurnIntensity); //UE_LOG(LogTemp, Warning, TEXT("RequestDirectMove Called")); }
619f17609be8693702c377dd7f96846c2873d10c
d76db7ad41bd606b2e7c4ef9ff1cef135626954e
/AISimulation/src/TestEnvironment/Physics/Collision/DistanceTo.h
994590ff59068bb37f52387c6eddd339914b04d4
[]
no_license
agarzonp/AISimulation
02ca2af09e723638be53af3f28d75afb43359f72
9fbbd4e8e453b9a6fcd34624a97ae64c8299774b
refs/heads/master
2021-09-15T10:57:56.917612
2018-05-31T07:03:58
2018-05-31T07:03:58
121,757,789
1
0
null
2018-05-09T23:31:29
2018-02-16T14:08:23
C++
UTF-8
C++
false
false
283
h
DistanceTo.h
#ifndef DISTANCE_TO_H #define DISTANCE_TO_H class DistanceTo { public: // Distance from point to plane static float Plane(const MathGeom::Vector3& point, const PlaneCollider& plane) { return glm::dot(point, plane.normal) - plane.d; } }; #endif // !DISTANCE_FROM_POINT_TO_H
3833bb364c5712b8ed16f4794fa8a29dd05508f6
4cba6096a61c0ccda0adfa0e3de6b9402c93a005
/gimp/data/blueprints/back/usr/include/c++/7/ext/pb_ds/detail/trie_policy/sample_trie_access_traits.hpp
b0f41693028b5283bb26dc8f482f9ac369b44477
[]
no_license
StanfordSNR/gg-results
da3de3ce52235c187c6178b0ceab32df2526abf5
16ac020603e4b1ef96b2d8c27d1683724cbb30b8
refs/heads/master
2021-08-06T16:11:06.747488
2019-01-05T21:41:24
2019-01-05T21:41:24
103,858,663
1
1
null
null
null
null
UTF-8
C++
false
false
163
hpp
sample_trie_access_traits.hpp
// GGHASH:VycTFzwl2OoMuqSQKL4Etkr6McP8KYR6ngFbrPC_FWec00000a99 #ifndef PB_DS_SAMPLE_TRIE_E_ACCESS_TRAITS_HPP #define PB_DS_SAMPLE_TRIE_E_ACCESS_TRAITS_HPP #endif
a7fc50237415013052cd522dd06625bb2c2d7bd7
911bcc69ad209abeae1b48fd05f616ed9f56f66b
/code/bsformula.h
62322842a6073f6845e5919702380ed59174c9a1
[]
no_license
Juice-2020/Implied-Tree-Pricer
38e31f8a0a740295b6de2cd28f534305e1ddd0ca
f6bdac651260578c11c00166af4259c3de116fb4
refs/heads/master
2022-12-16T03:33:16.129497
2020-09-20T08:17:00
2020-09-20T08:17:00
297,028,538
0
0
null
null
null
null
UTF-8
C++
false
false
1,406
h
bsformula.h
// // BSformula.h // Implied Tree // // Created by 陈家豪 on 2020/4/13. // Copyright © 2020 陈家豪. All rights reserved. // #ifndef BSformula_h #define BSformula_h #include <iostream> #include <cmath> // for std::exp() #include <cassert> // for assertion on inputs enum OptType{C, P}; double cnorm(double x); double bsformula(OptType optType,double K,double T, double S_0,double sigma,double rate,double q) { double sigmaSqrtT = sigma * std::sqrt(T); double d1 = (std::log(S_0 / K) + (rate-q) * T)/sigmaSqrtT + 0.5 * sigmaSqrtT; double d2 = d1 - sigmaSqrtT; double V_0; switch (optType) { case C: V_0 = S_0 *exp(-q*T)* cnorm(d1) - K * exp(-rate*T) * cnorm(d2); break; case P: V_0 = K * exp(-rate*T) * cnorm(-d2) - S_0 *exp(-q*T)* cnorm(-d1); break; default: throw "unsupported optionType"; } // std::cout << "The--"<< optType << " --option price is " << V_0 << std::endl; return V_0; } double cnorm(double x) { // constants double a1 = 0.254829592; double a2 = -0.284496736; double a3 = 1.421413741; double a4 = -1.453152027; double a5 = 1.061405429; double p = 0.3275911; int sign = 1; if (x < 0) sign = -1; x = fabs(x)/sqrt(2.0); double t = 1.0/(1.0 + p*x); double y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x); return 0.5*(1.0 + sign*y); } #endif /* BSformula_h */
d22d2577305b70c1c294af991d6627a26d76be55
9870e11c26c15aec3cc13bc910e711367749a7ff
/TC/tc_tchs_1_500.cpp
3d833ddd450d1f29ab5d7cda1b6957fe1027cc1c
[]
no_license
liuq901/code
56eddb81972d00f2b733121505555b7c7cbc2544
fcbfba70338d3d10bad2a4c08f59d501761c205a
refs/heads/master
2021-01-15T23:50:10.570996
2016-01-16T16:14:18
2016-01-16T16:14:18
12,918,517
1
1
null
null
null
null
UTF-8
C++
false
false
1,955
cpp
tc_tchs_1_500.cpp
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cctype> #include <ctime> #include <cstdarg> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <vector> #include <list> #include <deque> #include <stack> #include <queue> #include <set> #include <map> #include <utility> #include <algorithm> #include <numeric> #include <functional> #include <bitset> #include <complex> #include <iterator> #include <memory> #define SQR(x) ((x)*(x)) #define MAXN 1010 #define MAXM 1010 using namespace std; typedef long long ll; typedef long double ld; const int inf=1061109567; const int mod=1000000007; const double eps=1e-7; const double pi=acos(-1.0); struct SymbolFrequency { double language(vector <string> fre,vector <string> text) { int n=text.size(); for (int i=0;i<n;i++) { string s=text[i]; int l=s.size(); for (int j=0;j<l;j++) if (isalpha(s[j])) a+=s[j]; } double ans=1e100; n=fre.size(); for (int i=0;i<n;i++) ans=min(ans,count(fre[i])); return(ans); } private: string a; double count(string s) { double p[26]={0}; stringstream sin(s); int tot=0; while (1) { char ch; int x; sin>>ch>>x; p[ch-'a']=x/100.0; tot+=x; if (tot==100) break; } double ans=0; int n=a.size(),sum[26]={0}; for (int i=0;i<n;i++) sum[a[i]-'a']++; for (int i=0;i<26;i++) ans+=SQR(fabs(sum[i]-p[i]*n)); return(ans); } }; int main() { int n,m; vector <string> a,b; scanf("%d%*c",&n); a.resize(n); for (int i=0;i<n;i++) getline(cin,a[i]); scanf("%d%*c",&m); b.resize(m); for (int i=0;i<m;i++) getline(cin,b[i]); SymbolFrequency p; printf("%lf\n",p.language(a,b)); system("pause"); return(0); }
79ac3d4b219a1fdb9b998cd98f1671f6ba1cdbeb
fe833387af9d007043af2a596ec9d151fe422ee4
/QDbusSender/send.cpp
c2df7bf1d9dba62233b13dfc29ce2eac702c8415
[]
no_license
SeanLee00/qtPathview
5ad739b8d098636d00b03e1d2d50a9ec35ded14a
b9072b1cf21e40e0faaa1eb34311785442a5b800
refs/heads/master
2023-02-23T07:32:14.713297
2021-01-25T03:50:00
2021-01-25T03:50:00
332,268,567
0
0
null
null
null
null
UTF-8
C++
false
false
1,161
cpp
send.cpp
#include "send.h" #include <QTime> #include <QRandomGenerator> SEND::SEND(QObject *parent) { careateRandomNumber(); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(update())); timer->start(1000); // WorkerThread t; t.start(); } void SEND::careateRandomNumber() { QTime now = QTime::currentTime(); qsrand(now.msec()); rand = qrand(); } void SEND::send() { careateRandomNumber(); if (QDBusConnection::sessionBus().isConnected()) { msg = QDBusMessage::createSignal("/", "org.example.chat", "message"); qDebug() << "send message : " << rand; msg << rand; QDBusConnection::sessionBus().send(msg); emit numberChanged(); } } void SEND::dbusConnection() { QDBusConnection::sessionBus().registerObject("/", this); if (QDBusConnection::sessionBus().isConnected()) { msg = QDBusMessage::createSignal("/", "org.example.chat", "message"); } } int SEND::number() { return rand; } int SEND::randnumber() { return rand; } void SEND::update() { send(); } void WorkerThread::run() { qDebug()<<"From worker thread: "; }
599107a2a799fae5bdbb3c5fabd7a97f17eaf705
b1e740d32f7c47358821469547fade2657596231
/AirPollution/Group.cpp
a9d134e90ba1fd571f77c7c31de9d9e0d768829f
[]
no_license
FelixHoer/AirPollution
cd5edf7b29e06b2f0eccda25228b10691556da7e
c389846bfd460a5dda008c97a648f17697a5afde
refs/heads/master
2016-09-06T01:10:39.868052
2015-01-24T15:55:45
2015-01-26T14:40:47
26,930,156
0
1
null
null
null
null
UTF-8
C++
false
false
3,221
cpp
Group.cpp
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <glm/glm.hpp> #include "Window.h" #include "Group.h" Group::Group() {} Group::Group(char* name) : Node(name) {} void Group::addChild(Node* child) { child->setParent(this); children.push_back(child); recalculateBoundingSphere(); } void Group::addChildFirst(Node* child) { child->setParent(this); children.push_front(child); recalculateBoundingSphere(); } void Group::removeChild(Node* child) { child->setParent(NULL); children.remove(child); recalculateBoundingSphere(); } Node* Group::findDown(const std::string& name) { Node* result = NULL; result = Node::findDown(name); if (result != NULL) return result; for (std::list<Node*>::iterator it = children.begin(); it != children.end(); ++it) { result = (*it)->findDown(name); if (result != NULL) return result; } return NULL; } void Group::setup() { for (std::list<Node*>::iterator it = children.begin(); it != children.end(); ++it) (*it)->setup(); initializeBoundingSphere(); } void Group::update(const int delta_time) { for (std::list<Node*>::iterator it = children.begin(); it != children.end(); ++it) (*it)->update(delta_time); } void Group::updateVisibility(const glm::mat4& matrix) { BoundingSphere transformed_sphere = getBoundingSphere()->transform(matrix); Status status = Window::camera->getFrustum()->check(transformed_sphere); if (status == Status::OUTSIDE) setVisible(false); else if (status == Status::INSIDE) setVisible(true); else { visible = true; for (std::list<Node*>::iterator it = children.begin(); it != children.end(); ++it) (*it)->updateVisibility(matrix); } } void Group::setVisible(bool v) { visible = v; for (std::list<Node*>::iterator it = children.begin(); it != children.end(); ++it) (*it)->setVisible(v); } void Group::render(const glm::mat4& matrix) { if (!visible) return; // object was culled for (std::list<Node*>::iterator it = children.begin(); it != children.end(); ++it) (*it)->render(matrix); if (Window::debug) bounding_sphere.render(matrix); } void Group::initializeBoundingSphere() { glm::vec3 center = glm::vec3(0, 0, 0); int count = 0; // calculate center of mass of children for (std::list<Node*>::iterator it = children.begin(); it != children.end(); ++it) { BoundingSphere* sphere = (*it)->getBoundingSphere(); if (sphere == NULL) continue; center += sphere->getCenter(); count++; } if (count == 0) // count might be 0 { bounding_sphere = BoundingSphere(); return; } center /= count; // find max distance (center of child + radius) from that center float max_distance = 0.0f; for (std::list<Node*>::iterator it = children.begin(); it != children.end(); ++it) { BoundingSphere* sphere = (*it)->getBoundingSphere(); if (sphere == NULL) continue; float distance = glm::length(center - sphere->getCenter()) + sphere->getRadius(); if (distance > max_distance) max_distance = distance; } bounding_sphere = BoundingSphere(center, max_distance); } BoundingSphere* Group::getBoundingSphere() { return &bounding_sphere; }
13944f54b08e06d4b3419a0018d4e1ba7c72a796
71501709864eff17c873abbb97ffabbeba4cb5e3
/llvm13.0.0/libc/src/string/memcpy.cpp
5e70e00db1b9173bfb3920cabade7d8f5f79d89f
[ "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
LEA0317/LLVM-VideoCore4
d08ba6e6f26f7893709d3285bdbd67442b3e1651
7ae2304339760685e8b5556aacc7e9eee91de05c
refs/heads/master
2022-06-22T15:15:52.112867
2022-06-09T08:45:24
2022-06-09T08:45:24
189,765,789
1
0
NOASSERTION
2019-06-01T18:31:29
2019-06-01T18:31:29
null
UTF-8
C++
false
false
2,441
cpp
memcpy.cpp
//===-- Implementation of memcpy ------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// #include "src/string/memcpy.h" #include "src/__support/common.h" #include "src/string/memory_utils/elements.h" namespace __llvm_libc { // Design rationale // ================ // // Using a profiler to observe size distributions for calls into libc // functions, it was found most operations act on a small number of bytes. // This makes it important to favor small sizes. // // The tests for `count` are in ascending order so the cost of branching is // proportional to the cost of copying. // // The function is written in C++ for several reasons: // - The compiler can __see__ the code, this is useful when performing Profile // Guided Optimization as the optimized code can take advantage of branching // probabilities. // - It also allows for easier customization and favors testing multiple // implementation parameters. // - As compilers and processors get better, the generated code is improved // with little change on the code side. static void memcpy_impl(char *__restrict dst, const char *__restrict src, size_t count) { // Use scalar strategies (_1, _2, _3 ...) using namespace __llvm_libc::scalar; if (count == 0) return; if (count == 1) return Copy<_1>(dst, src); if (count == 2) return Copy<_2>(dst, src); if (count == 3) return Copy<_3>(dst, src); if (count == 4) return Copy<_4>(dst, src); if (count < 8) return Copy<HeadTail<_4>>(dst, src, count); if (count < 16) return Copy<HeadTail<_8>>(dst, src, count); if (count < 32) return Copy<HeadTail<_16>>(dst, src, count); if (count < 64) return Copy<HeadTail<_32>>(dst, src, count); if (count < 128) return Copy<HeadTail<_64>>(dst, src, count); return Copy<Align<_32, Arg::Src>::Then<Loop<_32>>>(dst, src, count); } LLVM_LIBC_FUNCTION(void *, memcpy, (void *__restrict dst, const void *__restrict src, size_t size)) { memcpy_impl(reinterpret_cast<char *>(dst), reinterpret_cast<const char *>(src), size); return dst; } } // namespace __llvm_libc
580ecac4656489a444b5dc4d374d1c7966ae4f9d
04a07a5a707b09c92a7704a01b6f6c1ad7c77012
/src/exstl.cpp
4a310a65b12002df21066960591166fd3253a2db
[]
no_license
centixkadon/libexstl
0d5bea01d1439098568a4ec5c3fc346d969a9a19
5129434adb4bad25e039ca9fa06b98d23c2e0a5e
refs/heads/master
2021-04-15T04:45:45.125008
2018-04-15T16:33:36
2018-04-15T16:33:36
126,823,783
0
0
null
null
null
null
UTF-8
C++
false
false
628
cpp
exstl.cpp
#include "exstl.hpp" namespace std { thread_ostream tout(cout); thread_endl_type tendl(tout.endl()); namespace chrono { tick_diff::tick_diff(string const & str) : _str(str), _tick(high_resolution_clock::now()), _diff(0.0) { _str = _str.substr(0, tick_diff_length); _str += string(tick_diff_length - _str.size(), ' ') + ": "; } string tick_diff::diff() { _diff = duration_cast<duration<double>>(high_resolution_clock::now() - _tick).count(); stringstream ss; ss << _str << _diff; return ss.str(); } size_t tick_diff::tick_diff_length = 10; } // namespace chrono } // namespace std
894b6fd449ab3fc8f750d8a8182cda2e4e63be63
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_949_httpd-2.4.18.cpp
3b8404f303c3ff035863524d8a0ad95e65f790b1
[]
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
246
cpp
httpd_repos_function_949_httpd-2.4.18.cpp
static const char *expr_var_fn(ap_expr_eval_ctx_t *ctx, const void *data) { char *var = (char *)data; SSLConnRec *sslconn = ssl_get_effective_config(ctx->c); return sslconn ? ssl_var_lookup_ssl(ctx->p, sslconn, ctx->r, var) : NULL; }
07db64acbf04601bf702ddd7ebc1250bc1ffa95c
b61d6293c1e09cc4482a9dbb5993ea5f22a3edd3
/Project/Engine/Primitives.h
6a7dc7359d14eb1a3f8f2f93748b011408e857b9
[]
no_license
Freedomhan/3D-Game-Engine
c4e56e9328297afcb46769bda578cdeb97e188d7
c2b7dfa752e0cdca13d7203b594228966fa2c0e1
refs/heads/master
2021-01-25T14:32:37.332171
2016-10-28T01:54:40
2016-10-28T01:54:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
503
h
Primitives.h
//Protection #pragma once //For data types #include <GL\glew.h> //Cleaner static class cPrimitives { public: static const GLfloat CUBE_VERT_DATA[24]; //This stores default shape data - Formatting is: x, y, z static const GLushort CUBE_ELEMENT_DATA[36]; //Contain faces, by joining verts static const GLfloat CUBE_UV_DATA[16]; //Holds UV data for the cube static const GLushort PLANE_ELEMENT_DATA[6]; //Join the two tris static const GLfloat PLANE_VERT_DATA[20]; //A plane - two tris } Primitives;
fbb87f995ef61616f9747f33dacffd957954f9e0
345862d6b503d624d17abce4855d2da066ee91df
/editor02/FPSCamera.h
4efa9a6fb77cbf208065b5cf4ddbb24cd2e01a4d
[]
no_license
trezor555/Editor
04b6dbd01aaffbcd5b6243a3ef5cce3576b82e11
badd28a35d35d57e3aee217733aeb0a548ff4bc1
refs/heads/master
2021-01-17T10:20:11.238029
2016-07-26T22:17:58
2016-07-26T22:17:58
56,427,385
0
0
null
null
null
null
UTF-8
C++
false
false
1,169
h
FPSCamera.h
#ifndef FPSCAMERA_H #define FPSCAMERA_H #define GLEW_STATIC #include <glm.hpp> #include <GL/glew.h> #include "BoundingBox.h" class FPSCamera { public: FPSCamera(float ScreenWidth, float ScreenHeight); FPSCamera(float ScreenWidth, float ScreenHeight, glm::vec3 cameraPos, glm::vec3 cameraFront, glm::vec3 cameraUp); void Update(float deltaTime); void MouseMove(double xpos, double ypos); void KeyboardMove(bool* keys, float deltaTime); float GetCameraSpeed(); void SetCameraSpeed(float val); glm::mat4 GetView(); glm::vec3 GetPosition(); void CreatePerspectiveProjection(int screenWidth, int screentHeight, float fov, float nearPlane, float farPlane); glm::mat4& GetProjectionMatrix(); BoundingBox bbox; glm::mat4 m_ProjectionMatrix; glm::vec3 cameraPos; glm::vec3 cameraFront; glm::vec3 cameraUp; GLfloat yaw; // Yaw is initialized to -90.0 degrees since a yaw of 0.0 results in a direction vector pointing to the right (due to how Eular angles work) so we initially rotate a bit to the left. GLfloat pitch; GLfloat lastX; GLfloat lastY; bool firstMouse; glm::mat4 view; void SetScreenSize(int width, int height); float m_cameraSpeed; }; #endif
64aa8bd2032cad59027a851257c75fc99777fdec
aeecb7f226ffa7c68b793455c1b8cc59acd89c32
/PathFinding/HybridAstar/Heuristics/HolonomicHeuristic.hpp
7a04b5943fdc0c0c10eb321200452e2b17cce9d1
[]
no_license
zhangzhecqut/carmen_hybrid_astar
72de9c46b377f4a15be1c7bc26a6ba414a6736e6
a538f7b7dec724a8eca37fc2a5f211cee3de979e
refs/heads/master
2021-09-25T04:14:17.128854
2018-10-18T01:27:06
2018-10-18T01:27:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,198
hpp
HolonomicHeuristic.hpp
/* // Author: josiasalexandre@gmail.com // Based on the Matt Bradley's Masters Degree thesis and work // Copyright (c) 2012 Matt Bradley // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef HYBRID_ASTAR_HOLOMIC_HEURISTIC_INFO_HPP #define HYBRID_ASTAR_HOLOMIC_HEURISTIC_INFO_HPP #include <queue> #include <opencv2/opencv.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include "../../../GridMap/InternalGridMap.hpp" #include "../../../Entities/Pose2D.hpp" #include "../../../Entities/Circle.hpp" #include "../../../PriorityQueue/PriorityQueue.hpp" namespace astar { class HolonomicHeuristic { private: // the current grid map reference pointer astar::InternalGridMapRef grid; // the current start pose astar::Pose2D start; // the current goal pose astar::Pose2D goal; // the complete circle double twopi; // the step angle double piece_angle; // a helper circle node class CircleNode { public: // the current circle reference astar::Circle circle; // the g cost value double g; // the total cost, included heuristic value double f; // the circle radius double radius; // the parent node CircleNode *parent; bool explored; // basic constructor CircleNode(const astar::Circle c, double r, double g_, double f_, CircleNode *p) : circle(c), g(g_), f(f_), radius(r), parent(p), explored(false) {} // the copy constructor CircleNode(const CircleNode& cn) : circle(cn.circle), g(cn.g), f(cn.f), radius(cn.circle.r), parent(nullptr), explored(cn.explored) {} // basic destructor ~CircleNode() { // reset the parent node to nullptr parent = nullptr; } // update the node values void UpdateValues(const CircleNode &cn) { // copy the node values // the circle position circle.position = cn.circle.position; // the circle radius circle.r = cn.circle.r; // the cost g = cn.g; // the heuristic cost f = cn.f; // the parent pointer parent = cn.parent; } // < operator overloading, for priority queue compare purpose bool operator<(const CircleNode &cn) const { return f < cn.f; } // Assignment operator void operator=(const CircleNode &cn) { // copy the values UpdateValues(cn); } }; // define the syntatic sugar types typedef CircleNode* CircleNodePtr; typedef CircleNode& CircleNodeRef; // define a comparator class class CircleNodePtrDistanceComparator { public: // operator overloading bool operator() (CircleNodePtr a, CircleNodePtr b) { // the default c++ stl is a max heap, so wee need to invert here return a->f > b->f; } }; // define a comparator class class CircleNodePtrRadiusComparator { public: // operator overloading bool operator() (CircleNodePtr a, CircleNodePtr b) { // the default c++ stl is a max heap return a->radius < b->radius; } }; // define the CircleNodePtrArray class CircleNodePtrArray { public: // the vector of circle nodes std::vector<CircleNodePtr> circles; }; // define the syntatic sugar type typedef CircleNodePtrArray* CircleNodePtrArrayPtr; typedef CircleNodePtrArray& CircleNodePtrArrayRef; // the resulting circle path CircleNodePtrArray circle_path; // the nearest open queue std::priority_queue<CircleNodePtr, std::vector<CircleNodePtr>, CircleNodePtrDistanceComparator> nearest_open; // the largest open queue std::priority_queue<CircleNodePtr, std::vector<CircleNodePtr>, CircleNodePtrRadiusComparator> largest_open; // the closed set std::vector<CircleNodePtr> closed; // THE HEURISTIC PRIVATE METHODS // verify if two circles overlaps with each other bool Overlap(const astar::Circle&, const astar::Circle&, double factor = 0.5); // get the nearest circle from a given pose CircleNodePtr NearestCircleNode(const astar::Pose2D&); // get the circle children CircleNodePtrArrayPtr GetChildren(CircleNodePtr); // clear the current CircleNodePtr sets void RemoveAllCircleNodes(); // rebuild the circle array void RebuildCirclePath(CircleNodePtr cn); // try to find a circle node inside the closed set bool NotExist(CircleNodePtr cn); // explore a given circle node void ExploreCircleNode(CircleNodePtr cn); // process a given node bool ProcessNode(CircleNodeRef goal, CircleNodePtr cn); // the current search method bool SpaceExploration(); // show void ShowCirclePath(); public: // THE HEURISTIC OBJECT METHODS // basic constructor HolonomicHeuristic(astar::InternalGridMapRef map); // update the Heuristic circle path with a new grid map, start and goal poses void UpdateHeuristic(astar::InternalGridMapRef, const astar::Pose2D&, const astar::Pose2D&); // get the heuristic value given a pose double GetHeuristicValue(const astar::Pose2D&); }; } #endif
29c75059ffbff03a706ee30e85b5ebd91602da28
7ab3757bde602ebe0b2f9e49d7e1d5f672ee150a
/easyeditor/include/ee/Camera.h
e7b0fbd837df0b677c2f06452f61585e7bcc85e1
[ "MIT" ]
permissive
brucelevis/easyeditor
310dc05084b06de48067acd7ef5d6882fd5b7bba
d0bb660a491c7d990b0dae5b6fa4188d793444d9
refs/heads/master
2021-01-16T18:36:37.012604
2016-08-11T11:25:20
2016-08-11T11:25:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
602
h
Camera.h
#ifndef _EASYEDITOR_CAMERA_H_ #define _EASYEDITOR_CAMERA_H_ #include <SM_Vector.h> #include <string> namespace ee { class Camera { public: virtual ~Camera() {} virtual std::string Type() const = 0; virtual void Reset() = 0; virtual sm::vec2 TransPosScreenToProject(int x, int y, int width, int height) const = 0; virtual sm::vec2 TransPosProjectToScreen(const sm::vec2& proj, int width, int height) const = 0; virtual void UpdateModelView() const = 0; virtual float GetScale() const = 0; virtual const sm::vec2& GetPosition() const = 0; }; // Camera } #endif // _EASYEDITOR_CAMERA_H_
0193e8c9d487dd4d2c8e9bdd3b477b253396b61e
900be47870a62b8055b99edac9e1b0f6c6f0dc35
/Source/Core/Platform/Guid.h
ca78ad42544316a212e0d22c3f4d101e73494bab
[]
no_license
simeks/pluto
e24fa1809eb06aeb8d41126402ab3825dae0f9d2
9f28fce900cbc8d7ebb56b79a9b6eaebb8141a67
refs/heads/master
2021-03-28T20:23:49.109098
2018-02-22T13:59:03
2018-02-22T13:59:03
75,561,384
2
0
null
null
null
null
UTF-8
C++
false
false
1,743
h
Guid.h
#ifndef __CORE_PLATFORM_GUID_H__ #define __CORE_PLATFORM_GUID_H__ #include <Core/Common.h> /// Represents a globally unique identifier struct Guid { Guid() { d1 = d2 = d3 = 0; for (int i = 0; i < 8; ++i) d4[i] = 0; } uint32_t d1; uint16_t d2; uint16_t d3; uint8_t d4[8]; bool is_valid() const { if (d1 != 0 || d2 != 0 || d3 != 0) return true; for (int i = 0; i < 8; i++) if (d4[i] != 0) return true; return false; } }; INLINE bool operator==(const Guid& x, const Guid& y) { if (x.d1 != y.d1 || x.d2 != y.d2 || x.d3 != y.d3) return false; for (int i = 0; i < 8; ++i) if (x.d4[i] != y.d4[i]) return false; return true; } INLINE bool operator!=(const Guid& x, const Guid& y) { return !(x == y); } INLINE bool operator<(const Guid& x, const Guid& y) { if (x.d1 < y.d1) return true; if (x.d1 > y.d1) return false; if (x.d2 < y.d2) return true; if (x.d2 > y.d2) return false; if (x.d3 < y.d3) return true; if (x.d3 > y.d3) return false; for (int i = 0; i < 8; ++i) { if (x.d4[i] < y.d4[i]) return true; if (x.d4[i] > y.d4[i]) return false; } return false; } namespace guid { CORE_API Guid create_guid(); /// Converts a GUID to a string of the format 00000000-0000-0000-0000-000000000000 CORE_API std::string to_string(const Guid& id); /// Converts a string of the format 00000000-0000-0000-0000-000000000000 to a GUID CORE_API Guid from_string(const std::string& str); } #endif // __CORE_PLATFORM_GUID_H__
9be9bc50e6eab7664187436ddd73260da8d49505
4cc67026ec3948d9100500adddafb148fb665649
/HuffmanNode.h
3f516d1f3a4db059fc628cb9d69a49d33af22580
[]
no_license
shiweixian2/HuffmanTest
f0ca97cf486056fdbb76cef69f5038c12a9e3d2b
ea56e521512f6db79dcdb5683cd8ecf4a02a8a8f
refs/heads/master
2021-01-10T03:46:51.082624
2016-02-28T08:21:36
2016-02-28T08:21:36
52,707,758
0
0
null
null
null
null
UTF-8
C++
false
false
545
h
HuffmanNode.h
/** * @author 石炜贤 * @date 2016/02/27 * * 构建霍夫曼树,使用最小堆 */ #ifndef HUFFMANTEST_HUFFMANNODE_H #define HUFFMANTEST_HUFFMANNODE_H template <class T> class HuffmanNode{ public: T key; //权值 HuffmanNode *left; //左孩子 HuffmanNode *right; //右孩子 HuffmanNode *parent; //父节点 /** * 构造函数 */ HuffmanNode(){} HuffmanNode(T value, HuffmanNode *l, HuffmanNode *r, HuffmanNode *p):key(value),left(l),right(r),parent(p){} }; #endif //HUFFMANTEST_HUFFMANNODE_H
1abeab8fd4f5b9d8caae0df7432df41896d16f68
917f7bf53f08a43a6b0d49aacc782e35bbc2a17c
/Boss.h
de4307622d105cc4f39613152fa6890dbe5c979a
[]
no_license
deonquentinzoss/Type.Start-
43ed9a7ccfbb919946446919301675b5df726f01
90a6d0df18705360d24aed14ffa25c648029aeef
refs/heads/main
2023-04-27T00:36:10.318344
2021-05-30T05:00:22
2021-05-30T05:00:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,019
h
Boss.h
#include "Object.h" #include "Setup.h" #ifndef Boss_h #define Boss_h class Boss { public: Boss(SDL_Renderer* renderer) { this->renderer = renderer; blinkTime = SDL_GetTicks(); walkTime = SDL_GetTicks(); setupClips(); loadFont(); } ~Boss() { free(); } void free() { } void loadFont() { font= TTF_OpenFont(CODE_FONT, CHARACTER_SCORE_FONT_SIZE); if(font==NULL){ printf("Error loading coworker font\n"); } } void render() { SDL_Rect renderQuad; if(!frozen){ if(walking){ if(facingRight){ renderQuad = {xPos,BOSS_SPAWN_Y, charRightClips[walkingFrameIndex].w*SCALESIZE, charRightClips[walkingFrameIndex].h*SCALESIZE}; SDL_RenderCopy(renderer, objectTexture, &charRightClips[walkingFrameIndex], &renderQuad); xPos+=WALKING_SPEED/speed; } else{ renderQuad = {xPos,BOSS_SPAWN_Y, charLeftClips[walkingFrameIndex].w*SCALESIZE, charLeftClips[walkingFrameIndex].h*SCALESIZE}; SDL_RenderCopy(renderer, objectTexture, &charLeftClips[walkingFrameIndex], &renderQuad); xPos-=WALKING_SPEED/speed; } if((SDL_GetTicks() - walkTime) > (WALKING_ANIMATION_CHANGE_SPEED)*speed){ walkingFrameIndex++; if(walkingFrameIndex == 5){ walkingFrameIndex = 1; } walkTime = SDL_GetTicks(); } } else{ if(facingRight){ renderQuad = {BOSS_SPAWN_X,BOSS_SPAWN_Y, charRightClips[0].w*SCALESIZE, charRightClips[0].h*SCALESIZE}; SDL_RenderCopy(renderer, objectTexture, &charRightClips[0], &renderQuad); } else{ renderQuad = {BOSS_SPAWN_X,BOSS_SPAWN_Y, charLeftClips[0].w*SCALESIZE, charLeftClips[0].h*SCALESIZE}; SDL_RenderCopy(renderer, objectTexture, &charLeftClips[0], &renderQuad); } } if(facingRight && xPos >= (OFFSET+100*SCALESIZE)){ facingRight = false; } else if(xPos <= (OFFSET + 0*SCALESIZE)){ facingRight = true; } } else{ if(facingRight){ renderQuad = {xPos,BOSS_SPAWN_Y, charRightClips[walkingFrameIndex].w*SCALESIZE, charRightClips[walkingFrameIndex].h*SCALESIZE}; SDL_RenderCopy(renderer, objectTexture, &charRightClips[walkingFrameIndex], &renderQuad); } else{ renderQuad = {xPos,BOSS_SPAWN_Y, charLeftClips[walkingFrameIndex].w*SCALESIZE, charLeftClips[walkingFrameIndex].h*SCALESIZE}; SDL_RenderCopy(renderer, objectTexture, &charLeftClips[walkingFrameIndex], &renderQuad); } } if(!heavyHead){ if(facingRight){ if(walkingFrameIndex%2==0 || !walking){ renderQuad = {xPos+1*SCALESIZE, BOSS_SPAWN_Y - 7*SCALESIZE, charHeadRight.w*SCALESIZE, charHeadRight.h*SCALESIZE}; } else{ renderQuad = {xPos+1*SCALESIZE, BOSS_SPAWN_Y - 6*SCALESIZE, charHeadRight.w*SCALESIZE, charHeadRight.h*SCALESIZE}; } SDL_RenderCopy(renderer, objectTexture, &charHeadRight, &renderQuad); } else{ if(walkingFrameIndex%2==0 || !walking){ renderQuad = {xPos+4*SCALESIZE, BOSS_SPAWN_Y - 7*SCALESIZE, charHeadLeft.w*SCALESIZE, charHeadLeft.h*SCALESIZE}; } else{ renderQuad = {xPos+4*SCALESIZE, BOSS_SPAWN_Y - 6*SCALESIZE, charHeadLeft.w*SCALESIZE, charHeadLeft.h*SCALESIZE}; } SDL_RenderCopy(renderer, objectTexture, &charHeadLeft, &renderQuad); } } else{ if(SDL_GetTicks()-heavyHeadTime > LETTER_LIFETIME){ heavyHead = false; } if(facingRight){ if(walkingFrameIndex%2==0 || !walking){ renderQuad = {xPos+1*SCALESIZE, BOSS_SPAWN_Y - 6*SCALESIZE, charHeadRight.w*SCALESIZE, charHeadRight.h*SCALESIZE}; } else{ renderQuad = {xPos+1*SCALESIZE, BOSS_SPAWN_Y - 5*SCALESIZE, charHeadRight.w*SCALESIZE, charHeadRight.h*SCALESIZE}; } SDL_RenderCopy(renderer, objectTexture, &charHeadRight, &renderQuad); } else{ if(walkingFrameIndex%2==0 || !walking){ renderQuad = {xPos+4*SCALESIZE, BOSS_SPAWN_Y - 6*SCALESIZE, charHeadLeft.w*SCALESIZE, charHeadLeft.h*SCALESIZE}; } else{ renderQuad = {xPos+4*SCALESIZE, BOSS_SPAWN_Y - 5*SCALESIZE, charHeadLeft.w*SCALESIZE, charHeadLeft.h*SCALESIZE}; } SDL_RenderCopy(renderer, objectTexture, &charHeadLeft, &renderQuad); } } if(!frozen){ tryToBlink(); } if(splash){ if(SDL_GetTicks() - coffeeTime > 100){ coffeeTime = SDL_GetTicks(); coffeeIndex++; } if(coffeeIndex == 6){ splash = false; } if(facingRight){ coffeeClips[coffeeIndex]->setX(xPos+10*SCALESIZE); printf("%d\n", coffeeIndex); } else{ coffeeClips[coffeeIndex]->setX(xPos+5*SCALESIZE); printf("%d\n", coffeeIndex); } if(walkingFrameIndex%2 && walking){ coffeeClips[coffeeIndex]->setY(BOSS_SPAWN_Y+2*SCALESIZE); } else{ coffeeClips[coffeeIndex]->setY(BOSS_SPAWN_Y+1*SCALESIZE); } coffeeClips[coffeeIndex]->render(); } } void tryToBlink(){ if((SDL_GetTicks() - blinkTime) > BOSS_BLINK_TIME){ blink = true; blinkTime = SDL_GetTicks(); } if(blink && ((SDL_GetTicks() - blinkTime) < BOSS_BLINK_DURATION)){ SDL_Rect blinkingEyes; double yPos; if(heavyHead){ yPos = BOSS_SPAWN_Y - 3*SCALESIZE; } else{ yPos = BOSS_SPAWN_Y - 4*SCALESIZE; } if(walkingFrameIndex%2==1 && walking){ yPos+=1*SCALESIZE; } if(facingRight){ blinkingEyes = {46, 75, 4, 1}; SDL_Rect renderQuad = {xPos+3*SCALESIZE, yPos, blinkingEyes.w*SCALESIZE, blinkingEyes.h*SCALESIZE}; SDL_RenderCopy(renderer, objectTexture, &blinkingEyes, &renderQuad); } else{ blinkingEyes = {45, 83, 4, 1}; SDL_Rect renderQuad = {xPos+5*SCALESIZE, yPos, blinkingEyes.w*SCALESIZE, blinkingEyes.h*SCALESIZE}; SDL_RenderCopy(renderer, objectTexture, &blinkingEyes, &renderQuad); } } else if(blink){ blink = false; } } void freeze(){ frozen = true; } void unfreeze(){ frozen = false; } bool collisionCheck(double x, double y){ if(facingRight){ if(x >= xPos && (x <= xPos + 7*SCALESIZE)){ if(y >= BOSS_SPAWN_Y - 10*SCALESIZE && y <= BOSS_SPAWN_Y - 5*SCALESIZE){ return true; } } } else { if(x >= xPos + 2*SCALESIZE && (x <= xPos + 9*SCALESIZE)){ if(y >= BOSS_SPAWN_Y - 10*SCALESIZE && y <= BOSS_SPAWN_Y - 5*SCALESIZE){ return true; } } } return false; } bool coffeeCollisionCheck(double x, double y){ if(facingRight){ if(x >= (xPos+9*SCALESIZE) && (x <= xPos+(13*SCALESIZE))){ if(y >= (BOSS_SPAWN_Y + 2*SCALESIZE) && y <= (BOSS_SPAWN_Y + 6*SCALESIZE)){ coffeeIndex = 0; splash = true; return true; } } } else{ if(x >= (xPos+5*SCALESIZE) && (x <= xPos+(9*SCALESIZE))){ if(y >= (BOSS_SPAWN_Y + 2*SCALESIZE) && y <= (BOSS_SPAWN_Y + 6*SCALESIZE)){ coffeeIndex = 0; splash = true; return true; } } } return false; } void setupClips() { charHeadRight.x = 1; charHeadRight.y = 145; charHeadRight.w = 7; charHeadRight.h = 7; charHeadLeft.x = 4; charHeadLeft.y = 171; charHeadLeft.w = 7; charHeadLeft.h = 7; for(int i = 0; i < 5; i++){ charRightClips[i].x = BOSS_OBJECT_X+(15*i); charRightClips[i].y = BOSS_OBJECT_Y; charRightClips[i].w = BOSS_OBJECT_W; charRightClips[i].h = BOSS_OBJECT_H; charLeftClips[i].x = BOSS_OBJECT_X+(15*i); charLeftClips[i].y = BOSS_OBJECT_Y+BOSS_OBJECT_H+7; charLeftClips[i].w = BOSS_OBJECT_W; charLeftClips[i].h = BOSS_OBJECT_H; } for(int i = 0; i < 7; i++){ coffeeClips[i] = new Object(11 + (3*i), 139, 2, 6, BOSS_SPAWN_X, BOSS_SPAWN_Y+1*SCALESIZE, renderer); } } void setObjectTexture(SDL_Texture* texture) { this->objectTexture = texture; for(int i = 0; i < 7; i++){ coffeeClips[i]->setObjectTexture(texture); } } void setHeavyHead(bool value){ heavyHead = true; heavyHeadTime = SDL_GetTicks(); } bool getWalking(){ return walking; } bool getFacingRight(){ return facingRight; } int getFrameIndex(){ return walkingFrameIndex; } double getSpeed(){ return speed; } void setSpeed(double value){ speed = value; } private: SDL_Texture* objectTexture = NULL; SDL_Renderer* renderer = NULL; SDL_Rect charRightClips[5]; SDL_Rect charLeftClips[5]; Object* coffeeClips[7]; SDL_Rect charHeadRight; SDL_Rect charHeadLeft; SDL_Color scoreColor; TTF_Font* font = NULL; int charIndex = 0; Uint32 blinkTime = 0; Uint32 walkTime = 0; Uint32 heavyHeadTime = 0; Uint32 coffeeTime = 0; bool blink = false; bool heavyHead = false; bool frozen = false; bool facingRight = false; bool walking = true; double xPos = BOSS_SPAWN_X; int walkingFrameIndex = 1; int coffeeIndex = 0; bool splash = false; double speed = 1; }; #endif
a141a2244eb8c82cb9f383efc03113750e0c56c1
164731f7b7932fc5d2eea480727274f5de6bcb2b
/WrapperRSA.h
ed09535455f9eecde2374c0ac2eea8c722a2ba6d
[]
no_license
dengkangyang/WrapperRSA
9c887558a1733887574f4be11753c6dd72ba2069
fe1eb30437a5b554e2fe95112c69a9b81eea4a27
refs/heads/master
2021-09-01T12:30:15.431372
2017-12-27T01:38:00
2017-12-27T01:38:00
115,467,102
0
0
null
null
null
null
GB18030
C++
false
false
2,212
h
WrapperRSA.h
/* 对openssl RSA算法的封装 RSA算法基础知识: RSA算法是由 Rivest,Shamir和Adleman在1978年提出发一种公匙密码算法. RSA算法是第一个设计完善的公匙密码算法. 该算法的数学基础是Euler定理, 并建立在大整数分解困难性之上. 即: 将两个大素数乘起来上相对容易的, 而分解两个大素数的积是计算上不可行的. RSA算法描述: 密匙生成: 找两个随机的大素数p和q, 计算n=pq 和 f(n)=(p-1)(q-1) ; 选择随机数e(一般用0x10001), 满足e与 f(n)互素. 计算 d = exp( e, -1 ) mod f(n) 公匙: (n,e) 私匙: (n,d,p,q) // 实际 (n,e,d)也都可以. 目前n的有效长度是1024bit是安全的, 建议2048bit. 数据填充问题: 标准填充有PKCS1 和 PSS. 如果1024bit(128byte), 则每次加密运算最多处理117字节. */ #ifndef _WRAPPERRSA_H_ #define _WRAPPERRSA_H_ #include <string> #include <openssl/rsa.h> class CWrapperOpenSSL { public: /* openssl的初始化动作. */ static void Init() ; /* openssl的结束清除动作. */ static void Cleanup() ; }; class CWrapperRSA { public: CWrapperRSA() ; ~CWrapperRSA() ; void ReInit() ; /* 初试化 public key. */ bool InitPublicKey( const char * pN, const char * pE ) ; /* 初试化 private key. */ bool InitPrivateKey( const char * pN, const char * pE, const char * pD ) ; /* 产生一个 BitLength位的 key. 公匙: (n,e) // 16进制string 私匙: (n,e,d) // 16进制string */ static bool GenKey( std::string& echoN, std::string& echoE, std::string& echoD, int BitLength = 1024 ) ; /* (用公匙)加密. */ bool Encrpt( unsigned char* pSrcBuf, int SrcSize, unsigned char* pDestBuf, int& echoDestSize ) ; /* (用私匙)解密. */ bool Decrpt( unsigned char* pSrcBuf, int SrcSize, unsigned char* pDestBuf, int& echoDestSize ) ; /* 查询原子包的大小. */ int QueryAtomSize() ; /* 查询 扣除填充部分 的大小. */ int QueryAtomSize_SubPadding() ; public: RSA* m_pKey ; // 填充模式, paul, 2010-11-20, add. // 注: 目前只支持了RSA_PKCS1_PADDING, 其他模式未支持. int m_padding ; }; #endif
49672780bc16d3e2a37982e68e1fc50dbe744a28
2ad44872929570ec56666024ca4acdef3ba8f7fe
/src/Entity.h
8426e941a7c8355ace6ac44d397b673fdb5b70ff
[]
no_license
lakritidis/SHTECLib
4978b4df89b1e2b0232a69831f0be4c4035960e2
d87f45cdb543e47df47102ff9dd4209d6ef1f97b
refs/heads/master
2023-02-22T13:26:09.664520
2023-02-20T08:27:00
2023-02-20T08:27:00
276,211,074
8
1
null
null
null
null
UTF-8
C++
false
false
1,650
h
Entity.h
#ifndef ENTITY_H #define ENTITY_H class Entity { protected: uint32_t id; uint16_t type; _score_t weight; uint32_t real_cluster_id; /// The following three elements constitute the Entity's Feature Vector. We implement it in /// this way and not as a separate class, in order to avoid an additional level of pointer /// dereferencing. Compared to the usage of an array of Feature objects, this approach /// accelerates the computation of similarity (or distance) between two entities by 20-30%. uint16_t num_tokens; class Token ** tokens; _score_t * token_weights; protected: void quicksort(uint16_t, uint16_t); public: Entity(); Entity(uint16_t); ~Entity(); _score_t cosine_similarity(class Entity *); _score_t euclidean_distance(class Entity *); uint32_t tokenize(char *, uint32_t, class TokensLexicon *, class TokensLexicon *, class Statistics *); void insert_token(uint32_t, char *, class TokensLexicon *, class TokensLexicon *, uint16_t *); void insert_token(class Token *, _score_t); void display(); void display_feature_vector(); void compute_token_scores(); void compute_entity_weight(); void divide_weights(double); void normalize_feature_vector(); void sort_feature_vector(); void set_id(uint32_t); void set_type(uint16_t); void set_num_tokens(uint16_t); void set_real_cluster_id(uint32_t); uint32_t get_id(); void get_text(char * ); uint16_t get_type(); uint16_t get_num_tokens(); uint32_t get_real_cluster_id(); Token * get_token(uint16_t); _score_t get_token_weight(uint16_t); _score_t get_weight(); }; #endif // ENTITY_H
f5a1bbb33d24ec385b9c061e12577f93443edadf
218978f926542320cb7287d8c8dffbca4c10cd28
/TextureBrush/renderer/Geo2D.h
b638363ea16015be2860ff74b20022c66a8b5211
[]
no_license
m-Just/TextureBrush
5d0b36f3d103794baf81a041b91af224781a423d
785111e56b9ba9c5490b1da086438b382c9b1a64
refs/heads/master
2021-01-19T06:43:20.199910
2016-07-30T12:32:30
2016-07-30T12:32:30
62,200,567
0
2
null
2016-07-27T07:40:16
2016-06-29T06:15:28
C++
UTF-8
C++
false
false
3,924
h
Geo2D.h
#pragma once #include "../preHeader.h" class Geo2D { public: /* general */ static void InterpLinear(glm::vec2 & v, double t, const glm::vec2 & v0, const glm::vec2 & v1); /* reflection over line */ static void PointReflectionOverLine(glm::vec2 & v, const glm::vec2 & p, const glm::vec2 & v1, const glm::vec2 & v2); //static SVGPattern * PatternReflectionOverLine(SVGPattern * pattern, const glm::vec2 & v1, const glm::vec2 & v2); /* line */ static void LineParams(double & A, double & B, double & C, const glm::vec2 & v1, const glm::vec2 & v2); static void PointOnLine(glm::vec2 & pt, double t, const glm::vec2 & p0, const glm::vec2 & p1); /* point and line */ static bool IsPointOnLineseg(const glm::vec2 & v, const glm::vec2 & v1, const glm::vec2 & v2, double precision = 0.0000001); static double DistanceBetweenPointLineseg(glm::vec2 & v, const glm::vec2 & p, const glm::vec2 & v1, const glm::vec2 & v2); static double tOfPointOnLine(const glm::vec2 & v, const glm::vec2 & v0, const glm::vec2 & v1); /* bezier */ static void BezierParams(glm::vec4 & coex, glm::vec4 & coey, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); static double DistanceBetweenPointBezier(glm::vec2 & v, const glm::vec2 & p, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); static void SplitBezier(std::vector<glm::vec2> & b1, std::vector<glm::vec2> & b2, double t, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); static void SplitBezier(std::vector<std::vector<glm::vec2>> & beziers, const std::vector<glm::vec2> & pts, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); static double tOfPointOnBezier(const glm::vec2 & v, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); static void CubicRoots(std::vector<double> & roots, const glm::vec4 & bezier_coeff); static void PointOnBezier(glm::vec2 & pt, double t, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); static void PointOnBezier(glm::vec2 & pt, double t, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2); static void PointOnCubicBezier_deCasteljau(glm::vec2 & pt, double t, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); static void PointOnQuadratic_deCasteljau(glm::vec2 & pt, double t, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2); static void GetPointProjection(double & t, const glm::vec2 & p, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); static double RefineProjection_(double t, double dist, double precision, const glm::vec2 & p, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); /* tangents and normals of Bezier */ static void DerivativeOnCubicBezier(glm::vec2 & dt, double t, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); static void SecondDerivativeOnCubicBezier(glm::vec2 & dt, double t, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); static void TangentOnCubicBeizer(glm::vec2 & ta, double t, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); static void NormalOnCubicBezier(glm::vec2 & no, double t, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); /* the art length of bezier curve */ /* refer to http://pomax.github.io/bezierinfo/#arclength */ static double GetCubicBeizerArcLength(double t, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); static double CubicBeizerArcLengthTo_t(double l, const glm::vec2 & p0, const glm::vec2 & p1, const glm::vec2 & p2, const glm::vec2 & p3); };
d9cbb22d8a2f1281b2795d26312bb5e32b15a1d7
04276306714223096567cf2587dc028f8afc1ce2
/CompilerCreationTool/Grammar/GrammarProductionFactory.h
9de340128f5bc519a92b5db9add97266cc8a6d11
[ "MIT" ]
permissive
vstdio/CompilerCreationTool
5523eb2a74b3d41f31bf7a69599fb9b2112ae9c9
03500f95e9c90f23685457124842d3feda2e821f
refs/heads/master
2022-02-09T15:12:24.921436
2019-06-09T18:05:05
2019-06-09T18:05:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
246
h
GrammarProductionFactory.h
#pragma once #include "IGrammarProductionFactory.h" namespace grammarlib { class GrammarProductionFactory : public IGrammarProductionFactory { public: std::unique_ptr<IGrammarProduction> CreateProduction(const std::string& line) override; }; }
b74ce0ce0d94e6131d239db6528306db4627d7bf
35a83cad99b5e69540ccd647d6e0be9735d0035a
/Building-the-Matrix/src/ImageLoader.cpp
a407d2090e66d2cd941d48a7a699e798b8bdd09e
[]
no_license
bencatterall/Building-the-Matrix
144d94c2b193f9081f39094ce625c345f4d591b8
a61bcd1aff306035e4954b4631ca9b7dc77681b4
refs/heads/master
2021-05-03T14:22:58.316805
2015-03-02T00:45:25
2015-03-02T00:45:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
554
cpp
ImageLoader.cpp
#include "ImageLoader.hpp" #include "../Dependencies/LodePNG/lodepng.hpp" #include <iostream> #include <string> #include <vector> std::vector<unsigned char> ImageLoader::loadImage(std::string filename, unsigned int& width, unsigned int& height) { //raw pixels in RGBA format //4 bytes per pixel std::vector<unsigned char> image; //decode unsigned error = lodepng::decode(image, width, height, filename.c_str()); if (error) { std::cerr << "ERROR: In loadImage: " << lodepng_error_text(error) << std::endl; return image; } return image; }
65a93bb461af507b3d26d8e3ad9cd8397d1fd902
19194c2f2c07ab3537f994acfbf6b34ea9b55ae7
/android-31/android/app/RemoteInput.def.hpp
effe84e7742275d15e7abb83b7f4712693e9b863
[ "GPL-3.0-only" ]
permissive
YJBeetle/QtAndroidAPI
e372609e9db0f96602da31b8417c9f5972315cae
ace3f0ea2678967393b5eb8e4edba7fa2ca6a50c
refs/heads/Qt6
2023-08-05T03:14:11.842336
2023-07-24T08:35:31
2023-07-24T08:35:31
249,539,770
19
4
Apache-2.0
2022-03-14T12:15:32
2020-03-23T20:42:54
C++
UTF-8
C++
false
false
1,857
hpp
RemoteInput.def.hpp
#pragma once #include "../../JObject.hpp" class JArray; class JArray; namespace android::content { class Intent; } namespace android::os { class Bundle; } namespace android::os { class Parcel; } class JString; class JString; namespace android::app { class RemoteInput : public JObject { public: // Fields static JObject CREATOR(); static jint EDIT_CHOICES_BEFORE_SENDING_AUTO(); static jint EDIT_CHOICES_BEFORE_SENDING_DISABLED(); static jint EDIT_CHOICES_BEFORE_SENDING_ENABLED(); static JString EXTRA_RESULTS_DATA(); static JString RESULTS_CLIP_LABEL(); static jint SOURCE_CHOICE(); static jint SOURCE_FREE_FORM_INPUT(); // QJniObject forward template<typename ...Ts> explicit RemoteInput(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} RemoteInput(QJniObject obj) : JObject(obj) {} // Constructors // Methods static void addDataResultToIntent(android::app::RemoteInput arg0, android::content::Intent arg1, JObject arg2); static void addResultsToIntent(JArray arg0, android::content::Intent arg1, android::os::Bundle arg2); static JObject getDataResultsFromIntent(android::content::Intent arg0, JString arg1); static android::os::Bundle getResultsFromIntent(android::content::Intent arg0); static jint getResultsSource(android::content::Intent arg0); static void setResultsSource(android::content::Intent arg0, jint arg1); jint describeContents() const; jboolean getAllowFreeFormInput() const; JObject getAllowedDataTypes() const; JArray getChoices() const; jint getEditChoicesBeforeSending() const; android::os::Bundle getExtras() const; JString getLabel() const; JString getResultKey() const; jboolean isDataOnly() const; void writeToParcel(android::os::Parcel arg0, jint arg1) const; }; } // namespace android::app
76c9e4e617fcb86bd96f04bddb63c3727e8353cb
5644c43e8df5d16c7b4ffec19aafc2b3ffdd69cb
/SDKD_2018_Spring_Team_Contest_F/D.cpp
ec8d67d37285c247309c4ec3bef24f3d287536a6
[]
no_license
ShiliXu1997/ACM_Code
cd7f8a414cb72d305df3836a0e3196a84d246137
69245f2f99c3b4af85cc9b7bbc4a9666e3cf8e0e
refs/heads/master
2020-04-17T04:09:30.934796
2020-02-26T07:26:43
2020-02-26T07:26:43
166,216,638
0
0
null
null
null
null
UTF-8
C++
false
false
937
cpp
D.cpp
//************************************************************************ // File Name: D.cpp // Author: Shili_Xu // E-Mail: shili_xu@qq.com // Created Time: 2018年04月07日 星期六 13时36分27秒 //************************************************************************ #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int MAXN = 1e6 + 5; int n, m, x; int a[MAXN], b[MAXN]; int main() { freopen("deposits.in", "r", stdin); freopen("deposits.out", "w", stdout); scanf("%d", &n); memset(a, 0, sizeof(a)); memset(b, 0, sizeof(b)); for (int i = 1; i <= n; i++) { scanf("%d", &x); a[x]++; } scanf("%d", &m); for (int i = 1; i <= m; i++) { scanf("%d", &x); b[x]++; } long long ans = 0; for (int i = 1; i < MAXN; i++) if (b[i]) { for (int j = 1; (long long)j * i < MAXN; j++) if (a[j * i]) ans += (long long)a[j * i] * b[i]; } printf("%lld\n", ans); return 0; }
f0794fa97b61ca56bc0ae0d5b661772a71360858
db6b3891c6f872c1c156797ba3e0c0a67a905203
/lib/Rest/EndpointList.h
ab4d48d9c10ccc64ea8ab35dc5d96b84844f4f15
[ "Apache-2.0" ]
permissive
AALEKH/arangodb
119c23a957dc381c7c15d4116c1621cb3b3bbea7
d193c2ff915c749c7838c8225fe6e2c90a324b4d
refs/heads/velocystream
2021-01-09T05:11:06.964249
2016-05-22T18:37:31
2016-05-22T18:37:31
50,135,630
0
0
null
2016-03-03T07:57:14
2016-01-21T20:46:45
C++
UTF-8
C++
false
false
4,662
h
EndpointList.h
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #ifndef LIB_REST_ENDPOINT_LIST_H #define LIB_REST_ENDPOINT_LIST_H 1 #include "Basics/Common.h" #include "Rest/Endpoint.h" namespace arangodb { namespace rest { class EndpointList { public: public: ////////////////////////////////////////////////////////////////////////////// /// @brief creates an endpoint list ////////////////////////////////////////////////////////////////////////////// EndpointList(); ////////////////////////////////////////////////////////////////////////////// /// @brief destroys an endpoint list ////////////////////////////////////////////////////////////////////////////// ~EndpointList(); public: ////////////////////////////////////////////////////////////////////////////// /// @brief returns whether the list is empty ////////////////////////////////////////////////////////////////////////////// bool empty() const { return _endpoints.empty(); } ////////////////////////////////////////////////////////////////////////////// /// @brief add a new endpoint ////////////////////////////////////////////////////////////////////////////// bool add(std::string const&, std::vector<std::string> const&, int, bool, Endpoint** = nullptr); ////////////////////////////////////////////////////////////////////////////// /// @brief remove a specific endpoint ////////////////////////////////////////////////////////////////////////////// bool remove(std::string const&, Endpoint**); ////////////////////////////////////////////////////////////////////////////// /// @brief return all databases for an endpoint ////////////////////////////////////////////////////////////////////////////// std::vector<std::string> const& getMapping(std::string const&) const; ////////////////////////////////////////////////////////////////////////////// /// @brief return all endpoints ////////////////////////////////////////////////////////////////////////////// std::map<std::string, std::vector<std::string>> getAll() const; ////////////////////////////////////////////////////////////////////////////// /// @brief return all endpoints with a certain prefix ////////////////////////////////////////////////////////////////////////////// std::map<std::string, Endpoint*> getByPrefix(std::string const&) const; ////////////////////////////////////////////////////////////////////////////// /// @brief return all endpoints with a certain encryption type ////////////////////////////////////////////////////////////////////////////// std::map<std::string, Endpoint*> getByPrefix(Endpoint::EncryptionType) const; ////////////////////////////////////////////////////////////////////////////// /// @brief return if there is an endpoint with a certain encryption type ////////////////////////////////////////////////////////////////////////////// bool has(Endpoint::EncryptionType) const; ////////////////////////////////////////////////////////////////////////////// /// @brief dump all endpoints used ////////////////////////////////////////////////////////////////////////////// void dump() const; ////////////////////////////////////////////////////////////////////////////// /// @brief return an encryption name ////////////////////////////////////////////////////////////////////////////// static std::string getEncryptionName(Endpoint::EncryptionType); private: ////////////////////////////////////////////////////////////////////////////// /// @brief list of endpoints ////////////////////////////////////////////////////////////////////////////// std::map<std::string, std::pair<Endpoint*, std::vector<std::string>>> _endpoints; }; } } #endif
1485385c53d4aa3f834049561a8848c16d8f869f
d96567f03bbd1e2bc70393c65272fcabb6c50467
/LDeque.cpp
7d662e85df5fa2361154dd2c72d539171b15928b
[]
no_license
bryanlopezrr/NotationConverter
b6df258b9f2fd5aa732b03b536bf4b415da0c463
d9bad49c321b183fa137877f2f3772bdd4fafeea
refs/heads/master
2020-06-03T05:54:01.556839
2019-06-12T00:32:53
2019-06-12T00:32:53
191,469,333
0
0
null
null
null
null
UTF-8
C++
false
false
1,266
cpp
LDeque.cpp
#include "LDeque.hpp" /*FYE: Functions were provided by the lecture notes given by Dr. Oropallo on this particular implementation of a deque data structure*/ //CONSTRUCTOR/DESTRUCTOR //-----------------------------------------------------------------------------------------> LDeque::LDeque() : D(), n(0) {} LDeque::~LDeque(){} //CHECK FOR SIZE OF DEQUE (No. OF NODES IN IT ) && IF ITS EMPTY //-----------------------------------------------------------------------------------------> int LDeque::size() const{ return n; } bool LDeque::empty() const { return n == 0; } //REFERENCE TO FRONT AND REAR OF DEQUE //-----------------------------------------------------------------------------------------> const string& LDeque::front() const throw () { return D.front(); } const string& LDeque::back() const throw () { return D.back(); } //ENQUEUE AND DEQUEUE //-----------------------------------------------------------------------------------------> void LDeque::removeFront() throw() { D.removeFront(); n--; } void LDeque::removeBack() throw() { D.removeBack(); n--; } void LDeque::insertFront(const string &e) { D.addFront(e); n++; } void LDeque::insertBack(const string &e) { D.addBack(e); n++; }
b03416d0ecd2acb57267ee8e12577f200bae4d08
101d466d0b709e713c7fceeb64930428ac21d894
/链表中倒数第k个结点/链表中倒数第k个结点/链表中倒数第k个结点.cpp
87aee0d37632ff8f9f15d0a765fad810fa03d3b9
[]
no_license
jfyh5388/SwordOffer
3a37adfa903b80c0728c3a6e60f830962ee2ed86
a1798946067e0e559430ced17bfde95e94ca7c58
refs/heads/master
2021-01-23T05:50:53.312671
2018-07-08T02:35:43
2018-07-08T02:35:43
102,478,550
0
0
null
null
null
null
UTF-8
C++
false
false
1,426
cpp
链表中倒数第k个结点.cpp
#include<iostream> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; class Solution { public: ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { unsigned int j=1; ListNode *p1=pListHead; ListNode *p2=pListHead; if(pListHead==NULL||k==0) return NULL; for(j=1;j<k;j++) { if(p2->next==NULL) return NULL; else p2=p2->next; } while(p2->next!=NULL) { p1=p1->next; p2=p2->next; } return p1; } }; int main() { struct ListNode* head=(ListNode *)malloc(sizeof(ListNode)); struct ListNode* data1=(ListNode *)malloc(sizeof(ListNode)); struct ListNode* data2=(ListNode *)malloc(sizeof(ListNode)); struct ListNode* data3=(ListNode *)malloc(sizeof(ListNode)); struct ListNode* data4=(ListNode *)malloc(sizeof(ListNode)); struct ListNode* data5=(ListNode *)malloc(sizeof(ListNode)); struct ListNode* data6=(ListNode *)malloc(sizeof(ListNode)); Solution so; head->val=0; data1->val=1; data2->val=2; data3->val=3; data4->val=4; data5->val=5; head->next=data1; data1->next=data2; data2->next=data3; data3->next=data4; data4->next=data5; data5->next=data6; data6->next=NULL; cout<<so.FindKthToTail(head,6)->val<<endl; return 0; }
0307b0c9f7b631f7dca9f8848f4db73ff01625d0
fe1ca47c8095776eabc1d43f784e6139308b4451
/src/featbin/multiply-vectors.cc
8bbe54e4f368859fadc1ca7258d7c07f9c26d3a5
[ "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
hhadian/kaldi
8d281c6d536fba9e9b13b7f25ef697b4013b26d8
054af6bda820a96dd8d026d144a5263314f31dd3
refs/heads/master
2022-02-27T01:41:23.517680
2021-12-18T16:23:52
2021-12-18T16:23:52
44,244,555
13
4
NOASSERTION
2018-11-16T19:51:57
2015-10-14T11:55:09
Shell
UTF-8
C++
false
false
6,052
cc
multiply-vectors.cc
// featbin/multiply-vectors.cc // Copyright 2020 Ivan Medennikov (STC-innovations Ltd) // See ../../COPYING for clarification regarding multiple authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "matrix/kaldi-matrix.h" #include "util/common-utils.h" namespace kaldi { // returns true if successfully multiplied. bool MultiplyVectors(const std::vector<Vector<BaseFloat> > &in, std::string utt, int32 tolerance, Vector<BaseFloat> *out) { // Check the lengths int32 min_len = in[0].Dim(), max_len = in[0].Dim(); for (int32 i = 1; i < in.size(); ++i) { int32 len = in[i].Dim(); if(len < min_len) min_len = len; if(len > max_len) max_len = len; } if (max_len - min_len > tolerance || min_len == 0) { KALDI_WARN << "Length mismatch " << max_len << " vs. " << min_len << (utt.empty() ? "" : " for utt ") << utt << " exceeds tolerance " << tolerance; out->Resize(0); return false; } if (max_len - min_len > 0) { KALDI_VLOG(2) << "Length mismatch " << max_len << " vs. " << min_len << (utt.empty() ? "" : " for utt ") << utt << " within tolerance " << tolerance; } out->Resize(min_len); out->Set(1.0); for (int32 i = 0; i < in.size(); ++i) { out->MulElements(in[i].Range(0, min_len)); } return true; } } // namespace kaldi int main(int argc, char *argv[]) { try { using namespace kaldi; using namespace std; const char *usage = "Multiply vectors frame-by-frame (assuming they have about the same durations, see --length-tolerance);\n" "Usage: multiply-vectors <in-rspecifier1> <in-rspecifier2> [<in-rspecifier3> ...] <out-wspecifier>\n" " or: multiply-vectors <in-rxfilename1> <in-rxfilename2> [<in-rxfilename3> ...] <out-wxfilename>\n" " e.g. multiply-vectors ark:vec1.ark ark:vec2.ark ark:out.ark\n" " or: multiply-vectors foo.mat bar.mat baz.mat\n" "See also: paste-feats, copy-vector, append-vector-to-feats\n"; ParseOptions po(usage); int32 length_tolerance = 0; bool binary = true; po.Register("length-tolerance", &length_tolerance, "If length is different, trim as shortest up to a frame " " difference of length-tolerance, otherwise exclude segment."); po.Register("binary", &binary, "If true, output files in binary " "(only relevant for single-file operation, i.e. no tables)"); po.Read(argc, argv); if (po.NumArgs() < 3) { po.PrintUsage(); exit(1); } if (ClassifyRspecifier(po.GetArg(1), NULL, NULL) != kNoRspecifier) { // We're operating on tables, e.g. archives. // Last argument is output string wspecifier = po.GetArg(po.NumArgs()); BaseFloatVectorWriter vector_writer(wspecifier); // First input is sequential string first_rspecifier = po.GetArg(1); SequentialBaseFloatVectorReader first_input(first_rspecifier); // Assemble vector of other input readers (with random-access) vector<RandomAccessBaseFloatVectorReader *> rest_inputs; for (int32 i = 2; i < po.NumArgs(); ++i) { string rspecifier = po.GetArg(i); RandomAccessBaseFloatVectorReader *rd = new RandomAccessBaseFloatVectorReader(rspecifier); rest_inputs.push_back(rd); } int32 num_done = 0, num_err = 0; // Main loop for (; !first_input.Done(); first_input.Next()) { string utt = first_input.Key(); KALDI_VLOG(2) << "Multiplying vectors for utterance " << utt; // Collect features from streams to vector 'vectors' vector<Vector<BaseFloat> > vectors(po.NumArgs() - 1); vectors[0] = first_input.Value(); size_t i; for (i = 0; i < rest_inputs.size(); ++i) { if (rest_inputs[i]->HasKey(utt)) { vectors[i + 1] = rest_inputs[i]->Value(utt); } else { KALDI_WARN << "Missing utt " << utt << " from input " << po.GetArg(i + 2); ++num_err; break; } } if (i != rest_inputs.size()) continue; Vector<BaseFloat> output; if (!MultiplyVectors(vectors, utt, length_tolerance, &output)) { ++num_err; continue; // it will have printed a warning. } vector_writer.Write(utt, output); ++num_done; } for (int32 i = 0; i < rest_inputs.size(); ++i) delete rest_inputs[i]; rest_inputs.clear(); KALDI_LOG << "Done " << num_done << " utts, errors on " << num_err; return (num_done == 0 ? -1 : 0); } else { // We're operating on rxfilenames|wxfilenames, most likely files. std::vector<Vector<BaseFloat> > vectors(po.NumArgs() - 1); for (int32 i = 1; i < po.NumArgs(); ++i) ReadKaldiObject(po.GetArg(i), &(vectors[i - 1])); Vector<BaseFloat> output; if (!MultiplyVectors(vectors, "", length_tolerance, &output)) return 1; // it will have printed a warning. std::string output_wxfilename = po.GetArg(po.NumArgs()); WriteKaldiObject(output, output_wxfilename, binary); KALDI_LOG << "Wrote multiplied vector to " << output_wxfilename; return 0; } } catch (const std::exception &e) { std::cerr << e.what(); return -1; } }
1dbe65e13a2111c2f3a45267217d5703bc251bbe
493fde66d377d35cdf0f66e4f9357907dc689bcc
/crypto/symmetric_encryptor_unittest.cc
4001cdcc118820372c2c7fcafd17cd8d855be2c3
[]
no_license
wqx081/mpr_crypto_system
46a8c9724c5381847a4068372710d7855b0b2fd0
4e09446beb1d9d6b665b276771fb5f0a05fffd79
refs/heads/master
2020-04-06T07:07:49.361926
2016-08-30T12:34:27
2016-08-30T12:34:27
64,392,801
0
0
null
null
null
null
UTF-8
C++
false
false
3,590
cc
symmetric_encryptor_unittest.cc
#include "crypto/symmetric_key.h" #include "crypto/symmetric_encryptor.h" #include "crypto/symmetric_crypt.h" #include "base/string_encode.h" #ifdef MPR_SM4_TEST #include "third_party/libsm4/MPRSymmCrypt.h" #endif // MPR_SM4_TEST #include "base/file.h" #include "base/file_path.h" #include "base/file_util.h" #include <gtest/gtest.h> TEST(SymmetricEncryptor, CBC_ts) { std::string key_string; base::ReadFileToString(base::FilePath("/home/wqx/Downloads/hls/video.key"), &key_string); std::unique_ptr<crypto::SymmetricKey> key( crypto::SymmetricKey::Import( crypto::SymmetricKey::AES, key_string)); EXPECT_TRUE(key.get()); std::string iv("the iv: 16 bytes"); EXPECT_EQ(16U, iv.size()); std::shared_ptr<crypto::SymmetricCrypt> crypt = std::make_shared<crypto::CBCSymmetricCrypt>(iv); crypto::SymmetricEncryptor encryptor(key.get()); encryptor.SetCrypt(crypt.get()); std::string file_content; base::ReadFileToString(base::FilePath("/home/wqx/Downloads/hls/orig/my0.ts"), &file_content); std::string file_cipher; EXPECT_TRUE(encryptor.Encrypt(file_content, &file_cipher)); base::WriteFile(base::FilePath("/home/wqx/Downloads/hls/my0.ts"), file_cipher.data(), file_cipher.size()); } TEST(SymmetricEncryptor, CBC_EncryptAndDecrypt) { std::unique_ptr<crypto::SymmetricKey> key( crypto::SymmetricKey::DeriveKeyFromPassword( crypto::SymmetricKey::AES, "password", "saltiest", 1000, 256)); EXPECT_TRUE(key.get()); std::string iv("the iv: 16 bytes"); EXPECT_EQ(16U, iv.size()); std::shared_ptr<crypto::SymmetricCrypt> crypt = std::make_shared<crypto::CBCSymmetricCrypt>(iv); crypto::SymmetricEncryptor encryptor(key.get()); encryptor.SetCrypt(crypt.get()); std::string plaintext("this is the plaintext"); std::string ciphertext; EXPECT_TRUE(encryptor.Encrypt(plaintext, &ciphertext)); EXPECT_LT(0U, ciphertext.size()); std::string decrypted; EXPECT_TRUE(encryptor.Decrypt(ciphertext, &decrypted)); EXPECT_EQ(plaintext, decrypted); } TEST(SymmetricEncryptor, ECB_EncryptAndDecrypt) { std::unique_ptr<crypto::SymmetricKey> key = crypto::SymmetricKey::GenerateRandomKey( crypto::SymmetricKey::AES, 128); EXPECT_TRUE(key.get()); std::unique_ptr<crypto::SymmetricCrypt> crypt = make_unique<crypto::ECBSymmetricCrypt>(); crypto::SymmetricEncryptor encryptor(key.get(), crypt.get()); std::string plaintext("Hello, World"); std::string ciphertext; EXPECT_TRUE(encryptor.Encrypt(plaintext, &ciphertext)); LOG(INFO) << "ciphertext: " << base::HexEncode(ciphertext); std::string plaintext1("hello, worldaabb"); EXPECT_TRUE(encryptor.Encrypt(plaintext1, &ciphertext)); LOG(INFO) << "ciphertext1: " << base::HexEncode(ciphertext); std::string decrypted; EXPECT_TRUE(encryptor.Decrypt(ciphertext, &decrypted)); LOG(INFO) << "decrypted: " << decrypted; #ifdef MPR_SM4_TEST // check for MPR aes int ret; uint8_t buf[1024] = {0}; uint32_t buf_len = 1024; ret = MPRSymmCrypt_Init((unsigned char *)(key.get()->key().data()), 16, 0, 0, AES_ECB); CHECK(ret == 0); ret = MPRSymmCrypt_Decrypt((unsigned char *)(ciphertext.data()), ciphertext.length(), 0, buf, &buf_len); CHECK(ret == 0); LOG(INFO) << "ciphertext length: " << ciphertext.length(); LOG(INFO) << "last decrypt: " << (int)(buf[buf_len-1]); DCHECK((int)(buf[buf_len - 1]) == 4); #endif // MPR_SM4_TEST }
fd5ce9062b7b56e4668157addf030fd5eeb88b45
1fd4702fef8fd03fbc909e60cba68c6fa7cc963b
/rush00/Map.cpp
78fdc62f616e50aa4eafe28ad6fe5dd24966a936
[]
no_license
vplotton/cpp_pool
b46c4021794cf74d7597c7bb7e3c27b6e90722b6
0a920563869f57dcbd3127d25c32d3f5c693f597
refs/heads/master
2021-05-01T12:39:48.403465
2015-05-08T10:19:50
2015-05-08T10:19:50
28,803,579
0
0
null
null
null
null
UTF-8
C++
false
false
353
cpp
Map.cpp
#include "Map.hpp" Map::Map() { } Map::Map(Map const & src) { *this = src; } Map::~Map() { } Map & Map::operator=(Map const & rhs) { if (this != &rhs) { /* my implementation, don't forget to change this. */ } return (*this); } std::ostream & operator<<(std::ostream & o, Map const & i) { o << "Don't forget to change this."; return (o); }
fd881cbf62d163acbde012a23ea3b5d72d668457
be59d364aca6796e57118a208ee0fdc3c94ec8a6
/packages/node-libofx/OpenSP-1.5.2/include/InternalInputSource.h
9e19fa779c5dde52cfe2cffc6398972af3832a3e
[ "LicenseRef-scancode-unknown-license-reference", "LGPL-2.0-or-later", "MIT" ]
permissive
actualbudget/actual
94e983d23df6eeb564fa8b5ff3b9cc63f06dec97
63c3d07cb9d6e71ab61f7925ffcaafff870382c6
refs/heads/master
2023-09-04T07:06:53.208119
2023-09-03T23:15:44
2023-09-03T23:15:44
486,815,039
7,738
724
MIT
2023-09-14T02:11:25
2022-04-29T02:41:34
TypeScript
UTF-8
C++
false
false
1,345
h
InternalInputSource.h
// Copyright (c) 1994 James Clark // See the file COPYING for copying permission. #ifndef InternalInputSource_INCLUDED #define InternalInputSource_INCLUDED 1 #ifdef __GNUG__ #pragma interface #endif #include <stddef.h> #include "InputSource.h" #include "Allocator.h" #include "StringC.h" #include "types.h" #ifdef SP_NAMESPACE namespace SP_NAMESPACE { #endif class InputSourceOrigin; class Messenger; class NamedCharRef; class SP_API InternalInputSource : public InputSource { public: void *operator new(size_t sz, Allocator &alloc) { return alloc.alloc(sz); } void *operator new(size_t sz) { return Allocator::allocSimple(sz); } void operator delete(void *p) { Allocator::free(p); } #ifdef SP_HAVE_PLACEMENT_OPERATOR_DELETE void operator delete(void *p, Allocator &) { Allocator::free(p); } #endif InternalInputSource(const StringC &, InputSourceOrigin *); Xchar fill(Messenger &); void pushCharRef(Char ch, const NamedCharRef &); Boolean rewind(Messenger &); const StringC *contents(); InternalInputSource *asInternalInputSource(); ~InternalInputSource(); private: InternalInputSource(const InternalInputSource &); // undefined void operator=(const InternalInputSource &); // undefined Char *buf_; const StringC *contents_; }; #ifdef SP_NAMESPACE } #endif #endif /* not InternalInputSource_INCLUDED */
0a4eaff8e484de11230259ea1761ac2b5133f6df
1791461e6740f81c2dd6704ae6a899a6707ee6b1
/Contest/The 10th Ji Shou University Campus/F.cpp
6a2d9a5ecccd143e1d68e541cd823f878cf0e082
[ "MIT" ]
permissive
HeRaNO/OI-ICPC-Codes
b12569caa94828c4bedda99d88303eb6344f5d6e
4f542bb921914abd4e2ee7e17d8d93c1c91495e4
refs/heads/master
2023-08-06T10:46:32.714133
2023-07-26T08:10:44
2023-07-26T08:10:44
163,658,110
22
6
null
null
null
null
UTF-8
C++
false
false
865
cpp
F.cpp
#include <bits/stdc++.h> #define MAXN 1000005 using namespace std; int T,n,prime[MAXN], phi[MAXN], mu[MAXN]; bool not_prime[MAXN]; int tot; inline void LinearShaker(int n) { phi[1] = 1LL; mu[1] = 1LL; for (int i = 2; i <= n; i++) { if (!not_prime[i]) { prime[++tot] = i; phi[i] = i - 1; mu[i] = -1; } for (int j = 1; i * prime[j] <= n; j++) { not_prime[i * prime[j]] = true; if (!(i % prime[j])) { mu[i * prime[j]] = 0LL; phi[i * prime[j]] = phi[i] * prime[j]; break; } mu[i * prime[j]] = -mu[i]; phi[i * prime[j]] = phi[i] * (prime[j] - 1); } } return ; } int main() { LinearShaker(1000000); scanf("%d",&T); while (T--) { int cnt=0; scanf("%d",&n); for (int i=1;i<=tot;i++) if (prime[i]>n) break; else ++cnt; int cnto=cnt-1; if (cnto&1) puts("cxy"); else puts("-1"); } return 0; }
8adb5b7480b39331f7eba52f4a0e84c9b3d17925
6ee255175a0fd90f5929fd77305f3551063adbba
/4 in a row.cpp
ba00f49ad9cf7ca90e1428c3e185ba90666fc9de
[]
no_license
ludioo/game-4-in-a-row
d4f3db950776676d1aa39a4f29897859f3bd22a2
1f81bd33e986db432d7db1e5feca28c3a837b682
refs/heads/master
2021-08-31T02:16:21.239856
2017-12-20T06:45:49
2017-12-20T06:45:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,223
cpp
4 in a row.cpp
#include <iostream> using namespace std; char pemenang = ' '; char map[20][20] = { {"[=^=^=^=^=^=^=^=]"}, {"| | | | | | | | |"}, {"<=#=#=#=#=#=#=#=>"}, {"| | | | | | | | |"}, {"<=#=#=#=#=#=#=#=>"}, {"| | | | | | | | |"}, {"<=#=#=#=#=#=#=#=>"}, {"| | | | | | | | |"}, {"<=#=#=#=#=#=#=#=>"}, {"| | | | | | | | |"}, {"<=#=#=#=#=#=#=#=>"}, {"| | | | | | | | |"}, {"(=%=%=%=%=%=%=%=)"} }; char giliran = 'M'; // 'M' lalu 'K' //Penggunaan Function Selesai bool selesai() { int hitung; char symbol; bool status = false; //Proses for(int i = 1; i <= 12; i+=2) { for(int j = 1; j <= 20; j+=2) { //Mereset nilai dari variable hitung hitung = 1; //Jika kolom atau baris kosong maka akan mencetak Spasi if(map[i][j] == ' ') continue; //memberikan symbol pada map seperti 'M' atau 'B' symbol = map[i][j]; //Mengecheck kolom selanjutnya for(int k = j + 2; k <= 20; k+=2) { //Jika tidak sama if(map[i][k] != symbol) break; hitung++; //Increment variable hitung } //mengehitung apabila sudah ada yang terbentuk 4 horizontal maka dia menang if(hitung >= 4) { pemenang = symbol; break; } else if() } if(pemenang != ' ') break; } //Mengcheck pemenang return pemenang == ' ' ? false : true; } void cetakMap(); bool isiMap(int simpan); main() { //untuk menyimpan user input int simpan; while(!selesai()) { //Membersihkan layar system("cls"); //Mencetak map cetakMap(); //Inputan user dan outputnya cout<<"Giliran pemain "; if(giliran == 'M') cout<<"Merah"; else cout<<"Biru"; cout<<endl; while(1) { cout<<"Masukkan kolom: "; cin>>simpan; if(isiMap(simpan)) break; cout<<"Kolom tidak di temukan"<<endl<<endl; } //Merubah Giliran pemain giliran = giliran == 'M' ? 'B' : 'M'; } //membersihkan layar dan mencetak ulang map system("cls"); cetakMap(); //Mencetak siapa pemenangnya cout<<"\n\n=== Selamat pemenangnya adalah "; if(pemenang == 'M') cout<<"Merah"; else cout<<"Biru"; cout<<" ==="; } //Fungsi mencetak Map void cetakMap() { for(int i = 0; i < 13; i++) { for(int j = 0; j < 19; j++){ char t = map[i][j]; if(t == '=') cout<<char(205); else if(t == '|') cout<<char(186); else if(t == '#') cout<<char(206); else if(t == '^') cout<<char(203); else if(t == '<') cout<<char(204); else if(t == '>') cout<<char(185); else if(t == '%') cout<<char(202); else if(t == '[') cout<<char(201); else if(t == ']') cout<<char(187); else if(t == '(') cout<<char(200); else if(t == ')') cout<<char(188); else cout<<t; } cout<<endl; } } //Fungsi untuk mengisi map bool isiMap(int s) { //Mengecheck apabila kolom sudah penuh if(s < 1 || s > 8 || map[1][s * 2 - 1] != ' ') return false; //Bisa mengisi kolom yang kosong for(int i = 13; i >= 1; i-=2) { if(map[i][s * 2 - 1] == ' ') { map[i][s * 2 - 1] = giliran; break; } } return true; }
fee3c981f6508e9b5cf09b45aa8ddd4edf82ef46
a6fb0d94906aeb8b0a41f03e172faf58cfcfb1de
/Project2_string/test_less_than.cpp
7e6606dd1dea4d86e99e78606adcb403eafcdcd8
[]
no_license
atennan3/cs23001
1c61a04df6c831794b7d2085e8dd4b2245b37382
e069f7917450a981e0f93a36563bfbacd63a385d
refs/heads/master
2021-04-27T09:10:52.837912
2018-02-22T21:16:37
2018-02-22T21:16:37
122,508,747
0
1
null
null
null
null
UTF-8
C++
false
false
669
cpp
test_less_than.cpp
// Tests less than #include "string.hpp" #include <cassert> #include <iostream> //=========================================================================== int main () { { // Setup String str1, str2; // Test & Verify assert(str1 <= str2); } { // Setup String str1 = "a", str2 = "z"; // Test & Verify //assert(str1 <= str2); } { // Setup String str1 = "az", str2 = "zz"; // Test & Verify assert(str1 <= str2); } { // Setup String str1 = "az", str2 = "z"; // Test & Verify //assert(str1 < str2); } std::cout << "Done testing less than." << std::endl; }
47b9e372c37614542ee1252999775a33c3d4c733
406d0b58e2f1e536add8d441f4da6446d64a34af
/skeleton.hpp
816f7b0e81584c35cb17c5a3babd24487fe31230
[]
no_license
shinarit/wiz
2eb3051cc8a5497d21c0db5420b5dc8afdd3d85f
fc97002d2e928dfb6128545e87182b22d61a5147
refs/heads/master
2016-09-15T22:17:57.105410
2012-09-21T15:00:00
2012-09-21T15:00:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,220
hpp
skeleton.hpp
// // author: Kovacs Marton // email: tetra666@gmail.com // license: whatever. note my name // // skeleton.hpp // // skeleton for communicating with the game server // cobra style // #ifndef SKELETON_H #define SKELETON_H #include <vector> #include <utility> #include <istream> #include <ostream> struct Coordinate { typedef double CoordType; explicit Coordinate(CoordType x = CoordType(), CoordType y = CoordType()): x(x), y(y) {} CoordType x; CoordType y; Coordinate& operator+=(const Coordinate& rhs); Coordinate& operator*=(const Coordinate::CoordType& rhs); Coordinate& operator/=(const Coordinate::CoordType& rhs); }; Coordinate operator-(const Coordinate& op); Coordinate operator+(const Coordinate& lhs, const Coordinate& rhs); Coordinate operator-(const Coordinate& lhs, const Coordinate& rhs); Coordinate operator*(const Coordinate& lhs, const Coordinate::CoordType& rhs); Coordinate operator/(const Coordinate& lhs, const Coordinate::CoordType& rhs); Coordinate::CoordType Length(const Coordinate& vektor); Coordinate::CoordType Distance(const Coordinate& lhs, const Coordinate& rhs); Coordinate Normalize(const Coordinate& vektor, Coordinate::CoordType length); Coordinate Rotate90Cw(const Coordinate& vektor); Coordinate Rotate90Ccw(const Coordinate& vektor); class Skeleton { public: typedef std::vector<std::pair<int, Coordinate> > ShipList; typedef std::vector<std::pair<int, std::pair<Coordinate, Coordinate> > > LaserList; Skeleton(std::istream &in, std::ostream &out); void Begin(); int GetTeam(); Coordinate GetSpeed(); bool SetSpeed(const Coordinate& speed); Coordinate GetCenter(); bool Shoot(const Coordinate& target); ShipList GetEnemies(); ShipList GetTeammates(); LaserList GetBullets(); void End(); int sizeX; int sizeY; int shipSize; int shipSpeed; int bulletLimit; int cooldown; int laserLength; int laserSpeed; int deadTimer; private: std::string GetLine(); bool GetAck(const std::string& txt = "ack"); bool GetCoordinate(Coordinate& coord, const std::string& txt); std::istream& m_in; std::ostream& m_out; bool first; }; #endif // SKELETON_H
374c69f003664a99d2fad928ebfa0d184e199827
e56108a490f9420fa24b8f3644e05e567800aa0e
/test/URI/Test.Encoding.cpp
26187bef07f3e5c393787e3749561b2fa70f55fd
[ "MIT" ]
permissive
kurocha/uri
80d07235b54498c2b1fa6921ba945b20345bf96a
b920d01de5323126eaf539d4217d357b47fde64e
refs/heads/master
2021-06-27T01:07:15.341496
2019-09-19T11:26:02
2019-09-19T11:26:02
97,460,273
2
0
null
null
null
null
UTF-8
C++
false
false
2,249
cpp
Test.Encoding.cpp
// // Test.Encoding.cpp // This file is part of the "URI" project and released under the MIT License. // // Created by Samuel Williams on 17/7/2017. // Copyright, 2017, by Samuel Williams. All rights reserved. // #include <UnitTest/UnitTest.hpp> #include <URI/Encoding.hpp> #include <map> namespace URI { UnitTest::Suite EncodingTestSuite { "URI::Encoding", {"it can percent encode non-pchars", [](UnitTest::Examiner & examiner) { examiner.expect(Encoding::encode("foo bar")) == "foo%20bar"; } }, {"it can percent decode", [](UnitTest::Examiner & examiner) { examiner.expect(Encoding::decode("foo%20bar")) == "foo bar"; } }, {"it can encode query", [](UnitTest::Examiner & examiner) { std::map<std::string, std::string> arguments = { {"x[]", "http://www.google.com/search?q=lucid"} }; auto query = Encoding::encode_query(arguments.begin(), arguments.end()); examiner.expect(query) == "x[]=http://www.google.com/search%3Fq%3Dlucid"; } }, {"it doesn't encode unreserved characters", [](UnitTest::Examiner & examiner) { std::map<std::string, std::string> arguments = { {"clip", "{{1,2},{3,4}}"} }; auto query = Encoding::encode_query(arguments.begin(), arguments.end()); examiner.expect(query) == "clip={{1,2},{3,4}}"; } }, {"it can encode path", [](UnitTest::Examiner & examiner) { std::vector<std::string> entries = {"blog", "2017", "Apples/oranges & the path to fruit salad!"}; auto path = Encoding::encode_path(entries.begin(), entries.end()); examiner.expect(path) == "blog/2017/Apples%2Foranges%20&%20the%20path%20to%20fruit%20salad!"; } }, {"it can encode native path", [](UnitTest::Examiner & examiner) { auto encoded = Encoding::encode_path("foo:bar", ':', true); examiner.expect(encoded) == "foo/bar/"; } }, {"it can encode native path containing utf8", [](UnitTest::Examiner & examiner) { auto encoded = Encoding::encode_path("I/♥/You", '/', false); examiner.expect(encoded) == "I/%E2%99%A5/You"; auto decoded = Encoding::decode_path(encoded, '/'); examiner.expect(decoded) == "I/♥/You"; } }, }; }
1df562954771240c47ea9747caca3c7e83815eb8
6d088ec295b33db11e378212d42d40d5a190c54c
/contrib/brl/bseg/boxm2/vecf/tests/test_orbit.cxx
c67e23fca056458804eb9ea5f7dc1552a9120bb4
[]
no_license
vxl/vxl
29dffd5011f21a67e14c1bcbd5388fdbbc101b29
594ebed3d5fb6d0930d5758630113e044fee00bc
refs/heads/master
2023-08-31T03:56:24.286486
2023-08-29T17:53:12
2023-08-29T17:53:12
9,819,799
224
126
null
2023-09-14T15:52:32
2013-05-02T18:32:27
C++
UTF-8
C++
false
false
2,073
cxx
test_orbit.cxx
//: // \file // \author J.L. Mundy // \date 11/19/14 #include <iostream> #include <fstream> #include "testlib/testlib_test.h" #ifdef _MSC_VER # include "vcl_msvc_warnings.h" #endif #include "vgl/vgl_box_3d.h" #include "vnl/vnl_vector_fixed.h" #include "vil/vil_image_view.h" #include "vil/vil_save.h" #include "vil/vil_load.h" #include "vul/vul_timer.h" #include <boct/boct_bit_tree.h> #include <boxm2/boxm2_util.h> #include <boxm2/io/boxm2_lru_cache.h> #include "vul/vul_file.h" #include "../boxm2_vecf_orbit_scene.h" #include "../boxm2_vecf_orbit_params.h" #include "../boxm2_vecf_eyelid.h" #include "../boxm2_vecf_eyelid_crease.h" typedef vnl_vector_fixed<unsigned char, 16> uchar16; //#define BUILD_TEST_ORBIT void test_orbit() { #ifdef BUILD_TEST_ORBIT boxm2_vecf_eyelid_crease ec; #if 0 double t = 1.0; std::cout << "{\n"; for(double x = -10.0; x<=10.0; x+=0.5){ double y = ec.gi(x, t); std::cout << "{" << x << ','<<y<<"},"; } std::cout << "}\n"; std::cout << ec.t(0.0,5.70955-0.88) << ' ' << ec.t(0.0,8.91894-0.88)<< '\n'; #endif #if 1 // Set up the scenes std::string base_dir_path = "c:/Users/mundy/VisionSystems/Janus/experiments/vector_flow/"; //std::string orbit_scene_path = base_dir_path + "orbit/orbit.25.xml"; //std::string target_scene_path = base_dir_path + "orbit/target_orbit.25.xml"; std::string orbit_scene_path = base_dir_path + "orbit/orbit.xml"; std::string target_scene_path = base_dir_path + "orbit/target_orbit.xml"; if(!vul_file::exists(orbit_scene_path)) { std::cout<<"orbit scene file) does not exist"<<std::endl; return; } //bool init = false; bool init = true; boxm2_vecf_orbit_scene* orbit = new boxm2_vecf_orbit_scene(orbit_scene_path, init); if(init) boxm2_cache::instance()->write_to_disk(); #if 0 boxm2_scene_sptr target_scene = new boxm2_scene(target_scene_path); boxm2_cache::instance()->add_scene(target_scene); orbit->map_to_target(target_scene); boxm2_cache::instance()->write_to_disk(); #endif #endif #endif //BUILD_TEST_ORBIT } TESTMAIN( test_orbit );
ee6324ab9c679eddf8f9ebbcfb894dcbe27453da
8d88c774dd7979401f434c1b0e35e4cb9a42938e
/380.Insert Delete GetRandom O(1).cpp
bc808229c5d66fb2a40d61e38905fe57fe10f3d6
[]
no_license
yycccccccc/Leetcode
15a76eca96f6d5420416d806b5372bdf2c55efbf
8e879cc1495e47f1230e968b941543326cb28f38
refs/heads/master
2020-05-27T08:09:58.411710
2019-03-28T06:46:43
2019-03-28T06:46:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,550
cpp
380.Insert Delete GetRandom O(1).cpp
题意: 设计一个数组结构能够执行插入,删除和获取随机数字的操作。 方法一:set 思路: 1.用set获取随机数组的操作不是线性的,但是为了熟悉一下set的操作。 2.set的特点是有序和去重,key按照递增排序;unordered_set的特点是去重,key是无序的。 3.set中插入操作是insert(),删除操作是erase(),判断set中有没有想找的值可以用count()来查找,也可以用s.find(值)!=s.end(),表示已经查找到。 4.set需要用迭代器来遍历,可以是从set.begin()开始,到不等于s.end()为止 也可以设置一个迭代器,用advance()函数对迭代器进行偏移操作,advance(it,n)表示向后偏移n个位置,n为整数 5.c++中rand()表示随机数发生器,可以产生随机数,本题中需要对产生的随机数取余用来产生移动的位置 6.注意输出迭代器的值的时候需要*it用取值符号。 class RandomizedSet { private: unordered_set<int> set; public: /** Initialize your data structure here. */ RandomizedSet() { } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ bool insert(int val) { if(set.count(val)) return false; else{ set.insert(val); return true; } } /** Removes a value from the set. Returns true if the set contained the specified element. */ bool remove(int val) { if(!set.count(val)) return false; else{ set.erase(val); return true; } } /** Get a random element from the set. */ int getRandom() { auto iter = set.begin(); advance(iter,rand()%set.size()); return *iter; } }; /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * bool param_1 = obj.insert(val); * bool param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */ 方法2:unordered_map 思路: 1.用一个数组记录所有数字,map用来记录值和值在数组中的对应关系 2.insert就分别在数组和map中插入即可 remove需要先在数组中把要删除的位置交换到最后一位上,同时更新map中的对应值,在map中删除,从数组最后pop_back()即可 3.最后输出随机数从数组中找rand()%vec.size()的值就可以 class RandomizedSet { private: unordered_map<int,int>map; vector<int>vec; public: /** Initialize your data structure here. */ RandomizedSet() { } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ bool insert(int val) { if(map.count(val)) return false; vec.push_back(val); map[val] = vec.size()-1; return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ bool remove(int val) { if(!map.count(val)) return false; int last = vec.back(); map[last] = map[val]; vec[map[val]] = last; vec.pop_back(); map.erase(val); return true; } /** Get a random element from the set. */ int getRandom() { return vec[rand()%vec.size()]; } }; /** * Your RandomizedSet object will be instantiated and called as such: * RandomizedSet obj = new RandomizedSet(); * bool param_1 = obj.insert(val); * bool param_2 = obj.remove(val); * int param_3 = obj.getRandom(); */
582c85d696733e4844221baa8e34d57b35b132b3
da487a14017908e4c65dd63f3629b1f744181166
/lib/r2ca_lib.cpp
44d434b87a29fea79bb1fe08e3d68ef4b744572d
[]
no_license
hori-takeshi/rtos_arduino
81584009c663568294fca20ffe90514bc5054e07
d6eb9b7fba0ad2462db2419b8379cb7649fe1310
refs/heads/master
2023-02-05T10:34:32.860098
2020-05-30T01:52:06
2020-05-30T01:52:06
267,990,886
0
0
null
null
null
null
IBM852
C++
false
false
7,270
cpp
r2ca_lib.cpp
#include "r2ca.h" #include "r2ca_lib.h" extern "C" { extern void yield(void); extern void r2ca_ena_int(uint_t intno); extern void r2ca_dis_int(uint_t intno); } #ifdef R2CA_ENABLE_PROFILING volatile uint32_t r2ca_idle_result; volatile uint32_t r2ca_isr_result; volatile uint32_t r2ca_dispatch_result; volatile uint32_t r2ca_timer_isr_result; volatile uint32_t r2ca_usb_isr_result; volatile uint32_t r2ca_sercom0_isr_result; volatile uint32_t r2ca_sercom2_isr_result; volatile uint32_t r2ca_sercom3_isr_result; volatile uint32_t r2ca_sercom4_isr_result; volatile uint32_t r2ca_sercom5_isr_result; volatile uint32_t r2ca_eic_isr_result; volatile uint32_t r2ca_tc5_isr_result; volatile uint32_t r2ca_rtc_isr_result; static volatile uint32_t r2ca_idle_cnt; static volatile uint32_t r2ca_isr_cnt; static volatile uint32_t r2ca_dispatch_cnt; static volatile uint32_t r2ca_timer_isr_cnt; static volatile uint32_t r2ca_usb_isr_cnt; static volatile uint32_t r2ca_sercom0_isr_cnt; static volatile uint32_t r2ca_sercom2_isr_cnt; static volatile uint32_t r2ca_sercom3_isr_cnt; static volatile uint32_t r2ca_sercom4_isr_cnt; static volatile uint32_t r2ca_sercom5_isr_cnt; static volatile uint32_t r2ca_eic_isr_cnt; static volatile uint32_t r2ca_tc5_isr_cnt; static volatile uint32_t r2ca_rtc_isr_cnt; static volatile uint32_t r2ca_profiling_cyccnt; #endif /* R2CA_ENABLE_PROFILING */ Inline void r2ca_di(void){ Asm("cpsid f":::"memory"); } /* * FAULTMASKé╠âNâŐâA */ Inline void r2ca_ei(void){ Asm("cpsie f":::"memory"); } void r2ca_init(intptr_t exinf) { init(); //wiring.c } void r2ca_ena_int(uint_t intno) { if (ena_int(intno + 16) != E_OK) { while(1); //ToDo } } void r2ca_dis_int(uint_t intno) { if (dis_int(intno + 16) != E_OK) { while(1); //ToDo } } extern const DeviceVectors exception_table; static uint32_t time_slice = 0; /* * Cyclic Handler */ void r2ca_CycHandler(intptr_t exinf) { int i; if (++time_slice == R2CA_RR_SCHEDULE_CYCLE) { time_slice = 0; for(i = 1; i < 16; i++){ if (R2CA_RR_SCHEDULE_PRI & (1 << i)) { irot_rdq(i); } } } #ifdef R2CA_ENABLE_PROFILING r2ca_di(); r2ca_isr_cnt++; r2ca_timer_isr_cnt++; r2ca_profiling_cyccnt++; if(r2ca_profiling_cyccnt == R2CA_PROFILING_CYC_MS){ r2ca_idle_result= r2ca_idle_cnt; r2ca_isr_result= r2ca_isr_cnt; r2ca_dispatch_result= r2ca_dispatch_cnt; r2ca_timer_isr_result= r2ca_timer_isr_cnt; r2ca_usb_isr_result= r2ca_usb_isr_cnt; r2ca_sercom0_isr_result= r2ca_sercom0_isr_cnt; r2ca_sercom2_isr_result= r2ca_sercom2_isr_cnt; r2ca_sercom3_isr_result= r2ca_sercom3_isr_cnt; r2ca_sercom4_isr_result= r2ca_sercom4_isr_cnt; r2ca_sercom5_isr_result= r2ca_sercom5_isr_cnt; r2ca_eic_isr_result= r2ca_eic_isr_cnt; r2ca_tc5_isr_result= r2ca_tc5_isr_cnt; r2ca_rtc_isr_result= r2ca_rtc_isr_cnt; r2ca_idle_cnt = 0; r2ca_isr_cnt = 0; r2ca_dispatch_cnt = 0; r2ca_timer_isr_cnt = 0; r2ca_usb_isr_cnt = 0; r2ca_sercom0_isr_cnt = 0; r2ca_sercom2_isr_cnt = 0; r2ca_sercom3_isr_cnt = 0; r2ca_sercom4_isr_cnt = 0; r2ca_sercom5_isr_cnt = 0; r2ca_eic_isr_cnt = 0; r2ca_tc5_isr_cnt = 0; r2ca_rtc_isr_cnt = 0; r2ca_profiling_cyccnt = 0; } r2ca_ei(); #endif /* R2CA_ENABLE_PROFILING */ ((void(*)(void))(exception_table.pfnSysTick_Handler))(); } /* * Interrupt Handler */ void r2ca_USB_Handler(void) { #ifdef R2CA_ENABLE_PROFILING r2ca_di(); r2ca_usb_isr_cnt++; r2ca_isr_cnt++; r2ca_ei(); #endif /* R2CA_ENABLE_PROFILING */ ((void(*)(void))(exception_table.pfnUSB_Handler))(); } void r2ca_SERCOM0_Handler(void) { #ifdef R2CA_ENABLE_PROFILING r2ca_di(); r2ca_sercom0_isr_cnt++; r2ca_isr_cnt++; r2ca_ei(); #endif /* R2CA_ENABLE_PROFILING */ ((void(*)(void))(exception_table.pfnSERCOM0_Handler))(); } #ifdef R2CA_USE_SERIAL3 #define PIN_SERIAL3_RX 49 /* D5 */ #define PIN_SERIAL3_TX 48 /* D4 */ Uart Serial3(&sercom2, PIN_SERIAL3_RX, PIN_SERIAL3_TX); void r2ca_SERCOM2_Handler(void) { #ifdef R2CA_ENABLE_PROFILING r2ca_di(); r2ca_sercom2_isr_cnt++; r2ca_isr_cnt++; r2ca_ei(); #endif /* R2CA_ENABLE_PROFILING */ Serial3.IrqHandler(); } #endif /* R2CA_USE_SERIAL3 */ void r2ca_SERCOM3_Handler(void) { #ifdef R2CA_ENABLE_PROFILING r2ca_di(); r2ca_sercom3_isr_cnt++; r2ca_isr_cnt++; r2ca_ei(); #endif /* R2CA_ENABLE_PROFILING */ ((void(*)(void))(exception_table.pfnSERCOM3_Handler))(); } void r2ca_SERCOM4_Handler(void) { #ifdef R2CA_ENABLE_PROFILING r2ca_di(); r2ca_sercom4_isr_cnt++; r2ca_isr_cnt++; r2ca_ei(); #endif /* R2CA_ENABLE_PROFILING */ ((void(*)(void))(exception_table.pfnSERCOM4_Handler))(); } #ifdef TOPPERS_USE_ARDUINO_SERIAL void r2ca_SERCOM5_Handler(void) { #ifdef R2CA_ENABLE_PROFILING r2ca_di(); r2ca_sercom5_isr_cnt++; r2ca_isr_cnt++; r2ca_ei(); #endif /* R2CA_ENABLE_PROFILING */ ((void(*)(void))(exception_table.pfnSERCOM5_Handler))(); } #endif /* TOPPERS_USE_ARDUINO_SERIAL */ void r2ca_EIC_Handler(void) { #ifdef R2CA_ENABLE_PROFILING r2ca_di(); r2ca_eic_isr_cnt++; r2ca_isr_cnt++; r2ca_ei(); #endif /* R2CA_ENABLE_PROFILING */ ((void(*)(void))(exception_table.pfnEIC_Handler))(); } void r2ca_TC5_Handler(void) { #ifdef R2CA_ENABLE_PROFILING r2ca_di(); r2ca_tc5_isr_cnt++; r2ca_isr_cnt++; r2ca_ei(); #endif /* R2CA_ENABLE_PROFILING */ ((void(*)(void))(exception_table.pfnTC5_Handler))(); } void r2ca_RTC_Handler(void) { #ifdef R2CA_ENABLE_PROFILING r2ca_di(); r2ca_rtc_isr_cnt++; r2ca_isr_cnt++; r2ca_ei(); #endif /* R2CA_ENABLE_PROFILING */ ((void(*)(void))(exception_table.pfnRTC_Handler))(); } /* * For delay */ void yield(void){ time_slice = 0; #ifdef R2CA_ENABLE_PROFILING r2ca_di(); r2ca_dispatch_cnt++; r2ca_ei(); #endif /* R2CA_ENABLE_PROFILING */ dly_tsk(0); } extern void setup(void); extern void loop(void); const ID task_id[] = { #if R2CA_NUM_TASK > 0 R2CA_TASK1, #endif /* R2CA_NUM_TASK > 0 */ #if R2CA_NUM_TASK > 1 R2CA_TASK2, #endif /* R2CA_NUM_TASK > 1 */ #if R2CA_NUM_TASK > 2 R2CA_TASK3, #endif /* R2CA_NUM_TASK > 2 */ #if R2CA_NUM_TASK > 3 R2CA_TASK4, #endif /* R2CA_NUM_TASK > 3 */ #if R2CA_NUM_TASK > 4 R2CA_TASK5, #endif /* R2CA_NUM_TASK > 4 */ }; void r2ca_maintask(intptr_t exinf) { int i; syslog(LOG_NOTICE, "Arduino Main Task start!"); #ifdef USBCON USBDevice.init(); USBDevice.attach(); #endif /* USBCON */ analogReference(AR_DEFAULT); setup(); for(i = 0; i < R2CA_NUM_TASK; i++) { act_tsk(task_id[i]); } while(1){ loop(); if (serialEventRun) serialEventRun(); } } #define R2CA_TASK_BODY(NUM) \ extern void loop##NUM(void); \ \ void \ r2ca_task##NUM(intptr_t exinf) \ { \ while(1){ \ loop##NUM(); \ } \ } #if R2CA_NUM_TASK > 0 R2CA_TASK_BODY(1) #endif /* R2CA_NUM_TASK > 0 */ #if R2CA_NUM_TASK > 1 R2CA_TASK_BODY(2) #endif /* R2CA_NUM_TASK > 1 */ #if R2CA_NUM_TASK > 2 R2CA_TASK_BODY(3) #endif /* R2CA_NUM_TASK > 2 */ #if R2CA_NUM_TASK > 3 R2CA_TASK_BODY(4) #endif /* R2CA_NUM_TASK > 3 */ #if R2CA_NUM_TASK > 4 R2CA_TASK_BODY(5) #endif /* R2CA_NUM_TASK > 4 */ #ifdef R2CA_ENABLE_PROFILING void r2ca_idle_task(intptr_t exinf) { while(1){ r2ca_di(); r2ca_idle_cnt++; r2ca_ei(); } } #endif /* R2CA_ENABLE_PROFILING */
d3404bfde3a33c0652ae7453ea5ce75fbde5b662
9a888c6ddd86c1938cd672c5f2ac24e928e48665
/EDITCTLS/SIMPLE/SIMPLE.CPP
1b5b357e7535e6b3001b0b9eeb3ce6f09f5c37e2
[ "BSD-3-Clause" ]
permissive
OS2World/DEV-SAMPLES-BOOK-Power_GUI_Programming_with_VisualAge_for_Cpp
228390f4876520bb72afd5a25fc985fb6ea82de8
919dfa422daf18d2bbb924213a0a813c06565720
refs/heads/master
2020-05-29T18:33:38.074186
2019-05-29T22:02:13
2019-05-29T22:02:13
189,303,859
0
0
null
null
null
null
UTF-8
C++
false
false
1,349
cpp
SIMPLE.CPP
//************************************************************ // Edit Controls - Simple Edit Example // // Copyright (C) 1994, Law, Leong, Love, Olson, Tsuji. // Copyright (c) 1997 John Wiley & Sons, Inc. // All Rights Reserved. //************************************************************ #include <iapp.hpp> #include <ientryfd.hpp> #include <iframe.hpp> #include <imcelcv.hpp> #include <imle.hpp> #include <istring.hpp> void main() { // Create the frame, client canvas and edit controls. IFrameWindow aFrame( "Simple edit example" ); IMultiCellCanvas aClient( 1000, &aFrame, &aFrame ); IEntryField myEntryField( 1001, &aClient, &aClient ); IMultiLineEdit myMLE( 1002, &aClient, &aClient ); // Add the edit controls to the canvas. aClient .addToCell( &myEntryField, 2, 2 ) .addToCell( &myMLE, 2, 4 ); // Set the text of the entry field. myEntryField.setText( "Common Text Operations" ); // Query the text of the entry field. IString text = myEntryField.text(); // Find the length of the text in the entry field. int length = myEntryField.textLength(); // Now apply the same functions to an MLE. myMLE.setText( "Common Text Operations" ); text = myMLE.text(); length = myMLE.textLength(); aFrame .setClient( &aClient ) .setFocus() .show(); IApplication::current().run(); } 
b78ba3cb44171d1646ca808a3ae0637916083242
0d7ab97cf6d58ba24f4c8d6228fb46e38df69478
/src/sp.hpp
125a584b7b876bd9929a733a5560111b25397d69
[]
no_license
cheng-hsiang-chiu/sequence_pair_floorplan
d0851d23fffd160391837a320ea6bea32ab75f92
9520ada7e5d4ea62e98c394581d5ed1ac05fcf3d
refs/heads/master
2023-03-01T12:52:51.463319
2021-01-29T01:04:02
2021-01-29T01:04:02
328,098,012
0
0
null
null
null
null
UTF-8
C++
false
false
20,018
hpp
sp.hpp
#include <iostream> #include <vector> #include <random> #include <map> #include <chrono> #include <fstream> #include <queue> #include <utility> #include <algorithm> #include <iterator> #include <cassert> #define SP_FROZEN_TEMPERATURE 0.1 #define SP_MAX_ITERATIONS_PER_TEMPERATURE 1000 #define SP_RANDOM_MOVES 60 #define SP_P 0.99 #define SP_T0 -1 namespace sp { struct Node{ size_t id; size_t width; size_t height; size_t llx; size_t lly; Node(size_t n_id, size_t n_width, size_t n_height, size_t n_llx, size_t n_lly) : id(n_id), width(n_width), height(n_height), llx(n_llx), lly(n_lly) {} }; class SequencePair{ friend class SequencePairTester; public: SequencePair() = default; void optimize(); void open(const std::string input_file); void dump(std::ostream& os) const; void dump_json(std::string output_file) const; private: size_t _num_modules = 0; std::string _input_file; std::vector<Node> _modules; std::vector<Node> _modules_best; std::vector<size_t> _positive_sequence_curr; std::vector<size_t> _negative_sequence_curr; std::vector<size_t> _positive_sequence_prop; std::vector<size_t> _negative_sequence_prop; std::vector<size_t> _positive_sequence_best; std::vector<size_t> _negative_sequence_best; std::random_device _rd; std::mt19937 _gen{_rd()}; size_t _urx = 0; size_t _ury = 0; std::vector<size_t> _topology_order; std::vector<size_t> _cost; std::map<size_t, size_t> _mapping; std::vector<std::vector<size_t>> _adjacency_list_horizontal; std::vector<std::vector<size_t>> _adjacency_list_vertical; std::vector<size_t> _in_degree_horizontal; std::vector<size_t> _in_degree_vertical; std::vector<size_t> _in_degree; std::queue<size_t> _queue; std::vector<size_t> _seq; std::vector<bool> _is_exist; void _generate_initial_pair(); double _calculate_initial_temperature(); void _simulated_annealing(const double initial_temperature); size_t _generate_neighbors(); size_t _pack( const std::vector<size_t>& positive_sequence, const std::vector<size_t>& negative_sequence, const size_t operation); void _pack_helper( const std::vector<size_t>& positive_sequence, const std::vector<size_t>& negative_sequence, const bool is_horizontal, const size_t operation); void _dump_cost(std::string output_file) const; void _rotate_module(); void _swap_two_nodes_positive_sequence(); void _swap_two_nodes_negative_sequence(); void _swap_two_nodes_two_sequences(); void _generate_adjacency_list( const std::vector<size_t>& positive_sequence, const std::vector<size_t>& negative_sequence, const bool is_horizontal); void _get_topology_order(const bool is_horizontal); void _get_longest_path(const bool is_horizontal); }; // read in the module configurations void SequencePair::open(const std::string input_file) { _input_file = input_file; std::ifstream infile(input_file); if (!infile) { std::cerr << "File could not be opened!!\n"; std::exit(EXIT_FAILURE); } size_t width, height, id, index = 0; infile >> _num_modules; _modules.reserve(_num_modules); while (infile >> id >> width >> height) { _modules.emplace_back(id, width, height, 0, 0); _mapping.emplace(id, index++); } std::cout << "Modules are successfully opened!!\n"; } // dump floorplan to console void SequencePair::dump(std::ostream& os) const { for (size_t i = 0; i < _num_modules; ++i) { os << _modules[i].id << ' ' << _modules[i].llx << ' ' << _modules[i].lly << ' ' << _modules[i].width << ' ' << _modules[i].height << '\n'; } } // dump floorplan to a file with a json extesion void SequencePair::dump_json(std::string output_file) const { //_dump_cost(output_file); if (output_file.rfind(".json") == std::string::npos) { output_file.append(".json"); } std::ofstream outfile(output_file, std::ios::out); if (!outfile) { std::cerr << "File could not be opened for writing\n"; std::exit(EXIT_FAILURE); } // generate json output outfile << "{\"circuit\":\"" << _input_file << "\"" << ",\"block_number\":" << _num_modules << ",\"llx\":0" << ",\"lly\":0" << ",\"urx\":" << _urx << ",\"ury\":" << _ury << ",\"area\":" << (_urx * _ury) << ",\"coordinates\":" << "["; for (size_t i = 0; i < _num_modules; ++i) { outfile << "{\"idx\":" << _modules[i].id << ",\"llx\":" << _modules[i].llx << ",\"lly\":" << _modules[i].lly << ",\"width\":" << _modules[i].width << ",\"height\":" << _modules[i].height; if(i == _num_modules-1) { outfile << "}"; } else { outfile << "},"; } } outfile << "]}"; } // dump the cost void SequencePair::_dump_cost(const std::string output_file) const { std::ofstream outfile(output_file + "_cost.txt", std::ios::out); if (!outfile) { std::cerr << "File could not be opened for writing\n"; std::exit(EXIT_FAILURE); } for (auto c : _cost) { outfile << c << '\n'; } } // generate an initial pair void SequencePair::_generate_initial_pair() { _adjacency_list_horizontal.resize(_num_modules); _adjacency_list_vertical.resize(_num_modules); for (size_t i = 0; i < _num_modules; ++i) { _adjacency_list_horizontal.at(i).resize(_num_modules); _adjacency_list_vertical.at(i).resize(_num_modules); } _in_degree_horizontal.resize(_num_modules); _in_degree_vertical.resize(_num_modules); _topology_order.resize(_num_modules); _is_exist.resize(_num_modules); _positive_sequence_curr.resize(_num_modules); _negative_sequence_curr.resize(_num_modules); _positive_sequence_prop.resize(_num_modules); _negative_sequence_prop.resize(_num_modules); _positive_sequence_best.resize(_num_modules); _negative_sequence_best.resize(_num_modules); for (size_t i = 0; i < _num_modules; ++i) { _positive_sequence_curr.at(i) = _modules[i].id; _negative_sequence_curr.at(i) = _modules[i].id; } _positive_sequence_prop = _positive_sequence_curr; _negative_sequence_prop = _negative_sequence_curr; _positive_sequence_best = _positive_sequence_curr; _negative_sequence_best = _negative_sequence_curr; /* _positive_sequence[0] = 1; _positive_sequence[1] = 2; _positive_sequence[2] = 4; _positive_sequence[3] = 5; _positive_sequence[4] = 3; _positive_sequence[5] = 0; _negative_sequence[0] = 3; _negative_sequence[1] = 2; _negative_sequence[2] = 0; _negative_sequence[3] = 1; _negative_sequence[4] = 4; _negative_sequence[5] = 5; */ } // generate the optimized floorplan void SequencePair::optimize() { _generate_initial_pair(); auto tbeg = std::chrono::steady_clock::now(); double initial_temperature = _calculate_initial_temperature(); auto tend = std::chrono::steady_clock::now(); std::cout << "initial temperature = " << initial_temperature << '\n'; std::cout << "calculate initial temperature completed: " << std::chrono::duration_cast<std::chrono::microseconds>(tend-tbeg).count() << " microseconds\n"; tbeg = std::chrono::steady_clock::now(); _simulated_annealing(initial_temperature); tend = std::chrono::steady_clock::now(); std::cout << "simulated annealing completed: " << std::chrono::duration_cast<std::chrono::microseconds>(tend-tbeg).count() << " microseconds\n"; _modules = _modules_best; tbeg = std::chrono::steady_clock::now(); size_t area = _pack(_positive_sequence_curr, _negative_sequence_curr, 1); tend = std::chrono::steady_clock::now(); std::cout << "pack modules completed: " << std::chrono::duration_cast<std::chrono::microseconds>(tend-tbeg).count() << " microseconds" << std::endl; } // calculate initial temperature double SequencePair::_calculate_initial_temperature() { size_t num_moves = 0; double total_area_change = 0.0; double delta_area, avg_area_change, init_temperature; size_t area_curr = _pack(_positive_sequence_curr, _negative_sequence_curr, 1); size_t area_prop = area_curr; while (num_moves < SP_RANDOM_MOVES) { size_t operation = _generate_neighbors(); area_prop = _pack(_positive_sequence_prop, _negative_sequence_prop, operation); delta_area = area_prop > area_curr ? (area_prop - area_curr) : (area_curr - area_prop); total_area_change += delta_area; ++num_moves; area_curr = area_prop; } _positive_sequence_curr = _positive_sequence_prop; _negative_sequence_curr = _negative_sequence_prop; _positive_sequence_best = _positive_sequence_prop; _negative_sequence_best = _negative_sequence_prop; avg_area_change = total_area_change / num_moves; init_temperature = SP_P < 1 ? (SP_T0 * avg_area_change) / log(SP_P) : avg_area_change / log(SP_P); return init_temperature; } // perform simulated annealing void SequencePair::_simulated_annealing(const double initial_temperature) { std::uniform_real_distribution<> dis(0.0, 1.0); double temperature = initial_temperature; size_t area_best = _urx * _ury; size_t area_curr = area_best; size_t area_prop = area_curr; double cost = 0; size_t operation = 0; while (temperature > SP_FROZEN_TEMPERATURE) { for (size_t iter = 0; iter < SP_MAX_ITERATIONS_PER_TEMPERATURE; iter++) { _positive_sequence_prop = _positive_sequence_curr; _negative_sequence_prop = _negative_sequence_curr; operation = _generate_neighbors(); area_prop = _pack(_positive_sequence_prop, _negative_sequence_prop, operation); cost = area_prop < area_curr ? (double)-1*(area_curr - area_prop) : (area_prop - area_curr); //_cost.emplace_back(area_best); if (cost < 0) { //_cost.push_back(area_prop); if (operation != 0) { _positive_sequence_curr = _positive_sequence_prop; _negative_sequence_curr = _negative_sequence_prop; } area_curr = area_prop; if (area_prop < area_best) { _positive_sequence_best = _positive_sequence_prop; _negative_sequence_best = _negative_sequence_prop; area_best = area_prop; _modules_best = _modules; } } else { auto prob = std::exp(-cost / temperature); if (prob > dis(_gen)) { //_cost.push_back(area_prop); if (operation != 0) { _positive_sequence_curr = _positive_sequence_prop; _negative_sequence_curr = _negative_sequence_prop; } area_curr = area_prop; } } } temperature *= 0.95; } _positive_sequence_curr = _positive_sequence_best; _negative_sequence_curr = _negative_sequence_best; } // generate neighbors size_t SequencePair::_generate_neighbors() { std::uniform_real_distribution<> dis(0.0, 4.0); size_t choice = static_cast<size_t>(dis(_gen)); switch(choice) { case 0: _rotate_module(); break; case 1: _swap_two_nodes_positive_sequence(); break; case 2: _swap_two_nodes_negative_sequence(); break; case 3: _swap_two_nodes_two_sequences(); break; } return choice; } // pack the modules size_t SequencePair::_pack(const std::vector<size_t>& positive_sequence, const std::vector<size_t>& negative_sequence, const size_t operation) { _pack_helper(positive_sequence, negative_sequence, true, operation); _pack_helper(positive_sequence, negative_sequence, false, operation); size_t urx = 0, ury = 0; for (size_t i = 0; i < _num_modules; ++i) { if (_modules[i].llx + _modules[i].width > urx) { urx = _modules[i].llx + _modules[i].width; } if (_modules[i].lly + _modules[i].height > ury) { ury = _modules[i].lly + _modules[i].height; } } _urx = urx; _ury = ury; return (_urx * _ury); } // pack helper void SequencePair::_pack_helper( const std::vector<size_t>& positive_sequence, const std::vector<size_t>& negative_sequence, const bool is_horizontal, const size_t operation) { if (operation != 0) { _generate_adjacency_list(positive_sequence, negative_sequence, is_horizontal); } _get_topology_order(is_horizontal); _get_longest_path(is_horizontal); } // rotate a moudle void SequencePair::_rotate_module() { std::uniform_real_distribution<> dis(0.0, _modules.size()); size_t idx = static_cast<size_t>(dis(_gen)); std::swap(_modules[idx].width, _modules[idx].height); } // swap two modules in positive sequence void SequencePair::_swap_two_nodes_positive_sequence() { std::uniform_real_distribution<> dis(0.0, _num_modules); size_t idx1 = static_cast<size_t>(dis(_gen)); size_t idx2 = static_cast<size_t>(dis(_gen)); while (idx1 == idx2) { idx2 = static_cast<size_t>(dis(_gen)); } std::swap(_positive_sequence_prop[idx1], _positive_sequence_prop[idx2]); } // swap two modules in negative sequence void SequencePair::_swap_two_nodes_negative_sequence() { std::uniform_real_distribution<> dis(0.0, _num_modules); size_t idx1 = static_cast<size_t>(dis(_gen)); size_t idx2 = static_cast<size_t>(dis(_gen)); while (idx1 == idx2) { idx2 = static_cast<size_t>(dis(_gen)); } std::swap(_negative_sequence_prop[idx1], _negative_sequence_prop[idx2]); } // swap two moduels in both sequences void SequencePair::_swap_two_nodes_two_sequences() { std::uniform_real_distribution<> dis(0.0, _num_modules); size_t pidx1 = static_cast<size_t>(dis(_gen)); size_t pidx2 = static_cast<size_t>(dis(_gen)); while (pidx1 == pidx2) { pidx2 = static_cast<size_t>(dis(_gen)); } std::vector<size_t>::iterator it; it = std::find(_negative_sequence_prop.begin(), _negative_sequence_prop.end(), _positive_sequence_prop[pidx1]); assert (it != _negative_sequence_prop.end()); size_t nidx1 = std::distance(_negative_sequence_prop.begin(), it); it = std::find(_negative_sequence_prop.begin(), _negative_sequence_prop.end(), _positive_sequence_prop[pidx2]); assert (it != _negative_sequence_prop.end()); size_t nidx2 = std::distance(_negative_sequence_prop.begin(), it); std::swap(_positive_sequence_prop[pidx1], _positive_sequence_prop[pidx2]); std::swap(_negative_sequence_prop[nidx1], _negative_sequence_prop[nidx2]); } // generate adjacency_list void SequencePair::_generate_adjacency_list( const std::vector<size_t>& positive_sequence, const std::vector<size_t>& negative_sequence, const bool is_horizontal) { std::vector<size_t>::const_iterator it; size_t pidx = 0, nidx = 0; if (is_horizontal) { for (auto& list : _adjacency_list_horizontal) list.clear(); for (size_t i = 0; i < _num_modules; ++i) { _in_degree_horizontal.at(i) = 0; } } else { for (auto& list : _adjacency_list_vertical) list.clear(); for (size_t i = 0; i < _num_modules; ++i) { _in_degree_vertical.at(i) = 0; } } _is_exist.clear(); for (size_t i = 1; i < _num_modules; ++i) { _is_exist[positive_sequence[i]] = true; } while (pidx < _num_modules) { size_t node1_id = positive_sequence[pidx]; _is_exist[node1_id] = false; it = std::find(negative_sequence.begin(), negative_sequence.end(), node1_id); assert(it != negative_sequence.end()); nidx = std::distance(negative_sequence.begin(), it); // adjacency_list for horizontal dag if (is_horizontal) { for (size_t i = nidx+1; i < _num_modules; ++i) { if (_is_exist[negative_sequence[i]]) { _adjacency_list_horizontal[node1_id].emplace_back(negative_sequence[i]); _in_degree_horizontal.at(negative_sequence[i]) = _in_degree_horizontal.at(negative_sequence[i]) + 1; } } } // adjacency_list for vertical dag else { for (size_t i = 0; i < nidx; ++i) { if (_is_exist[negative_sequence[i]]) { _adjacency_list_vertical[negative_sequence[i]].emplace_back(node1_id); _in_degree_vertical.at(node1_id) = _in_degree_vertical.at(node1_id) + 1; } } /* for (int i = static_cast<int>(nidx)-1; i >= 0; --i) { if (_is_exist[negative_sequence[i]]) { _adjacency_list_vertical[negative_sequence[i]].emplace_back(node1_id); _in_degree_vertical.at(node1_id) = _in_degree_vertical.at(node1_id) + 1; } } */ } ++pidx; } } // get topology order of the adjacency_list void SequencePair::_get_topology_order( const bool is_horizontal) { if (is_horizontal) { _in_degree = _in_degree_horizontal; } else { _in_degree = _in_degree_vertical; } _topology_order.clear(); for (size_t i = 0; i < _num_modules; ++i) { if (_in_degree[i] == 0) { _queue.push(i); } } while (!_queue.empty()) { size_t n = _queue.front(); _queue.pop(); _topology_order.emplace_back(n); if (is_horizontal) { for (size_t i = 0; i < _adjacency_list_horizontal[n].size(); ++i) { if ((--_in_degree[_adjacency_list_horizontal[n][i]]) == 0) { _queue.push(_adjacency_list_horizontal[n][i]); } } } else { for (size_t i = 0; i < _adjacency_list_vertical[n].size(); ++i) { if ((--_in_degree[_adjacency_list_vertical[n][i]]) == 0) { _queue.push(_adjacency_list_vertical[n][i]); } } } } } // get the longest path void SequencePair::_get_longest_path(const bool is_horizontal) { // TODO: if(is_horizontal) { for(size_t i=0; i< _num_modules; ++i) { _modules[i].llx = 0; } // TODO: can we do this // std::memset(src, num_bytes, 0); } else { for(size_t i=0; i< _num_modules; ++i) { _modules[i].lly = 0; } } //for (size_t i = 0; i < _num_modules; ++i) { // // if(is_horizontal) { // _modules[i].llx = 0; // } // else { // _modules[i].lly = 0; // } //} size_t cost = 0; size_t sid = 0; for (size_t i = 0; i < _num_modules; ++i) { sid = _topology_order[i]; if (is_horizontal) { for (size_t j = 0; j < _adjacency_list_horizontal.at(sid).size(); ++j) { cost = _modules[_mapping.at(sid)].width; if (_modules[_mapping.at(_adjacency_list_horizontal.at(sid).at(j))].llx < _modules[_mapping.at(sid)].llx + cost) { _modules[_mapping.at(_adjacency_list_horizontal.at(sid).at(j))].llx = _modules[_mapping.at(sid)].llx + cost; } } } else { for (size_t j = 0; j < _adjacency_list_vertical.at(sid).size(); ++j) { cost = _modules[_mapping.at(sid)].height; if (_modules[_mapping.at(_adjacency_list_vertical.at(sid).at(j))].lly < _modules[_mapping.at(sid)].lly + cost) { _modules[_mapping.at(_adjacency_list_vertical.at(sid).at(j))].lly = _modules[_mapping.at(sid)].lly + cost; } } } } } }
fd4679e0aa770dcfaf8ca6222960d5e2413025f3
0ebf0dffca0c1c32684cccb7465157ce35a07355
/xa_nnlib/test/tf_micro_lite/test/tensorflow/tensorflow/lite/experimental/micro/simple_tensor_allocator.cpp
ef1082df3de1181fc47339775b14fb393bce5810
[ "LicenseRef-scancode-other-permissive" ]
permissive
nyadla-sys/nnlib-hifi4
19b0cd947e58ae4c0577bedc8b388238999d9419
13b1ac756a48f763f02c936e0a87feeabbb808b9
refs/heads/master
2021-05-25T21:13:31.680706
2020-05-08T22:25:37
2020-05-08T22:25:37
253,921,342
0
0
null
2020-04-07T21:57:59
2020-04-07T21:57:59
null
UTF-8
C++
false
false
7,008
cpp
simple_tensor_allocator.cpp
/******************************************************************************* * Copyright (c) 2018-2020 Cadence Design Systems, Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to use this Software with Cadence processor cores only and * not with any other processors and platforms, 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. ******************************************************************************/ /* Copyright 2018 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. ==============================================================================*/ #include "tensorflow/lite/experimental/micro/simple_tensor_allocator.h" #include "tensorflow/lite/core/api/flatbuffer_conversions.h" namespace tflite { namespace { TfLiteStatus TfLiteTypeSizeOf(TfLiteType type, size_t* size, ErrorReporter* reporter) { switch (type) { case kTfLiteFloat32: *size = sizeof(float); break; case kTfLiteInt16: *size = sizeof(int16_t); break; case kTfLiteInt32: *size = sizeof(int32_t); break; case kTfLiteUInt8: *size = sizeof(uint8_t); break; case kTfLiteInt64: *size = sizeof(int64_t); break; case kTfLiteBool: *size = sizeof(bool); break; case kTfLiteComplex64: *size = sizeof(float) * 2; break; default: reporter->Report( "Only float32, int16, int32, int64, uint8, bool, complex64 " "supported currently."); return kTfLiteError; } return kTfLiteOk; } TfLiteStatus BytesRequired(const tflite::Tensor& flatbuffer_tensor, size_t dims_size, size_t* bytes, size_t* type_size, ErrorReporter* error_reporter) { TfLiteType tf_lite_type; TF_LITE_ENSURE_STATUS(ConvertTensorType(flatbuffer_tensor.type(), &tf_lite_type, error_reporter)); TF_LITE_ENSURE_STATUS( TfLiteTypeSizeOf(tf_lite_type, type_size, error_reporter)); *bytes = dims_size * (*type_size); return kTfLiteOk; } uint8_t* AlignPointerRoundUp(uint8_t* data, size_t alignment) { size_t data_as_size_t = reinterpret_cast<size_t>(data); uint8_t* aligned_result = reinterpret_cast<uint8_t*>( ((data_as_size_t + (alignment - 1)) / alignment) * alignment); return aligned_result; } } // namespace TfLiteStatus SimpleTensorAllocator::AllocateTensor( const tflite::Tensor& flatbuffer_tensor, int create_before, int destroy_after, const flatbuffers::Vector<flatbuffers::Offset<Buffer>>* buffers, ErrorReporter* error_reporter, TfLiteTensor* result) { TF_LITE_ENSURE_STATUS(ConvertTensorType(flatbuffer_tensor.type(), &result->type, error_reporter)); result->is_variable = flatbuffer_tensor.is_variable(); result->data.raw = nullptr; result->bytes = 0; if (auto* buffer = (*buffers)[flatbuffer_tensor.buffer()]) { if (auto* array = buffer->data()) { if (size_t array_size = array->size()) { result->data.raw = const_cast<char*>(reinterpret_cast<const char*>(array->data())); size_t type_size; TF_LITE_ENSURE_STATUS(BytesRequired(flatbuffer_tensor, array_size, &result->bytes, &type_size, error_reporter)); } } } if (result->data.raw) { result->allocation_type = kTfLiteMmapRo; } else { int data_size = 1; for (int n = 0; n < flatbuffer_tensor.shape()->Length(); ++n) { data_size *= flatbuffer_tensor.shape()->Get(n); } size_t type_size; TF_LITE_ENSURE_STATUS(BytesRequired(flatbuffer_tensor, data_size, &result->bytes, &type_size, error_reporter)); result->data.raw = reinterpret_cast<char*>(AllocateMemory(result->bytes, type_size)); if (result->data.raw == nullptr) { const char* tensor_name = flatbuffer_tensor.name()->c_str(); if (tensor_name == nullptr) { tensor_name = "<None>"; } error_reporter->Report( "Couldn't allocate memory for tensor '%s', wanted %d bytes but only " "%d were available", tensor_name, result->bytes, (data_size_max_ - data_size_)); return kTfLiteError; } result->allocation_type = kTfLiteArenaRw; } result->dims = reinterpret_cast<TfLiteIntArray*>(AllocateMemory( sizeof(int) * (flatbuffer_tensor.shape()->Length() + 1), sizeof(int))); result->dims->size = flatbuffer_tensor.shape()->Length(); for (int n = 0; n < flatbuffer_tensor.shape()->Length(); ++n) { result->dims->data[n] = flatbuffer_tensor.shape()->Get(n); } if (flatbuffer_tensor.quantization()) { result->params.scale = flatbuffer_tensor.quantization()->scale()->Get(0); result->params.zero_point = flatbuffer_tensor.quantization()->zero_point()->Get(0); } result->allocation = nullptr; if (flatbuffer_tensor.name()) { result->name = flatbuffer_tensor.name()->c_str(); } else { result->name = "<No name>"; } result->delegate = nullptr; result->buffer_handle = 0; result->data_is_stale = false; return kTfLiteOk; } uint8_t* SimpleTensorAllocator::AllocateMemory(size_t size, size_t alignment) { uint8_t* current_data = data_ + data_size_; uint8_t* aligned_result = AlignPointerRoundUp(current_data, alignment); uint8_t* next_free = aligned_result + size; size_t aligned_size = (next_free - current_data); if ((data_size_ + aligned_size) > data_size_max_) { // TODO(petewarden): Add error reporting beyond returning null! return nullptr; } data_size_ += aligned_size; return aligned_result; } } // namespace tflite
30a89539b5af02faf976117cb5414849a47972bd
85a50ab1eef4724ee83ec19c5af708b02cb0dfc3
/include/Talon/Graphics/InputClassification.h
2c7769b66ca1eff51590cc062d264f064317529b
[]
no_license
mattrudder/Talon
5ca428dbcd4e5c5879978640205fb43c3074aca4
650cc522f7854bd52da308042b42a2a4bb1ca728
refs/heads/master
2021-01-21T19:35:09.831748
2012-07-26T16:01:00
2012-07-26T16:01:00
3,830,382
2
0
null
null
null
null
UTF-8
C++
false
false
133
h
InputClassification.h
#pragma once #include <Talon/TalonPublic.h> namespace Talon { enum class InputClassification { PerVertex, PerInstance, }; }
e9717b2c17f4dd54ee5b9473b71aca1b5000a6cc
e76014ab83cd6b16779d3436c1f32d0eaad4fa4b
/GameController.cc
7dfffb9aa6095ba5f11451fda8d74f6f088c6846
[]
no_license
JoshJWight/NemesisHeist
c2a84f7a8e752daf6290af3d68ae93af0944595f
558b9b013928ea06508ae3b28b98fb599ab70e12
refs/heads/master
2022-12-29T02:26:20.650733
2020-10-15T01:04:31
2020-10-15T01:04:31
302,820,211
0
0
null
null
null
null
UTF-8
C++
false
false
2,240
cc
GameController.cc
#include "GameController.hh" #include <SFML/Window/Keyboard.hpp> GameController::GameController() : m_graphics(800, 600) { m_player.reset(new GameObject); m_player->pos = point_t(0, 0); m_player->colliderType = CIRCLE; m_player->size = point_t(10, 10); m_player->sprite.setTexture(TextureBank::get("smiley.png")); m_player->moveSpeed = 1; std::shared_ptr<GameObject> obj(new GameObject); obj-> pos = point_t(10, 10); obj-> colliderType = BOX; obj-> size = point_t(20, 20); obj->sprite.setTexture(TextureBank::get("box.png")); std::shared_ptr<GameObject> obj2(new GameObject); obj2-> pos = point_t(-20, -30); obj2-> colliderType = BOX; obj2-> size = point_t(20, 30); obj2->sprite.setTexture(TextureBank::get("box.png")); m_objects.push_back(m_player); m_objects.push_back(obj); m_objects.push_back(obj2); } void GameController::mainLoop() { //~60 FPS int msPerFrame = 16; std::chrono::duration<int, std::milli> frameDuration(msPerFrame); while(true) { auto frameStart = std::chrono::system_clock::now(); tick(); std::this_thread::sleep_until(frameStart + frameDuration); } } void GameController::tick() { point_t mouseWorldPos = m_graphics.getMousePos(); //Player movement - maybe should go in a separate method or class if(sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { m_player->pos.y += m_player->moveSpeed; } else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { m_player->pos.y -= m_player->moveSpeed; } else if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { m_player->pos.x -= m_player->moveSpeed; } else if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { m_player->pos.x += m_player->moveSpeed; } for(int i=0; i<m_objects.size(); i++) { for(int j=0; j<m_objects.size(); j++) { if( i==j ) { continue; } if(m_objects[i]->isColliding(*(m_objects[j]))) { std::cout << "Object " << i << " colliding with object " << j << std::endl; } } } m_graphics.draw(m_objects); }
9b720d38c8a6f847d71b4000fb80dc860043c727
751fe73c7a0188dfe27c9fe78c0410b137db91fb
/redis/test/rediscpp/RedisZset.h
8b6860cd8265e4ef93bf788f66853fedf35840bc
[]
no_license
longshadian/estl
0b1380e9dacfc4e193e1bb19401de28dd135fedf
3dba7a84abc8dbf999ababa977279e929a0a6623
refs/heads/master
2021-07-09T19:29:06.402311
2021-04-05T14:16:21
2021-04-05T14:16:21
12,356,617
3
1
null
null
null
null
GB18030
C++
false
false
870
h
RedisZset.h
#pragma once #include "RedisType.h" namespace rediscpp { class RedisZset { public: RedisZset(ContextGuard& context); ~RedisZset() = default; long long ZADD(Buffer key, long long score, Buffer value); //有序集合范围内的成员和分数 std::vector<Buffer> ZRANGE(Buffer key, int start, int end); std::vector<std::pair<Buffer, Buffer>> ZRANGE_WITHSCORES(Buffer key, int start, int end); //有序集合范围内的成员和分数,降序 //first: value //second: score std::vector<Buffer> ZREVRANGE(Buffer key, int start, int end); std::vector<std::pair<Buffer, Buffer>> ZREVRANGE_WITHSCORES(Buffer key, int start, int end); //在有序集合增加成员的分数 long long ZINCRBY(Buffer key, long long increment, Buffer value); private: ContextGuard& m_context; }; }
1f2c635d6e7822bbddb4e007bf07d44211a28063
31559c6769749852992379766e9d4ae992bc7e6d
/Particle System/src/standard/EmitterWithinSphere.hpp
b1e76946569ad0c918335fc2bfc3bb6ffac14414
[]
no_license
Grevor/OSM2-Particle-System
84161b1f3c270a0971380eb90ca69faf90b2fb1b
7d62eeec1b53218a75e148a66f9bce4dc4b61319
refs/heads/master
2021-01-22T05:33:12.892385
2014-06-08T16:12:27
2014-06-08T16:12:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,506
hpp
EmitterWithinSphere.hpp
/* * EmitterWithinSphere.hpp * * Created on: 7 maj 2014 */ #ifndef EMITTERWITHINSPHERE_HPP_ #define EMITTERWITHINSPHERE_HPP_ #include "../utilities/Emitter.h" #include <Eigen/Eigen> #include "StandardParticle.hpp" #include <boost/random.hpp> #include <time.h> using namespace boost; class EmitterWithinSphere : public Emitter<Vector3f> { boost::mt19937 RNG; boost::uniform_real<float> range; boost::variate_generator<boost::mt19937, boost::uniform_real<float>> randomG; //static bool started = false; Vector3f sphereMiddle, bias; float radius; public: EmitterWithinSphere(Vector3f& middle, float radius) : RNG(time(NULL)), range(0,1), randomG(RNG,range) { Vector3f noBias {1,1,1}; init(middle, radius, noBias); } EmitterWithinSphere(Vector3f& middle, float radius, Vector3f& bias) : RNG(time(NULL)), range(0,1), randomG(RNG,range) { init(middle,radius,bias); } void init(Vector3f& middle, float radius, Vector3f& bias) { sphereMiddle = middle; this->radius = radius; this->bias = bias; //if(!started) { //started = true; // RNG = boost::mt19937(time(NULL)); // range = boost::uniform_real<float>(0,1); // randomG = boost::variate_generator<boost::mt19937, boost::uniform_real<float>>(RNG, range); //} } Vector3f emit() override { Vector3f res; for(int i = 0; i < 3; i++) res[i] = (randomG()-.5) * bias[i] * radius + sphereMiddle[i]; return res; } }; #endif /* EMITTERWITHINSPHERE_HPP_ */
872409fea34740c4962a8b64ecac0c810dbab0c4
d1b5b63d453b3b54a61f894404b63f3e41b42889
/main.cpp
19636e73487a7bdd9ba13f61e5a1d1ad3822cdf2
[]
no_license
raslandarawsheh/homework
47c7e996d4a51a957d90e9af6cddd8d6beeadffd
a6a173fccd041087a5b3b046becc8119a690bc07
refs/heads/master
2020-07-22T10:24:20.701112
2019-09-09T00:42:14
2019-09-09T01:12:41
207,167,233
0
0
null
null
null
null
UTF-8
C++
false
false
1,754
cpp
main.cpp
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <netdb.h> #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> #include <iostream> using namespace cv; using namespace std; int send_data(Mat img) { //img = (img.reshape(0,1)); int imgSize = img.total()*img.elemSize(); printf("size = %d\n", imgSize); int send_sock; struct sockaddr_un client; /* Create socket on which to send. */ send_sock = socket(AF_UNIX, SOCK_STREAM, 0); if (send_sock < 0) { perror("opening unix socket"); exit(1); } /* Construct name of socket to send to. */ client.sun_family = AF_UNIX; strcpy(client.sun_path, "/tmp/tmp"); if (connect(send_sock, (struct sockaddr *)&client, sizeof(struct sockaddr_un)) < 0) { close(send_sock); perror("connecting stream socket"); exit(1); } write(send_sock, &imgSize, sizeof imgSize); write(send_sock, img.data, imgSize); close(send_sock); unlink("/tmp/tmp"); } int main( int argc, char** argv ) { String imageName( "img.jpg" ); // by default Mat image; image = imread( samples::findFile( imageName ), IMREAD_COLOR ); // Read the file if(image.empty()) // Check for invalid input { cout << "Could not open or find the image" << std::endl ; return -1; } if(! image.data ) { cout << "Could not open or find the image" << std::endl ; return -1; } send_data(image); namedWindow( "Display window", WINDOW_AUTOSIZE ); // Create a window for display. imshow( "Display window", image ); // Show our image inside it. waitKey(0); // Wait for a keystroke in the window return 0; }
ad329008ae7fb6e51fd15c3c9ae9f5ea7f1dd841
535b8599d2185c847631afc1576e067a0d060fe3
/leetcode/leetcode96-Unique-Binary-Search-Trees.cc
53feb8ed9f349ce64fdd9cf18a2b552017453077
[]
no_license
pingyu/magical-codes
d5ae4313287369d4bb61da44c334dcaf418d1da8
104f078fd19445f11478b96a3b0fb0c99b3be9f5
refs/heads/master
2022-06-18T01:19:52.100654
2022-05-05T01:59:25
2022-05-05T01:59:25
175,943,330
0
0
null
2022-06-17T01:37:24
2019-03-16T07:57:49
C++
UTF-8
C++
false
false
790
cc
leetcode96-Unique-Binary-Search-Trees.cc
#include <bits/stdc++.h> using std::cout; using std::cin; class Solution { public: int numTrees(int n) { std::vector<int> vec(n+1); vec[1] = 1; for (int i=2; i<=n; i++) { vec[i] = 2 * vec[i - 1]; if (i >= 3) { for (int j=1; j<i - 1; j++) { vec[i] += vec[j] * vec[i - 1 - j]; } } } return vec[n]; } }; struct Case { int n; int expect; }; int main() { Case cases[] = { {3, 5}, {0, 0}, {1, 1}, {2, 2}, {4, 4}, }; Solution sln; for (auto& c: cases) { int r = sln.numTrees(c.n); cout << "n: " << c.n << ", r: " << r << ", expect: " << c.expect << "\n"; } return 0; }
5ada9bbdad4e027211c1dcf43a8af1aee5bfd1b5
d9236f1b37663dcd8d935d8d76d9cd4cb24d9846
/Kernel/Drivers/Device.cpp
04759e2b33be8d1d3c568421169bfec266acd86d
[ "Apache-2.0" ]
permissive
UltraOS/UltraLegacy
8f167531553d91d7d22ef22d761657bd084fd23f
2ed2879c96a7095b5077df5ba5db5b30a6565417
refs/heads/master
2023-08-23T22:31:11.572601
2021-10-29T19:48:54
2021-10-29T19:48:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
562
cpp
Device.cpp
#include "Device.h" #include "DeviceManager.h" namespace kernel { Device::Device(Category category) : m_category(category) { DeviceManager::the().register_self(this); } Device::~Device() { DeviceManager::the().unregister_self(this); } void Device::make_child_of(Device* parent) { DeviceManager::the().add_child(parent, this); } bool Device::is_primary() { return DeviceManager::the().primary_of_category(m_category).load(MemoryOrder::ACQUIRE) == this; } void Device::make_primary() { DeviceManager::the().set_as_primary(this); } }
bd8d81b26d4dba595f094e6944adba964b505321
8dee7f236ecccb1d2a8ca496a9826353f5bd9d78
/include/bmp/extralifebmp2.h
c8dfe3c8568ff49e809a1597cbabe02bf1ce8bab
[ "MIT" ]
permissive
ant512/EarthShakerDS
6675bc3f3df6923b56ef820ca8d748de57f5b52b
c23920bb96652570616059ee4b807e82617c2385
refs/heads/master
2020-05-18T13:14:12.995125
2015-02-08T06:05:01
2015-02-08T06:05:01
15,246,988
1
0
null
null
null
null
UTF-8
C++
false
false
174
h
extralifebmp2.h
#ifndef _EXTRALIFEBMP2_H_ #define _EXTRALIFEBMP2_H_ #include <bitmapwrapper.h> class ExtraLifeBmp2 : public WoopsiGfx::BitmapWrapper { public: ExtraLifeBmp2(); }; #endif
1a893b7d38bf8b38cfb78764de3ac556eccc323d
615a68de83307164408ddeb7f09ff33578c7647e
/Example/MyForm.h
a006fda9538b240fb50cd810b4439418fdde2a08
[]
no_license
NazariiProshyn/SLAE-with-FinForms-interface
a6092d94dd3fc807e2955a004e710f18f706c91e
39129867dc1110c5700518e4d0ace22d409e6c67
refs/heads/master
2022-12-01T11:53:31.220483
2020-08-20T00:45:56
2020-08-20T00:45:56
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
4,669
h
MyForm.h
#pragma once namespace Example { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Сводка для MyForm /// </summary> public ref class MyForm : public System::Windows::Forms::Form { public: MyForm(void) { InitializeComponent(); // //TODO: добавьте код конструктора // } protected: /// <summary> /// Освободить все используемые ресурсы. /// </summary> ~MyForm() { if (components) { delete components; } } private: System::Windows::Forms::MenuStrip^ menuStrip1; protected: private: System::Windows::Forms::ToolStripMenuItem^ проПрограмуToolStripMenuItem; private: System::Windows::Forms::Button^ button1; private: /// <summary> /// Обязательная переменная конструктора. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Требуемый метод для поддержки конструктора — не изменяйте /// содержимое этого метода с помощью редактора кода. /// </summary> void InitializeComponent(void) { this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip()); this->проПрограмуToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->button1 = (gcnew System::Windows::Forms::Button()); this->menuStrip1->SuspendLayout(); this->SuspendLayout(); // // menuStrip1 // this->menuStrip1->ImageScalingSize = System::Drawing::Size(20, 20); this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(1) { this->проПрограмуToolStripMenuItem }); this->menuStrip1->Location = System::Drawing::Point(0, 0); this->menuStrip1->Name = L"menuStrip1"; this->menuStrip1->Size = System::Drawing::Size(312, 30); this->menuStrip1->TabIndex = 0; this->menuStrip1->Text = L"menuStrip1"; // // проПрограмуToolStripMenuItem // this->проПрограмуToolStripMenuItem->Name = L"проПрограмуToolStripMenuItem"; this->проПрограмуToolStripMenuItem->Size = System::Drawing::Size(124, 24); this->проПрограмуToolStripMenuItem->Text = L"Про програму"; this->проПрограмуToolStripMenuItem->Click += gcnew System::EventHandler(this, &MyForm::проПрограмуToolStripMenuItem_Click); // // button1 // this->button1->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom) | System::Windows::Forms::AnchorStyles::Left) | System::Windows::Forms::AnchorStyles::Right)); this->button1->BackColor = System::Drawing::SystemColors::ActiveCaption; this->button1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(204))); this->button1->Location = System::Drawing::Point(77, 118); this->button1->Name = L"button1"; this->button1->Size = System::Drawing::Size(150, 75); this->button1->TabIndex = 1; this->button1->Text = L"Розпочати роботу"; this->button1->UseVisualStyleBackColor = false; this->button1->Click += gcnew System::EventHandler(this, &MyForm::button1_Click); // // MyForm // this->AutoScaleDimensions = System::Drawing::SizeF(8, 16); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->BackColor = System::Drawing::SystemColors::AppWorkspace; this->ClientSize = System::Drawing::Size(312, 283); this->Controls->Add(this->button1); this->Controls->Add(this->menuStrip1); this->MainMenuStrip = this->menuStrip1; this->MaximumSize = System::Drawing::Size(330, 330); this->MinimumSize = System::Drawing::Size(330, 330); this->Name = L"MyForm"; this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen; this->Text = L"MyForm"; this->menuStrip1->ResumeLayout(false); this->menuStrip1->PerformLayout(); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e); private: System::Void проПрограмуToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e); }; }
3eb1eb09828324bf073cacb29ef56b8334276650
8538c2c60ac5b59b3ccd3724892fa2a7d3612473
/editor/Propertys/PropertyGUI.cpp
cfb634d1ded26c2e0ca8d47c689a0a4f77189db1
[]
no_license
songchengjiang/Lutra
f514c9833740d0d6a4fac3097cca55dc8d6e37bc
9af2c212c191035616637663f1d7a981000b26be
refs/heads/master
2023-02-19T08:13:42.290764
2021-01-22T14:35:00
2021-01-22T14:35:00
326,599,218
0
0
null
null
null
null
UTF-8
C++
false
false
105
cpp
PropertyGUI.cpp
// // PropertyGUI.cpp // Editor // // Created by JasonCheng on 2021/1/9. // #include "PropertyGUI.h"
29e4a234888f7b0f5b9117acbc2a46a46ff0834e
968cb6195b76d70f9d2046d8f43f29e7db7fb572
/game_pause.cpp
355d63ee78062d4af1d9952fd161ed50b244f53e
[]
no_license
KodFreedom/Impact
bb2e867b446fbbc4f9dd4dc7105ff5b541c492c5
b1dfa8e80b235b67178431841a625f69c5eec135
refs/heads/master
2021-01-01T04:37:25.290972
2017-07-14T08:58:51
2017-07-14T08:58:51
97,211,582
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
11,294
cpp
game_pause.cpp
//-------------------------------------------------------------------------------- // // GamePause.cpp // Author : Xu Wenjie // Date : 2016-06-07 //-------------------------------------------------------------------------------- // Update : // //-------------------------------------------------------------------------------- #include "main.h" #include "game_pause.h" #include "sound.h" #include "fade.h" #include "input.h" #include "joystick.h" //-------------------------------------------------------------------------------- // 定数定義 //-------------------------------------------------------------------------------- #define PAUSE_POS_X (SCREEN_WIDTH * 0.5f)//ポリゴンの表示位置X #define PAUSE_POS_Y (SCREEN_HEIGHT * 0.6f)//ポリゴンの表示位置Y #define PAUSE_WIDTH (400.0f) #define PAUSE_HEIGHT (200.0f) #define PAUSE_RESUME_POS_X (SCREEN_WIDTH * 0.5f)//ポリゴンの表示位置X #define PAUSE_RESUME_POS_Y (SCREEN_HEIGHT * 0.6f - 30.0f)//ポリゴンの表示位置Y #define PAUSE_RESUME_WIDTH (251.0f) #define PAUSE_RESUME_HEIGHT (50.0f) #define PAUSE_RETURN_POS_X (SCREEN_WIDTH * 0.5f)//ポリゴンの表示位置X #define PAUSE_RETURN_POS_Y (SCREEN_HEIGHT * 0.6f + 30.0f)//ポリゴンの表示位置Y #define PAUSE_RETURN_WIDTH (146.0f) #define PAUSE_RETURN_HEIGHT (50.0f) #define PAUSE_BG_POS_X (-0.5f)//ポリゴンの表示位置X #define PAUSE_BG_POS_Y (-0.5f)//ポリゴンの表示位置Y #define PAUSE_BG_WIDTH (SCREEN_WIDTH) #define PAUSE_BG_HEIGHT (SCREEN_HEIGHT) #define PAUSE_TEXTURENAME "data/TEXTURE/gamepause.png"//ファイル名 //-------------------------------------------------------------------------------- // プロトタイプ宣言 //-------------------------------------------------------------------------------- HRESULT MakeVerTexGamePause(LPDIRECT3DDEVICE9 pDevice); //-------------------------------------------------------------------------------- // 構造体定義 //-------------------------------------------------------------------------------- typedef enum { PAUSE_NONE, PAUSE_RESUME, PAUSE_RETURN_TO_MENU, PAUSE_MAX }PAUSE; //-------------------------------------------------------------------------------- // グローバル変数 //-------------------------------------------------------------------------------- LPDIRECT3DTEXTURE9 g_pTextureGamePause = NULL;//textureインターフェース LPDIRECT3DVERTEXBUFFER9 g_pVtxBufferGamePause = NULL;//頂点バッファ管理インターフェースポインタ PAUSE g_pause; //-------------------------------------------------------------------------------- // 初期化処理 //-------------------------------------------------------------------------------- void InitGamePause(void) { LPDIRECT3DDEVICE9 pDevice = GetDevice();//デバイス取得 g_pause = PAUSE_NONE; if (FAILED(MakeVerTexGamePause(pDevice)))//textureポインタへのポインタ { MessageBox(NULL, "MakeVerTexGamePause ERROR!!", "エラー", MB_OK | MB_ICONWARNING); } //ハードディスクからTextureの読み込み //※エラーチェック必須 if (FAILED(D3DXCreateTextureFromFile(pDevice, PAUSE_TEXTURENAME, &g_pTextureGamePause))) { MessageBox(NULL, "D3DXCreateTextureFromFile ERROR!!", "エラー", MB_OK | MB_ICONWARNING); } } //-------------------------------------------------------------------------------- // 終了処理 //-------------------------------------------------------------------------------- void UninitGamePause(void) { //safe release if (g_pVtxBufferGamePause != NULL) { g_pVtxBufferGamePause->Release(); g_pVtxBufferGamePause = NULL; } if (g_pTextureGamePause != NULL) { g_pTextureGamePause->Release(); g_pTextureGamePause = NULL; } } //-------------------------------------------------------------------------------- // 更新処理 //-------------------------------------------------------------------------------- bool UpdateGamePause(void) { //key入力 if (GetJoystickTrigger(XBOX_CONTROLLER_NUM, DIJ_BUTTON, DIJ_XBOX_MENU) || GetJoystickTrigger(PS4_CONTROLLER_NUM, DIJ_BUTTON, DIJ_PS4_OPTIONS))//Pause { g_pause = PAUSE_RESUME; } if (g_pause == PAUSE_NONE) { return false; } //key入力 if (GetJoystickTrigger(XBOX_CONTROLLER_NUM, DIJ_L_STICKY, DIJ_XBOX_L_UP) || GetJoystickTrigger(PS4_CONTROLLER_NUM, DIJ_L_STICKY, DIJ_PS4_L_UP) || GetJoystickTrigger(XBOX_CONTROLLER_NUM, DIJ_L_STICKY, DIJ_XBOX_L_DOWN) || GetJoystickTrigger(PS4_CONTROLLER_NUM, DIJ_L_STICKY, DIJ_PS4_L_DOWN)) { g_pause = g_pause == PAUSE_RESUME ? PAUSE_RETURN_TO_MENU : PAUSE_RESUME; } if (GetJoystickTrigger(XBOX_CONTROLLER_NUM, DIJ_BUTTON, DIJ_XBOX_B) || GetJoystickTrigger(PS4_CONTROLLER_NUM, DIJ_BUTTON, DIJ_PS4_◯)) { g_pause = PAUSE_NONE; return false; } if (GetJoystickTrigger(XBOX_CONTROLLER_NUM, DIJ_BUTTON, DIJ_XBOX_A) || GetJoystickTrigger(PS4_CONTROLLER_NUM, DIJ_BUTTON, DIJ_PS4_×)) { PlaySound(SOUND_LABEL_SE_PRESS); switch (g_pause) { case PAUSE_RESUME://refuse g_pause = PAUSE_NONE; return false; break; case PAUSE_RETURN_TO_MENU://return to menu SetFade(FADE_OUT, MODE_TITLE); return true; break; default: break; } } //仮想アドレスを取得するためのポインタ VERTEX_2D *pVtx; float fWork; //頂点バッファをロックして、仮想アドレスを取得する g_pVtxBufferGamePause->Lock(0, 0, (void**)&pVtx, 0); //texture頂点 for (int nCnt = 0;nCnt < PAUSE_MAX - 1;nCnt++) { fWork = (g_pause - nCnt) % 2 * 0.5f + 0.5f; pVtx[nCnt * 4 + 0].color = D3DXCOLOR(fWork, fWork, fWork, 1.0f); pVtx[nCnt * 4 + 1].color = D3DXCOLOR(fWork, fWork, fWork, 1.0f); pVtx[nCnt * 4 + 2].color = D3DXCOLOR(fWork, fWork, fWork, 1.0f); pVtx[nCnt * 4 + 3].color = D3DXCOLOR(fWork, fWork, fWork, 1.0f); } //仮想アドレス解放 g_pVtxBufferGamePause->Unlock(); return true; } //-------------------------------------------------------------------------------- // 描画処理 //-------------------------------------------------------------------------------- void DrawGamePause(void) { if (g_pause == PAUSE_NONE) { return; } LPDIRECT3DDEVICE9 pDevice = GetDevice();//デバイス取得 pDevice->SetStreamSource( 0,//ストリーム番号 g_pVtxBufferGamePause, 0,//オフセット(開始位置) sizeof(VERTEX_2D));//ストライド量 pDevice->SetFVF(FVF_VERTEX_2D);//頂点フォーマットの設定 //Textureの設定 pDevice->SetTexture(0, g_pTextureGamePause); //プリミティブ描画 pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 12, NUM_POLYGON); pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 8, NUM_POLYGON); pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, NUM_POLYGON); pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 4, NUM_POLYGON); } //-------------------------------------------------------------------------------- // 頂点の作成 //-------------------------------------------------------------------------------- HRESULT MakeVerTexGamePause(LPDIRECT3DDEVICE9 pDevice) { if (FAILED(pDevice->CreateVertexBuffer( sizeof(VERTEX_2D) * NUM_VERTEX * 4,//作成したい頂点バッファのサイズ D3DUSAGE_WRITEONLY,//頂点バッファの使用方法 FVF_VERTEX_2D,//書かなくても大丈夫 D3DPOOL_MANAGED,//メモリ管理方法(managed:デバイスにお任せ) &g_pVtxBufferGamePause,// NULL// ))) { return E_FAIL; } //仮想アドレスを取得するためのポインタ VERTEX_2D *pVtx; //頂点バッファをロックして、仮想アドレスを取得する g_pVtxBufferGamePause->Lock( 0,//範囲 0,//範囲 (void**)&pVtx,//アドレスが書かれたメモ帳のアドレス 0); //頂点座標の設定(2D座標、右回り) pVtx[0].pos = D3DXVECTOR3(PAUSE_RESUME_POS_X - PAUSE_RESUME_WIDTH * 0.5f, PAUSE_RESUME_POS_Y - PAUSE_RESUME_HEIGHT * 0.5f, 0.0f); pVtx[1].pos = D3DXVECTOR3(PAUSE_RESUME_POS_X + PAUSE_RESUME_WIDTH * 0.5f, PAUSE_RESUME_POS_Y - PAUSE_RESUME_HEIGHT * 0.5f, 0.0f); pVtx[2].pos = D3DXVECTOR3(PAUSE_RESUME_POS_X - PAUSE_RESUME_WIDTH * 0.5f, PAUSE_RESUME_POS_Y + PAUSE_RESUME_HEIGHT * 0.5f, 0.0f); pVtx[3].pos = D3DXVECTOR3(PAUSE_RESUME_POS_X + PAUSE_RESUME_WIDTH * 0.5f, PAUSE_RESUME_POS_Y + PAUSE_RESUME_HEIGHT * 0.5f, 0.0f); pVtx[4].pos = D3DXVECTOR3(PAUSE_RETURN_POS_X - PAUSE_RETURN_WIDTH * 0.5f, PAUSE_RETURN_POS_Y - PAUSE_RETURN_HEIGHT * 0.5f, 0.0f); pVtx[5].pos = D3DXVECTOR3(PAUSE_RETURN_POS_X + PAUSE_RETURN_WIDTH * 0.5f, PAUSE_RETURN_POS_Y - PAUSE_RETURN_HEIGHT * 0.5f, 0.0f); pVtx[6].pos = D3DXVECTOR3(PAUSE_RETURN_POS_X - PAUSE_RETURN_WIDTH * 0.5f, PAUSE_RETURN_POS_Y + PAUSE_RETURN_HEIGHT * 0.5f, 0.0f); pVtx[7].pos = D3DXVECTOR3(PAUSE_RETURN_POS_X + PAUSE_RETURN_WIDTH * 0.5f, PAUSE_RETURN_POS_Y + PAUSE_RETURN_HEIGHT * 0.5f, 0.0f); pVtx[8].pos = D3DXVECTOR3(PAUSE_POS_X - PAUSE_WIDTH * 0.5f, PAUSE_POS_Y - PAUSE_HEIGHT * 0.5f, 0.0f); pVtx[9].pos = D3DXVECTOR3(PAUSE_POS_X + PAUSE_WIDTH * 0.5f, PAUSE_POS_Y - PAUSE_HEIGHT * 0.5f, 0.0f); pVtx[10].pos = D3DXVECTOR3(PAUSE_POS_X - PAUSE_WIDTH * 0.5f, PAUSE_POS_Y + PAUSE_HEIGHT * 0.5f, 0.0f); pVtx[11].pos = D3DXVECTOR3(PAUSE_POS_X + PAUSE_WIDTH * 0.5f, PAUSE_POS_Y + PAUSE_HEIGHT * 0.5f, 0.0f); //rhwの設定(必ず1.0f) for (int nCnt = 0;nCnt < PAUSE_MAX - 1;nCnt++) { float fWork = (g_pause - nCnt) % 2 * 0.5f + 0.5f; pVtx[nCnt * 4 + 0].color = D3DXCOLOR(fWork, fWork, fWork, 1.0f); pVtx[nCnt * 4 + 1].color = D3DXCOLOR(fWork, fWork, fWork, 1.0f); pVtx[nCnt * 4 + 2].color = D3DXCOLOR(fWork, fWork, fWork, 1.0f); pVtx[nCnt * 4 + 3].color = D3DXCOLOR(fWork, fWork, fWork, 1.0f); } //頂点カラーの設定(0〜255の整数値) pVtx[8 + 0].color = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[8 + 1].color = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[8 + 2].color = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[8 + 3].color = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); for (int nCnt = 0;nCnt < PAUSE_MAX;nCnt++) { pVtx[nCnt * 4 + 0].rhw = 1.0f; pVtx[nCnt * 4 + 1].rhw = 1.0f; pVtx[nCnt * 4 + 2].rhw = 1.0f; pVtx[nCnt * 4 + 3].rhw = 1.0f; //texture頂点 pVtx[nCnt * 4 + 0].tex = D3DXVECTOR2(0.0f, 1.0f / 3.0f * nCnt); pVtx[nCnt * 4 + 1].tex = D3DXVECTOR2(1.0f, 1.0f / 3.0f * nCnt); pVtx[nCnt * 4 + 2].tex = D3DXVECTOR2(0.0f, 1.0f / 3.0f * nCnt + 1.0f / 3.0f); pVtx[nCnt * 4 + 3].tex = D3DXVECTOR2(1.0f, 1.0f / 3.0f * nCnt + 1.0f / 3.0f); } pVtx[12].pos = D3DXVECTOR3(PAUSE_BG_POS_X, PAUSE_BG_POS_Y, 0.0f); pVtx[13].pos = D3DXVECTOR3(PAUSE_BG_POS_X + PAUSE_BG_WIDTH, PAUSE_BG_POS_Y, 0.0f); pVtx[14].pos = D3DXVECTOR3(PAUSE_BG_POS_X, PAUSE_BG_POS_Y + PAUSE_BG_HEIGHT, 0.0f); pVtx[15].pos = D3DXVECTOR3(PAUSE_BG_POS_X + PAUSE_BG_WIDTH, PAUSE_BG_POS_Y + PAUSE_BG_HEIGHT, 0.0f); //頂点カラーの設定(0〜255の整数値) pVtx[12].color = D3DXCOLOR(1.0f, 1.0f, 1.0f, 0.5f); pVtx[13].color = D3DXCOLOR(1.0f, 1.0f, 1.0f, 0.5f); pVtx[14].color = D3DXCOLOR(1.0f, 1.0f, 1.0f, 0.5f); pVtx[15].color = D3DXCOLOR(1.0f, 1.0f, 1.0f, 0.5f); pVtx[12].rhw = 1.0f; pVtx[13].rhw = 1.0f; pVtx[14].rhw = 1.0f; pVtx[15].rhw = 1.0f; //texture頂点 pVtx[12].tex = D3DXVECTOR2(0.98f, 0.98f); pVtx[13].tex = D3DXVECTOR2(0.99f, 0.98f); pVtx[14].tex = D3DXVECTOR2(0.98f, 0.99f); pVtx[15].tex = D3DXVECTOR2(0.99f, 0.99f); //仮想アドレス解放 g_pVtxBufferGamePause->Unlock(); return S_OK; }
46b71619bdfc0934de29b45ed5a39aef338259b3
599153c3b43f65e603d5ace2fdac954e66f187af
/vijos/1218.cpp
323c47d4c6b2d629fd4c71440135df2d579e0f71
[]
no_license
davidzyc/oi
d7c538df5520f36afc9f652fed6862f2658e5a3e
88cfea0d3ce62a7ecd176a4285bbfeac419d6360
refs/heads/master
2021-05-12T11:49:26.147403
2019-10-25T14:18:03
2019-10-25T14:18:03
117,396,742
0
1
null
2018-01-14T12:22:38
2018-01-14T02:54:50
C++
UTF-8
C++
false
false
1,394
cpp
1218.cpp
#include<cstdio> #include<iostream> #include<cstring> #define MAXN 105 #define MAXM 10 #define INF 2100000000 using namespace std; int dpmin[MAXM][MAXN], dpmax[MAXM][MAXN]; int main(){ int n, m, a[MAXN], s[MAXN] = {0}, ansmin, ansmax; cin >> n >> m; for(int i=1; i<=n; i++){ cin >> a[i]; s[i] = s[i-1] + a[i]; } for(int i=n+1; i<=n*2; i++){ a[i] = a[i-n]; s[i] = s[i-1] + a[i]; } // for(int i=1; i<=n*2; i++){ // cout << a[i] << " "; // } // cout << endl; // for(int i=1; i<=n*2; i++){ // cout << s[i] << " "; // } ansmin = INF; ansmax = 0; for(int st=0; st<n; st++){ // memset(dpmin, 0, sizeof(dp)); memset(dpmax, 0, sizeof(dpmax)); for(int j=1; j<=n; j++){ dpmax[1][j] = (s[j+st] - s[st] + 1000000) % 10; dpmin[1][j] = (s[j+st] - s[st] + 1000000) % 10; // cout << dpmax[1][j] << " "; } for(int i=2; i<=m; i++){ for(int j=i; j<=n; j++){ dpmin[i][j] = INF; for(int k=i-1; k<j; k++){ dpmax[i][j] = max(dpmax[i][j], dpmax[i-1][k] * ((s[j+st]-s[k+st]+1000000)%10) ); dpmin[i][j] = min(dpmin[i][j], dpmin[i-1][k] * ((s[j+st]-s[k+st]+1000000)%10) ); } } } ansmax = max(ansmax, dpmax[m][n]); ansmin = min(ansmin, dpmin[m][n]); // cout << dpmin[m][n] << endl; } cout << ansmin << endl << ansmax; // cout << (-1)%10; return 0; }
3cebc72bbf3da9fa0a9eea2320c820ba4775fbff
3bcb6548b63edbfaae717ffad00fde716e9fa104
/test/sql/type_sql_test.cpp
6c46359f13bf6dc4f475c505fcf4aeea01a373b5
[ "Apache-2.0" ]
permissive
Handora/peloton
9b06fea5723afef43ba7ebea895d260fb48ed93b
aa8f8dc64ff9adeb261224055c56f50defefb517
refs/heads/master
2020-03-28T08:07:50.556941
2018-10-20T07:40:08
2018-10-20T07:40:08
147,946,283
1
0
Apache-2.0
2018-09-08T15:36:24
2018-09-08T15:36:24
null
UTF-8
C++
false
false
7,797
cpp
type_sql_test.cpp
//===----------------------------------------------------------------------===// // // Peloton // // type_sql_test.cpp // // Identification: test/sql/type_sql_test.cpp // // Copyright (c) 2015-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include "catalog/catalog.h" #include "common/harness.h" #include "concurrency/transaction_manager_factory.h" #include "sql/testing_sql_util.h" namespace peloton { namespace test { class TypeSQLTests : public PelotonTest { protected: virtual void SetUp() override { PelotonTest::SetUp(); auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); auto txn = txn_manager.BeginTransaction(); catalog::Catalog::GetInstance()->CreateDatabase(txn, DEFAULT_DB_NAME); txn_manager.CommitTransaction(txn); } virtual void TearDown() override { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); auto txn = txn_manager.BeginTransaction(); catalog::Catalog::GetInstance()->DropDatabaseWithName(txn, DEFAULT_DB_NAME); txn_manager.CommitTransaction(txn); PelotonTest::TearDown(); } }; /** * Check whether we can INSERT values that we have reserved for our NULL * indicators The DBMS should throw an error to prevent you from doing that */ TEST_F(TypeSQLTests, TypeLimitSQLTest) { const std::vector<type::TypeId> typeLimitSQLTestTypes = { type::TypeId::BOOLEAN, type::TypeId::TINYINT, type::TypeId::SMALLINT, type::TypeId::INTEGER, type::TypeId::TIMESTAMP, // FIXME type::TypeId::BIGINT, // FIXME type::TypeId::DECIMAL, // FIXME type::TypeId::DATE }; for (auto col_type : typeLimitSQLTestTypes) { // CREATE TABLE that contains a column for each type std::string table_name = "tbl" + TypeIdToString(col_type); std::string sql = StringUtil::Format( "CREATE TABLE %s(id INT PRIMARY KEY, b %s);", table_name.c_str(), TypeIdToString(col_type).c_str()); LOG_TRACE("SQL: %s", sql.c_str()); TestingSQLUtil::ExecuteSQLQuery(sql); // Then try to insert the min value std::ostringstream os; os << "INSERT INTO " << table_name << " VALUES (1, "; switch (col_type) { case type::TypeId::BOOLEAN: os << (int32_t)type::PELOTON_BOOLEAN_NULL; break; case type::TypeId::TINYINT: os << (int32_t)type::PELOTON_INT8_NULL; break; case type::TypeId::SMALLINT: os << type::PELOTON_INT16_NULL; break; case type::TypeId::INTEGER: os << type::PELOTON_INT32_NULL; break; case type::TypeId::BIGINT: os << type::PELOTON_INT64_NULL; break; case type::TypeId::DECIMAL: os << type::PELOTON_DECIMAL_NULL; break; case type::TypeId::TIMESTAMP: os << type::PELOTON_TIMESTAMP_NULL; break; case type::TypeId::DATE: os << type::PELOTON_DATE_NULL; break; default: { // Nothing to do! } } // SWITCH os << ");"; // This should throw an error because the query // is trying to insert a value that is not in a valid range for the type auto result = TestingSQLUtil::ExecuteSQLQuery(os.str()); LOG_TRACE("%s => %s", TypeIdToString(col_type).c_str(), os.str().c_str()); EXPECT_EQ(ResultType::FAILURE, result); } } void CheckQueryResult(std::vector<ResultValue> result, std::vector<std::string> expected, size_t tuple_descriptor_size) { EXPECT_EQ(result.size(), expected.size()); for (size_t i = 0; i < result.size(); i++) { for (size_t j = 0; j < tuple_descriptor_size; j++) { int idx = i * tuple_descriptor_size + j; std::string s = std::string(result[idx].begin(), result[idx].end()); EXPECT_EQ(s, expected[i]); } } } TEST_F(TypeSQLTests, VarcharTest) { TestingSQLUtil::ExecuteSQLQuery("CREATE TABLE foo(name varchar(250));"); for (const std::string &name : {"Alice", "Peter", "Cathy", "Bob", "Alicia", "David"}) { std::string sql = "INSERT INTO foo VALUES ('" + name + "');"; TestingSQLUtil::ExecuteSQLQuery(sql); } // NULL for good measure TestingSQLUtil::ExecuteSQLQuery("INSERT INTO foo VALUES (NULL);"); std::vector<ResultValue> result; std::vector<FieldInfo> tuple_descriptor; std::string error_message; int rows_changed; std::string query; std::vector<std::string> expected{}; query = "SELECT * FROM foo WHERE name = 'Alice';"; expected = {"Alice"}; TestingSQLUtil::ExecuteSQLQuery(query.c_str(), result, tuple_descriptor, rows_changed, error_message); CheckQueryResult(result, expected, tuple_descriptor.size()); query = "SELECT * FROM foo WHERE name = 'david';"; expected = {}; TestingSQLUtil::ExecuteSQLQuery(query.c_str(), result, tuple_descriptor, rows_changed, error_message); CheckQueryResult(result, expected, tuple_descriptor.size()); query = "SELECT * FROM foo WHERE name = 'Ann';"; expected = {}; TestingSQLUtil::ExecuteSQLQuery(query.c_str(), result, tuple_descriptor, rows_changed, error_message); CheckQueryResult(result, expected, tuple_descriptor.size()); query = "SELECT * FROM foo WHERE name = 'Alice' OR name = 'Alicia';"; expected = {"Alice", "Alicia"}; TestingSQLUtil::ExecuteSQLQuery(query.c_str(), result, tuple_descriptor, rows_changed, error_message); CheckQueryResult(result, expected, tuple_descriptor.size()); query = "SELECT * FROM foo WHERE name != 'Bob' AND name != 'David';"; expected = {"Alice", "Peter", "Cathy", "Alicia"}; TestingSQLUtil::ExecuteSQLQuery(query.c_str(), result, tuple_descriptor, rows_changed, error_message); CheckQueryResult(result, expected, tuple_descriptor.size()); query = "SELECT * FROM foo WHERE name >= 'A' AND name <= 'D';"; expected = {"Alice", "Cathy", "Bob", "Alicia"}; TestingSQLUtil::ExecuteSQLQuery(query.c_str(), result, tuple_descriptor, rows_changed, error_message); CheckQueryResult(result, expected, tuple_descriptor.size()); query = "SELECT * FROM foo WHERE name > 'David';"; expected = {"Peter"}; TestingSQLUtil::ExecuteSQLQuery(query.c_str(), result, tuple_descriptor, rows_changed, error_message); CheckQueryResult(result, expected, tuple_descriptor.size()); query = "SELECT * FROM foo WHERE name <= 'Alicia';"; expected = {"Alice", "Alicia"}; TestingSQLUtil::ExecuteSQLQuery(query.c_str(), result, tuple_descriptor, rows_changed, error_message); CheckQueryResult(result, expected, tuple_descriptor.size()); query = "SELECT * FROM foo WHERE name LIKE '%li%'"; expected = {"Alice", "Alicia"}; TestingSQLUtil::ExecuteSQLQuery(query.c_str(), result, tuple_descriptor, rows_changed, error_message); CheckQueryResult(result, expected, tuple_descriptor.size()); query = "SELECT * FROM foo WHERE name LIKE '_____'"; expected = {"Alice", "Peter", "Cathy", "David"}; TestingSQLUtil::ExecuteSQLQuery(query.c_str(), result, tuple_descriptor, rows_changed, error_message); CheckQueryResult(result, expected, tuple_descriptor.size()); query = "SELECT * FROM foo WHERE name LIKE '%th'"; expected = {}; TestingSQLUtil::ExecuteSQLQuery(query.c_str(), result, tuple_descriptor, rows_changed, error_message); CheckQueryResult(result, expected, tuple_descriptor.size()); } } // namespace test } // namespace peloton
a03a1e7b45a2c1012df589c0f2ebc62abed05dcf
da1500e0d3040497614d5327d2461a22e934b4d8
/third_party/skia/gm/simple_magnification.cpp
45f9b575823a972a995af8e7110c549c257596d2
[ "BSD-3-Clause", "GPL-1.0-or-later", "LGPL-2.0-or-later", "Apache-2.0", "MIT" ]
permissive
youtube/cobalt
34085fc93972ebe05b988b15410e99845efd1968
acefdaaadd3ef46f10f63d1acae2259e4024d383
refs/heads/main
2023-09-01T13:09:47.225174
2023-09-01T08:54:54
2023-09-01T08:54:54
50,049,789
169
80
BSD-3-Clause
2023-09-14T21:50:50
2016-01-20T18:11:34
null
UTF-8
C++
false
false
4,925
cpp
simple_magnification.cpp
/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm/gm.h" #include "include/core/SkBitmap.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkColorPriv.h" #include "include/core/SkImage.h" #include "include/core/SkImageFilter.h" #include "include/core/SkImageInfo.h" #include "include/core/SkPaint.h" #include "include/core/SkPoint.h" #include "include/core/SkRect.h" #include "include/core/SkRefCnt.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/core/SkSurface.h" #include "include/core/SkTypes.h" #include "include/effects/SkImageFilters.h" #include "include/gpu/GrTypes.h" #include <utility> class GrContext; static sk_sp<SkImage> make_image(GrContext* context, int size, GrSurfaceOrigin origin) { if (context) { SkImageInfo ii = SkImageInfo::Make(size, size, kN32_SkColorType, kPremul_SkAlphaType); sk_sp<SkSurface> surf(SkSurface::MakeRenderTarget(context, SkBudgeted::kYes, ii, 0, origin, nullptr)); if (surf) { SkCanvas* canvas = surf->getCanvas(); canvas->clear(SK_ColorRED); const struct { SkPoint fPt; SkColor fColor; } rec[] = { { { 1.5f, 1.5f }, SK_ColorGREEN }, { { 2.5f, 1.5f }, SK_ColorBLUE }, { { 1.5f, 2.5f }, SK_ColorCYAN }, { { 2.5f, 2.5f }, SK_ColorGRAY }, }; SkPaint paint; for (const auto& r : rec) { paint.setColor(r.fColor); canvas->drawPoints(SkCanvas::kPoints_PointMode, 1, &r.fPt, paint); } return surf->makeImageSnapshot(); } } SkBitmap bm; bm.allocN32Pixels(size, size); bm.eraseColor(SK_ColorRED); *bm.getAddr32(1, 1) = SkPackARGB32(0xFF, 0x00, 0xFF, 0x00); *bm.getAddr32(2, 1) = SkPackARGB32(0xFF, 0x00, 0x00, 0xFF); *bm.getAddr32(1, 2) = SkPackARGB32(0xFF, 0x00, 0xFF, 0xFF); *bm.getAddr32(2, 2) = SkPackARGB32(0xFF, 0x88, 0x88, 0x88); return SkImage::MakeFromBitmap(bm); } /* * This GM creates an image with a 2x2: * Green | Blue * ------------ * Cyan | Gray * block of pixels in one corner of a 33x33 field. The 'srcRect' feature of the * SkMagnifierImageFilter is then used to blow it up with different inset border widths. * * In GPU-mode we wind up drawing 4 rects: * * BottomLeft origin + 1-wide inset | TopLeft origin + 1-wide inset * ---------------------------------------------------------------- * BottomLeft origin + 7-wide inset | TopLeft origin + 7-wide inset * * In Raster-mode the source origin isn't used. */ class SimpleMagnificationGM : public skiagm::GM { public: SimpleMagnificationGM() { this->setBGColor(0xFFCCCCCC); } protected: SkString onShortName() override { return SkString("simple-magnification"); } SkISize onISize() override { return SkISize::Make(3*kPad+2*kImgSize, 3*kPad+2*kImgSize); } void draw(SkCanvas* canvas, sk_sp<SkImage> image, const SkIPoint& offset, int inset) { sk_sp<SkImageFilter> imgSrc(SkImageFilters::Image(std::move(image))); SkRect srcRect = SkRect::MakeXYWH(1.0f, 1.0f, 2.0f, 2.0f); sk_sp<SkImageFilter> magFilter(SkImageFilters::Magnifier(srcRect, inset, imgSrc)); SkPaint paint; paint.setImageFilter(std::move(magFilter)); canvas->save(); canvas->translate(offset.fX, offset.fY); SkRect rect = SkRect::MakeWH(kImgSize, kImgSize); canvas->drawRect(rect, paint); canvas->restore(); } DrawResult onDraw(SkCanvas* canvas, SkString* errorMsg) override { GrContext* context = canvas->getGrContext(); sk_sp<SkImage> bottomLImg = make_image(context, kImgSize, kBottomLeft_GrSurfaceOrigin); sk_sp<SkImage> topLImg = make_image(context, kImgSize, kTopLeft_GrSurfaceOrigin); if (!bottomLImg || !topLImg) { *errorMsg = "Could not load images. Did you forget to set the resourcePath?"; return DrawResult::kFail; } int bigOffset = 2 * kPad + kImgSize; this->draw(canvas, bottomLImg, SkIPoint::Make(kPad, kPad), 1); this->draw(canvas, topLImg, SkIPoint::Make(bigOffset, kPad), 1); this->draw(canvas, bottomLImg, SkIPoint::Make(kPad, bigOffset), 7); this->draw(canvas, topLImg, SkIPoint::Make(bigOffset, bigOffset), 7); return DrawResult::kOk; } private: static const int kImgSize = 33; static const int kPad = 2; typedef skiagm::GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM(return new SimpleMagnificationGM;)
bd2993924a165f9b799b6009f3214510ad45f23b
81528f582dd6d727bc0661723f0258e4e6ecc881
/solutions/11349-SymmetricMatrix/11349.cpp
2ded3f9b49aade35b0968becc845b35595658bbd
[]
no_license
remerson/uva
6123e283b0b4762acc6a131df1c5ee5b8cb029a0
d3a288d13657af45229421bfa6f3cbd3e8fa40c2
refs/heads/master
2023-07-22T17:20:27.577541
2023-07-15T21:01:05
2023-07-15T21:01:05
18,739,804
2
1
null
null
null
null
UTF-8
C++
false
false
3,605
cpp
11349.cpp
#include <cstdio> #include <cmath> #include <queue> #include <stack> #include <algorithm> #include <iostream> #ifndef ONLINE_JUDGE #define DEBUG(X) { X; } //#define DEBUG_INPUT(X) { X; } #define DEBUG_INPUT(X) #else #define DEBUG(X) #define DEBUG_INPUT(X) #endif using namespace std; const unsigned MAX_N = 128; long long matrix[MAX_N * MAX_N]; namespace { const int BLOCK_SIZE_BYTES = MAX_N * MAX_N * 16; const int NUM_BLOCKS = 2; class input { public: explicit input() : size_(0), index_(0), current_(0), eof_(false) { #ifdef ONLINE_JUDGE std::ios_base::sync_with_stdio(false); #endif read_block(); } inline bool read_int(long long &v) { bool negative = false; v = 0; if(size_ > 16) { while(!isdigit(*current_)) { if(*current_ == '-') negative = true; advance(); } while(isdigit(*current_)) { v = v * 10 + *current_ - '0'; advance(); } } else { while(!isdigit(*current_) && !end_reached()) { if(*current_ == '-') negative = true; advance(); } while(isdigit(*current_) && !end_reached()) { v = v * 10 + *current_ - '0'; advance(); } } if(negative) v *= -1; DEBUG_INPUT(printf("size_ = %d v = %d\n", size_, v)); return !end_reached(); } inline bool end_reached() const { return // eof_ && size_ == 0; } private: inline void advance() { DEBUG_INPUT(printf("advance (pre) size_ = %d current = [%c]\n", size_, *current_)); --size_; if(size_ == 0) { //if(!eof_) read_block(); } else { ++current_; } DEBUG_INPUT(printf("advance (post) size_ = %d current = [%c]\n", size_, *current_)); } inline void read_block() { current_ = &blocks_[index_][0]; //size_ = fread(current_, sizeof(char), BLOCK_SIZE_BYTES); size_ = read(0, current_, sizeof(char) * BLOCK_SIZE_BYTES); //eof_ = (feof(stdin) != 0); eof_ = (size_ == 0); #ifndef ONLINE_JUDGE char output[BLOCK_SIZE_BYTES + 1]; strncpy(output, blocks_[index_], BLOCK_SIZE_BYTES); printf("READ BLOCK [%s]\n", output); #endif DEBUG_INPUT(printf("READ BLOCK size = %d eof = %s\n", size_, eof_ ? "yes" : "no")); ++index_; index_ = index_ % NUM_BLOCKS; DEBUG_INPUT(printf("next index = %d\n", index_)); } // Remaining bytes left in current block size_t size_; size_t index_; char *current_; char blocks_[NUM_BLOCKS][BLOCK_SIZE_BYTES]; bool eof_; }; } // namespace int main() { input inp; long long t; inp.read_int(t); for(int q = 1; q <= t; ++q) { long long n; inp.read_int(n); DEBUG(printf("N = %d\n", n)); const long long n2 = n * n; DEBUG(printf("N2 = %d\n", n2)); matrix[0] = 0; bool symmetric = true; for(int i = 0; i < n2; ++i) { inp.read_int(matrix[++matrix[0]]); if(matrix[matrix[0]] < 0) symmetric = false; } int i = 1; int j = n2; if(symmetric) while(j > i) { DEBUG(printf("TEST matrix[%d] = %lld matrix[%d] = %lld\n", i, matrix[i], j, matrix[j])); if(matrix[i] != matrix[j]) { symmetric = false; break; } ++i; --j; } printf("Test #%d: %symmetric.\n", q, symmetric ? "S" : "Non-s"); } return 0; }
6c4284204833e9b65ec918bcc257f864a24a39f9
40aea90d4258ba94c4d49b61f17708376b2d6d74
/microbit/slither/source/MoveService.cpp
da523fd830b006f5859b2e537fce9222911ad520
[ "MIT" ]
permissive
novucs/microbit-slither
0a82d8b85bd3efc86d1c96cccb2c3df0738fd4c1
efe54520a180cdaee03fc212fada0766726a7d6b
refs/heads/master
2021-04-15T16:45:58.170204
2019-01-27T12:22:34
2019-01-27T12:22:34
126,509,709
6
0
null
null
null
null
UTF-8
C++
false
false
3,260
cpp
MoveService.cpp
#include "MoveService.h" namespace slither { MoveService::MoveService(BLEDevice &ble) : ble(ble) {} void MoveService::initialize() { // Create the speed and direction characteristics. GattCharacteristic directionCharacteristic(MoveDirectionCharacteristicUUID, (uint8_t *) directionBuffer, 0, sizeof(directionBuffer), GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY); GattCharacteristic speedCharacteristic(MoveSpeedCharacteristicUUID, (uint8_t *) speedBuffer, 0, sizeof(speedBuffer), GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY); directionBuffer[0] = 0; directionBuffer[1] = 0; speedBuffer[0] = 0; // Ensure all messages are encrypted and preventing // man-in-the-middle attacks. directionCharacteristic.requireSecurity(SecurityManager::MICROBIT_BLE_SECURITY_LEVEL); speedCharacteristic.requireSecurity(SecurityManager::MICROBIT_BLE_SECURITY_LEVEL); // Create and add this service to the micro:bit GATT table. GattCharacteristic *characteristics[] = {&directionCharacteristic, &speedCharacteristic}; GattService service(MoveServiceUUID, characteristics, sizeof(characteristics) / sizeof(GattCharacteristic *)); ble.addService(service); // Set the direction and speed replies for read requests. directionHandle = directionCharacteristic.getValueHandle(); ble.gattServer().write(directionHandle, (uint8_t *) directionBuffer, sizeof(directionBuffer)); speedHandle = speedCharacteristic.getValueHandle(); ble.gattServer().write(speedHandle, (uint8_t *) speedBuffer, sizeof(directionBuffer)); } void MoveService::sendDirection(uint8_t x, uint8_t y) { if (!ble.getGapState().connected) { return; } directionBuffer[0] = x; directionBuffer[1] = y; ble.gattServer().notify(directionHandle, (uint8_t *) directionBuffer, sizeof(directionBuffer)); } void MoveService::sendSpeed(uint8_t speed) { if (!ble.getGapState().connected) { return; } speedBuffer[0] = speed; ble.gattServer().notify(speedHandle, (uint8_t *) speedBuffer, sizeof(speedBuffer)); } const uint8_t MoveServiceUUID[] = { 0xaa, 0xb7, 0x93, 0x43, 0x9a, 0x83, 0x48, 0x86, 0xa1, 0xd3, 0x32, 0xa8, 0x00, 0x25, 0x99, 0x37 }; const uint8_t MoveDirectionCharacteristicUUID[] = { 0xe4, 0x99, 0x0f, 0x35, 0x28, 0xf4, 0x40, 0xd8, 0xbf, 0xa2, 0xf0, 0x51, 0x18, 0x72, 0x0a, 0x28 }; const uint8_t MoveSpeedCharacteristicUUID[] = { 0xe4, 0x99, 0x0e, 0x35, 0x28, 0xf4, 0x40, 0xd8, 0xbf, 0xa2, 0xf0, 0x51, 0x18, 0x72, 0x0a, 0x28 }; }
c56e44eb0398e0dcd71f01c009934267f26cbb02
ed933bfebfb7b587be8ab5920b9a99372da3508b
/abdul5.cpp
eb537776ab391f7b2cb90894105f4143ec85cf80
[]
no_license
Yashvishnoi/C_PROGRAMS
68736165cc433f3c14678eecb5e17b0c2a68ca65
94189d351658ecf43d0314e135c66f4fa891b6b1
refs/heads/master
2023-07-03T21:46:31.632933
2021-08-12T05:53:51
2021-08-12T05:53:51
241,179,064
0
0
null
null
null
null
UTF-8
C++
false
false
233
cpp
abdul5.cpp
#include<iostream> using namespace std; int main() { float n,b,a,d; cout<<"enter the basic salary percentage alowance percentage deduction"; cin>>b; cin>>a; cin>>d; n=b+(b*a)/100+(b*d)/100; cout<<"the net salary is "<<n; return 0; }
43b2186dfa89badf425a7fea0aab79cabbbb080e
ac2b22aa24a755ceb26c106612a97a5b49e1fd48
/AEACD/AEACD.cpp
4a72234bd5afca1f6418fd431a96de7bb3aaad17
[]
no_license
UngureanuTeodor/AEACD
8aefc2127d137609f5c8a5934dda8a8b0c0ad4cd
bc93021599fa1e8e027ed548f556a5b707a60266
refs/heads/master
2020-04-09T02:36:05.412327
2018-12-04T00:02:33
2018-12-04T00:02:33
159,947,126
0
0
null
null
null
null
UTF-8
C++
false
false
2,019
cpp
AEACD.cpp
#include "stdafx.h" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "tesseract/baseapi.h" #include <iostream> #include "Preprocesare.cpp" #include "Filtre.cpp" #include "Tesseract.cpp" using namespace cv; using namespace std; void main_andrei() {} void Pas1_Preprocesare() { Preprocesare preprocesare; // Otsu Binarization Mat src_rj = imread("Alice in Wonderland.jpg", IMREAD_COLOR); namedWindow("Alice in Wonderland", WINDOW_NORMAL); imshow("Alice in Wonderland", src_rj); resizeWindow("Alice in Wonderland", 512, 830); Mat dst_otsu = preprocesare.OtsuThresholding("Alice in Wonderland.jpg"); // Display Otsu char* window_name = "Otsu Thresholding"; namedWindow(window_name, WINDOW_NORMAL); imshow(window_name, dst_otsu); resizeWindow(window_name, 512, 830); // Skew Detection and Correction Mat src = imread("skew.jpg", 0); imshow("Skewed", src); Mat thr = preprocesare.BinaryInverseThresholding(src); imshow("Binary Inverse Thresholding", thr); // Display Rotated Mat rotated = preprocesare.DeskewRotationAndCorrection(src, thr); imshow("Deskewed", rotated); Tesseract tesseract; tesseract.TesseractTool(rotated); } void Pas2_AplicareFiltre() { Filtre filtre; // Illumination Correction Mat image_clahe = filtre.IlluminationCorrection("illumination_correction.png"); // Display Illumination Correction char* window_name = "Illumination Correction"; namedWindow(window_name, WINDOW_NORMAL); imshow(window_name, image_clahe); resizeWindow(window_name, 960, 540); // Blur Correction int R = 2; int snr = 20; Mat blur_correction = filtre.BlurCorrection("blurry.jpg", R, snr); // Display Blur Correction imshow("Blur Correction", blur_correction); } void main_teo() { // Pas1_Preprocesare(); Pas2_AplicareFiltre(); } void main_alex() { } int main(int argc, char** argv) { // main_alex(); // main_andrei(); main_teo(); waitKey(); return 0; }
b85930dbc38e5a59d88cfeb1446f07c3bb4172fe
ee924e1303ffcdb8e206b014bfe344209876feb3
/C++STL/Prac4/zad3.cpp
ebb6964c132e22d74967e743c156e76ff61cacfd
[]
no_license
Stachnikov/Studia-II-UWR
82ad018634037c295e0d7a61e51bf06c4723e6eb
7b2f798e1836c20963affa664ba8ea05e1fb167e
refs/heads/master
2020-05-16T07:10:18.068542
2020-04-08T14:29:47
2020-04-08T14:29:47
182,866,963
0
0
null
null
null
null
ISO-8859-1
C++
false
false
687
cpp
zad3.cpp
#include <iostream> #include <vector> #include <string> #include <list> #include <set> #include <algorithm> int main(){ std::vector<double> v1 = {1.2 , 0.7, 0.1, 12.3, 31.1, 5.3, 9.4, 8.1, 1.8, 1.0}; std::set<int> s1 = {1, 2, 0, 4, -2, 42, 12, 8, 321, -123}; // Wyznacz œredni¹ arytmetyczn¹ (dotyczy kolekcji z liczbami). double sum =0.0; auto it = s1.begin(); std::for_each(v1.begin(), v1.end(), [&sum,&v1](double num){sum += num/v1.size(); }); std::cout << sum << "\n"; sum=0.0; std::for_each(s1.begin(), s1.end(), [&sum,&s1,&it](int num){ sum += num; ++it; if(it == s1.end()) sum = (int)(sum/s1.size());}); std::cout << sum << "\n"; return 0; }
d4d31b4a453d2b7fc57b4db1e2b82dd95e9df375
f08e8d5c45d7a39042f2217998170f7dea7036b7
/Store/TransactionManager.h
00a1bf64625f348467d4879f41c41564f216ad16
[]
no_license
DeVonFire27/DTW_Inventory
ed3a770c180336cb67e3e2fe79ba0032410168b1
79237befc68970d54be19f4f5423c81e63ed4698
refs/heads/master
2021-01-10T18:02:58.251492
2016-04-02T01:00:04
2016-04-02T01:00:04
55,271,200
0
0
null
null
null
null
UTF-8
C++
false
false
454
h
TransactionManager.h
#pragma once #include "Store.h" #include "SLList.h" #include "Inventory.h" class TransactionManager { struct Transaction { Item theItem; bool bought; }; Store theStore; Inventory theInventory; SLList<Transaction> theHistory; unsigned int refunds; void AddTransaction(Transaction t); public: TransactionManager(); void Buy(); void Sell(); void Undo(); void FullDisplay(); bool StoreStuff(char * job); };
dca43aa33a9280e31c8de2a964c6d1c73d2f2f5b
3992fa91db2f7293dc5089c9dedb3bb2f8ef0059
/src/bullet.hpp
85c51716ec2148a048abc631491088db52037e75
[]
no_license
danniely/2d_zombie_game
4e2d61540adb09aaf697a5f30560dfe35ebfd815
50dc38c5fb5075fccf8427897125085c034bd589
refs/heads/master
2020-09-28T08:39:47.449647
2019-12-08T21:51:39
2019-12-08T21:51:39
226,736,373
0
0
null
null
null
null
UTF-8
C++
false
false
762
hpp
bullet.hpp
// // bullet.hpp // fantastic-finale-danniely // // Created by user on 11/19/19. // #ifndef bullet_hpp #define bullet_hpp #include <stdio.h> #include "ofMain.h" #include <iostream> #include <math.h> class bullet{ public: bullet(); bullet(float x, float y, float dir_x, float dir_y, float angle); ~bullet(); void setup(float x, float y, float dir_x, float dir_y, float angle); void update(); void draw(); void initialize(); bool maxDistanceReached(); float getDistance(); float fireDist; float lifeTime; ofImage bullet_; float bullet_x, bullet_y; float direc_x, direc_y; float bulletSpeed = 8; float rotate_ang; double total_direc; char is_exist = '0'; }; #endif /* bullet_hpp */
afc0da6e3c8a1ded820b168737e9ad09c64ef1e3
cd1e9c722a7fadf5b40be36ebeb894f00b7bd2f0
/chromium/ppapi/proxy/ppb_url_loader_proxy.h
523488b35b103c6005ad5525b17be49a20d2395f
[ "BSD-3-Clause" ]
permissive
collinjackson/gles2-bc-nacl
7621ed984d39b2b77b3dff92cb5212b9a3b3ddb9
dcd4dd9608cb3976b4294c7277a3fcb7f8184a16
refs/heads/master
2021-01-01T17:16:22.874626
2011-02-19T22:24:46
2011-02-19T22:24:46
1,387,543
1
2
null
null
null
null
UTF-8
C++
false
false
3,731
h
ppb_url_loader_proxy.h
// Copyright (c) 2010 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 PPAPI_PPB_URL_LOADER_PROXY_H_ #define PPAPI_PPB_URL_LOADER_PROXY_H_ #include "ppapi/c/pp_completion_callback.h" #include "ppapi/c/pp_instance.h" #include "ppapi/c/pp_module.h" #include "ppapi/c/pp_resource.h" #include "ppapi/c/pp_size.h" #include "ppapi/c/pp_var.h" #include "ppapi/cpp/completion_callback.h" #include "ppapi/proxy/host_resource.h" #include "ppapi/proxy/interface_proxy.h" #include "ppapi/proxy/proxy_non_thread_safe_ref_count.h" struct PPB_URLLoader; struct PPB_URLLoaderTrusted; namespace pp { namespace proxy { struct PPBURLLoader_UpdateProgress_Params; class PPB_URLLoader_Proxy : public InterfaceProxy { public: PPB_URLLoader_Proxy(Dispatcher* dispatcher, const void* target_interface); virtual ~PPB_URLLoader_Proxy(); static const Info* GetInfo(); // URLLoader objects are normally allocated by the Create function, but // they are also provided to PPP_Instance.OnMsgHandleDocumentLoad. This // function allows the proxy for DocumentLoad to create the correct plugin // proxied info for the given browser-supplied URLLoader resource ID. static PP_Resource TrackPluginResource( const HostResource& url_loader_resource); const PPB_URLLoader* ppb_url_loader_target() const { return reinterpret_cast<const PPB_URLLoader*>(target_interface()); } // InterfaceProxy implementation. virtual bool OnMessageReceived(const IPC::Message& msg); private: // Data associated with callbacks for ReadResponseBody. struct ReadCallbackInfo; // Plugin->renderer message handlers. void OnMsgCreate(PP_Instance instance, HostResource* result); void OnMsgOpen(const HostResource& loader, const HostResource& request_info, uint32_t serialized_callback); void OnMsgFollowRedirect(const HostResource& loader, uint32_t serialized_callback); void OnMsgGetResponseInfo(const HostResource& loader, HostResource* result); void OnMsgReadResponseBody(const HostResource& loader, int32_t bytes_to_read); void OnMsgFinishStreamingToFile(const HostResource& loader, uint32_t serialized_callback); void OnMsgClose(const HostResource& loader); // Renderer->plugin message handlers. void OnMsgUpdateProgress( const PPBURLLoader_UpdateProgress_Params& params); void OnMsgReadResponseBodyAck(const HostResource& pp_resource, int32_t result, const std::string& data); // Handles callbacks for read complete messages. Takes ownership of the info // pointer. void OnReadCallback(int32_t result, ReadCallbackInfo* info); CompletionCallbackFactory<PPB_URLLoader_Proxy, ProxyNonThreadSafeRefCount> callback_factory_; }; class PPB_URLLoaderTrusted_Proxy : public InterfaceProxy { public: PPB_URLLoaderTrusted_Proxy(Dispatcher* dispatcher, const void* target_interface); virtual ~PPB_URLLoaderTrusted_Proxy(); static const Info* GetInfo(); const PPB_URLLoaderTrusted* ppb_url_loader_trusted_target() const { return reinterpret_cast<const PPB_URLLoaderTrusted*>(target_interface()); } // InterfaceProxy implementation. virtual bool OnMessageReceived(const IPC::Message& msg); private: // Plugin->renderer message handlers. void OnMsgGrantUniversalAccess(const HostResource& loader); }; } // namespace proxy } // namespace pp #endif // PPAPI_PPB_URL_LOADER_PROXY_H_
16ca0e58af28bbb8a6d411ba3d412312ae83dba5
165ac3afde4c1b3d27fb97b2a87b328127df43a3
/Vulkan/TextureLoader.cpp
b56ffa95f5ccb6f0ff9839803b59ae554dce07f8
[ "LicenseRef-scancode-public-domain" ]
permissive
Alphonse-xu/dissertation
484c3487d8bde4ad40c652d823d176a01b98c9aa
2a71e4ab7493419c18a3108ccf6544c797a66a8a
refs/heads/master
2021-01-04T03:55:18.302396
2019-11-14T07:35:10
2019-11-14T07:35:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,376
cpp
TextureLoader.cpp
#include "TextureLoader.h" #include "../Shared/nv_dds.h" #include "Image2D.h" #include "LogicDevice.h" #include "DeviceMemory.h" using namespace QZL; const std::string TextureLoader::kPath = "../Assets/Textures/"; const std::string TextureLoader::kExt = ".dds"; TextureLoader::TextureLoader(const LogicDevice* logicDevice, DeviceMemory* deviceMemory) : logicDevice_(logicDevice), deviceMemory_(deviceMemory) { } TextureLoader::~TextureLoader() { for (auto it : textures_) { SAFE_DELETE(it.second); } } // adapted from https://vulkan-tutorial.com/Texture_mapping/Images Image2D* TextureLoader::loadTexture(const std::string& fileName) { if (textures_.count(fileName)) return textures_[fileName]; DEBUG_OUT("Loading texture " << fileName); nv_dds::CDDSImage image; image.load(kPath + fileName + kExt, false); ENSURES(image.is_valid()); VkFormat format = convertToVkFormat(image.get_format()); MemoryAllocationDetails stagingBuffer = deviceMemory_->createBuffer(MemoryAllocationPattern::kStaging, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, image.get_size()); uint8_t* data = static_cast<uint8_t*>(deviceMemory_->mapMemory(stagingBuffer.id)); memcpy(data, image, image.get_size()); deviceMemory_->unmapMemory(stagingBuffer.id); // make Image2D and transfer the data from the staging buffer textures_[fileName] = new Image2D(logicDevice_, deviceMemory_, Image2D::makeImageCreateInfo(image.get_width(), image.get_height(), 1, VK_SAMPLE_COUNT_1_BIT, format, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT), MemoryAllocationPattern::kStaticResource, { VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL }); deviceMemory_->transferMemory(stagingBuffer.buffer, textures_[fileName]->getImage(), 0, image.get_width(), image.get_height()); textures_[fileName]->changeLayout({ VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL }); deviceMemory_->deleteAllocation(stagingBuffer.id, stagingBuffer.buffer); image.clear(); return textures_[fileName]; } VkFormat TextureLoader::convertToVkFormat(unsigned int oldFormat) { switch (oldFormat) { case 33777: return VK_FORMAT_BC1_RGB_UNORM_BLOCK; case 33778: return VK_FORMAT_BC2_UNORM_BLOCK; case 33779: return VK_FORMAT_BC3_UNORM_BLOCK; default: ENSURES(false); } }
73a43f24088b204e7bd9c9cc9354c1120e8ad0b6
89376968953265afbb1b39f3ce4c096a746eb8f8
/TP6/exo1.cpp
c0e98d4158cf5fcf1a391a7a83ff7f8563e370f8
[]
no_license
leogenot/AlgoProg
27d57262deb214f915b741eef080a40b4e8f1885
11acded5c19d131fd0435c3906f0f591c3844956
refs/heads/master
2023-04-15T00:18:46.332168
2021-04-16T10:24:32
2021-04-16T10:24:32
344,190,223
0
0
null
null
null
null
UTF-8
C++
false
false
3,136
cpp
exo1.cpp
#include "tp6.h" #include <QApplication> #include <time.h> MainWindow* w = nullptr; void Graph::buildFromAdjenciesMatrix(int **adjacencies, int nodeCount) { /** * Make a graph from a matrix * first create all nodes, add it to the graph then connect them * this->appendNewNode * this->nodes[i]->appendNewEdge */ for (int i = 0; i < nodeCount; i++) { GraphNode* node= new GraphNode(i); this->appendNewNode(node); } for (int i = 0; i < nodeCount; i++) { for (int j = 0; j < nodeCount; j++) { if (adjacencies[i][j]!=0){ this->nodes[i]->appendNewEdge(this->nodes[j],adjacencies[i][j]); } } } } void Graph::deepTravel(GraphNode *first, GraphNode *nodes[], int &nodesSize, bool visited[]) { /** * Fill nodes array by travelling graph starting from first and using recursivity */ nodes[nodesSize] = first; Edge* edge; visited[first->value] = true; nodesSize++; for (edge = first->edges; edge != NULL; edge = edge->next) { if (visited[edge->destination->value] == false) { deepTravel(edge->destination, nodes, nodesSize, visited); } } } void Graph::wideTravel(GraphNode *first, GraphNode *nodes[], int &nodesSize, bool visited[]) { /** * Fill nodes array by travelling graph starting from first and using queue * nodeQueue.push(a_node) * nodeQueue.front() -> first node of the queue * nodeQueue.pop() -> remove first node of the queue * nodeQueue.size() -> size of the queue */ std::queue<GraphNode*> nodeQueue; nodeQueue.push(first); Edge* edge; while (nodeQueue.size()!= 0) { GraphNode* node = nodeQueue.front(); nodeQueue.pop(); nodes[nodesSize] = node; nodesSize++; visited[node->value] = true; for (edge = node->edges; edge != NULL; edge = edge->next) { if (visited[edge->destination->value] == false) { nodeQueue.push(edge->destination); } } } } bool Graph::detectCycle(GraphNode *first, bool visited[]) { /** Detect if there is cycle when starting from first (the first may not be in the cycle) Think about what's happen when you get an already visited node **/ std::queue<GraphNode*> nodeQueue; nodeQueue.push(first); Edge* edge; while (nodeQueue.size()!=0) { GraphNode* node = nodeQueue.front(); nodeQueue.pop(); visited[node->value] = true; for (edge = node->edges; edge != NULL; edge = edge->next) { if (visited[edge->destination->value] == false) { nodeQueue.push(edge->destination); } else { return true; } } } return false; } int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow::instruction_duration = 150; w = new GraphWindow(); w->show(); return a.exec(); }
021b5f8c407a860e075af008709d24c840019a2d
afc8d5a9b1c2dd476ea59a7211b455732806fdfd
/Configurations/EFT/BoostedVh/Tools/addrecome.cc
37d0d67c65154d71414e0aca31dbd1ac3b903b9b
[]
no_license
latinos/PlotsConfigurations
6d88a5ad828dde4a7f45c68765081ed182fcda21
02417839021e2112e740607b0fb78e09b58c930f
refs/heads/master
2023-08-18T20:39:31.954943
2023-08-18T09:23:34
2023-08-18T09:23:34
39,819,875
10
63
null
2023-08-10T14:08:04
2015-07-28T07:36:50
Python
UTF-8
C++
false
false
5,783
cc
addrecome.cc
#include "LatinoAnalysis/MultiDraw/interface/TTreeFunction.h" #include "LatinoAnalysis/MultiDraw/interface/FunctionLibrary.h" #include "TSystem.h" #include "iostream" #include "vector" #include "TLorentzVector.h" #include "TMath.h" #include "JHUGenMELA/MELA/interface/Mela.h" #include "TSystem.h" #include <map> #include "TString.h" class AddRecoME : public multidraw::TTreeFunction { public: //Class Constructor AddRecoME(char const* name); //Class Destructor ~AddRecoME() { } //Functions from Multidraw namespace (TTreeFunction class) char const* getName() const override {return "AddRecoME"; } TTreeFunction* clone() const override {return new AddRecoME(name_.c_str());} unsigned getNdata() override {return 1; } //This function will return the required value double evaluate(unsigned) override; protected: void bindTree_(multidraw::FunctionLibrary&) override; //name of the required ME std::string name_; //Needed variables to select the events UIntValueReader* nCleanJet{}; FloatArrayReader* CleanJet_pt{}; FloatArrayReader* CleanJet_eta{}; FloatArrayReader* CleanJet_phi{}; IntArrayReader* CleanJet_jetIdx{}; FloatArrayReader* Jet_mass{}; UIntValueReader* nLepton{}; FloatArrayReader* Lepton_pt{}; FloatArrayReader* Lepton_eta{}; FloatArrayReader* Lepton_phi{}; FloatValueReader* MET_pt{}; FloatValueReader* PuppiMET_pt{}; FloatValueReader* PuppiMET_phi{}; private: Double_t LHCsqrts_= 13., mh_= 125.; TVar::VerbosityLevel verbosity_ = TVar::SILENT; static Mela* mela; }; Mela* AddRecoME :: mela = 0; AddRecoME::AddRecoME(char const* name): TTreeFunction() { name_ = name; if(mela == 0) mela = new Mela(LHCsqrts_, mh_, verbosity_); } double AddRecoME::evaluate(unsigned) { std::map<TString, float> MatrixElementsMap; TLorentzVector L1(0.,0.,0.,0.); TLorentzVector L2(0.,0.,0.,0.); TLorentzVector LL(0.,0.,0.,0.); TLorentzVector NuNu(0.,0.,0.,0.); TLorentzVector Higgs(0.,0.,0.,0.); TLorentzVector J1(0.,0.,0.,0.); TLorentzVector J2(0.,0.,0.,0.); unsigned ncleanjet{*nCleanJet->Get()}; unsigned nlep{*nLepton->Get()}; float Pmet_pt{*PuppiMET_pt->Get()}; float Pmet_phi{*PuppiMET_phi->Get()}; if(ncleanjet>1 && nlep>1){ L1.SetPtEtaPhiM(Lepton_pt->At(0), Lepton_eta->At(0), Lepton_phi->At(0), 0.0); L2.SetPtEtaPhiM(Lepton_pt->At(1), Lepton_eta->At(1), Lepton_phi->At(1), 0.0); LL = L1 + L2; double nunu_px = Pmet_pt*cos(Pmet_phi); double nunu_py = Pmet_pt*sin(Pmet_phi); double nunu_pz = LL.Pz(); double nunu_m = 30.0; double nunu_e = sqrt(nunu_px*nunu_px + nunu_py*nunu_py + nunu_pz*nunu_pz + nunu_m*nunu_m); NuNu.SetPxPyPzE(nunu_px, nunu_py, nunu_pz, nunu_e); Higgs = LL + NuNu; double hm = Higgs.M(); int indx_oj1 = CleanJet_jetIdx->At(0); int indx_oj2 = CleanJet_jetIdx->At(1); J1.SetPtEtaPhiM(CleanJet_pt->At(0), CleanJet_eta->At(0), CleanJet_phi->At(0), Jet_mass->At(indx_oj1)); J2.SetPtEtaPhiM(CleanJet_pt->At(1), CleanJet_eta->At(1), CleanJet_phi->At(1), Jet_mass->At(indx_oj2)); SimpleParticleCollection_t daughter_coll; SimpleParticleCollection_t associated_coll; daughter_coll.push_back(SimpleParticle_t(25,Higgs)); associated_coll.push_back(SimpleParticle_t(0,J1)); associated_coll.push_back(SimpleParticle_t(0,J2)); mela->setCandidateDecayMode(TVar::CandidateDecay_Stable); mela->setInputEvent(&daughter_coll, &associated_coll, 0, 0); mela->setCurrentCandidateFromIndex(0); float me_qcd_hsm = 0.; float me_qcd_hm = 0.; float me_qcd_mixhm = 0.; float me_zh_hlzg = 0.; float me_vbf_hlzg = 0.; mela->setProcess(TVar::HSMHiggs, TVar::JHUGen, TVar::JJQCD); mela->computeProdP(me_qcd_hsm, true); MatrixElementsMap.insert({"me_qcd_hsm", me_qcd_hsm}); mela->setProcess(TVar::H0minus, TVar::JHUGen, TVar::JJQCD); mela->computeProdP(me_qcd_hm, true); MatrixElementsMap.insert({"ME_qcd_hm", me_qcd_hm}); mela->setProcess(TVar::SelfDefine_spin0, TVar::JHUGen, TVar::JJQCD); mela->selfDHzzcoupl[0][gHIGGS_VV_1][0] = 1.; mela->selfDHzzcoupl[0][gHIGGS_VV_4][0] = 1.; mela->selfDHggcoupl[0][gHIGGS_GG_4][0] = 1; mela->selfDHggcoupl[0][gHIGGS_GG_2][0] = 1; mela->computeProdP(me_qcd_mixhm, true); MatrixElementsMap.insert({"ME_qcd_mixhm", me_qcd_mixhm}); mela->setProcess(TVar::H0_Zgsg1prime2, TVar::JHUGen, TVar::Had_ZH); mela->computeProdP(me_zh_hlzg, true); MatrixElementsMap.insert({"ME_zh_hlzg", me_zh_hlzg}); mela->setProcess(TVar::H0_Zgsg1prime2, TVar::JHUGen, TVar::JJVBF); mela->computeProdP(me_vbf_hlzg, true); MatrixElementsMap.insert({"ME_vbf_hlzg", me_vbf_hlzg}); mela->resetInputEvent(); float required_matrixelement = MatrixElementsMap.find(name_)->second; return (double)required_matrixelement; } else return -9999; } void AddRecoME::bindTree_(multidraw::FunctionLibrary& _library) { //CleanJets _library.bindBranch(nCleanJet, "nCleanJet"); _library.bindBranch(CleanJet_pt, "CleanJet_pt"); _library.bindBranch(CleanJet_eta, "CleanJet_eta"); _library.bindBranch(CleanJet_phi, "CleanJet_phi"); _library.bindBranch(CleanJet_jetIdx, "CleanJet_jetIdx"); //Jets _library.bindBranch(Jet_mass, "Jet_mass"); //Leptons _library.bindBranch(nLepton, "nLepton"); _library.bindBranch(Lepton_pt, "Lepton_pt"); _library.bindBranch(Lepton_eta, "Lepton_eta"); _library.bindBranch(Lepton_phi, "Lepton_phi"); //MET _library.bindBranch(MET_pt, "MET_pt"); _library.bindBranch(PuppiMET_pt, "PuppiMET_pt"); _library.bindBranch(PuppiMET_phi, "PuppiMET_phi"); }
1337c591ef38957d95d40def97fecfd1b32c0bf4
3693a4c271684c2b6d913ea694b100806ed28dbd
/Classes/Models/Characters/States/StateHandlers/Enemies/Enemy/StateHandlerBuilder.h
4850dcab211b5ec9f8bad779ec88b1430d34e26a
[ "MIT" ]
permissive
HectorHernandezMarques/NinjaNoMeiyo
1f99d13a66a3203df5a3dbb55cc8d86ffca53394
4ae0b99e12d172a34e84de990e47817deed632e2
refs/heads/master
2021-03-24T12:16:15.388635
2018-06-04T23:31:25
2018-06-04T23:31:25
84,374,001
0
1
null
null
null
null
UTF-8
C++
false
false
740
h
StateHandlerBuilder.h
#ifndef NINJANOMEIYO_MODELS_CHARACTERS_STATES_STATEHANDLERS_ENEMIES_ENEMY_STATEHANDLERBUILDER_H #define NINJANOMEIYO_MODELS_CHARACTERS_STATES_STATEHANDLERS_ENEMIES_ENEMY_STATEHANDLERBUILDER_H #include "../../../../Enemies/Enemy.h" #include "./EnemyStateHandler.h" namespace NinjaNoMeiyo { namespace Models { namespace Characters { namespace States { namespace StateHandlers { namespace Enemies { namespace Enemy { class StateHandlerBuilder { public: StateHandlerBuilder(Characters::Enemies::Enemy &enemy); virtual ~StateHandlerBuilder(); StateHandler& getStateHandler(); private: StateHandler *stateHandler; }; } } } } } } } #endif
9bf969ea0403d9d1ab0981e8b72173720399cf16
236fe7ae958a1fb4c2ab7e4d911e4336695751b9
/include/esp_cxx/httpd/mongoose_event_manager.h
70e7c084272bf190ae3ce336d7b5408e6ccf34cb
[ "BSD-3-Clause" ]
permissive
awong-dev/esp_cxx
1aeaca919a0663bf0e39b46a91843c8da240ffba
9a80ec04a9bf9bbf75806d1f8c14303101f23a84
refs/heads/master
2020-06-11T17:15:49.906776
2019-12-27T07:31:14
2019-12-27T07:31:14
194,034,320
1
1
null
null
null
null
UTF-8
C++
false
false
1,260
h
mongoose_event_manager.h
#ifndef ESPCXX_HTTPD_EVENT_MANAGER_H_ #define ESPCXX_HTTPD_EVENT_MANAGER_H_ #include <array> #include <functional> #include "esp_cxx/event_manager.h" #include "esp_cxx/task.h" #include "mongoose.h" namespace esp_cxx { class HttpRequest; class MongooseEventManager : public EventManager { public: MongooseEventManager(); ~MongooseEventManager() override; // Makes an http connection and asynchronously sends the result to |handler| void HttpConnect(std::function<void(HttpRequest)> handler, const std::string& uri, const char* extra_headers = nullptr, const char* post_data = nullptr); mg_mgr* underlying_manager() { return &underlying_manager_; } void Wake() override; private: void Poll(int timeout_ms) override; // See |signaling_task_| below. static void SignalTask(void* param); mg_mgr underlying_manager_; TaskRef executing_task_ = TaskRef::CreateForCurrent(); // Calling mg_broadcast() from Wake() in various contexts such as wifi // events can deadlock the LWIP stack. Use a separate thread to bounce // the wake message off of in order to avoid the deadlock. Task signaling_task_; }; } // namespace esp_cxx #endif // ESPCXX_HTTPD_EVENT_MANAGER_H_
8925d9bc75072f94b76cc283ec1dfe5428640886
e8a0f5c31572b2559213a5a1ddf7dad9bde5c7ab
/libs/full/include/include/hpx/memory.hpp
12498300f24613005cc63be5905175839f89faf8
[ "BSL-1.0", "LicenseRef-scancode-free-unknown" ]
permissive
AnshMishra2001/hpx
193d02aa13b26e07f5e9ec7be18afaee7651f2a4
00846a06bf2653c595b43aed3abe02c42998e230
refs/heads/master
2022-12-26T22:42:23.112970
2020-10-04T16:53:12
2020-10-04T16:53:12
301,199,192
0
0
BSL-1.0
2020-10-11T13:42:55
2020-10-04T18:31:28
null
UTF-8
C++
false
false
872
hpp
memory.hpp
// Copyright (c) 2020 ETH Zurich // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <hpx/parallel/memory.hpp> #include <hpx/parallel/container_memory.hpp> namespace hpx { using hpx::parallel::uninitialized_copy; using hpx::parallel::uninitialized_copy_n; using hpx::parallel::uninitialized_default_construct; using hpx::parallel::uninitialized_default_construct_n; using hpx::parallel::uninitialized_fill; using hpx::parallel::uninitialized_fill_n; using hpx::parallel::uninitialized_move; using hpx::parallel::uninitialized_move_n; using hpx::parallel::uninitialized_value_construct; using hpx::parallel::uninitialized_value_construct_n; } // namespace hpx
234b4bba7b5ff175fb0b644f4d46158413a4de61
9046787aaf7dd030af23dc583edbca8518bb5dfa
/Server/Server/Packet.h
862718abc2cdc4136ff37b840487b790c004e5aa
[]
no_license
IvanNovgorodtsev/UDP-text-protocol
013917edeedd99a7d01a6e8389dc5437937a1a12
1ec31b0dc08a0c099ed45fff09dc0dba5a479464
refs/heads/master
2021-08-28T09:00:52.028294
2017-12-11T19:25:11
2017-12-11T19:25:11
112,791,231
0
0
null
null
null
null
UTF-8
C++
false
false
1,009
h
Packet.h
#pragma once #include<string> using namespace std; class Packet { public: string message; int message_size = message.size(); Packet(); Packet(string OP, string PO, string dane, int liczba, string ID_name, int ID, string time_name, string time); void setMessage(string m); string getMessage(); void setTime(string time); string getTime(); void setID(int id); int getID(); void setLiczba(int number); int getLiczba(); void setOP(string OP); string getOP(); void setPO(string PO); string getPO(); void packing(); void unpacking(); void setDane(string dane); string getDane(); void setID_name(string name); string getID_name(); void setTime_name(string time); string getTime_name(); private: string OP; // pole operacji string PO; // pole odpowiedzi string dane; // pole nazwy dla liczby int liczba; // liczba przeslana przez klienta string ID_name; // pole nazwy ID int ID; // pole ID string time_name; // pole nazwy czasu string time; // pole czasu };