text
stringlengths
8
6.88M
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Arjan van Leeuwen */ #ifndef VISUAL_DEVICE_HANDLER_H #define VISUAL_DEVICE_HANDLER_H class VisualDevice; class OpWidget; /** @brief Makes sure that a visual device handler exists for a certain widget * * Instantiate this class with a given OpWidget to make sure that a visual device * exists for that widget as long as the VisualDeviceHandler is in scope. * This can be used to execute several functions of an OpWidget that only run * if a VisualDevice is present. * * Example: * { * VisualDeviceHandler handler(widget); * widget->GetPreferedSize(&width, &height, 1, 1); * } * */ class VisualDeviceHandler { public: VisualDeviceHandler(OpWidget* widget); ~VisualDeviceHandler(); private: OpWidget* m_widget; VisualDevice* m_vd; }; #endif // VISUAL_DEVICE_HANDLER_H
/* * Copyright (C) 2008 Alex Shulgin * * This file is part of png++ the C++ wrapper for libpng. PNG++ is free * software; the exact copying conditions are as follows: * * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ #ifndef PNGPP_CONFIG_HPP_INCLUDED #define PNGPP_CONFIG_HPP_INCLUDED #pragma once #include <stdint.h> namespace png { #ifdef PNG_gAMA_SUPPORTED static inline constexpr const bool png_gama_supported{true}; #else static inline constexpr const bool png_gama_supported{false}; #endif #ifdef PNG_FLOATING_POINT_SUPPORTED static inline constexpr const bool png_floating_point_supported{true}; #else static inline constexpr const bool png_floating_point_supported{false}; #endif #ifdef PNG_1_0_X static inline constexpr const bool png_1_0_x{true}; #else static inline constexpr const bool png_1_0_x{false}; #endif #ifdef PNG_tRNS_SUPPORTED static inline constexpr const bool png_trns_supported{true}; #else static inline constexpr const bool png_trns_supported{false}; #endif #ifdef PNG_READ_16_TO_8_SUPPORTED static inline constexpr const bool png_read_16_to_8_supported{true}; #else static inline constexpr const bool png_read_16_to_8_supported{false}; #endif #ifdef PNG_READ_EXPAND_SUPPORTED static inline constexpr const bool png_read_expand_supported{true}; #else static inline constexpr const bool png_read_expand_supported{false}; #endif #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED static inline constexpr const bool png_read_strip_alpha_supported{true}; #else static inline constexpr const bool png_read_strip_alpha_supported{false}; #endif #ifdef PNG_READ_BGR_SUPPORTED static inline constexpr const bool png_read_bgr_supported{true}; #else static inline constexpr const bool png_read_bgr_supported{false}; #endif #ifdef PNG_WRITE_BGR_SUPPORTED static inline constexpr const bool png_write_bgr_supported{true}; #else static inline constexpr const bool png_write_bgr_supported{false}; #endif #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED static inline constexpr const bool png_read_rgb_to_gray_supported{true}; #else static inline constexpr const bool png_read_rgb_to_gray_supported{true}; #endif #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED static inline constexpr const bool png_read_gray_to_rgb_supported{true}; #else static inline constexpr const bool png_read_gray_to_rgb_supported{false}; #endif #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED static inline constexpr const bool png_read_swap_alpha_supported{true}; #else static inline constexpr const bool png_read_swap_alpha_supported{false}; #endif #ifdef PNG_WRITE_SWAP_ALPHA_SUPPORTED static inline constexpr const bool png_write_swap_alpha_supported{true}; #else static inline constexpr const bool png_write_swap_alpha_supported{false}; #endif #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED static inline constexpr const bool png_read_invert_alpha_supported{true}; #else static inline constexpr const bool png_read_invert_alpha_supported{false}; #endif #ifdef PNG_WRITE_INVERT_ALPHA_SUPPORTED static inline constexpr const bool png_write_invert_alpha_supported{true}; #else static inline constexpr const bool png_write_invert_alpha_supported{false}; #endif #ifdef PNG_READ_FILLER_SUPPORTED static inline constexpr const bool png_read_filler_supported{true}; #else static inline constexpr const bool png_read_filler_supported{false}; #endif #ifdef PNG_WRITE_FILLER_SUPPORTED static inline constexpr const bool png_write_filler_supported{true}; #else static inline constexpr const bool png_write_filler_supported{false}; #endif #ifdef PNG_READ_PACK_SUPPORTED static inline constexpr const bool png_read_pack_supported{true}; #else static inline constexpr const bool png_read_pack_supported{false}; #endif #ifdef PNG_WRITE_PACK_SUPPORTED static inline constexpr const bool png_write_pack_supported{true}; #else static inline constexpr const bool png_write_pack_supported{false}; #endif #ifdef PNG_READ_PACKSWAP_SUPPORTED static inline constexpr const bool png_read_packswap_supported{true}; #else static inline constexpr const bool png_read_packswap_supported{false}; #endif #ifdef PNG_WRITE_PACKSWAP_SUPPORTED static inline constexpr const bool png_write_packswap_supported{true}; #else static inline constexpr const bool png_write_packswap_supported{false}; #endif #ifdef PNG_READ_SHIFT_SUPPORTED static inline constexpr const bool png_read_shift_supported{true}; #else static inline constexpr const bool png_read_shift_supported{false}; #endif #ifdef PNG_WRITE_SHIFT_SUPPORTED static inline constexpr const bool png_write_shift_supported{true}; #else static inline constexpr const bool png_write_shift_supported{false}; #endif #ifdef PNG_READ_INVERT_SUPPORTED static inline constexpr const bool png_read_invert_supported{true}; #else static inline constexpr const bool png_read_invert_supported{false}; #endif #ifdef PNG_WRITE_INVERT_SUPPORTED static inline constexpr const bool png_write_invert_supported{true}; #else static inline constexpr const bool png_write_invert_supported{false}; #endif #ifdef PNG_READ_USER_TRANSFORM_SUPPORTED static inline constexpr const bool png_read_user_transform_supported{true}; #else static inline constexpr const bool png_read_user_transform_supported{false}; #endif #ifdef PNG_WRITE_USER_TRANSFORM_SUPPORTED static inline constexpr const bool png_write_user_transform_supported{true}; #else static inline constexpr const bool png_write_user_transform_supported{false}; #endif #ifdef PNG_READ_SWAP_SUPPORTED constexpr const bool png_read_swap_supported{true}; #else constexpr const bool png_read_swap_supported{false}; #endif #ifdef PNG_WRITE_SWAP_SUPPORTED static inline constexpr const bool png_write_swap_supported{true}; #else static inline constexpr const bool png_write_swap_supported{false}; #endif #ifdef PNG_READ_INTERLACING_SUPPORTED constexpr const bool png_read_interlacing_supported{true}; #else constexpr const bool png_read_interlacing_supported{false}; #endif #ifdef PNG_WRITE_INTERLACING_SUPPORTED static inline constexpr const bool png_write_interlacing_supported{true}; #else static inline constexpr const bool png_write_interlacing_supported{false}; #endif static inline constexpr const bool __little_endian{ [](){ constexpr const uint16_t bytes{255u}; // fill one byte with 1's, the other byte with zero's constexpr const uint16_t test{(bytes & 0xFF00)}; // check which byte is all zero // note that if this isn't a valid way to determine endianess, then the system must behave endian neutral to our code and therefore // the result is irrelevant since the only time endianess matters to us is when using bitwise operations across byte boundaries // (or the compiler is entirely non-conformant, but we don't code for that) if constexpr (test == 0) { return true; } else { return false; } }() }; } // end namespace png #endif // PNGPP_CONFIG_HPP_INCLUDED
#include <Windows.h> #include <string> #include <D3D11.h> #include <d3dcompiler.h> using namespace std; //wnd thing HINSTANCE g_hInstance(NULL); HWND g_hWnd(NULL); UINT g_winWidth(640); UINT g_winHeight(480); //d3d thing ID3D11Device* g_dx11device(NULL); ID3D11DeviceContext* g_dx11context(NULL); IDXGISwapChain* g_dx11swapchain(NULL); ID3D11DepthStencilView* g_depthStencilView(NULL); ID3D11RenderTargetView* g_renderTargetView(NULL); //buf thing ID3D11VertexShader* g_pVertexShader = NULL; ID3D11PixelShader* g_pPixelShader = NULL; ID3D11InputLayout* g_pVertexLayout = NULL; ID3D11Buffer* g_pVertexBuffer = NULL; //my own char vshader[] = "struct VSin{\n" "float4 where : POSITION;\n" "float4 color : COLOR;\n" "};\n" "struct VSout{\n" "float4 where : SV_POSITION;\n" "float4 color : COLOR;\n" "};\n" "VSout main(VSin input){\n" "VSout output;\n" "output.where = input.where;\n" "output.color = input.color;\n" "return output;\n" "}\n"; char pshader[] = "struct PSin{\n" " float4 where : SV_POSITION;\n" " float4 color : COLOR;\n" "};\n" "float4 main(PSin input) : SV_TARGET{\n" " return input.color;\n" "}"; void Render() { // 绘制青色背景 float color[4] = {0.f, 1.f, 1.f, 1.0f}; g_dx11context->ClearRenderTargetView(g_renderTargetView,reinterpret_cast<float*>(&color)); g_dx11context->ClearDepthStencilView(g_depthStencilView,D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL,1.f,0); // 正式的场景绘制工作 g_dx11context->VSSetShader(g_pVertexShader, nullptr, 0); g_dx11context->PSSetShader(g_pPixelShader, nullptr, 0); g_dx11context->IASetInputLayout(g_pVertexLayout); UINT stride = 32; UINT offset = 0; g_dx11context->IASetVertexBuffers(0, 1, &g_pVertexBuffer, &stride, &offset); g_dx11context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); g_dx11context->Draw(3, 0); // 显示 g_dx11swapchain->Present(0,0); } void Freemyctx() { } int Initmyctx() { HRESULT hr; //1. Compile vshader and pshader ID3DBlob* VSBlob = NULL; ID3DBlob* VSError= NULL; ID3DBlob* PSBlob = NULL; ID3DBlob* PSError= NULL; hr = D3DCompile( vshader, sizeof(vshader), "vs", 0, 0, //define, include "main", "vs_5_0", //entry, target 0, 0, //flag1, flag2 &VSBlob, &VSError ); if(FAILED(hr)){ MessageBox(NULL, (char*)VSError->GetBufferPointer(), "D3DCompile(vshader)",MB_OK); return 0; } hr = D3DCompile( pshader, sizeof(pshader), "ps", 0, 0, //define, include "main", "ps_5_0", //entry, target 0, 0, //flag1, flag2 &PSBlob, &PSError ); if(FAILED(hr)){ MessageBox(NULL, (char*)PSError->GetBufferPointer(), "D3DCompile(pshader)",MB_OK); return 0; } //2. Create vshader and pshader hr = g_dx11device->CreateVertexShader(VSBlob->GetBufferPointer(), VSBlob->GetBufferSize(), NULL, &g_pVertexShader ); if(FAILED(hr)){ VSBlob->Release(); return hr; } hr = g_dx11device->CreatePixelShader(PSBlob->GetBufferPointer(), PSBlob->GetBufferSize(), NULL, &g_pPixelShader ); if(FAILED(hr)){ PSBlob->Release(); return hr; } //3. input layout D3D11_INPUT_ELEMENT_DESC dies[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0,16, D3D11_INPUT_PER_VERTEX_DATA, 0} }; g_dx11device->CreateInputLayout(dies, 2, VSBlob->GetBufferPointer(), VSBlob->GetBufferSize(), &g_pVertexLayout); // 设置三角形顶点 float vertices[][8] = { { 0.0f, 0.5f, 0.0f, 1.0, 1.0f, 0.0f, 0.0f, 1.0f}, { 0.5f,-0.5f, 0.0f, 1.0, 0.0f, 1.0f, 0.0f, 1.0f}, {-0.5f,-0.5f, 0.0f, 1.0, 0.0f, 0.0f, 1.0f, 1.0f} }; // 设置顶点缓冲区描述 D3D11_BUFFER_DESC vbd; ZeroMemory(&vbd, sizeof(vbd)); vbd.Usage = D3D11_USAGE_IMMUTABLE; vbd.ByteWidth = sizeof(vertices); vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; // 新建顶点缓冲区 D3D11_SUBRESOURCE_DATA Data; ZeroMemory(&Data, sizeof(Data)); Data.pSysMem = vertices; hr = g_dx11device->CreateBuffer(&vbd, &Data, &g_pVertexBuffer); if(FAILED(hr)){ MessageBox(NULL, "CreateBuffer", "Error", MB_OK); return hr; } return 1; } void FreeD3D11() { g_depthStencilView->Release(); g_renderTargetView->Release(); g_dx11swapchain->Release(); g_dx11context->Release(); g_dx11device->Release(); } BOOL InitD3D11() { // a.创建设备和上下文 D3D_FEATURE_LEVEL myFeatureLevel; UINT createDeviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif HRESULT hr = D3D11CreateDevice( NULL, // 默认显示适配器 D3D_DRIVER_TYPE_HARDWARE, 0, // 不使用软件设备 createDeviceFlags, NULL, 0, // 默认的特征等级数组 D3D11_SDK_VERSION, &g_dx11device, &myFeatureLevel, &g_dx11context ); if(FAILED(hr)) { MessageBox(NULL, "Create d3d11 device failed!", "error",MB_OK); return FALSE; } // b.4X多重采样质量等级 UINT m4xMsaaQuality(0); g_dx11device->CheckMultisampleQualityLevels( DXGI_FORMAT_R8G8B8A8_UNORM, 4, &m4xMsaaQuality); // c.准备交换链属性 DXGI_SWAP_CHAIN_DESC sd = {0}; sd.BufferDesc.Width = g_winWidth; sd.BufferDesc.Height = g_winHeight; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; sd.SampleDesc.Count = 4; sd.SampleDesc.Quality = m4xMsaaQuality-1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.BufferCount = 1; sd.OutputWindow = g_hWnd; sd.Windowed = true; sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; sd.Flags = 0; // d.创建交换链 IDXGIDevice *dxgiDevice(NULL); g_dx11device->QueryInterface(__uuidof(IDXGIDevice),(void**)(&dxgiDevice)); IDXGIAdapter *dxgiAdapter(NULL); dxgiDevice->GetParent(__uuidof(IDXGIAdapter),(void**)(&dxgiAdapter)); IDXGIFactory *dxgiFactory(NULL); dxgiAdapter->GetParent(__uuidof(IDXGIFactory),(void**)(&dxgiFactory)); hr = dxgiFactory->CreateSwapChain(g_dx11device, &sd, &g_dx11swapchain); if(FAILED(hr)) { MessageBox(NULL, "Create swap chain failed!", "error",MB_OK); return FALSE; } dxgiFactory->Release(); dxgiAdapter->Release(); dxgiDevice->Release(); // e.创建渲染目标视图 ID3D11Texture2D *backBuffer(NULL); g_dx11swapchain->GetBuffer(0,__uuidof(ID3D11Texture2D),reinterpret_cast<void**>(&backBuffer)); hr = g_dx11device->CreateRenderTargetView(backBuffer,NULL,&g_renderTargetView); if(FAILED(hr)) { MessageBox(NULL, "Create render target view failed!", "error",MB_OK); return FALSE; } backBuffer->Release(); // f.创建深度缓冲区和其视图 D3D11_TEXTURE2D_DESC depthStencilDesc = {0}; depthStencilDesc.Width = g_winWidth; depthStencilDesc.Height = g_winHeight; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilDesc.SampleDesc.Count = 4; depthStencilDesc.SampleDesc.Quality = m4xMsaaQuality-1; depthStencilDesc.Usage = D3D11_USAGE_DEFAULT; depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthStencilDesc.CPUAccessFlags = 0; depthStencilDesc.MiscFlags = 0; ID3D11Texture2D *depthStencilBuffer(NULL); hr = g_dx11device->CreateTexture2D(&depthStencilDesc,NULL,&depthStencilBuffer); if(FAILED(hr)) { MessageBox(NULL, "Create depth stencil buffer failed!", "error",MB_OK); return FALSE; } hr = g_dx11device->CreateDepthStencilView(depthStencilBuffer,NULL,&g_depthStencilView); if(FAILED(hr)) { MessageBox(NULL, "Create depth stencil view failed!", "error",MB_OK); return FALSE; } // g.将视图绑定到输出合并器阶段 g_dx11context->OMSetRenderTargets(1,&g_renderTargetView,g_depthStencilView); depthStencilBuffer->Release(); // h.设置视口 D3D11_VIEWPORT vp = {0}; vp.TopLeftX = 0.f; vp.TopLeftY = 0.f; vp.Width = static_cast<float>(g_winWidth); vp.Height = static_cast<float>(g_winHeight); vp.MinDepth = 0.f; vp.MaxDepth = 1.f; g_dx11context->RSSetViewports(1,&vp); return TRUE; } LRESULT CALLBACK WinProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CLOSE: PostQuitMessage(0); return 0; } return DefWindowProc(hwnd,msg,wParam,lParam); } void FreeWin32() { } BOOL InitWin32() { WNDCLASS wndcls; wndcls.cbClsExtra = 0; wndcls.cbWndExtra = 0; wndcls.hbrBackground = (HBRUSH)COLOR_WINDOW; wndcls.hCursor = LoadCursor(NULL,IDC_ARROW); wndcls.hIcon = LoadIcon(NULL,IDI_APPLICATION); wndcls.hInstance = g_hInstance; wndcls.lpfnWndProc = WinProc; wndcls.lpszClassName = "d3d11"; wndcls.lpszMenuName = NULL; wndcls.style = CS_HREDRAW | CS_VREDRAW; if(!RegisterClass(&wndcls)){ MessageBox(NULL, "Register window failed!", "error",MB_OK); return FALSE; } g_hWnd = CreateWindow( "d3d11", "d3d11", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,CW_USEDEFAULT, g_winWidth,g_winHeight, NULL, NULL, g_hInstance, NULL ); if(!g_hWnd){ MessageBox(NULL, "Create window failed!", "error",MB_OK); return FALSE; } ShowWindow(g_hWnd,SW_SHOW); UpdateWindow(g_hWnd); return TRUE; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR cmdLine, int cmdShow) { g_hInstance = hInstance; if(!InitWin32())return -1; if(!InitD3D11())return -1; if(!Initmyctx())return -1; MSG msg = {0}; //主消息循环,也是游戏当中的主循环 while(msg.message != WM_QUIT) { while(PeekMessage(&msg, 0, 0, 0, PM_REMOVE)){ TranslateMessage(&msg); DispatchMessage(&msg); } Render(); } Freemyctx(); FreeD3D11(); FreeWin32(); return 0; }
// Created on: 2014-11-14 // Created by: Varvara POSKONINA // Copyright (c) 2005-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _SelectBasics_PickResult_HeaderFile #define _SelectBasics_PickResult_HeaderFile #include <gp_Pnt.hxx> //! This structure provides unified access to the results of Matches() method in all sensitive entities, //! so that it defines a Depth (distance to the entity along picking ray) and a closest Point on entity. struct SelectBasics_PickResult { public: //! Return closest result between two Pick Results according to Depth value. static const SelectBasics_PickResult& Min (const SelectBasics_PickResult& thePickResult1, const SelectBasics_PickResult& thePickResult2) { return thePickResult1.Depth() <= thePickResult2.Depth() ? thePickResult1 : thePickResult2; } public: //! Empty constructor defining an invalid result. SelectBasics_PickResult() : myObjPickedPnt (RealLast(), 0.0, 0.0), myDepth (RealLast()), myDistToCenter (RealLast()) {} //! Constructor with initialization. SelectBasics_PickResult (Standard_Real theDepth, Standard_Real theDistToCenter, const gp_Pnt& theObjPickedPnt) : myObjPickedPnt (theObjPickedPnt), myDepth (theDepth), myDistToCenter (theDistToCenter) {} public: //! Return TRUE if result was been defined. Standard_Boolean IsValid() const { return myDepth != RealLast(); } //! Reset depth value. void Invalidate() { myDepth = RealLast(); myObjPickedPnt = gp_Pnt (RealLast(), 0.0, 0.0); myNormal.SetValues (0.0f, 0.0f, 0.0f); } //! Return depth along picking ray. Standard_Real Depth() const { return myDepth; } //! Set depth along picking ray. void SetDepth (Standard_Real theDepth) { myDepth = theDepth; } //! Return TRUE if Picked Point lying on detected entity was set. Standard_Boolean HasPickedPoint() const { return myObjPickedPnt.X() != RealLast(); } //! Return picked point lying on detected entity. //! WARNING! Point is defined in local coordinate system and should be translated into World System before usage! const gp_Pnt& PickedPoint() const { return myObjPickedPnt; } //! Set picked point. void SetPickedPoint (const gp_Pnt& theObjPickedPnt) { myObjPickedPnt = theObjPickedPnt; } //! Return distance to geometry center (auxiliary value for comparing results). Standard_Real DistToGeomCenter() const { return myDistToCenter; } //! Set distance to geometry center. void SetDistToGeomCenter (Standard_Real theDistToCenter) { myDistToCenter = theDistToCenter; } //! Return (unnormalized) surface normal at picked point or zero vector if undefined. //! WARNING! Normal is defined in local coordinate system and should be translated into World System before usage! const NCollection_Vec3<float>& SurfaceNormal() const { return myNormal; } //! Set surface normal at picked point. void SetSurfaceNormal (const NCollection_Vec3<float>& theNormal) { myNormal = theNormal; } //! Set surface normal at picked point. void SetSurfaceNormal (const gp_Vec& theNormal) { myNormal.SetValues ((float )theNormal.X(), (float )theNormal.Y(), (float )theNormal.Z()); } private: gp_Pnt myObjPickedPnt; //!< User-picked selection point onto object NCollection_Vec3<float> myNormal; //!< surface normal Standard_Real myDepth; //!< Depth to detected point Standard_Real myDistToCenter; //!< Distance from 3d projection user-picked selection point to entity's geometry center }; #endif // _SelectBasics_PickResult_HeaderFile
#ifndef epic_cursor_h__ #define epic_cursor_h__ #include "image.h" #include <array> class Cursor { public: enum class Mode : int { Normal, PanningGallery, PanningImage, Selecting, Selected, Exit }; template <typename T = int> T ordinal(Mode m) { return static_cast<T>(m); } Cursor(); ~Cursor(); void init(int w, int h); /// \brief Set cursor position centered around mouseX and mouseY. void setPos(int mouseX, int mouseY); void setSize(int w, int h); void setMode(Cursor::Mode); void draw(); void update(float dt); /// \brief Set the time in seconds for the ring to complete one rotation. void setRingTime(float seconds); private: /// \brief Set the bounds of the ring so they match up with the cursor image. void updateRingBounds(); void createRingTexture(); void clearRingTexture(); void setImage(Image *img); /// \brief Start of stop the animated ring. If false, the ring is reset. void setAnimate(bool); Cursor::Mode m_mode; static const int IMAGES_LENGTH = 6; std::array<Image *, IMAGES_LENGTH> images; Image *m_img; ///< Current cursor image. Image *m_circleSection; ///< Section of circle. SDL_Texture *m_target; ///< SDL target texture. SDL_Rect m_ringBounds; ///< Bounds for target texture. bool m_animate; ///< True if should animate. bool m_alreadyAnimating; float m_angle; ///< Current angle of texture rotation. float m_da; ///< Number of degrees per second. }; #endif
// SimpleGraphic Engine // (c) David Gowor, 2014 // // Module: Core Image // #include "common.h" #include "core_image.h" #include "_lib/jpeglib.h" #include "_lib/tiffio.h" #include "_lib/png.h" #ifndef __bool_true_false_are_defined #define __bool_true_false_are_defined #endif #include "_lib/gif_lib.h" // ======= // Classes // ======= #define BLP2_MAGIC 0x32504C42 // "BLP2" // Generic client data structure, used by JPEG, TIFF and PNG struct clientData_s { IConsole* con; const char* fileName; ioStream_c* io; }; // ========= // Raw Image // ========= image_c::image_c(IConsole* conHnd) : con(conHnd) { dat = NULL; } image_c::~image_c() { Free(); } void image_c::CopyRaw(int inType, dword inWidth, dword inHeight, const byte* inDat) { if (dat) delete dat; comp = inType & 0xF; type = inType; width = inWidth; height = inHeight; dat = new byte[width * height * comp]; memcpy(dat, inDat, width * height * comp); } void image_c::Free() { delete dat; dat = NULL; } bool image_c::Load(char* fileName) { return true; // o_O } bool image_c::Save(char* fileName) { return true; // o_O } bool image_c::ImageInfo(char* fileName, imageInfo_s* info) { return true; // o_O } image_c* image_c::LoaderForFile(IConsole* conHnd, char* fileName) { fileInputStream_c in; if (in.FileOpen(fileName, true)) { conHnd->Warning("'%s' doesn't exist or cannot be opened", fileName); return NULL; } // Attempt to detect image file type from first 4 bytes of file byte dat[4]; if (in.Read(dat, 4)) { conHnd->Warning("'%s': cannot read image file (file is corrupt?)", fileName); return NULL; } if (dat[0] == 0xFF && dat[1] == 0xD8) { // JPEG Start Of Image marker return new jpeg_c(conHnd); } else if (*(dword*)dat == 0x002A4949 || *(dword*)dat == 0x2A004D4D) { // Little-endian / Big-endian marker + version return new tiff_c(conHnd); } else if (*(dword*)dat == 0x474E5089) { // 0x89 P N G return new png_c(conHnd); } else if (*(dword*)dat == 0x38464947) { // G I F 8 return new gif_c(conHnd); } else if (*(dword*)dat == BLP2_MAGIC) { // B L P 2 return new blp_c(conHnd); } else if ((dat[1] == 0 && (dat[2] == 2 || dat[2] == 3 || dat[2] == 10 || dat[2] == 11)) || (dat[1] == 1 && (dat[2] == 1 || dat[2] == 9))) { // Detect all valid image types (whether supported or not) return new targa_c(conHnd); } conHnd->Warning("'%s': unsupported image file format", fileName); return NULL; } // =========== // Targa Image // =========== #pragma pack(push,1) struct tgaHeader_s { byte idLen; byte colorMapType; byte imgType; word colorMapIndex; word colorMapLen; byte colorMapDepth; word xOrigin, yOrigin; word width, height; byte depth; byte descriptor; }; #pragma pack(pop) bool targa_c::Load(char* fileName) { Free(); // Open the file fileInputStream_c in; if (in.FileOpen(fileName, true)) { return true; } // Read header tgaHeader_s hdr; if (in.TRead(hdr)) { con->Warning("TGA '%s': couldn't read header", fileName); return true; } if (hdr.colorMapType) { con->Warning("TGA '%s': color mapped images not supported", fileName); return true; } in.Seek(hdr.idLen, SEEK_CUR); // Try to match image type int ittable[3][3] = { 3, 8, IMGTYPE_GRAY, 2, 24, IMGTYPE_BGR, 2, 32, IMGTYPE_BGRA }; int it_m; for (it_m = 0; it_m < 3; it_m++) { if (ittable[it_m][0] == (hdr.imgType & 7) && ittable[it_m][1] == hdr.depth) break; } if (it_m == 3) { con->Warning("TGA '%s': unsupported image type (it: %d pd: %d)", fileName, hdr.imgType, hdr.depth); return true; } // Read image width = hdr.width; height = hdr.height; comp = hdr.depth >> 3; type = ittable[it_m][2]; int rowSize = width * comp; dat = new byte[height * rowSize]; bool flipV = !(hdr.descriptor & 0x20); if (hdr.imgType & 8) { // Decode RLE image for (dword row = 0; row < height; row++) { int rowBase = (flipV? height - row - 1 : row) * rowSize; int x = 0; do { byte rlehdr; in.TRead(rlehdr); int rlen = ((rlehdr & 0x7F) + 1) * comp; if (x + rlen > rowSize) { con->Warning("TGA '%s': invalid RLE coding (overlong row)", fileName); delete dat; return true; } if (rlehdr & 0x80) { byte rpk[4]; in.Read(rpk, comp); for (int c = 0; c < rlen; c++, x++) dat[rowBase + x] = rpk[c % comp]; } else { in.Read(dat + rowBase + x, rlen); x+= rlen; } } while (x < rowSize); } } else { // Raw image if (flipV) { for (int row = height - 1; row >= 0; row--) { in.Read(dat + row * rowSize, rowSize); } } else { in.Read(dat, height * rowSize); } } return false; } bool targa_c::Save(char* fileName) { // Find a suitable image type int ittable[3][3] = { 1, IMGTYPE_GRAY, 3, 3, IMGTYPE_BGR, 2, 4, IMGTYPE_BGRA, 2 }; int it_m; for (it_m = 0; it_m < 3; it_m++) { if (ittable[it_m][0] == comp && ittable[it_m][1] == type) break; } if (it_m == 3) { // Image type not supported return true; } // Open the file fileOutputStream_c out; if (out.FileOpen(fileName, true)) { return true; } // Write header tgaHeader_s hdr; memset(&hdr, 0, sizeof(hdr)); hdr.width = width; hdr.height = height; hdr.depth = comp << 3; hdr.imgType = ittable[it_m][2] + rle * 8; out.TWrite(hdr); // Write image dword rowSize = width * comp; if (rle) { byte* packet = new byte[comp * 128 + 4]; dword mask = 0xFFFFFFFF >> ((4 - comp) << 3); for (int y = height - 1; y >= 0; y--) { byte* p = dat + y * rowSize; byte hdr = 255; dword lastPix; memOutputStream_c line(512); for (dword x = 0; x < width; x++, p+= comp) { dword pix = *(dword*)p & mask; if (hdr == 255) { // Start new packet *(dword*)packet = pix; hdr = 0; } else if (hdr & 0x80) { // Run-length packet, check for continuance if (pix == lastPix) { hdr++; if (hdr == 255) { // Max length, write it line.TWrite(hdr); line.Write(packet, comp); } } else { line.TWrite(hdr); line.Write(packet, comp); *(dword*)packet = pix; hdr = 0; } } else if (hdr) { // Raw packet, check if a run-length packet could be created with the last pixel if (pix == lastPix) { hdr--; line.TWrite(hdr); line.Write(packet, comp * (hdr + 1)); *(dword*)packet = pix; hdr = 129; } else if (hdr == 127) { // Packet is already full, write it line.TWrite(hdr); line.Write(packet, comp * (hdr + 1)); *(dword*)packet = pix; hdr = 0; } else { hdr++; *(dword*)(packet + comp * hdr) = pix; } } else { // New packet, check if this could become a run-length packet if (pix == lastPix) { hdr = 129; } else { hdr = 1; *(dword*)(packet + comp) = pix; } } lastPix = pix; } if (hdr < 255) { // Leftover packet, write it line.TWrite(hdr); line.Write(packet, hdr & 0x80? comp : comp * (hdr + 1)); } line.MemOutput(&out); } delete packet; } else { // Raw for (int y = height - 1; y >= 0; y--) { out.Write(dat + y * rowSize, rowSize); } } return false; } bool targa_c::ImageInfo(char* fileName, imageInfo_s* info) { // Open the file fileInputStream_c in; if (in.FileOpen(fileName, true)) { return true; } // Read header tgaHeader_s hdr; if (in.TRead(hdr) || hdr.colorMapType) { return true; } info->width = hdr.width; info->height = hdr.height; if ((hdr.imgType & 7) == 3 && hdr.depth == 8) { info->alpha = false; info->comp = 1; } else if ((hdr.imgType & 7) == 2 && hdr.depth == 24) { info->alpha = false; info->comp = 3; } else if ((hdr.imgType & 7) == 2 && hdr.depth == 32) { info->alpha = true; info->comp = 4; } else { return true; } return false; } // ========== // JPEG Image // ========== struct jpegError_s: public jpeg_error_mgr { jpegError_s() { jpeg_std_error(this); output_message = MSGOut; error_exit = FatalError; } static void MSGOut(j_common_ptr cinfo) { char buffer[JMSG_LENGTH_MAX]; (*cinfo->err->format_message)(cinfo, buffer); clientData_s* cd = (clientData_s*)cinfo->client_data; //cd->con->Warning("JPEG '%s': %s", cd->fileName, buffer); } static void FatalError(j_common_ptr cinfo) { MSGOut(cinfo); //throw 1; } }; // JPEG Reading struct jpegRead_s: public jpeg_source_mgr { ioStream_c* in; byte buffer[1024]; jpegRead_s(ioStream_c* in) : in(in) { init_source = Init; term_source = Term; fill_input_buffer = Fill; skip_input_data = SkipInput; resync_to_restart = jpeg_resync_to_restart; } static void Init(j_decompress_ptr jdecomp) { jpegRead_s* jr = (jpegRead_s*)jdecomp->src; jr->next_input_byte = jr->buffer; jr->bytes_in_buffer = 0; } static void Term(j_decompress_ptr jdecomp) { } static boolean Fill(j_decompress_ptr jdecomp) { static unsigned char dummyEOI[2] = {0xFF, JPEG_EOI}; jpegRead_s* jr = (jpegRead_s*)jdecomp->src; size_t avail = jr->in->GetLen() - jr->in->GetPos(); if (avail) { jr->next_input_byte = jr->buffer; jr->bytes_in_buffer = __min(avail, 1024); jr->in->Read(jr->buffer, jr->bytes_in_buffer); } else { jr->next_input_byte = dummyEOI; jr->bytes_in_buffer = 2; } return true; } static void SkipInput(j_decompress_ptr jdecomp, long count) { jpegRead_s* jr = (jpegRead_s*)jdecomp->src; while (count > 0) { if (jr->bytes_in_buffer == 0) { Fill(jdecomp); } long skip = __min(count, (long)jr->bytes_in_buffer); jr->next_input_byte+= skip; jr->bytes_in_buffer-= skip; count-= skip; } } }; bool jpeg_c::Load(char* fileName) { Free(); // Open the file fileInputStream_c in; if (in.FileOpen(fileName, true)) { return true; } // Initialise decompressor jpegError_s jerror; jpeg_decompress_struct jdecomp; jdecomp.err = &jerror; jpeg_create_decompress(&jdecomp); clientData_s cd; cd.fileName = fileName; cd.con = con; jdecomp.client_data = &cd; // Initialise source manager jpegRead_s src(&in); jdecomp.src = &src; byte** rows = NULL; try { // Read header jpeg_read_header(&jdecomp, true); width = jdecomp.image_width; height = jdecomp.image_height; comp = jdecomp.num_components; if (comp != 1 && comp != 3) { con->Warning("JPEG '%s': unsupported component count '%d'", fileName, comp); jpeg_destroy_decompress(&jdecomp); return true; } type = comp == 1? IMGTYPE_GRAY : IMGTYPE_RGB; // Allocate image and generate row pointers dat = new byte[width * height * comp]; rows = new byte*[height]; for (dword r = 0; r < height; r++) { rows[r] = dat + r * width * comp; } // Decompress jpeg_start_decompress(&jdecomp); while (jdecomp.output_scanline < height) { jpeg_read_scanlines(&jdecomp, rows + jdecomp.output_scanline, height - jdecomp.output_scanline); } jpeg_finish_decompress(&jdecomp); } catch (...) { } delete rows; jpeg_destroy_decompress(&jdecomp); return false; } // JPEG Writing struct jpegWrite_s: public jpeg_destination_mgr { ioStream_c* out; byte buffer[1024]; jpegWrite_s(ioStream_c* out) : out(out) { init_destination = Init; term_destination = Term; empty_output_buffer = Empty; } static void Init(j_compress_ptr jcomp) { jpegWrite_s* jw = (jpegWrite_s*)jcomp->dest; jw->next_output_byte = jw->buffer; jw->free_in_buffer = 1024; } static void Term(j_compress_ptr jcomp) { jpegWrite_s* jw = (jpegWrite_s*)jcomp->dest; jw->out->Write(jw->buffer, 1024 - jw->free_in_buffer); } static boolean Empty(j_compress_ptr jcomp) { jpegWrite_s* jw = (jpegWrite_s*)jcomp->dest; jw->out->Write(jw->buffer, 1024); jw->next_output_byte = jw->buffer; jw->free_in_buffer = 1024; return true; } }; bool jpeg_c::Save(char* fileName) { // JPEG only supports RGB and grayscale images if (type != IMGTYPE_RGB && type != IMGTYPE_GRAY) { return true; } // Open the file fileOutputStream_c out; if (out.FileOpen(fileName, true)) { return true; } // Initialise compressor jpegError_s jerror; jpeg_compress_struct jcomp; jcomp.err = &jerror; jpeg_create_compress(&jcomp); clientData_s cd; cd.fileName = fileName; cd.con = con; jcomp.client_data = &cd; // Initialise destination manager jpegWrite_s dst(&out); jcomp.dest = &dst; // Set image parameters jcomp.image_width = width; jcomp.image_height = height; if (type == IMGTYPE_GRAY) { jcomp.input_components = 1; jcomp.in_color_space = JCS_GRAYSCALE; } else { jcomp.input_components = 3; jcomp.in_color_space = JCS_RGB; } jpeg_set_defaults(&jcomp); jpeg_set_quality(&jcomp, quality, true); // Generate row pointers byte** rows = new byte*[height]; for (dword r = 0; r < height; r++) { rows[r] = dat + r * width * comp; } try { // Compress jpeg_start_compress(&jcomp, true); jpeg_write_scanlines(&jcomp, rows, height); jpeg_finish_compress(&jcomp); } catch (...) { dst.Term(&jcomp); } delete rows; jpeg_destroy_compress(&jcomp); return false; } // JPEG Image Info bool jpeg_c::ImageInfo(char* fileName, imageInfo_s* info) { // Open the file fileInputStream_c in; if (in.FileOpen(fileName, true)) { return true; } // Initialise decompressor jpegError_s jerror; jpeg_decompress_struct jdecomp; jdecomp.err = &jerror; jpeg_create_decompress(&jdecomp); clientData_s cd; cd.fileName = fileName; cd.con = con; jdecomp.client_data = &cd; // Initialise source manager jpegRead_s src(&in); jdecomp.src = &src; try { // Read header jpeg_read_header(&jdecomp, true); } catch (...) { jpeg_destroy_decompress(&jdecomp); return true; } info->width = jdecomp.image_width; info->height = jdecomp.image_height; info->alpha = false; info->comp = jdecomp.num_components; jpeg_destroy_decompress(&jdecomp); return (comp != 1 && comp != 3); } // ========== // TIFF Image // ========== static void ITIFF_ErrorProc(thandle_t clientData, const char* module, const char* fmt, va_list va) { clientData_s* cd = (clientData_s*)clientData; char text[1024]; vsprintf(text, fmt, va); cd->con->Warning("TIFF '%s': Error in '%.20s%s': %s", cd->fileName, module, strlen(module)>20?"...":"", text); } static void ITIFF_WarningProc(thandle_t clientData, const char* module, const char* fmt, va_list va) { clientData_s* cd = (clientData_s*)clientData; char text[1024]; vsprintf(text, fmt, va); cd->con->Warning("TIFF '%s': Warning in '%.20s%s': %s", cd->fileName, module, strlen(module)>20?"...":"", text); } static tsize_t ITIFF_ReadProc(thandle_t clientData, tdata_t data, tsize_t len) { clientData_s* cd = (clientData_s*)clientData; return cd->io->Read(data, len)? 0 : len; } static tsize_t ITIFF_WriteProc(thandle_t clientData, tdata_t data, tsize_t len) { clientData_s* cd = (clientData_s*)clientData; return cd->io->Write(data, len)? 0 : len; } static toff_t ITIFF_SeekProc(thandle_t clientData, toff_t pos, int mode) { clientData_s* cd = (clientData_s*)clientData; cd->io->Seek((size_t)pos, mode); return cd->io->GetPos(); } static int ITIFF_CloseProc(thandle_t clientData) { return 0; } static toff_t ITIFF_SizeProc(thandle_t clientData) { clientData_s* cd = (clientData_s*)clientData; return cd->io->GetLen(); } bool tiff_c::Load(char* fileName) { Free(); // Open the file fileInputStream_c in; if (in.FileOpen(fileName, true)) { return true; } // Initialise TIFF TIFFSetErrorHandler(NULL); TIFFSetErrorHandlerExt(ITIFF_ErrorProc); TIFFSetWarningHandler(NULL); TIFFSetWarningHandlerExt(ITIFF_WarningProc); clientData_s cd; cd.con = con; cd.fileName = fileName; cd.io = &in; TIFF* t = TIFFClientOpen(fileName, "r", &cd, ITIFF_ReadProc, ITIFF_WriteProc, ITIFF_SeekProc, ITIFF_CloseProc, ITIFF_SizeProc, NULL, NULL); if ( !t ) { return true; } // Get image info and read image TIFFGetField(t, TIFFTAG_IMAGEWIDTH, &width); TIFFGetField(t, TIFFTAG_IMAGELENGTH, &height); dat = new byte[width * height * 4]; comp = 4; type = IMGTYPE_RGBA; bool ret = !TIFFReadRGBAImageOriented(t, width, height, (dword*)dat, ORIENTATION_TOPLEFT, 0); TIFFClose(t); return ret; } bool tiff_c::Save(char* fileName) { // Only save RGB or RGBA if (type != IMGTYPE_RGB && type != IMGTYPE_RGBA) { return true; } // Open the file fileOutputStream_c out; if (out.FileOpen(fileName, true)) { return true; } // Initialise TIFF TIFFSetErrorHandler(NULL); TIFFSetErrorHandlerExt(ITIFF_ErrorProc); TIFFSetWarningHandler(NULL); TIFFSetWarningHandlerExt(ITIFF_WarningProc); clientData_s cd; cd.con = con; cd.fileName = fileName; cd.io = &out; TIFF* t = TIFFClientOpen(fileName, "w", &cd, ITIFF_ReadProc, ITIFF_WriteProc, ITIFF_SeekProc, ITIFF_CloseProc, ITIFF_SizeProc, NULL, NULL); if ( !t ) { return true; } // Save image TIFFSetField(t, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(t, TIFFTAG_BITSPERSAMPLE, 8); TIFFSetField(t, TIFFTAG_SAMPLESPERPIXEL, comp); TIFFSetField(t, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); TIFFSetField(t, TIFFTAG_COMPRESSION, COMPRESSION_LZW); TIFFSetField(t, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); for (dword r = 0; r < height; r++) { TIFFWriteScanline(t, dat + r*width*comp, r); } TIFFClose(t); return false; } bool tiff_c::ImageInfo(char* fileName, imageInfo_s* info) { // Open the file fileInputStream_c in; if (in.FileOpen(fileName, true)) { return true; } // Initialise TIFF TIFFSetErrorHandler(NULL); TIFFSetErrorHandlerExt(ITIFF_ErrorProc); TIFFSetWarningHandler(NULL); TIFFSetWarningHandlerExt(ITIFF_WarningProc); clientData_s cd; cd.con = con; cd.fileName = fileName; cd.io = &in; TIFF* t = TIFFClientOpen(fileName, "r", &cd, ITIFF_ReadProc, ITIFF_WriteProc, ITIFF_SeekProc, ITIFF_CloseProc, ITIFF_SizeProc, NULL, NULL); if ( !t ) { return true; } // Get image info TIFFGetField(t, TIFFTAG_IMAGEWIDTH, &info->width); TIFFGetField(t, TIFFTAG_IMAGELENGTH, &info->height); TIFFGetField(t, TIFFTAG_SAMPLESPERPIXEL, &info->comp); info->alpha = info->comp == 4; TIFFClose(t); return false; } // ========= // PNG Image // ========= static void IPNG_ErrorProc(png_structp png, const char* msg) { clientData_s* cd = (clientData_s*)png_get_error_ptr(png); cd->con->Warning("PNG '%s': %s", cd->fileName, msg); } // PNG Reading static void IPNG_ReadProc(png_structp png, png_bytep data, png_size_t len) { ioStream_c* in = (ioStream_c*)png_get_io_ptr(png); if (in->Read(data, len)) { png_error(png, "Truncated file"); } } bool png_c::Load(char* fileName) { Free(); // Open file and check signature fileInputStream_c in; if (in.FileOpen(fileName, true)) { return true; } byte sig[8]; if (in.Read(sig, 8) || png_sig_cmp(sig, 0, 8)) { con->Warning("PNG '%s': invalid signature", fileName); return true; } // Initialise PNG reader clientData_s cd; cd.con = con; cd.fileName = fileName; png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, &cd, IPNG_ErrorProc, IPNG_ErrorProc); png_infop info = png_create_info_struct(png); if (setjmp(png_jmpbuf(png))) { png_destroy_read_struct(&png, &info, NULL); return true; } png_set_read_fn(png, &in, IPNG_ReadProc); // Read image png_set_sig_bytes(png, 8); png_read_png(png, info, PNG_TRANSFORM_GRAY_TO_RGB | PNG_TRANSFORM_SCALE_16, NULL); // Copy image data width = png_get_image_width(png, info); height = png_get_image_height(png, info); comp = png_get_channels(png, info); switch (comp) { case 3: type = IMGTYPE_RGB; break; case 4: type = IMGTYPE_RGBA; break; default: con->Warning("PNG '%s': unknown image type %d", fileName, comp); png_destroy_read_struct(&png, &info, NULL); return true; }; dat = new byte[width * height * comp]; byte** rows = png_get_rows(png, info); for (dword y = 0; y < height; y++) { memcpy(dat + y * width * comp, rows[y], width * comp); } png_destroy_read_struct(&png, &info, NULL); return false; } // PNG Writing static void IPNG_WriteProc(png_structp png, png_bytep data, png_size_t len) { fileOutputStream_c* out = (fileOutputStream_c*)png_get_io_ptr(png); out->Write(data, len); } static void IPNG_FlushProc(png_structp png) { fileOutputStream_c* out = (fileOutputStream_c*)png_get_io_ptr(png); out->FileFlush(); } bool png_c::Save(char* fileName) { if (type != IMGTYPE_RGB && type != IMGTYPE_RGBA) { return true; } // Open file fileOutputStream_c out; if (out.FileOpen(fileName, true)) { return true; } // Initialise PNG writer clientData_s cd; cd.fileName = fileName; cd.con = con; png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, &cd, IPNG_ErrorProc, IPNG_ErrorProc); png_infop pnginfo = png_create_info_struct(png); if (setjmp(png_jmpbuf(png))) { png_destroy_write_struct(&png, &pnginfo); return true; } png_set_write_fn(png, &out, IPNG_WriteProc, IPNG_FlushProc); // Write image png_set_IHDR(png, pnginfo, width, height, 8, type == IMGTYPE_RGBA? PNG_COLOR_TYPE_RGB_ALPHA : PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT); byte** rows = new byte*[height]; for (dword r = 0; r < height; r++) { rows[r] = dat + r * width * comp; } png_set_rows(png, pnginfo, rows); png_write_png(png, pnginfo, PNG_TRANSFORM_IDENTITY, NULL); delete rows; png_destroy_write_struct(&png, &pnginfo); return false; } // PNG Image Info bool png_c::ImageInfo(char* fileName, imageInfo_s* info) { // Open file and check signature fileInputStream_c in; if (in.FileOpen(fileName, true)) { return true; } byte sig[8]; if (in.Read(sig, 8) || png_sig_cmp(sig, 0, 8)) { return true; } // Initialise PNG reader clientData_s cd; cd.con = con; cd.fileName = fileName; png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, &cd, IPNG_ErrorProc, IPNG_ErrorProc); png_infop pnginfo = png_create_info_struct(png); if (setjmp(png_jmpbuf(png))) { png_destroy_read_struct(&png, &pnginfo, NULL); return true; } png_set_read_fn(png, &in, IPNG_ReadProc); // Get image info png_set_sig_bytes(png, 8); png_read_info(png, pnginfo); info->width = png_get_image_width(png, pnginfo); info->height = png_get_image_height(png, pnginfo); int type = png_get_color_type(png, pnginfo); png_destroy_read_struct(&png, &pnginfo, NULL); if (type & PNG_COLOR_MASK_COLOR) { if (type & PNG_COLOR_MASK_ALPHA) { info->alpha = true; info->comp = 4; } else { info->alpha = false; info->comp = 3; } } else { return true; } return false; } // ========= // GIF Image // ========= static int IGIF_ReadProc(GifFileType* gif, GifByteType* buf, int len) { ioStream_c* in = (ioStream_c*)gif->UserData; if (in->Read(buf, len)) { return 0; } return len; } bool gif_c::Load(char* fileName) { // Open file fileInputStream_c in; if (in.FileOpen(fileName, true)) { return true; } // Initialise GIF reader int code; GifFileType* gif = DGifOpen(&in, IGIF_ReadProc, &code); if ( !gif ) { con->Warning("'%s': error '%d' opening GIF", fileName, code); in.FileClose(); return true; } // Read image if (DGifSlurp(gif) != GIF_OK) { con->Warning("'%s': error '%d' reading GIF", fileName, gif->Error); DGifCloseFile(gif, NULL); in.FileClose(); return true; } // Convert image width = gif->SavedImages[0].ImageDesc.Width; height = gif->SavedImages[0].ImageDesc.Height; comp = 4; type = IMGTYPE_RGBA; dat = new byte[width * height * comp]; ColorMapObject* map = gif->SColorMap? gif->SColorMap : gif->SavedImages[0].ImageDesc.ColorMap; GraphicsControlBlock gcb; DGifSavedExtensionToGCB(gif, 0, &gcb); byte* pix = dat; for (dword p = 0; p < width * height; p++, pix+= 4) { byte index = gif->SavedImages[0].RasterBits[p]; if (index == gcb.TransparentColor) { pix[0] = pix[1] = pix[2] = pix[3] = 0; } else { pix[0] = map->Colors[index].Red; pix[1] = map->Colors[index].Green; pix[2] = map->Colors[index].Blue; pix[3] = 255; } } DGifCloseFile(gif, NULL); in.FileClose(); return false; } bool gif_c::Save(char* fileName) { // HELL no. return true; } bool gif_c::ImageInfo(char* fileName, imageInfo_s* info) { return true; } // ========= // BLP Image // ========= enum blpType_e { BLP_JPEG, BLP_PALETTE, BLP_DXTC }; #pragma pack(push,1) struct blpHeader_s { dword id; dword unknown1; byte type; byte alphaDepth; byte alphaType; byte hasMipmaps; dword width; dword height; }; struct blpMipmapHeader_s { dword offset[16]; dword size[16]; }; #pragma pack(pop) bool blp_c::Load(char* fileName) { Free(); // Open the file fileInputStream_c in; if (in.FileOpen(fileName, true)) { return true; } // Read header blpHeader_s hdr; if (in.TRead(hdr)) { return true; } if (hdr.id != BLP2_MAGIC) { con->Warning("'%s' is not a BLP2 file", fileName); return true; } if (hdr.type != BLP_DXTC || !hdr.hasMipmaps) { // To hell with compatability con->Warning("'%s': unsupported image type (type: %d hasMipmaps: %d)", fileName, hdr.type, hdr.hasMipmaps); return true; } if (hdr.alphaDepth == 0) { comp = 3; type = IMGTYPE_RGB_DXT1; } else if (hdr.alphaDepth == 1) { comp = 4; type = IMGTYPE_RGBA_DXT1; } else if (hdr.alphaDepth == 8) { comp = 4; if (hdr.alphaType == 7) { type = IMGTYPE_RGBA_DXT5; } else { type = IMGTYPE_RGBA_DXT3; } } else { con->Warning("'%s': unsupported alpha type (alpha depth: %d alpha type %d)", fileName, hdr.alphaDepth, hdr.alphaType); return true; } width = hdr.width; height = hdr.height; // Read the mipmap header blpMipmapHeader_s mip; in.TRead(mip); // Read image int isize = 0; int numMip; for (int c = 0; c < 16; c++) { if (mip.size[c] == 0) { numMip = c; break; } isize+= mip.size[c]; } dat = new byte[isize + numMip*sizeof(dword)]; byte* datPtr = dat; for (int c = 0; c < numMip; c++) { memcpy(datPtr, mip.size + c, sizeof(dword)); datPtr+= sizeof(dword); in.Seek(mip.offset[c], SEEK_SET); in.Read(datPtr, mip.size[c]); datPtr+= mip.size[c]; } return false; } bool blp_c::Save(char* fileName) { // No. return true; } bool blp_c::ImageInfo(char* fileName, imageInfo_s* info) { // Open the file fileInputStream_c in; if (in.FileOpen(fileName, true)) { return true; } // Read header blpHeader_s hdr; if (in.TRead(hdr)) { return true; } if (hdr.id != BLP2_MAGIC) { return true; } if (hdr.type != BLP_DXTC) { // To hell with compatability return true; } if (hdr.alphaDepth == 0) { info->alpha = false; info->comp = 3; } else if (hdr.alphaDepth == 1 || hdr.alphaDepth == 8) { info->alpha = true; info->comp = 4; } else { return true; } info->width = hdr.width; info->height = hdr.height; return false; }
// simulation.cpp #include <chrono> #include <iostream> #include "BlobCrystallinOligomer/simulation.h" namespace simulation { using movetype::MetMCMovetype; using movetype::VMMCMovetype; using std::chrono::steady_clock; using std::cout; using std::setw; NVTMCSimulation::NVTMCSimulation(Config& conf, Energy& ene, InputParams params, RandomGens& random_num): m_config {conf}, m_energy {ene}, m_random_num {random_num}, m_beta {1/params.m_temp}, m_steps {params.m_steps}, m_duration {params.m_duration}, m_logging_freq {params.m_logging_freq}, m_config_output_freq {params.m_config_output_freq}, m_op_output_freq {params.m_op_output_freq}, m_vtf_file {params.m_output_filebase + ".vtf", conf}, m_patch_file {params.m_output_filebase + ".patch"}, m_pipe_vtf_file {params.m_output_filebase + "_pipe.vtf", conf}, m_pipe_patch_file {params.m_output_filebase + "_pipe.patch"} { m_pipe_vtf_file.close(); m_pipe_patch_file.close(); construct_movetypes(params); } void NVTMCSimulation::run() { auto start = steady_clock::now(); for (stepT step {1}; step != (m_steps + 1); step++) { // Do a move int movetype_i {select_movetype()}; MCMovetype& movetype {*m_movetypes[movetype_i]}; bool accepted {movetype.move()}; m_move_attempts[movetype_i]++; m_move_accepts[movetype_i] += accepted; // Check if maximum allowed time reached std::chrono::duration<double> dt {(steady_clock::now() - start)}; if (dt.count() > m_duration) { cout << "Maximum time allowed reached\n"; break; } // Log if (m_logging_freq and step % m_logging_freq == 0) { log_move(step, movetype.get_label(), accepted); } // Output configuration and order parameters if (m_config_output_freq and step % m_config_output_freq == 0) { m_vtf_file.write_step(m_config, step); m_patch_file.write_step(m_config); m_pipe_vtf_file.open_write_close(m_config, step); m_pipe_patch_file.open_write_step_close(m_config); } //if (m_op_output_freq and step % m_op_output_freq) { // Write op to file //} } log_summary(); } void NVTMCSimulation::construct_movetypes(InputParams params) { // This is pretty ugly // Also creates the cumalitive probability array double cum_prob {0}; if (params.m_translation_met) { MCMovetype* movetype; string label {"TranslationMetMCMovetype"}; string movemap_type {"translation"}; movetype = new MetMCMovetype {m_config, m_energy, m_random_num, params, label, movemap_type}; m_movetypes.emplace_back(movetype); cum_prob += params.m_translation_met; m_cum_probs.push_back(cum_prob); } if (params.m_rotation_met) { MCMovetype* movetype; string label {"RotationMetMCMovetype"}; string movemap_type {"rotation"}; movetype = new MetMCMovetype {m_config, m_energy, m_random_num, params, label, movemap_type}; m_movetypes.emplace_back(movetype); cum_prob += params.m_rotation_met; m_cum_probs.push_back(cum_prob); } if (params.m_translation_vmmc) { MCMovetype* movetype; string label {"TranslationVMMCMovetype"}; string movemap_type {"translation"}; movetype = new VMMCMovetype {m_config, m_energy, m_random_num, params, label, movemap_type}; m_movetypes.emplace_back(movetype); cum_prob += params.m_translation_vmmc; m_cum_probs.push_back(cum_prob); } if (params.m_rotation_vmmc) { MCMovetype* movetype; string label {"RotationVMMCMovetype"}; string movemap_type {"rotation"}; movetype = new VMMCMovetype {m_config, m_energy, m_random_num, params, label, movemap_type}; m_movetypes.emplace_back(movetype); cum_prob += params.m_rotation_vmmc; m_cum_probs.push_back(cum_prob); } if (params.m_ntd_flip) { MCMovetype* movetype; string label {"NTDFlipMCMovetype"}; string movemap_type {"ntdflip"}; movetype = new MetMCMovetype {m_config, m_energy, m_random_num, params, label, movemap_type}; m_movetypes.emplace_back(movetype); cum_prob += params.m_ntd_flip; m_cum_probs.push_back(cum_prob); } // Prepare vectors that track movetype information for (size_t i {0}; i != m_movetypes.size(); i++) { m_move_attempts.push_back(0); m_move_accepts.push_back(0); } } int NVTMCSimulation::select_movetype() { double prob {m_random_num.uniform_real()}; size_t i; for (i = 0; i != m_cum_probs.size(); i++) { if (prob < m_cum_probs[i]) { break; } } return i; } void NVTMCSimulation::log_move(stepT step, string label, bool accepted) { cout << "Step: " << step << "\n"; cout << "Movetype: " << label << "\n"; cout << "Accepted: " << accepted << "\n"; cout << "Energy: " << m_energy.calc_total_energy() << "\n"; cout << "\n"; } void NVTMCSimulation::log_summary() { cout << "Run summary" << "\n"; cout << "Movetype" << setw(10); cout << "Attempts" << setw(10); cout << "Accepts" << setw(10); cout << "Frequency" << "\n"; for (size_t i {0}; i != m_movetypes.size(); i++) { cout << m_movetypes[i]->get_label() << setw(10); cout << m_move_attempts[i] << setw(10); cout << m_move_accepts[i] << setw(10); cout << static_cast<double>(m_move_accepts[i]) / m_move_attempts[i] << "\n"; } } }
#pragma once #include "events/event.hpp" #include <LabRender/Camera.h> #include <memory> #ifdef _MSC_VER // suppress warnings until USD is cleaned up # pragma warning(push) # pragma warning(disable : 4244 4305) #endif #include <pxr/usd/usd/stage.h> #ifdef _MSC_VER // suppress warnings until USD is cleaned up # pragma warning(pop) #endif namespace lab { class AnimationTrack; class Camera; class EditState { struct _Detail; _Detail * _detail = nullptr; public: enum ManipulatorMode { Translate, Rotate, Scale }; enum ManipSpace { Local, Global }; EditState(); ~EditState(); ManipulatorMode manipulator_mode() const; UsdStageRefPtr stage(); typedef float float16[16]; const float16 & manipulated_matrix() const; AnimationTrack & animation_root(); }; // camera extern event<void(float deltax, float deltay)> evt_camera_mouse; extern event<void(std::shared_ptr<Camera>)> evt_bind_view_camera; extern event<void(CameraRig::Mode)> evt_set_camera_mode; // manipulator extern event<void(EditState::ManipulatorMode)> evt_set_manipulator_mode; extern event<void(const EditState::float16 &)> evt_set_manipulated_matrix; // stage extern event<void()> evt_new_stage; extern event<void(UsdStageRefPtr)> evt_stage_created; extern event<void(UsdStageRefPtr)> evt_stage_closing; extern event<void(const std::string&)> evt_new_layer; extern event<void(const std::string&)> evt_layer_created; } // lab
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2002 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Alexander Remen (alexr) */ #include "core/pch.h" #ifdef M2_SUPPORT #include "DeleteFolderDialog.h" #include "adjunct/m2/src/engine/index.h" #include "adjunct/m2/src/engine/engine.h" #include "modules/locale/locale-enum.h" #include "modules/locale/oplanguagemanager.h" /***************************************************************************** ** ** DeleteFolderDialog::Init ** *****************************************************************************/ OP_STATUS DeleteFolderDialog::Init(UINT32 id, DesktopWindow* parent_window) { m_id = id; OpString title, message, format, name; Index *index = g_m2_engine->GetIndexById(m_id); if (index) { index->GetName(name); } if (name.IsEmpty()) name.Set(""); g_languageManager->GetString(Str::S_REMOVE_FOLDER, format); title.Reserve(name.Length() + format.Length()); uni_sprintf(title.CStr(), format.CStr(), name.CStr()); if (id >= IndexTypes::FIRST_NEWSGROUP && id < IndexTypes::LAST_NEWSGROUP) { g_languageManager->GetString(Str::S_UNSUBSCRIBE_NEWSGROUP_WARNING, message); } else if (id >= IndexTypes::FIRST_IMAP && id < IndexTypes::LAST_IMAP) { g_languageManager->GetString(Str::S_UNSUBSCRIBE_IMAP_WARNING, message); } else { g_languageManager->GetString(Str::S_DELETE_FOLDER_WARNING, format); message.Reserve(name.Length() + format.Length()); uni_sprintf(message.CStr(), format.CStr(), name.CStr()); } return SimpleDialog::Init(WINDOW_NAME_DELETE_MAIL_FOLDER, title, message, parent_window); } /***************************************************************************** ** ** DeleteFolderDialog::OnOk ** *****************************************************************************/ UINT32 DeleteFolderDialog::OnOk() { g_m2_engine->RemoveIndex(m_id); return 0; } #endif //M2_SUPPORT
#include <iostream> using namespace std; int main() { const int num = 4; int* ptr =(int*)(&num); *ptr = 20; cout <<&num<<" " <<num << endl; cout << ptr << " " <<*ptr << endl; return 0; }
// Created on: 1998-10-29 // Created by: Jean Yves LEBEY // Copyright (c) 1998-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _TopOpeBRep_Hctxff2d_HeaderFile #define _TopOpeBRep_Hctxff2d_HeaderFile #include <BRepAdaptor_Surface.hxx> #include <GeomAbs_SurfaceType.hxx> #include <TopoDS_Face.hxx> DEFINE_STANDARD_HANDLE(TopOpeBRep_Hctxff2d, Standard_Transient) class TopOpeBRep_Hctxff2d : public Standard_Transient { public: Standard_EXPORT TopOpeBRep_Hctxff2d(); Standard_EXPORT void SetFaces (const TopoDS_Face& F1, const TopoDS_Face& F2); Standard_EXPORT void SetHSurfaces (const Handle(BRepAdaptor_Surface)& S1, const Handle(BRepAdaptor_Surface)& S2); Standard_EXPORT void SetTolerances (const Standard_Real Tol1, const Standard_Real Tol2); Standard_EXPORT void GetTolerances (Standard_Real& Tol1, Standard_Real& Tol2) const; Standard_EXPORT Standard_Real GetMaxTolerance() const; Standard_EXPORT const TopoDS_Face& Face (const Standard_Integer I) const; Standard_EXPORT Handle(BRepAdaptor_Surface) HSurface (const Standard_Integer I) const; Standard_EXPORT Standard_Boolean SurfacesSameOriented() const; Standard_EXPORT Standard_Boolean FacesSameOriented() const; Standard_EXPORT Standard_Boolean FaceSameOrientedWithRef (const Standard_Integer I) const; DEFINE_STANDARD_RTTIEXT(TopOpeBRep_Hctxff2d,Standard_Transient) protected: private: Standard_EXPORT void SetHSurfacesPrivate(); TopoDS_Face myFace1; Handle(BRepAdaptor_Surface) mySurface1; GeomAbs_SurfaceType mySurfaceType1; Standard_Boolean myf1surf1F_sameoriented; TopoDS_Face myFace2; Handle(BRepAdaptor_Surface) mySurface2; GeomAbs_SurfaceType mySurfaceType2; Standard_Boolean myf2surf1F_sameoriented; Standard_Boolean mySurfacesSameOriented; Standard_Boolean myFacesSameOriented; Standard_Real myTol1; Standard_Real myTol2; }; #endif // _TopOpeBRep_Hctxff2d_HeaderFile
#pragma once #include <SFML/System/Vector2.hpp> #include <SFML/System/Vector3.hpp> namespace pure { template <typename T> float dot(sf::Vector2<T> lv, sf::Vector2<T> rv) { return lv.x * rv.x + lv.y * rv.y; } template <typename T> float dot(sf::Vector3<T> lv, sf::Vector3<T> rv) { return lv.x * rv.x + lv.y * rv.y + lv.z * rv.z; } }
#include <settings/settings.h> #include <GetFromFile.h> Settings getSettings(const std::string &fileName) { GetFromFile dataFile(fileName); Settings settings; settings.dt = dataFile.getWord<double>("timeStep"); settings.time = dataFile.getWord<double>("time"); settings.TLeft = dataFile.getWord<double>("tempLeft"); settings.TRight = dataFile.getWord<double>("tempRight"); settings.TTop = dataFile.getWord<double>("tempTop"); settings.TBot = dataFile.getWord<double>("tempBot"); settings.TInitial = dataFile.getWord<double>("tempIni"); settings.maxTolerance = dataFile.getWord<double>("MAX_TOLERANCE"); return settings; }
/* * Copyright 2016 Freeman Zhang <zhanggyb@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef SKLAND_WAYLAND_KEYBOARD_HPP_ #define SKLAND_WAYLAND_KEYBOARD_HPP_ #include "seat.hpp" #include <skland/core/delegate.hpp> namespace skland { namespace wayland { class Keyboard { Keyboard(const Keyboard &) = delete; Keyboard &operator=(const Keyboard &) = delete; public: Keyboard() : wl_keyboard_(nullptr) {} ~Keyboard() { if (wl_keyboard_) wl_keyboard_destroy(wl_keyboard_); } void Setup(const Seat &seat) { Destroy(); wl_keyboard_ = wl_seat_get_keyboard(seat.wl_seat_); wl_keyboard_add_listener(wl_keyboard_, &kListener, this); } void Destroy() { if (wl_keyboard_) { wl_keyboard_destroy(wl_keyboard_); wl_keyboard_ = nullptr; } } void SetUserData(void *user_data) { wl_keyboard_set_user_data(wl_keyboard_, user_data); } void *GetUserData() const { return wl_keyboard_get_user_data(wl_keyboard_); } uint32_t GetVersion() const { return wl_keyboard_get_version(wl_keyboard_); } bool IsValid() const { return nullptr != wl_keyboard_; } DelegateRef<void(uint32_t, int32_t, uint32_t)> keymap() { return keymap_; } DelegateRef<void(uint32_t, struct wl_surface *, struct wl_array *)> enter() { return enter_; } DelegateRef<void(uint32_t, struct wl_surface *)> leave() { return leave_; } DelegateRef<void(uint32_t, uint32_t, uint32_t, uint32_t)> key() { return key_; } DelegateRef<void(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)> modifiers() { return modifiers_; } DelegateRef<void(int32_t, int32_t)> repeat_info() { return repeat_info_; } private: static void OnKeymap(void *data, struct wl_keyboard *wl_keyboard, uint32_t format, int32_t fd, uint32_t size); static void OnEnter(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, struct wl_surface *wl_surface, struct wl_array *keys); static void OnLeave(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, struct wl_surface *wl_surface); static void OnKey(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, uint32_t time, uint32_t key, uint32_t state); static void OnModifiers(void *data, struct wl_keyboard *wl_keyboard, uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, uint32_t group); static void OnRepeatInfo(void *data, struct wl_keyboard *wl_keyboard, int32_t rate, int32_t delay); static const struct wl_keyboard_listener kListener; struct wl_keyboard *wl_keyboard_; Delegate<void(uint32_t, int32_t, uint32_t)> keymap_; Delegate<void(uint32_t, struct wl_surface *, struct wl_array *)> enter_; Delegate<void(uint32_t, struct wl_surface *)> leave_; Delegate<void(uint32_t, uint32_t, uint32_t, uint32_t)> key_; Delegate<void(uint32_t, uint32_t, uint32_t, uint32_t, uint32_t)> modifiers_; Delegate<void(int32_t, int32_t)> repeat_info_; }; } } #endif // SKLAND_WAYLAND_KEYBOARD_HPP_
// Copyright (c) 2019, tlblanc <tlblanc1490 at gmail dot com> #ifndef OS_FILESTREAM_H_ #define OS_FILESTREAM_H_ #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "io/sink.hpp" #include "io/source.hpp" #include <memory> class FileException { public: FileException(const char *msg, int err): m_msg(msg), m_err(err){ } inline const char *msg() const noexcept { return m_msg; } inline int err() const noexcept { return m_err; } private: const char *m_msg; const int m_err; }; class FileStream final : public Sink, public Source { public: FileStream(const char *pathname, int flags, mode_t mode): m_err(0) { m_fd = ::open(pathname, flags, mode); if (m_fd == -1) { throw FileException("failed to open file", errno); } } ~FileStream() { if (m_fd > -1) { close(m_fd); m_fd = -1; } } FileStream(const FileStream &file) = delete; FileStream(FileStream &&file) { this->m_fd = file.m_fd; this->m_err = file.m_err; file.m_fd = -1; } FileStream& operator=(const FileStream &file) = delete; FileStream& operator=(FileStream &&file) = delete; static FileStream open( const char *pathname, int flags, mode_t mode); static std::unique_ptr<FileStream> open_ptr( const char *pathname, int flags, mode_t mode); static FileStream open_read(const char *pathname); static std::unique_ptr<FileStream> open_read_ptr(const char *pathname); static FileStream open_write(const char *pathname); static std::unique_ptr<FileStream> open_write_ptr(const char *pathname); static FileStream create(const char *pathname); static std::unique_ptr<FileStream> create_ptr(const char *pathname); static FileStream create_tmp(const char *dir); static std::unique_ptr<FileStream> create_tmp_ptr(const char *dir); inline int err() const noexcept { return m_err; } Status write(const uint8_t *src, size_t len, size_t *wbytes) noexcept; Status read(uint8_t *src, size_t len, size_t *rbytes) noexcept; private: int m_err; int m_fd; }; #endif // OS_FILESTREAM_H_
#pragma once #include "gameNode.h" #include "vehicle.h" #include "NPC.h" class mainGame : public gameNode { private: entity * _player; npc* _character; vector<vehicle*> _vCars; float _zoom; public: mainGame(); ~mainGame(); HRESULT init(void); void release(void); void update(void); void render(); };
// // Created by micky on 15. 5. 22. // #ifndef JUDGESERVER_JUDGE_H #define JUDGESERVER_JUDGE_H #include <iostream> #include <string> #include <vector> #include "Thread.h" #include "SemaphoreObejct.h" #include "question.h" #include "InetSocket.h" using namespace Thread; class Judge : public Thread::Thread{ private: SemaphoreObejct in, out; SemaphoreObejct mutex; std::vector<question> _q_list; std::string createCode(const question &q) const; bool isCorrectCode(const std::string &code); inline question &getQuestion(); inline void popQuestion(); public: Judge(); ~Judge(); void submit(struct question q); int remain(); virtual void run(); }; #endif //JUDGESERVER_JUDGE_H
#include<iostream> using namespace std; int main() { int i,sum=0; for(i = 1; i <= 10; i++) { sum = sum + i; } cout<<"The sum of number from 1 to 10 is "<<sum; return 0; }
#pragma once #include <bm.h> namespace siu { /** * UID слоя на холсте. */ typedef std::string uidLayer_t; /** * Топология для обмена битовыми картами между объектами. */ typedef bm::bvector<> topology_t; /** * Декларация слоя. */ typedef std::pair< uidLayer_t, topology_t > layer_t; // Методы ниже помогают построить объекты по шаблонам. /** * Возведение целого числа в степень двойки. * Спасает при создании шаблонов, которые надо параметризировать, вычислив * возведение в степень. */ template <long num, size_t n, size_t y = 1> struct pow2 { enum { value = pow2< num * num, (n >> 1), n & 1 ? num * y : y >::value }; }; template <long num, size_t y> struct pow2< num, 0, y > { enum { value = y }; }; /** * = B^N *//* template< int B, int N > struct powN { enum { value = B * Pow< B, N-1 >::value }; }; template< int B > struct Pow< B, 0 > { enum { value = 1 }; }; */ }
#line 1 "D:/Clicks_git/B/Boost-INV_Click/SW/example/c/ARM/STM/Click_Boost_INV_STM.c" #line 1 "d:/clicks_git/b/boost-inv_click/sw/example/c/arm/stm/click_boost_inv_types.h" #line 1 "c:/users/public/documents/mikroelektronika/mikroc pro for arm/include/stdint.h" typedef signed char int8_t; typedef signed int int16_t; typedef signed long int int32_t; typedef signed long long int64_t; typedef unsigned char uint8_t; typedef unsigned int uint16_t; typedef unsigned long int uint32_t; typedef unsigned long long uint64_t; typedef signed char int_least8_t; typedef signed int int_least16_t; typedef signed long int int_least32_t; typedef signed long long int_least64_t; typedef unsigned char uint_least8_t; typedef unsigned int uint_least16_t; typedef unsigned long int uint_least32_t; typedef unsigned long long uint_least64_t; typedef signed long int int_fast8_t; typedef signed long int int_fast16_t; typedef signed long int int_fast32_t; typedef signed long long int_fast64_t; typedef unsigned long int uint_fast8_t; typedef unsigned long int uint_fast16_t; typedef unsigned long int uint_fast32_t; typedef unsigned long long uint_fast64_t; typedef signed long int intptr_t; typedef unsigned long int uintptr_t; typedef signed long long intmax_t; typedef unsigned long long uintmax_t; #line 1 "d:/clicks_git/b/boost-inv_click/sw/example/c/arm/stm/click_boost_inv_config.h" #line 1 "d:/clicks_git/b/boost-inv_click/sw/example/c/arm/stm/click_boost_inv_types.h" #line 3 "d:/clicks_git/b/boost-inv_click/sw/example/c/arm/stm/click_boost_inv_config.h" const uint32_t _BOOSTINV_I2C_CFG[ 1 ] = { 100000 }; #line 1 "d:/clicks_git/b/boost-inv_click/sw/library/__boostinv_driver.h" #line 1 "c:/users/public/documents/mikroelektronika/mikroc pro for arm/include/stdint.h" #line 58 "d:/clicks_git/b/boost-inv_click/sw/library/__boostinv_driver.h" extern const uint8_t _BOOSTINV_REG_POSITIVE_VOUT; extern const uint8_t _BOOSTINV_REG_NEGATIVE_VOUT; extern const uint8_t _BOOSTINV_REG_CONFIG ; extern const uint8_t _BOOSTINV_REG_COMMAND ; extern const uint8_t _BOOSTINV_REG_OTP0 ; extern const uint8_t _BOOSTINV_REG_OTP1 ; extern const uint8_t _BOOSTINV_REG_OTP2 ; extern const uint8_t _BOOSTINV_CFG_LOCKOUT_BIT_ENABLE ; extern const uint8_t _BOOSTINV_CFG_LOCKOUT_BIT_DISABLE ; extern const uint8_t _BOOSTINV_CFG_VPLUS_ENABLE ; extern const uint8_t _BOOSTINV_CFG_VPLUS_DISABLE ; extern const uint8_t _BOOSTINV_CFG_IRAMP_1uA ; extern const uint8_t _BOOSTINV_CFG_IRAMP_2uA ; extern const uint8_t _BOOSTINV_CFG_IRAMP_4uA ; extern const uint8_t _BOOSTINV_CFG_IRAMP_8uA ; extern const uint8_t _BOOSTINV_CFG_PDDIS_ENABLE ; extern const uint8_t _BOOSTINV_CFG_PDDIS_DISABLE ; extern const uint8_t _BOOSTINV_CFG_PUSEQ_OUTPUTS_DISABLED ; extern const uint8_t _BOOSTINV_CFG_PUSEQ_VOUTN_RAMP_1ST ; extern const uint8_t _BOOSTINV_CFG_PUSEQ_VOUTP_RAMP_1ST ; extern const uint8_t _BOOSTINV_CFG_PUSEQ_BOTH_RAMP_TOGETHER; extern const uint8_t _BOOSTINV_CMD_WRITE_OTP_MEMORY ; extern const uint8_t _BOOSTINV_CMD_CLEAR_OTP_FAULT ; extern const uint8_t _BOOSTINV_CMD_RESET ; extern const uint8_t _BOOSTINV_CMD_SWITCHES_OFF ; extern const uint8_t _BOOSTINV_CMD_REGISTER_SELECT_POS_VOUT; extern const uint8_t _BOOSTINV_CMD_REGISTER_SELECT_NEG_VOUT; extern const uint8_t _BOOSTINV_CMD_REGISTER_SELECT_CONFIG ; extern const uint8_t _BOOSTINV_CMD_REGISTER_SELECT_OTP2 ; extern const uint8_t _BOOSTINV_CMD_REGISTER_SELECT_OTP1 ; extern const uint8_t _BOOSTINV_CMD_REGISTER_SELECT_OTP0 ; #line 106 "d:/clicks_git/b/boost-inv_click/sw/library/__boostinv_driver.h" void boostinv_i2cDriverInit( const uint8_t* gpioObj, const uint8_t* i2cObj, uint8_t slave); #line 113 "d:/clicks_git/b/boost-inv_click/sw/library/__boostinv_driver.h" void boostinv_gpioDriverInit( const uint8_t* gpioObj); #line 123 "d:/clicks_git/b/boost-inv_click/sw/library/__boostinv_driver.h" void boostinv_writeByte(uint8_t reg, uint8_t _data); #line 131 "d:/clicks_git/b/boost-inv_click/sw/library/__boostinv_driver.h" uint8_t boostinv_readByte(uint8_t reg); #line 136 "d:/clicks_git/b/boost-inv_click/sw/library/__boostinv_driver.h" void boostinv_enable(); #line 145 "d:/clicks_git/b/boost-inv_click/sw/library/__boostinv_driver.h" void boostinv_setPositiveVoltage(uint16_t voltage); #line 154 "d:/clicks_git/b/boost-inv_click/sw/library/__boostinv_driver.h" void boostinv_setNegativeVoltage(int16_t voltage); #line 31 "D:/Clicks_git/B/Boost-INV_Click/SW/example/c/ARM/STM/Click_Boost_INV_STM.c" uint16_t Positive_Vout; int16_t Negative_Vout; void systemInit() { mikrobus_gpioInit( _MIKROBUS1, _MIKROBUS_RST_PIN, _GPIO_OUTPUT ); mikrobus_i2cInit( _MIKROBUS1, &_BOOSTINV_I2C_CFG[0] ); Delay_ms( 100 ); } void applicationInit() { boostinv_i2cDriverInit( ( const uint8_t* )&_MIKROBUS1_GPIO, ( const uint8_t* )&_MIKROBUS1_I2C, 0x31 ); boostinv_enable(); boostinv_writeByte(_BOOSTINV_REG_COMMAND, _BOOSTINV_CMD_REGISTER_SELECT_POS_VOUT | _BOOSTINV_CMD_REGISTER_SELECT_NEG_VOUT | _BOOSTINV_CMD_REGISTER_SELECT_CONFIG ); } void applicationTask() { Positive_Vout = 3200; boostinv_setPositiveVoltage(Positive_Vout); Delay_ms( 5000 ); Positive_Vout = 7750; boostinv_setPositiveVoltage(Positive_Vout); Delay_ms( 5000 ); Positive_Vout = 12000; boostinv_setPositiveVoltage(Positive_Vout); Delay_ms( 5000 ); Positive_Vout = 7750; boostinv_setPositiveVoltage(Positive_Vout); Delay_ms( 5000 ); Negative_Vout = -1450; boostinv_setNegativeVoltage(Negative_Vout); Delay_ms( 5000 ); Negative_Vout = -6700; boostinv_setNegativeVoltage(Negative_Vout); Delay_ms( 5000 ); Negative_Vout = -11050; boostinv_setNegativeVoltage(Negative_Vout); Delay_ms( 5000 ); Negative_Vout = -6700; boostinv_setNegativeVoltage(Negative_Vout); Delay_ms( 5000 ); } void main() { systemInit(); applicationInit(); while (1) { applicationTask(); } }
// // C++ Implementation: mess // // Description: // // // Author: Jally <jallyx@163.com>, (C) 2009 // // Copyright: See COPYING file that comes with this distribution // // #include "mess.h" #include "utils.h" PalInfo::PalInfo():ipv4(0), segdes(NULL), version(NULL), user(NULL), host(NULL), name(NULL), group(NULL), photo(NULL), sign(NULL), iconfile(NULL), encode(NULL), flags(0), packetn(0), rpacketn(0) {} PalInfo::~PalInfo() { g_free(segdes); g_free(version); g_free(user); g_free(host); g_free(name); g_free(group); g_free(photo); g_free(sign); g_free(iconfile); g_free(encode); } GroupInfo::GroupInfo():grpid(0), type(GROUP_BELONG_TYPE_REGULAR), name(NULL), member(NULL), buffer(NULL), dialog(NULL) {} GroupInfo::~GroupInfo() { g_free(name); g_slist_free(member); g_object_unref(buffer); } FileInfo::FileInfo():fileid(0), packetn(0), fileattr(0), filesize(-1), finishedsize(0),fileown(NULL), filepath(NULL) {} FileInfo::~FileInfo() { g_free(filepath); } MsgPara::MsgPara():pal(NULL), stype(MESSAGE_SOURCE_TYPE_PAL), btype(GROUP_BELONG_TYPE_REGULAR), dtlist(NULL) {} MsgPara::~MsgPara() { for (GSList *tlist = dtlist; tlist; tlist = g_slist_next(tlist)) delete (ChipData *)tlist->data; g_slist_free(dtlist); } ChipData::ChipData():type(MESSAGE_CONTENT_TYPE_STRING), data(NULL) {} ChipData::~ChipData() { g_free(data); } NetSegment::NetSegment():startip(NULL), endip(NULL), description(NULL) {} NetSegment::~NetSegment() { g_free(startip); g_free(endip); g_free(description); } SessionAbstract::SessionAbstract() {} SessionAbstract::~SessionAbstract() {} TransAbstract::TransAbstract() {} TransAbstract::~TransAbstract() {}
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <sstream> #include <string.h> #include <queue> #include <vector> #include <set> #include <map> #include <numeric> typedef long long LL; typedef unsigned long long ULL; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int pr[3333], prn[3333], pn = 0; LL f[22][444][3333]; int an; int a[20]; LL Calc(LL R) { if (R == 1000000000000000000ll) --R; if (R == 0) return 0; an = 0; while (R > 0) { a[an++] = R % 10; R /= 10; } LL ans = 0; int ad = 0, ads = 0; for (int i = an - 1; i >= 0; i--) { for (int d = 0; d < a[i]; d++) ans += f[i][ad + d][ads + d * d]; ad += a[i]; ads += a[i] * a[i]; } ans += f[0][ad][ads]; return ans; } //int s[11111111], ss[11111111]; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); /* for (int i = 2; i < 2000; i++) { pr[i] = true; for (int j = 2; j < i; j++) if (i % j == 0) { pr[i] = false; break; } } int ans = 0; s[0] = 0; ss[0] = 0; for (int i = 1; i <= 100000; i++) { s[i] = s[i / 10] + i % 10; ss[i] = ss[i / 10] + (i % 10) * (i % 10); if (pr[s[i]] && pr[ss[i]]) { cout << i << endl; ans++; } } cout << ans << endl; return 0; */ for (int i = 2; i < 3000; i++) { pr[i] = true; for (int j = 0; j < pn; j++) if (i % prn[j] == 0) { pr[i] = false; break; } if (pr[i]) prn[pn++] = i; } for (int i = 0; prn[i] < 444; i++) for (int j = 0; j < pn ; j++) f[0][prn[i]][prn[j]] = 1; int mass = 18 * 10; int masss = 18 * 90; for (int l = 1; l < 18; ++l) { for (int d = 0; d < 10; d++) for (int i = 0; i <= mass - d; ++i) for (int j = 0; j <= masss - d * d; ++j) { // if (f[l - 1][i + d][j + d * d]) cout << d << " " << l << " " << i << " " << j << " + " << f[l - 1][i + d][j + d * d] << endl; f[l][i][j] += f[l - 1][i + d][j + d * d]; } } int T; LL A, B; cin >> T; while (T--) { cin >> A >> B; cout << Calc(B) - Calc(A - 1) << endl; } return 0; }
/* * MIT License * * Copyright (c) 2017 by J. Daly at Michigan State University * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef ByteCuts_H #define ByteCuts_H #include "ByteCutsNode.h" #include "TreeBuilder.h" class ByteCutsClassifier { public: ByteCutsClassifier(const std::vector<Rule>& rules, const std::vector<ByteCutsNode*>& trees, const std::vector<int>& priorities, const std::vector<size_t>& sizes); ByteCutsClassifier(const std::unordered_map<std::string, std::string>& args); ~ByteCutsClassifier(); void ConstructClassifier(const std::vector<Rule>& rules); int ClassifyAPacket(const Packet& packet); Memory MemSizeBytes() const { Memory mem = 0; int rulesize = 19; for (const ByteCutsNode* t : trees) { mem += t->Size(rulesize); } return mem; } size_t NumTables() const { return trees.size(); } size_t NumGoodTrees() const { return goodTrees; } size_t NumBadTrees() const { return badTrees; } size_t RulesInTable(size_t tableIndex) const { return sizes[tableIndex]; } size_t PriorityOfTable(size_t tableIndex) const { return priorities[tableIndex]; } int HeightOfTree(size_t tableIndex) const { return trees[tableIndex]->Height(); } int CostOfTree(size_t tableIndex) const { return trees[tableIndex]->Cost(); } private: bool IsWideAddress(Interval s) const; void BuildTree(const std::vector<Rule>& rules); void BuildBadTree(const std::vector<Rule>& rules); std::vector<Rule> Separate(const std::vector<Rule>& rules, std::vector<Rule>& remain); std::vector<Rule> rules; std::vector<ByteCutsNode*> trees; std::vector<int> priorities; std::vector<size_t> sizes; double dredgeFraction; double turningPoint; double minFrac; size_t goodTrees = 0; size_t badTrees = 0; }; #endif
#pragma once #include <memory> #include <QListWidgetItem> #include <QDialog> #include "PhoneticDictionaryViewModel.h" namespace Ui { class PhoneticDictDialog; } namespace PticaGovorun { class PhoneticDictionaryDialog : public QDialog { Q_OBJECT public: explicit PhoneticDictionaryDialog(QWidget *parent = 0); ~PhoneticDictionaryDialog(); public: void setPhoneticViewModel(std::shared_ptr<PhoneticDictionaryViewModel> phoneticDictViewModel); void attachDetachPhoneticViewModel(bool attach); protected: void closeEvent(QCloseEvent*) override; void showEvent(QShowEvent*) override; private slots: void lineEditCurrentWord_textEdited(const QString& text); void phoneticDictViewModel_matchedWordsChanged(); void listWidgetWords_itemDoubleClicked(QListWidgetItem* item); void phoneticDictViewModel_phoneticTrnascriptChanged(); void groupBoxBrowseDict_toggled(bool checked); void listWidgetWords_itemSelectionChanged(); void lineEditNewWord_textChanged(const QString & text); void pushButtonAddNewWord_clicked(); void findMatchedWords(); QString currentBrowsedDictId(); private: Ui::PhoneticDictDialog *ui; std::shared_ptr<PhoneticDictionaryViewModel> phoneticDictViewModel_; }; }
#include "Point.h" Point::Point() { m_x = 0; m_y = 0; } Point::Point(int x, int y) { m_x = x; m_y = y; } int Point::GetX() const { return m_x; } int Point::GetY() const { return m_y; } void Point::PrintCordinates() { std::cout << "Cordinates are: (" << m_x << "," << m_y << ")" << std::endl; } void Line::AddLine(Point& StraightLine) { m_StraightLine.push_back(StraightLine); } std::vector<Point> Line::GetLine() const { return m_StraightLine; } void Line:: DisplayVectorContents() { for(int i = 0; i < m_StraightLine.size(); ++i) { std::cout << "Cordinate " << i + 1 << " is: " << m_StraightLine[i].GetX() << "," << m_StraightLine[i].GetY() << std::endl; } }
//O(nlogn) Time and O(n) Space complexity solution class Solution { public: //Function to find maximum of each subarray of size k. vector <int> max_of_subarrays(int *arr, int n, int k) { vector<int> ans; priority_queue<pair<int,int>> pq; for(int i =0;i<k;i++){ pq.push({arr[i],i}); } ans.push_back(pq.top().first); for(int i =k;i<n;i++){ pq.push({arr[i],i}); int index = pq.top().second; while(index<i-k+1){ pq.pop(); index=pq.top().second; } ans.push_back(arr[index]); } return ans; } };
#include <iostream> #include <vector> #include <queue> #include <cstring> #include <map> #include <set> using namespace std; #define int long long #define P pair<int,int> #define pb push_back #define endl '\n' const int N = 3e5 + 5; vector <int> Graph[N]; int vis[N]; vector <int> pol; int n, k, d; map <P, int> road; set <int> s; void bfs() { queue <int> q; for (auto x : pol) { q.push(x); vis[x] = 1; } while (!q.empty()) { int temp = q.front(); q.pop(); for (auto to : Graph[temp]) { if (!vis[to]) { vis[to] = 1; q.push(to); s.erase(road[ {temp, to}]); } } } } void solve() { cin >> n >> k >> d; while (k--) { int x; cin >> x; pol.pb(x); } for (int i = 1; i < n; i++) { int u, v; cin >> u >> v; Graph[u].pb(v); Graph[v].pb(u); s.insert(i); road[ {u, v}] = i; road[ {v, u}] = i; } memset(vis, 0, sizeof(vis)); bfs(); cout << s.size() << endl; for (auto x : s) cout << x << " "; cout << endl; return ; } int32_t main() { ios_base:: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif // code starts solve(); return 0; }
#include<bits/stdc++.h> using namespace std; int main() { // only gravity will pull me down // Print first n Fibonacci Numbers int t, n; cin >> t; while (t--) { cin >> n; long dp[n+1]; dp[1] = 1; dp[2] = 1; for(int i=3; i<=n; i++) dp[i] = dp[i-1] + dp[i-2]; for(int i=1; i<=n; i++) cout << dp[i] << " "; cout << endl; } return 0; }
// // bwocc.hpp // // // Created by Elliott Sloate on 10/22/20. // #ifndef bwocc_hpp #define bwocc_hpp #include <stdio.h> #endif /* bwocc_hpp */
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef BAJKA_ABSTRACTMODEL_H_ #define BAJKA_ABSTRACTMODEL_H_ #include "IModel.h" #include "../util/ReflectionMacros.h" #include "IBox.h" #include "IGroup.h" namespace Model { class BoxGroup; class AbstractModel : public IModel { public: d__ AbstractModel () : parent (0), translate (Geometry::ZERO_POINT), angle (0), scale (1), view (0), controller (0), layout (NULL) {} virtual ~AbstractModel () {} /*--------------------------------------------------------------------------*/ virtual Geometry::Point getTranslate () const; m_ (setTranslate) virtual void setTranslate (Geometry::Point const &p); virtual Geometry::Point getCenter () const; m_ (setCenter) virtual void setCenter (Geometry::Point const &p); virtual Geometry::Point computeCenter () const = 0; virtual double getAngle () const { return angle; } m_ (setAngle) virtual void setAngle (double a) { angle = a; } virtual double getScale () const { return scale; } m_ (setScale) virtual void setScale (double s) { scale = s; } virtual Geometry::AffineMatrix getMatrix () const; /*--------------------------------------------------------------------------*/ m_ (getLayout) Layout *getLayout () { return layout; } m_ (setLayout) void setLayout (Layout *l) { layout = l; } /*--------------------------------------------------------------------------*/ virtual bool isBox () const { return false; } virtual bool isGroup () const { return false; } /*--------------------------------------------------------------------------*/ virtual IModel *findContains (Geometry::Point const &p); virtual Geometry::Box getBoundingBox () const { return getBoundingBoxImpl (getMatrix ()); } /*--------------------------------------------------------------------------*/ virtual void update (Event::UpdateEvent *e); /*--------------------------------------------------------------------------*/ /** * TODO Może wszędzie gdzie tu jest IModel dać IGroup? */ IModel *getParent () { return parent; } void setParent (IModel *m) { parent = m; } void onParentSet (IModel *m) {} S_ (setParent2) virtual void setParent2 (IModel *p); /*--------------------------------------------------------------------------*/ m_ (getView) virtual View::IView *getView () { return view; } S_ (setView) void setView (View::IView *v) { view = v; } m_ (getController) Controller::IController *getController () { return controller; } S_ (setController) void setController (Controller::IController *c) { controller = c; } protected: IModel *parent; Geometry::Point translate; double angle; double scale; private: std::auto_ptr <Geometry::Point> center; View::IView *view; Controller::IController *controller; Layout *layout; E_ (AbstractModel) }; } /* namespace Model1 */ # endif /* ABSTRACTMODEL_H_ */
#pragma once #include "../../Toolbox/Toolbox.h" #include "Texture.h" #include "../Image/Image.h" namespace ae { class FramebufferAttachement; /// \ingroup graphics /// <summary> /// 2D samplable data that can be link to a shader to be rendered. /// </summary> class AERO_CORE_EXPORT Texture2D : public Texture { public: /// <summary>Create an empty texture 2D.</summary> /// <param name="_Width">The width of the texture.</param> /// <param name="_Height">The height of the texture.</param> /// <param name="_Format">Format of the texture : channels, type.</param> Texture2D( Uint32 _Width, Uint32 _Height, TexturePixelFormat _Format = TexturePixelFormat::DefaultTexture ); /// <summary>Create an empty texture with framebuffer attachement settings.</summary> /// <param name="_Width">The width of the texture.</param> /// <param name="_Height">The height of the texture.</param> /// <param name="_FramebufferAttachement">Settings to apply.</param> Texture2D( Uint32 _Width, Uint32 _Height, const FramebufferAttachement& _FramebufferAttachement ); /// <summary>Create an empty texture 2D.</summary> /// <param name="_Width">The width of the texture.</param> /// <param name="_Height">The height of the texture.</param> /// <param name="_Format">Format of the texture : channels, type.</param> virtual void Set( Uint32 _Width, Uint32 _Height, TexturePixelFormat _Format = TexturePixelFormat::DefaultTexture ); /// <summary>Create an empty texture with framebuffer attachement settings.</summary> /// <param name="_Width">The width of the texture.</param> /// <param name="_Height">The height of the texture.</param> /// <param name="_FramebufferAttachement">Settings to apply.</param> virtual void Set( Uint32 _Width, Uint32 _Height, const FramebufferAttachement& _FramebufferAttachement ); /// <summary>Resize the texture 1D.</summary> /// <param name="_Width">The width of the texture.</param> /// <param name="_Height">The height of the texture.</param> void Resize( Uint32 _Width, Uint32 _Height ); /// <summary>Get the width of the texture.</summary> /// <returns>Width of the texture.</returns> Uint32 GetWidth() const; /// <summary>Get the height of the texture.</summary> /// <returns>Height of the texture.</returns> Uint32 GetHeight() const; /// <summary>Called by the framebuffer to attach the texture to it.</summary> void AttachToFramebuffer( const FramebufferAttachement& _Attachement ) const override; /// <summary>Retrieve texture data from the GPU and store it in an image.</summary> /// <returns>Image containing the texture data.</returns> Image ToImage() const; /// <summary> /// Function called by the editor. /// It allows the class to expose some attributes for user editing. /// Think to call all inherited class function too when overloading. /// </summary> virtual void ToEditor(); protected: /// <summary>Constructor that does nothing. For inherited class only.</summary> Texture2D(); protected: /// <summary>Create an empty texture.</summary> virtual void SetupEmpty(); protected: /// <summary>Width of the texture.</summary> Uint32 m_Width; /// <summary>Width of the texture.</summary> Uint32 m_Height; }; } // ae
/* ======================================================================== DEVise Data Visualization Software (c) Copyright 1992-1996 By the DEVise Development Group Madison, Wisconsin All Rights Reserved. ======================================================================== Under no circumstances is this software to be copied, distributed, or altered in any way without prior permission from the DEVise Development Group. */ /* Implementation of DataSourceFileDesc class. Note that the file descriptor is fdopen()'d, giving a file pointer _file, but when this is class returns a file descriptor to any requestor, fileno(_file) is returned instead of _fd. This is because a derived class may have substituted some other file pointer in place of _file, so fileno(_fileno) is no longer the same as _fd. DataSourceWeb is one example of this behavior. */ /* $Id: DataSourceFileDesc.c,v 1.1 1996/07/01 19:21:25 jussi Exp $ $Log: DataSourceFileDesc.c,v $ Revision 1.1 1996/07/01 19:21:25 jussi Initial revision. */ #define _DataSourceFileDesc_c_ #include <stdio.h> #include <string.h> #include <errno.h> //#include <unistd.h> //#include <sys/param.h> #include <sys/types.h> #include <sys/stat.h> #include "DataSourceFileDesc.h" #include "Util.h" #include "DevError.h" //#define DEBUG #if !defined(lint) && defined(RCSID) static char rcsid[] = "$RCSfile: DataSourceFileDesc.c,v $ $Revision: 1.1 $ $State: Exp $"; #endif static char * srcFile = __FILE__; /*------------------------------------------------------------------------------ * function: DataSourceFileDesc::DataSourceFileDesc * DataSourceFileDesc constructor. */ DataSourceFileDesc::DataSourceFileDesc(int fd, char *label) : DataSourceFileStream("no file", label) { DO_DEBUG(printf("DataSourceFileDesc::DataSourceFileDesc(%d,%s)\n", fd, (label != NULL) ? label : "null")); _fd = fd; } /*------------------------------------------------------------------------------ * function: DataSourceFileDesc::~DataSourceFileDesc * DataSourceFileDesc destructor. */ DataSourceFileDesc::~DataSourceFileDesc() { DO_DEBUG(printf("DataSourceFileDesc::~DataSourceFileDesc()\n")); if (_fd >= 0) close(_fd); } /*------------------------------------------------------------------------------ * function: DataSourceFileDesc::Open * Do an fdopen() on the file descriptor. */ DevStatus DataSourceFileDesc::Open(char *mode) { DO_DEBUG(printf("DataSourceFileDesc::Open()\n")); _file = fdopen(_fd, mode); if (_file == NULL) { char errBuf[MAXPATHLEN+100]; sprintf(errBuf, "unable to open file descriptor %d", _fd); reportError(errBuf, errno); return StatusFailed; } return StatusOk; } /*------------------------------------------------------------------------------ * function: DataSourceFileDesc::IsOk * Return true if file descriptor is valid. */ Boolean DataSourceFileDesc::IsOk() { if (_fd < 0 || _file == NULL) return false; return true; } /*------------------------------------------------------------------------------ * function: DataSourceFileDesc::Close * Do a close() on the file descriptor. */ DevStatus DataSourceFileDesc::Close() { DO_DEBUG(printf("DataSourceFileDesc::Close()\n")); if (close(_fd) < 0) { reportError("error closing file", errno); _fd = -1; return StatusFailed; } _fd = -1; // So destructor doesn't try to close it again. return DataSourceFileStream::Close(); } /*============================================================================*/
#include <iostream> bool stugum(char** &arr, int &x, int &y, int size) { if((x == size) || (x == 0) || (y == 0) || (y == size)) { return true; } else if(*arr[x + 1] == '_' || *arr[x + 1] == '*') { if(*arr[x + 1] == '_') { *arr[x + 1] = '*'; } else { *arr[x + 1] = '_'; } return stugum(arr, ++x, y, size); } else if(*arr[x - 1] == '_' || *arr[x - 1] == '*') { if(*arr[x - 1] == '_') { *arr[x - 1] = '*'; } else { *arr[x - 1] = '_'; } return stugum(arr, --x, y, size); } else if(*arr[y + 1] == '_' || *arr[y + 1] == '*') { if(*arr[y + 1] == '_') { *arr[y + 1] = '*'; } else { *arr[y + 1] = '_'; } return stugum(arr, x, ++y, size); } else if(*arr[y - 1] == '_' || *arr[y - 1] == '*') { if(*arr[y - 1] == '_') { *arr[y - 1] = '*'; } else { *arr[y - 1] = '_'; } return stugum(arr, x, --y, size); } else { return false; } } int main() { const int size = 5; char **arr = new char* [size]; for(int i = 0; i < size; ++i) { arr[i] = new char [size]; } for(int i = 0; i < size; ++i) { std::cout << "nermuceq " << i << "-rd tox@"; for(int j = 0; j < size; ++j) { std::cin >> arr[i][j]; } std::cout << '\n'; } int i = 0; int j = 0; do { std::cout << "vorne mutq@:" << std::endl; std::cout << "vor toxum e mutq@::"; std::cin >> i; std::cout << "vor sjunum e na::"; std::cin >> j; } while (arr[i][j] == '#'); int k = stugum(arr, j, i, size); if(k == 1) { std::cout << "elq ka" << std::endl; } else { std::cout << "elq chka" << std::endl; } for(int i = 0; i < size; ++i) { for(int j = 0; j < size; ++j) { std::cout << arr[i][j]; } std::cout << '\n'; } for(i = 0; i < size; ++i) { delete []arr[i]; } delete []arr; return 0; }
#include <cstdlib> #include <time.h> #include <iostream> #include<fstream> using namespace std; #include "Restaurant.h" #include "..\Events\ArrivalEvent.h" Restaurant::Restaurant() { pGUI = NULL; } void Restaurant::RunSimulation() { pGUI = new GUI; PROG_MODE mode = pGUI->getGUIMode(); switch (mode) //Add a function for each mode in next phases { case MODE_INTR: //Interactive break; case MODE_STEP: //StepByStep break; case MODE_SLNT: //Silent break; case MODE_DEMO: break; }; } ////////////////////////////////// Event handling functions ///////////////////////////// //Executes ALL events that should take place at current timestep void Restaurant::ExecuteEvents(int CurrentTimeStep) { Event *pE; while (EventsQueue.peekFront(pE)) //as long as there are more events { if (pE->getEventTime() > CurrentTimeStep) //no more events at current timestep return; pE->Execute(this); EventsQueue.dequeue(pE); //remove event from the queue delete pE; //deallocate event object from memory } } Restaurant::~Restaurant() { if (pGUI) delete pGUI; } void Restaurant::Load_Data(ifstream& read) { read >> Num_Cooks_N >> Num_Cooks_V >> Num_Cooks_G; int Total = Num_Cooks_N + Num_Cooks_V + Num_Cooks_G; int numberofevents; int N_speed, V_speed, G_speed; read >> N_speed >> V_speed >> G_speed; for (int i = 0; i < Total; i++) { if (i < Num_Cooks_N) { Cook* cook = new Cook('N', N_speed); COOKS_Queue.enqueue(cook); } else if (i < Num_Cooks_V + Num_Cooks_N) { Cook* cook = new Cook('V', V_speed); COOKS_Queue.enqueue(cook); } else { Cook* cook = new Cook('G', G_speed); COOKS_Queue.enqueue(cook); } } //setCooks(N_speed, V_speed, G_speed); read >> NUM_ORD >> NORM_BREAK >> VIP_BRAEK >> VEG_BREAK; read >> AutoP >> numberofevents; char event_Type; char order_Type; int id, ord_size, etime; double money; Order* order; ArrivalEvent* arr_event; for (int i = 0; i < numberofevents; i++) { read >> event_Type; if (event_Type == 'R') { read >> order_Type >> etime >> id >> ord_size >> money; arr_event = new ArrivalEvent(etime, id, order_Type, ord_size, money); EventsQueue.enqueue(arr_event); } else if (event_Type == 'X') { read >> etime >> id; CancelEvent* cancel_event = new CancelEvent(etime, id); EventsQueue.enqueue(cancel_event); } else if (event_Type == 'P') { read >> etime >> id >> money; PromotionEvent* promote_event = new PromotionEvent(etime, id, money); EventsQueue.enqueue(promote_event); } } } void Restaurant::Delete_Order(int n) { Order* order = nullptr; Queue<Order*> Q_O1, Q_O2; while (ON_LIST.DeleteFirst(order)) //looking for the required order { if (order) { if (order->GetID() == n && order->getStatus() == WAIT) //check if we can delete the order { Num_WOrd_N--; while (ORDERS_Queue.dequeue(order)) //delete the order from the orders list { if (order->GetID() != n) { Q_O2.enqueue(order); } } while (Q_O2.dequeue(order)) { ORDERS_Queue.enqueue(order); } } else Q_O1.enqueue(order); } } while (Q_O1.dequeue(order)) { ON_LIST.InsertEnd(order); //refill the normal orders list } } void Restaurant::FillDrawingList() { Order* order; Queue<Order*> TEMPO_Queue; Cook* cook; Queue<Cook*> TEMPC_Queue; while (!COOKS_Queue.isEmpty()) { COOKS_Queue.dequeue(cook); pGUI->AddToDrawingList(cook); TEMPC_Queue.enqueue(cook); } while (!TEMPC_Queue.isEmpty()) { TEMPC_Queue.dequeue(cook); COOKS_Queue.enqueue(cook); } while (!ORDERS_Queue.isEmpty()) { ORDERS_Queue.dequeue(order); pGUI->AddToDrawingList(order); TEMPO_Queue.enqueue(order); } while (!TEMPO_Queue.isEmpty()) { TEMPO_Queue.dequeue(order); ORDERS_Queue.enqueue(order); } } void Restaurant::AddtoORDERsLISTS(Order* po) { ORDERS_Queue.enqueue(po); //a general list of orders to keep them sorted by their arrival time switch (po->GetType())//putting every order in its type list { case TYPE_NRM: ON_LIST.InsertEnd(po); wait.enqueue(po); Num_wait++; Num_WOrd_N++; break; case TYPE_VIP: OV_LIST.enqueue(po); wait.enqueue(po); Num_wait++; Num_WOrd_V++; break; case TYPE_VGAN: OG_LIST.enqueue(po); wait.enqueue(po); Num_wait++; Num_WOrd_G++; break; } } void Restaurant::Promote_order(int n, int ex) { Order* order = nullptr; Queue<Order*> Q_O1; while (ON_LIST.DeleteFirst(order)) { if (order) { if (order->GetID() == n && order->getStatus() == WAIT) //check if we can promote the order { order->setMoney(order->GetMoney() + ex); order->SetType(TYPE_VIP); OV_LIST.enqueue(order); Num_WOrd_N--; Num_WOrd_V++; } else Q_O1.enqueue(order); } } while (Q_O1.dequeue(order)) { ON_LIST.InsertEnd(order); } } void Restaurant::Simulation_Function() { //nessasry initialization Num_wait = 0; Num_WOrd_N = 0; Num_WOrd_G = 0; Num_WOrd_V = 0; Queue <Order*> done; int num_cook = Num_Cooks_N + Num_Cooks_V + Num_Cooks_G; pGUI = new GUI; //reading from the textfile ifstream read("Data_File.txt"); int CurrentTimeStep = 1; //calling loading function Load_Data(read); //clearing the screen pGUI->ResetDrawingList(); Order* temp = new Order; while (!EventsQueue.isEmpty() || !ON_LIST.isEmpty() || !OG_LIST.isEmpty() || !OV_LIST.isEmpty() || !InService_N.isEmpty() || !InService_V.isEmpty() || !InService_G.isEmpty()) { //it executes the events of this current step as long as there are any if (!EventsQueue.isEmpty()) ExecuteEvents(CurrentTimeStep); //each timestep //if there are any waiting vegan orders we move them to in service if (!OG_LIST.isEmpty()) { OG_LIST.dequeue(temp); InService_G.enqueue(temp); temp->setStatus(SRV); Num_WOrd_G--; } ////if there are any waiting VIP orders we move them to in service if (!OV_LIST.isEmpty()) { OV_LIST.dequeue(temp); temp->setStatus(SRV); InService_V.enqueue(temp); Num_WOrd_V--; } //if there are any waiting normal orders we move them to in service if (!ON_LIST.isEmpty()) { ON_LIST.DeleteFirst(temp); temp->setStatus(SRV); InService_N.enqueue(temp); Num_WOrd_N--; } //every five timesteps if (CurrentTimeStep % 5 == 0) { ////if there are any in service vegan orders we move them to finished if (!InService_G.isEmpty()) { InService_G.dequeue(temp); done.enqueue(temp); temp->setStatus(DONE); } ////if there are any in service normal orders we move them to finished if (!InService_N.isEmpty()) { InService_N.dequeue(temp); done.enqueue(temp); temp->setStatus(DONE); } ////if there are any in service VIP orders we move them to finished if (!InService_V.isEmpty()) { InService_V.dequeue(temp); done.enqueue(temp); temp->setStatus(DONE); } } pGUI->ResetDrawingList(); FillDrawingList(); //writing in the status bar number of available cooks of each type and number of waiting orders of each type string message; message = "TS: " + to_string(CurrentTimeStep) + " " + "#C: " + to_string(num_cook) + " " + "#N_C: " + to_string(Num_Cooks_N) + " " + "#V_C: " + to_string(Num_Cooks_V) + " " + "#G_C: " + to_string(Num_Cooks_G); message = message + " " + "#W_ORD: " + to_string(Num_WOrd_N + Num_WOrd_V + Num_WOrd_G) + " " + "#N_ORD: " + to_string(Num_WOrd_N) + " " + "#G_ORD: " + to_string(Num_WOrd_G) + " " + "#V_ORD: " + to_string(Num_WOrd_V); pGUI->PrintMessage(message); //drawing the cooks and orders on the screen in their specific position pGUI->UpdateInterface(); //waiting for mouse click to go to the next timestep pGUI->waitForClick(); CurrentTimeStep++; //clearing the screen from the previous timestep } //nessasry pointers deleting }
#include<iostream> #include "game.h" #include "map.h" using namespace std; int main() { make_map(? , ? , 10, 20); make_map(? , ? , 10, 20); make_map(? , ? , 10, 20); // 게임 창 생성 int checking = 1; char key; while (checking) { cout << "K: 게임 시작 L : 게임 종료"; cin >> key; switch (key) { case K: case k: { game_start(); break; } case L: case l: { game_over(); break; } default: { cout << "K또는 L를 누르세요"; break; } } } }
// // talkservice.cpp // AutoCaller // // Created by Micheal Chen on 2017/7/17. // // #include "talkservice.hpp" #include "imservice.hpp" TalkService* TalkService::getInstance() { static TalkService inst; return &inst; } IYouMeVoiceEngine* TalkService::getTalkEngine() { IYouMeVoiceEngine *engine = IYouMeVoiceEngine::getInstance(); CC_ASSERT(engine != nullptr); engine->init(this, "YOUMEBC2B3171A7A165DC10918A7B50A4B939F2A187D0", "r1+ih9rvMEDD3jUoU+nj8C7VljQr7Tuk4TtcByIdyAqjdl5lhlESU0D+SoRZ30sopoaOBg9EsiIMdc8R16WpJPNwLYx2WDT5hI/HsLl1NJjQfa9ZPuz7c/xVb8GHJlMf/wtmuog3bHCpuninqsm3DRWiZZugBTEj2ryrhK7oZncBAAE=", RTC_CN_SERVER, ""); return engine; } TalkService::TalkService() { // IYouMeVoiceEngine *voice_engine = IYouMeVoiceEngine::getInstance(); //voice_engine->init(this, "", "", "", ""); YouMeErrorCode talkerrcode = IYouMeVoiceEngine::getInstance()->init(this, "YOUMEBC2B3171A7A165DC10918A7B50A4B939F2A187D0", "r1+ih9rvMEDD3jUoU+nj8C7VljQr7Tuk4TtcByIdyAqjdl5lhlESU0D+SoRZ30sopoaOBg9EsiIMdc8R16WpJPNwLYx2WDT5hI/HsLl1NJjQfa9ZPuz7c/xVb8GHJlMf/wtmuog3bHCpuninqsm3DRWiZZugBTEj2ryrhK7oZncBAAE=", RTC_CN_SERVER, ""); CHECK_RETURN_CODE(talkerrcode, "Initialize talk engine success", "Initialize talk engine failed"); } TalkService::~TalkService() { //IYouMeVoiceEngine::getInstance()->unInit(); //delete this; } void TalkService::init() { YouMeErrorCode errcode = IYouMeVoiceEngine::getInstance()->init(this, TALK_APPKEY, TALK_APPSECRET, RTC_CN_SERVER, ""); CHECK_RETURN_CODE(errcode, "Initialize success", "Initialize failed"); } void TalkService::onPcmData(int channelNum, int samplingRateHz, int bytesPerSample, void* data, int dataSizeInByte) { } void TalkService::onRequestRestAPI(int requestID, const YouMeErrorCode &iErrorCode, const char *strQuery, const char *strResult) { } //void TalkService::onMemberChange(const char *channel // , std::list<MemberChange> &listMemberChange) //{ // //} void TalkService::onMemberChange(const char *channel, const char *listMemberChange, bool bUpdate) { } //void TalkService::onBroadcast(const YouMeBroadcast bc, const char *channel, const char *param1, const char *param2, const char *strContent) //{ // //} //talk callback //这里是talk的回调函数 void TalkService::onEvent(const YouMeEvent event, const YouMeErrorCode error, const char *channel, const char *param) { cocos2d::log("Callback onevent !"); cocos2d::log("channel is %s", channel); switch (event) { case YOUME_EVENT_INIT_OK: { cocos2d::log("Talk init OK"); } break; case YOUME_EVENT_JOIN_OK: cocos2d::log("[Youme Test] Join channel Ok!"); break; case YOUME_EVENT_JOIN_FAILED: cocos2d::log("[Youme Test] Join channel Failed !"); break; case YOUME_EVENT_RESUMED: break; case YOUME_EVENT_LEAVED_ALL: break; case YOUME_EVENT_BGM_FAILED: break; case YOUME_EVENT_MIC_CTR_ON: break; case YOUME_EVENT_LEAVED_ONE: break; case YOUME_EVENT_PAUSED: break; case YOUME_EVENT_REC_FAILED: break; case YOUME_EVENT_BGM_STOPPED: break; case YOUME_EVENT_INIT_FAILED: break; case YOUME_EVENT_MIC_CTR_OFF: break; case YOUME_EVENT_RECONNECTED: break; case YOUME_EVENT_MY_MIC_LEVEL: break; case YOUME_EVENT_OTHERS_MIC_ON: break; case YOUME_EVENT_RECONNECTING: break; case YOUME_EVENT_SPEAK_SUCCESS: cocos2d::log("[Youme Test]Callback: switch channel to speak success!"); break; case YOUME_EVENT_SPEAK_FAILED: cocos2d::log("[Youme Test]Callback: switch channel to speak failed!"); break; case YOUME_EVENT_OTHERS_MIC_OFF: break; case YOUME_EVENT_SPEAKER_CTR_ON: break; case YOUME_EVENT_LISTEN_OTHER_ON: break; case YOUME_EVENT_OTHERS_VOICE_ON: break; case YOUME_EVENT_SPEAKER_CTR_OFF: break; case YOUME_EVENT_LISTEN_OTHER_OFF: break; case YOUME_EVENT_OTHERS_VOICE_OFF: break; case YOUME_EVENT_OTHERS_SPEAKER_ON: break; case YOUME_EVENT_OTHERS_SPEAKER_OFF: break; default: break; } }
#include <iostream> using namespace std; int main() { int i=1, n; cout<<"Enter any number to print the table:"; cin>>n; cout<<"Table of "<<n<<endl; do{ cout<<n<<" * "<<i<<" = "<<n*i<<endl; i++; }while(i<=10); return 0; }
/* * Lanq(Lan Quick) * Solodov A. N. (hotSAN) * 2016 * LqWrk - Worker class. * Recive and handle command from LqWrkBoss. */ #include "LqWrk.hpp" #include "LqAlloc.hpp" #include "LqWrkBoss.hpp" #include "LqLog.h" #include "LqOs.h" #include "LqConn.h" #include "LqTime.hpp" #include "LqFile.h" #include "LqAtm.hpp" #include "LqLib.h" #define __METHOD_DECLS__ #include "LqAlloc.hpp" #include "LqQueueCmd.hpp" #include <time.h> #include <stdint.h> #if !defined(LQPLATFORM_WINDOWS) #include <signal.h> #endif /* * Use this macro if you want protect sync operations calling close handlers. * When this macro used, thread caller of sync methods, waits until worker thread leave r/w/c handler. * When close handler called by worker thread, thread-caller of sync kind method continue enum. * Disable this macro if you want to shift the entire responsibility of the user. */ //#define LQWRK_ENABLE_RW_HNDL_PROTECT /* * This macro used for some platform kind LqSysPollCheck functions * When used, never add/remove to/from event list, while worker thread is in LqSysPollCheck function */ #define LQWRK_ENABLE_WAIT_LOCK #ifdef LQWRK_ENABLE_WAIT_LOCK #define LqWrkWaiterLock(Wrk) ((LqWrk*)(Wrk))->WaiterLock() #define LqWrkWaiterUnlock(Wrk) ((LqWrk*)(Wrk))->WaiterUnlock() #define LqWrkWaiterLockMain(Wrk) ((LqWrk*)(Wrk))->WaiterLockMain() #else #define LqWrkWaiterLock(Wrk) ((void)0) #define LqWrkWaiterUnlock(Wrk) ((void)0) #define LqWrkWaiterLockMain(Wrk) ((void)0) #endif #define LqWrkCallConnHandler(Conn, Flags, Wrk) { \ auto Handler = ((LqConn*)(Conn))->Proto->Handler; \ ((LqWrk*)(Wrk))->Unlock(); \ Handler((LqConn*)(Conn), (Flags)); \ ((LqWrk*)(Wrk))->Lock(); \ } #define LqWrkCallConnCloseHandler(Conn, Wrk) { \ auto Handler = ((LqConn*)(Conn))->Proto->CloseHandler; \ LqAtmIntrlkOr(((LqConn*)(Conn))->Flag, _LQEVNT_FLAG_NOW_EXEC); \ ((LqWrk*)(Wrk))->Unlock(); \ Handler((LqConn*)(Conn)); \ ((LqWrk*)(Wrk))->Lock(); \ } #define LqWrkCallEvntFdHandler(EvntHdr, Flags, Wrk) { \ auto Handler = ((LqEvntFd*)(EvntHdr))->Handler; \ ((LqWrk*)(Wrk))->Unlock(); \ Handler((LqEvntFd*)(EvntHdr), (Flags)); \ ((LqWrk*)(Wrk))->Lock(); \ } #define LqWrkCallEvntFdCloseHandler(EvntHdr, Wrk) { \ auto Handler = ((LqEvntFd*)(EvntHdr))->CloseHandler; \ LqAtmIntrlkOr(((LqEvntFd*)(EvntHdr))->Flag, _LQEVNT_FLAG_NOW_EXEC); \ ((LqWrk*)(Wrk))->Unlock(); \ Handler((LqEvntFd*)(EvntHdr)); \ ((LqWrk*)(Wrk))->Lock(); \ } #define LqWrkCallEvntHdrCloseHandler(Event, Wrk) { \ if(LqClientGetFlags(Event) & _LQEVNT_FLAG_CONN){ \ LqWrkCallConnCloseHandler(Event, Wrk); \ }else{ \ LqWrkCallEvntFdCloseHandler(Event, Wrk);} \ } /* * Enum event changes * Use only by worker thread */ #define LqWrkEnumChangesEvntDo(Wrk, EventFlags) \ {((LqWrk*)(Wrk))->Lock(); \ ((LqWrk*)(Wrk))->DeepLoop++; \ for(LqEvntFlag EventFlags = __LqSysPollEnumEventBegin(&(((LqWrk*)(Wrk))->EventChecker)); EventFlags != ((LqEvntFlag)0); EventFlags = __LqEvntEnumEventNext(&(((LqWrk*)(Wrk))->EventChecker))) #define LqWrkEnumChangesEvntWhile(Wrk) \ if(((--((LqWrk*)(Wrk))->DeepLoop) <= ((intptr_t)0)) && \ __LqSysPollIsRestruct(&(((LqWrk*)(Wrk))->EventChecker))) { \ __LqSysPollRestructAfterRemoves(&(((LqWrk*)(Wrk))->EventChecker)); \ } \ ((LqWrk*)(Wrk))->Unlock(); \ } /* * Use when enum by another thread or by worker tread */ #define LqWrkEnumEvntDo(Wrk, IndexName) { \ LqEvntInterator IndexName; \ ((LqWrk*)(Wrk))->Lock(); \ ((LqWrk*)(Wrk))->AcceptAllEventFromQueue(); \ ((LqWrk*)(Wrk))->DeepLoop++; \ for(auto __r = __LqSysPollEnumBegin(&(((LqWrk*)(Wrk))->EventChecker), &(IndexName)); __r; __r = __LqSysPollEnumNext(&(((LqWrk*)(Wrk))->EventChecker), &(IndexName))) #define LqWrkEnumEvntWhile(Wrk) \ if(((--((LqWrk*)(Wrk))->DeepLoop) <= ((intptr_t)0)) && \ __LqSysPollIsRestruct(&(((LqWrk*)(Wrk))->EventChecker))) { \ LqWrkWaiterLock(Wrk); \ __LqSysPollRestructAfterRemoves(&(((LqWrk*)(Wrk))->EventChecker)); \ LqWrkWaiterUnlock(Wrk); \ } \ ((LqWrk*)(Wrk))->Unlock(); \ } /* * Use when enum by worker(owner) thread */ #define LqWrkEnumEvntOwnerDo(Wrk, IndexName) { \ LqEvntInterator IndexName; \ ((LqWrk*)(Wrk))->Lock(); \ ((LqWrk*)(Wrk))->DeepLoop++; \ for(auto __r = __LqSysPollEnumBegin(&(((LqWrk*)(Wrk))->EventChecker), &IndexName); __r; __r = __LqSysPollEnumNext(&(((LqWrk*)(Wrk))->EventChecker), &IndexName)) #define LqWrkEnumEvntOwnerWhile(Wrk) \ if(((--((LqWrk*)(Wrk))->DeepLoop) <= ((intptr_t)0)) && \ __LqSysPollIsRestruct(&(((LqWrk*)(Wrk))->EventChecker))) { \ __LqSysPollRestructAfterRemoves(&(((LqWrk*)(Wrk))->EventChecker)); \ } \ ((LqWrk*)(Wrk))->Unlock(); \ } /* * Custum enum, use in LqWrkBoss::TransferAllEvnt */ #define LqWrkEnumEvntNoLkDo(Wrk, IndexName) { \ LqEvntInterator IndexName; \ ((LqWrk*)(Wrk))->DeepLoop++; \ for(auto __r = __LqSysPollEnumBegin(&(((LqWrk*)(Wrk))->EventChecker), &IndexName); __r; __r = __LqSysPollEnumNext(&(((LqWrk*)(Wrk))->EventChecker), &IndexName)) #define LqWrkEnumEvntNoLkWhile(Wrk) \ if(((--((LqWrk*)(Wrk))->DeepLoop) <= ((intptr_t)0)) && \ __LqSysPollIsRestruct(&(((LqWrk*)(Wrk))->EventChecker))) { \ LqWrkWaiterLock(Wrk); \ __LqSysPollRestructAfterRemoves(&(((LqWrk*)(Wrk))->EventChecker)); \ LqWrkWaiterUnlock(Wrk); \ } \ } #define LqWrkUpdateAllMaskByOwner(Wrk, DelProc) { \ ((LqWrk*)(Wrk))->Lock(); \ ((LqWrk*)(Wrk))->DeepLoop++; \ LqSysPollUpdateAllMask(&((LqWrk*)(Wrk))->EventChecker, ((LqWrk*)(Wrk)), (DelProc));\ ((LqWrk*)(Wrk))->DeepLoop--; \ ((LqWrk*)(Wrk))->Unlock(); \ } #define LqWrkUpdateAllMask(Wrk, DelProc, Res) { \ ((LqWrk*)(Wrk))->Lock(); \ ((LqWrk*)(Wrk))->AcceptAllEventFromQueue(); \ ((LqWrk*)(Wrk))->DeepLoop++; \ (Res) = LqSysPollUpdateAllMask(&((LqWrk*)(Wrk))->EventChecker, ((LqWrk*)(Wrk)), (DelProc));\ if(((--((LqWrk*)(Wrk))->DeepLoop) <= ((intptr_t)0)) && \ __LqSysPollIsRestruct(&(((LqWrk*)(Wrk))->EventChecker))) { \ LqWrkWaiterLock(Wrk); \ __LqSysPollRestructAfterRemoves(&(((LqWrk*)(Wrk))->EventChecker)); \ LqWrkWaiterUnlock(Wrk); \ } \ ((LqWrk*)(Wrk))->Unlock(); } /* * Wait events, use only by worker thread */ #define LqWrkWaitEvntsChanges(Wrk) { \ LqWrkWaiterLockMain(Wrk); \ LqSysPollCheck(&((LqWrk*)(Wrk))->EventChecker, LqTimeGetMaxMillisec()); \ LqWrkWaiterUnlock(Wrk); \ } /* * Remove event by interator */ #define LqWrkRemoveByInterator(Wrk, Iter) { \ LqWrkWaiterLock(Wrk); \ LqSysPollRemoveByInterator(&((LqWrk*)(Wrk))->EventChecker, (Iter)); \ LqWrkWaiterUnlock(Wrk); \ } #define LqEvntHdrLock(EvntHdr) LqAtmLkWr(((LqClientHdr*)(EvntHdr))->Lk) #define LqEvntHdrUnlock(EvntHdr) LqAtmUlkWr(((LqClientHdr*)(EvntHdr))->Lk) #define LqWrkUnsetWrkOwner(EvntHdr) { \ LqEvntHdrLock(EvntHdr); \ ((LqClientHdr*)(EvntHdr))->WrkOwner = NULL; \ LqEvntHdrUnlock(EvntHdr); \ } #define LqWrkSetWrkOwner(EvntHdr, NewOwner) { \ LqEvntHdrLock(EvntHdr); \ ((LqClientHdr*)(EvntHdr))->WrkOwner = (NewOwner); \ LqEvntHdrUnlock(EvntHdr); \ } enum { LQWRK_CMD_RM_CONN_ON_TIME_OUT, LQWRK_CMD_RM_CONN_ON_TIME_OUT_PROTO, LQWRK_CMD_ASYNC_CALL, LQWRK_CMD_ASYNC_CALL_11, LQWRK_CMD_CLOSE_ALL_CONN, LQWRK_CMD_RM_CONN_BY_IP, LQWRK_CMD_CLOSE_CONN_BY_PROTO, LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD, LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD_FIN, LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD11, LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD_FIN11, LQWRK_CMD_TRANSFER_CLIENTS_AND_DELETE_FROM_BOSS }; #pragma pack(push) #pragma pack(LQSTRUCT_ALIGN_MEM) struct LqWrkCmdWaitEvnt { void(LQ_CALL*EventAct)(void*); void* UserData; inline LqWrkCmdWaitEvnt() {} inline LqWrkCmdWaitEvnt(void(LQ_CALL*NewEventProc)(void*), void* NewUserData): EventAct(NewEventProc), UserData(NewUserData) {} }; struct LqWrkCmdCloseByTimeout { LqTimeMillisec TimeLive; const LqProto* Proto; inline LqWrkCmdCloseByTimeout() {} inline LqWrkCmdCloseByTimeout(const LqProto* NewProto, LqTimeMillisec Millisec): Proto(NewProto), TimeLive(Millisec) {} }; struct LqWrkAsyncEventForAllFd { int(LQ_CALL*EventAct)(void*, size_t, void*, LqClientHdr*, LqTimeMillisec); void* UsrData; size_t UsrDataSize; inline LqWrkAsyncEventForAllFd( void* UserData, size_t UserDataSize, int(LQ_CALL*NewEventAct)(void*, size_t, void*, LqClientHdr*, LqTimeMillisec) ) { if((UserDataSize > ((size_t)0)) && (UserData != NULL)) { UsrData = LqMemAlloc(UserDataSize); UsrDataSize = UserDataSize; memcpy(UsrData, UserData, UserDataSize); } else { UsrData = NULL; UsrDataSize = ((size_t)0); } EventAct = NewEventAct; } inline LqWrkAsyncEventForAllFd(LqWrkAsyncEventForAllFd& Src) { UsrData = Src.UsrData; EventAct = Src.EventAct; UsrDataSize = Src.UsrDataSize; Src.UsrData = NULL; } ~LqWrkAsyncEventForAllFd() { if(UsrData != NULL) LqMemFree(UsrData); } }; typedef struct LqWrkAsyncCallFin { uintptr_t(LQ_CALL*EventFin)(void*, size_t); void* UsrData; size_t UsrDataSize; size_t CountPointers; LqWrkAsyncCallFin(uintptr_t(LQ_CALL*NewEventFin)(void*, size_t), void* UserData, size_t UserDataSize): CountPointers(0), EventFin(NewEventFin) { if((UserDataSize > ((size_t)0)) && (UserData != NULL)) { UsrData = LqMemAlloc(UserDataSize); UsrDataSize = UserDataSize; memcpy(UsrData, UserData, UserDataSize); } else { UsrData = NULL; UsrDataSize = ((size_t)0); } } ~LqWrkAsyncCallFin() { uintptr_t MdlHandle = EventFin(UsrData, UsrDataSize); if(MdlHandle) { LqLibFreeSafe(MdlHandle); } if(UsrData != NULL) LqMemFree(UsrData); } } LqWrkAsyncCallFin; struct LqWrkAsyncEventForAllFdAndCallFin { int(LQ_CALL*EventAct)(void*, size_t, void*, LqClientHdr*, LqTimeMillisec); void* UsrData; size_t UsrDataSize; LqShdPtr<LqWrkAsyncCallFin, LqFastAlloc::Delete, true, false, uintptr_t> FinPtr; inline LqWrkAsyncEventForAllFdAndCallFin( void* UserData, size_t UserDataSize, int(LQ_CALL*NewEventAct)(void*, size_t, void*, LqClientHdr*, LqTimeMillisec), LqShdPtr<LqWrkAsyncCallFin, LqFastAlloc::Delete, true, false, uintptr_t>& FinPtr ): FinPtr(FinPtr) { if((UserDataSize > ((size_t)0)) && (UserData != NULL)) { UsrData = LqMemAlloc(UserDataSize); UsrDataSize = UserDataSize; memcpy(UsrData, UserData, UserDataSize); } else { UsrData = NULL; UsrDataSize = ((size_t)0); } EventAct = NewEventAct; } inline LqWrkAsyncEventForAllFdAndCallFin(LqWrkAsyncEventForAllFdAndCallFin& Src): FinPtr(Src.FinPtr) { UsrData = Src.UsrData; EventAct = Src.EventAct; UsrDataSize = Src.UsrDataSize; Src.UsrData = NULL; } ~LqWrkAsyncEventForAllFdAndCallFin() { if(UsrData != NULL) LqMemFree(UsrData); } }; typedef struct LqWrkAsyncCallFin11 { std::function<uintptr_t()> FinFunc; size_t CountPointers; LqWrkAsyncCallFin11(std::function<uintptr_t()>& FinFun): CountPointers(0), FinFunc(FinFun) { } ~LqWrkAsyncCallFin11() { if(uintptr_t MdlHandle = FinFunc()) { FinFunc = nullptr; LqLibFreeSafe(MdlHandle); } } } LqWrkAsyncCallFin11; struct LqWrkAsyncEventForAllFdAndCallFin11 { std::function<int(LqWrkPtr&, LqClientHdr*)> EventAct; LqShdPtr<LqWrkAsyncCallFin11, LqFastAlloc::Delete, true, false, uintptr_t> FinPtr; inline LqWrkAsyncEventForAllFdAndCallFin11( std::function<int(LqWrkPtr&, LqClientHdr*)>& NewEventAct, LqShdPtr<LqWrkAsyncCallFin11, LqFastAlloc::Delete, true, false, uintptr_t>& NewFinPtr ):EventAct(NewEventAct), FinPtr(NewFinPtr) {} inline LqWrkAsyncEventForAllFdAndCallFin11(LqWrkAsyncEventForAllFdAndCallFin11& Src): FinPtr(Src.FinPtr), EventAct(Src.EventAct){} }; struct LqWrkAsyncEventForAllFd11 { std::function<int(LqWrkPtr&, LqClientHdr*)> EventAct; inline LqWrkAsyncEventForAllFd11(std::function<int(LqWrkPtr&, LqClientHdr*)>& NewEventAct): EventAct(NewEventAct) {} inline LqWrkAsyncEventForAllFd11(LqWrkAsyncEventForAllFd11& Src): EventAct(Src.EventAct){} }; struct LqWrkDeleteFromBossCmd { LqWrkBoss* Boss; bool IsTransfer; inline LqWrkDeleteFromBossCmd(LqWrkBoss* NewBoss, bool NewIsTransfer): Boss(NewBoss), IsTransfer(NewIsTransfer) {} }; #pragma pack(pop) static uint8_t _EmptyWrk[sizeof(LqWrk)]; static long long __LqWrkInitEmpty() { ((LqWrk*)_EmptyWrk)->CountPointers = 20; ((LqWrk*)_EmptyWrk)->Id = -1; return 1; } static long long __IdGen = __LqWrkInitEmpty(); static LqLocker<uintptr_t> __IdGenLocker; static long long GenId() { long long r; __IdGenLocker.LockWrite(); r = __IdGen; __IdGen++; __IdGenLocker.UnlockWrite(); return r; } LqWrkPtr LqWrk::New(bool IsStart) { return LqFastAlloc::New<LqWrk>(IsStart); } LqWrkPtr LqWrk::ByEvntHdr(LqClientHdr * EvntHdr) { LqAtmLkWr(EvntHdr->Lk); LqWrkPtr Res((((LqClientHdr*)(EvntHdr))->WrkOwner != NULL)? ((LqWrk*)((LqClientHdr*)(EvntHdr))->WrkOwner): ((LqWrk*)_EmptyWrk)); LqAtmUlkWr(EvntHdr->Lk); return Res; } LqWrkPtr LqWrk::GetNull() { return ((LqWrk*)_EmptyWrk); } bool LqWrk::IsNull(LqWrkPtr& WrkPtr) { return WrkPtr == ((LqWrk*)_EmptyWrk); } LQ_IMPORTEXPORT void LQ_CALL LqWrkDelete(LqWrk* This) { if(This->IsThisThread()) { This->ClearQueueCommands(); for(volatile size_t* t = &This->CountPointers; *t > 0; LqThreadYield()); for(unsigned i = 0; i < 10; i++) { This->Lock(); This->Unlock(); LqThreadYield(); } This->IsDelete = true; This->ExitThreadAsync(); return; } LqFastAlloc::Delete(This); } void LqWrk::AcceptAllEventFromQueue() { for(auto Command = EvntFdQueue.Fork(); Command;) { LqClientHdr* Hdr = Command.Val<LqClientHdr*>(); Command.Pop<LqClientHdr*>(); CountConnectionsInQueue--; LqLogInfo("LqWrk::AddEvnt()#%llu event {%i, %llx} recived\n", Id, Hdr->Fd, (unsigned long long)Hdr->Flag); } } void LqWrk::ExitHandlerFn(void * Data) { auto This = (LqWrk*)Data; if(This->IsDelete) LqFastAlloc::Delete(This); } LqWrk::LqWrk(bool IsStart): CountPointers(0), DeepLoop(intptr_t(0)), IsRecurseSkipCommands(false), LqThreadBase(([&] { Id = GenId(); LqString Str = "Worker #" + LqToString(Id); return Str; })().c_str()) { TimeStart = LqTimeGetLocMillisec(); CountConnectionsInQueue = 0; UserData = this; ExitHandler = ExitHandlerFn; IsDelete = false; IsSyncAllFlags = 0; auto NotifyFd = LqEventCreate(LQ_O_NOINHERIT); LqEvntFdInit(&NotifyEvent, NotifyFd, LQEVNT_FLAG_RD, NULL, NULL); LqSysPollInit(&EventChecker); if(IsStart) StartThreadSync(); } LqWrk::~LqWrk() { ExitThreadSync(); CloseAllClientsSync(); for(volatile size_t* t = &CountPointers; *t > 0; LqThreadYield()); for(unsigned i = 0; i < 10; i++) { Lock(); Unlock(); LqThreadYield(); } LqSysPollUninit(&EventChecker); LqFileClose(NotifyEvent.Fd); } long long LqWrk::GetId() const { return Id; } void LqWrk::DelProc(void* Data, LqEvntInterator* Iter) { LqClientHdr* Hdr = LqSysPollGetHdrByInterator(&((LqWrk*)Data)->EventChecker, Iter); if(LqClientGetFlags(Hdr) & _LQEVNT_FLAG_NOW_EXEC) return; LqWrkRemoveByInterator(Data, Iter); LqWrkUnsetWrkOwner(Hdr); LqWrkCallEvntHdrCloseHandler(Hdr, Data); } bool LqWrk::CmdIsOnlyOneTypeOfCommandInQueue(LqQueueCmd<uint8_t>::Interator& Inter, uint8_t TypeOfCommand) { if(!Inter) return true; if(Inter.Type != TypeOfCommand) return false; LqQueueCmd<uint8_t>::Interator Next = Inter.GetSkipped(); return CmdIsOnlyOneTypeOfCommandInQueue(Next, TypeOfCommand); } void LqWrk::ParseInputCommands() { /* * Recive async command loop. */ { auto Command = EvntFdQueue.Fork(); if(Command) { size_t RmHdrsSize = 0; LqClientHdr** RmHdrs = NULL; Lock(); do { LqClientHdr* Hdr = Command.Val<LqClientHdr*>(); Command.Pop<LqClientHdr*>(); CountConnectionsInQueue--; if(LqClientGetFlags(Hdr) & LQEVNT_FLAG_END) { RmHdrs = (LqClientHdr**)LqMemRealloc(RmHdrs, (RmHdrsSize + 1) * sizeof(RmHdrs[0])); RmHdrs[RmHdrsSize] = Hdr; RmHdrsSize++; } else { LqLogInfo("LqWrk::AddEvnt()#%llu event {%i, %llx} recived\n", Id, Hdr->Fd, (unsigned long long)Hdr->Flag); LqSysPollAddHdr(&EventChecker, Hdr); } } while(Command); Unlock(); if(RmHdrs != NULL) { for(size_t i = 0; i < RmHdrsSize; i++) { LqWrkUnsetWrkOwner(RmHdrs[i]); LqClientCallCloseHandler(RmHdrs[i]); } LqMemFree(RmHdrs); } } } for(auto Command = CommandQueue.Fork(); Command;) { switch(Command.Type) { case LQWRK_CMD_RM_CONN_ON_TIME_OUT: { /* * Remove zombie connections by time val. */ auto TimeLiveMilliseconds = Command.Val<LqTimeMillisec>(); Command.Pop<LqTimeMillisec>(); auto CurTime = LqTimeGetLocMillisec(); LqWrkEnumEvntOwnerDo(this, i) { auto Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i); if(LqClientIsConn(Evnt) && ((LqConn*)Evnt)->Proto->KickByTimeOutProc((LqConn*)Evnt, CurTime, TimeLiveMilliseconds)) { LqLogInfo("LqWrk::RemoveConnOnTimeOut()#%llu remove connection by timeout\n", Id); LqSysPollRemoveByInterator(&EventChecker, &i); LqWrkUnsetWrkOwner(Evnt); LqWrkCallConnCloseHandler(Evnt, this); } }LqWrkEnumEvntOwnerWhile(this); } break; case LQWRK_CMD_RM_CONN_ON_TIME_OUT_PROTO: { auto TimeLiveMilliseconds = Command.Val<LqWrkCmdCloseByTimeout>().TimeLive; auto Proto = Command.Val<LqWrkCmdCloseByTimeout>().Proto; Command.Pop<LqWrkCmdCloseByTimeout>(); auto CurTime = LqTimeGetLocMillisec(); LqWrkEnumEvntOwnerDo(this, i) { auto Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i); if(LqClientIsConn(Evnt) && (((LqConn*)Evnt)->Proto == Proto) && Proto->KickByTimeOutProc((LqConn*)Evnt, CurTime, TimeLiveMilliseconds)) { LqLogInfo("LqWrk::RemoveConnOnTimeOut()#%llu remove connection by timeout\n", Id); LqSysPollRemoveByInterator(&EventChecker, &i); LqWrkUnsetWrkOwner(Evnt); LqWrkCallConnCloseHandler(Evnt, this); } }LqWrkEnumEvntOwnerWhile(this); } break; case LQWRK_CMD_ASYNC_CALL: { /* Call procedure for wait event. */ LqWrkCmdWaitEvnt Tmp = Command.Val<LqWrkCmdWaitEvnt>(); Command.Pop<LqWrkCmdWaitEvnt>(); Tmp.EventAct(Tmp.UserData); } break; case LQWRK_CMD_ASYNC_CALL_11: { Command.Val<std::function<void()>>()(); Command.Pop<std::function<void()>>(); } break; case LQWRK_CMD_CLOSE_ALL_CONN: { /* Close all waiting connections. */ Command.Pop(); LqWrkEnumEvntOwnerDo(this, i) { auto Evnt = LqSysPollRemoveByInterator(&EventChecker, &i); LqWrkUnsetWrkOwner(Evnt); LqWrkCallEvntHdrCloseHandler(Evnt, this); }LqWrkEnumEvntOwnerWhile(this); } break; case LQWRK_CMD_RM_CONN_BY_IP: { LqConnAddr TmpVal = Command.Val<LqConnAddr>(); Command.Pop<LqConnAddr>(); CloseClientsByIpSync(&TmpVal.Addr); } break; case LQWRK_CMD_CLOSE_CONN_BY_PROTO: { auto Proto = Command.Val<const LqProto*>(); Command.Pop<const LqProto*>(); LqWrkEnumEvntOwnerDo(this, i) { auto Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i); if(LqClientIsConn(Evnt) && (((LqConn*)Evnt)->Proto == Proto)) { LqLogInfo("LqWrk::CloseConnByProto()#%llu remove connection by protocol\n", Id); LqSysPollRemoveByInterator(&EventChecker, &i); LqWrkUnsetWrkOwner(Evnt); LqWrkCallConnCloseHandler(Evnt, this); } }LqWrkEnumEvntOwnerWhile(this); } break; case LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD: { auto AsyncEvnt = &Command.Val<LqWrkAsyncEventForAllFd>(); auto CurTime = LqTimeGetLocMillisec(); LqWrkEnumEvntOwnerDo(this, i) { auto Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i); if(Evnt != ((LqClientHdr*)&NotifyEvent)) { switch(AsyncEvnt->EventAct(AsyncEvnt->UsrData, AsyncEvnt->UsrDataSize, this, Evnt, CurTime)) { case 1: LqSysPollRemoveByInterator(&EventChecker, &i); LqWrkUnsetWrkOwner(Evnt); break; case 2: LqSysPollRemoveByInterator(&EventChecker, &i); LqWrkUnsetWrkOwner(Evnt); LqWrkCallEvntHdrCloseHandler(Evnt, this); break; } } }LqWrkEnumEvntOwnerWhile(this); Command.Pop<LqWrkAsyncEventForAllFd>(); } break; case LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD_FIN: { auto AsyncEvnt = &Command.Val<LqWrkAsyncEventForAllFdAndCallFin>(); if(AsyncEvnt->EventAct != NULL) { auto CurTime = LqTimeGetLocMillisec(); LqWrkEnumEvntOwnerDo(this, i) { auto Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i); if(Evnt != ((LqClientHdr*)&NotifyEvent)) { switch(AsyncEvnt->EventAct(AsyncEvnt->UsrData, AsyncEvnt->UsrDataSize, this, Evnt, CurTime)) { case 1: LqSysPollRemoveByInterator(&EventChecker, &i); LqWrkUnsetWrkOwner(Evnt); break; case 2: LqSysPollRemoveByInterator(&EventChecker, &i); LqWrkUnsetWrkOwner(Evnt); LqWrkCallEvntHdrCloseHandler(Evnt, this); break; } } }LqWrkEnumEvntOwnerWhile(this); } Command.Pop<LqWrkAsyncEventForAllFdAndCallFin>(); } break; case LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD_FIN11: { auto AsyncEvnt = &Command.Val<LqWrkAsyncEventForAllFdAndCallFin11>(); LqWrkPtr ThisWrk = this; if(AsyncEvnt->EventAct != nullptr) { LqTimeMillisec CurTime = LqTimeGetLocMillisec(); LqWrkEnumEvntOwnerDo(this, i) { auto Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i); if(Evnt != ((LqClientHdr*)&NotifyEvent)) { switch(AsyncEvnt->EventAct(ThisWrk, Evnt)) { case 1: LqSysPollRemoveByInterator(&EventChecker, &i); LqWrkUnsetWrkOwner(Evnt); break; case 2: LqSysPollRemoveByInterator(&EventChecker, &i); LqWrkUnsetWrkOwner(Evnt); LqWrkCallEvntHdrCloseHandler(Evnt, this); break; } } }LqWrkEnumEvntOwnerWhile(this); } AsyncEvnt->EventAct = nullptr; Command.Pop<LqWrkAsyncEventForAllFdAndCallFin11>(); } break; case LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD11: { auto AsyncEvnt = &Command.Val<LqWrkAsyncEventForAllFd11>(); LqWrkPtr ThisWrk = this; if(AsyncEvnt->EventAct != nullptr) { LqTimeMillisec CurTime = LqTimeGetLocMillisec(); LqWrkEnumEvntOwnerDo(this, i) { auto Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i); if(Evnt != ((LqClientHdr*)&NotifyEvent)) { switch(AsyncEvnt->EventAct(ThisWrk, Evnt)) { case 1: LqSysPollRemoveByInterator(&EventChecker, &i); LqWrkUnsetWrkOwner(Evnt); break; case 2: LqSysPollRemoveByInterator(&EventChecker, &i); LqWrkUnsetWrkOwner(Evnt); LqWrkCallEvntHdrCloseHandler(Evnt, this); break; } } }LqWrkEnumEvntOwnerWhile(this); } AsyncEvnt->EventAct = nullptr; Command.Pop<LqWrkAsyncEventForAllFd11>(); } break; case LQWRK_CMD_TRANSFER_CLIENTS_AND_DELETE_FROM_BOSS: { const LqWrkPtr* WrkPtrs; intptr_t Count, RemoveIndex; LqWrkBoss* TargetWrkBoss; LqClientHdr** RmHdrs = NULL; intptr_t RmHdrsSize = (intptr_t)0; intptr_t Busy, Min, Index; bool CanDeleteWrkBoss = false; bool NeedRecurseClean = true; bool IsTransfer; TargetWrkBoss = Command.Val<LqWrkDeleteFromBossCmd>().Boss; IsTransfer = Command.Val<LqWrkDeleteFromBossCmd>().IsTransfer; Command.Pop<LqWrkDeleteFromBossCmd>(); CommandQueue.InsertBegin(Command); if(IsRecurseSkipCommands) { ParseInputCommands(); CommandQueue.PushBegin<LqWrkDeleteFromBossCmd>(LQWRK_CMD_TRANSFER_CLIENTS_AND_DELETE_FROM_BOSS, TargetWrkBoss, IsTransfer); return; } while(true) { /* Lock all worker boss */ TargetWrkBoss->Wrks.begin_locket_enum(&WrkPtrs, &Count); RemoveIndex = -((intptr_t)1); for(intptr_t i = 0; i < Count; i++) { if(WrkPtrs[i] == this) { /* Lock all commands queues */ auto AllQueueCmd = CommandQueue.LocketFork(); auto AllQueueClients = EvntFdQueue.LocketFork(); if(CmdIsOnlyOneTypeOfCommandInQueue(AllQueueCmd, LQWRK_CMD_TRANSFER_CLIENTS_AND_DELETE_FROM_BOSS)) { RemoveIndex = i; /* Filter all same commands */ LqQueueCmd<uint8_t>::Interator NewQueueCmd; while(AllQueueCmd) { if(AllQueueCmd.Val<LqWrkDeleteFromBossCmd>().Boss != TargetWrkBoss) { AllQueueCmd.Move(NewQueueCmd); } else { AllQueueCmd.Pop<LqWrkDeleteFromBossCmd>(); } } AllQueueCmd = NewQueueCmd; if(IsTransfer) { /* Transfer all clients to another workers */ LqWrkEnumEvntOwnerDo(this, j) { auto Evnt = LqSysPollGetHdrByInterator(&EventChecker, &j); if(Evnt != ((LqClientHdr*)&NotifyEvent)) { LqSysPollRemoveByInterator(&EventChecker, &j); if(Count == 1) { RmHdrs = (LqClientHdr**)LqMemRealloc(RmHdrs, (RmHdrsSize + 1) * sizeof(RmHdrs[0])); LqWrkUnsetWrkOwner(Evnt); RmHdrs[RmHdrsSize] = Evnt; RmHdrsSize++; } else { Min = LQ_NUMERIC_MAX(intptr_t); Index = -((intptr_t)1); for(intptr_t k = 0; k < Count; k++) { if(k == i) continue; Busy = WrkPtrs[k]->GetAssessmentBusy(); if(Busy < Min) Min = Busy, Index = k; } WrkPtrs[Index]->AddClientAsync(Evnt); } } }LqWrkEnumEvntOwnerWhile(this); while(AllQueueClients) { LqClientHdr* Evnt = AllQueueClients.Val<LqClientHdr*>(); AllQueueClients.Pop<LqClientHdr*>(); CountConnectionsInQueue--; if(Count == 1) { RmHdrs = (LqClientHdr**)LqMemRealloc(RmHdrs, (RmHdrsSize + 1) * sizeof(RmHdrs[0])); LqWrkUnsetWrkOwner(Evnt); RmHdrs[RmHdrsSize] = Evnt; RmHdrsSize++; } else { Min = LQ_NUMERIC_MAX(intptr_t); Index = -((intptr_t)1); for(intptr_t k = 0; k < Count; k++) { if(k == i) continue; Busy = WrkPtrs[k]->GetAssessmentBusy(); if(Busy < Min) Min = Busy, Index = k; } WrkPtrs[Index]->AddClientAsync(Evnt); } } } CanDeleteWrkBoss = TargetWrkBoss->NeedDelete && (Count == 1); NeedRecurseClean = false; } EvntFdQueue.LocketUnfork(AllQueueClients); CommandQueue.LocketUnfork(AllQueueCmd); break; } } TargetWrkBoss->Wrks.end_locket_enum(RemoveIndex); if(RmHdrs != NULL) { for(intptr_t i = ((intptr_t)0); i < RmHdrsSize; i++) { LqClientCallCloseHandler(RmHdrs[i]); } LqMemFree(RmHdrs); } if(CanDeleteWrkBoss) { LqFastAlloc::Delete(TargetWrkBoss); } if(NeedRecurseClean) { IsRecurseSkipCommands = true; ParseInputCommands(); IsRecurseSkipCommands = false; } else { break; } } } break; default: /* Is command unknown. */ Command.JustPop(); } } } void LqWrk::ClearQueueCommands() { for(auto Command = EvntFdQueue.Fork(); Command;) { auto Evnt = Command.Val<LqClientHdr*>(); Command.Pop<LqClientHdr*>(); LqWrkUnsetWrkOwner(Evnt); LqClientCallCloseHandler(Evnt); CountConnectionsInQueue--; } for(auto Command = CommandQueue.Fork(); Command;) { switch(Command.Type) { case LQWRK_CMD_ASYNC_CALL_11: Command.Pop<std::function<void()>>(); break; case LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD: Command.Pop<LqWrkAsyncEventForAllFd>(); break; case LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD_FIN: Command.Pop<LqWrkAsyncEventForAllFdAndCallFin>(); break; case LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD_FIN11: Command.Pop<LqWrkAsyncEventForAllFdAndCallFin11>(); break; case LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD11: Command.Pop<LqWrkAsyncEventForAllFd11>(); break; case LQWRK_CMD_TRANSFER_CLIENTS_AND_DELETE_FROM_BOSS: Command.Pop<LqWrkDeleteFromBossCmd>(); break; default: Command.JustPop(); } } } /* Main worker loop */ void LqWrk::BeginThread() { LqClientHdr* EvntHdr; LqEvntFlag OldFlags; uintptr_t Expected; LqLogInfo("LqWrk::BeginThread()#%llu begin worker thread\n", Id); #if !defined(LQPLATFORM_WINDOWS) signal(SIGPIPE, SIG_IGN); #endif Lock(); LqSysPollThreadInit(&EventChecker); Unlock(); AddClientSync((LqClientHdr*)&NotifyEvent); while(true) { if(LqEventReset(NotifyEvent.Fd)) { if(LqThreadBase::IsShouldEnd) break; ParseInputCommands(); if(LqThreadBase::IsShouldEnd) break; Expected = (uintptr_t)1; if(LqAtmCmpXchg(IsSyncAllFlags, Expected, (uintptr_t)0)) { LqWrkUpdateAllMaskByOwner(this, DelProc); } } LqWrkEnumChangesEvntDo(this, Revent) { EvntHdr = LqSysPollGetHdrByCurrent(&EventChecker); OldFlags = EvntHdr->Flag; LqAtmIntrlkOr(EvntHdr->Flag, _LQEVNT_FLAG_NOW_EXEC); if(LqClientIsConn(EvntHdr)) { if(Revent & (LQEVNT_FLAG_ERR | LQEVNT_FLAG_WR | LQEVNT_FLAG_RD | LQEVNT_FLAG_CONNECT | LQEVNT_FLAG_ACCEPT)) { LqWrkCallConnHandler(EvntHdr, Revent, this); //Is removed current connection in handler if(LqSysPollGetHdrByCurrent(&EventChecker) != EvntHdr) continue; } } else { if(Revent & (LQEVNT_FLAG_ERR | LQEVNT_FLAG_WR | LQEVNT_FLAG_RD | LQEVNT_FLAG_CONNECT | LQEVNT_FLAG_ACCEPT)) { LqWrkCallEvntFdHandler(EvntHdr, Revent, this); //Is removed current connection in handler if(LqSysPollGetHdrByCurrent(&EventChecker) != EvntHdr) continue; } } if((Revent & (LQEVNT_FLAG_HUP | LQEVNT_FLAG_RDHUP | LQEVNT_FLAG_END)) || (LqClientGetFlags(EvntHdr) & LQEVNT_FLAG_END)) { LqSysPollRemoveCurrent(&EventChecker); LqWrkUnsetWrkOwner(EvntHdr); LqWrkCallEvntHdrCloseHandler(EvntHdr, this); } else { LqAtmIntrlkAnd(EvntHdr->Flag, ~_LQEVNT_FLAG_NOW_EXEC); if(EvntHdr->Flag != OldFlags) //If have event changes LqSysPollSetMaskByCurrent(&EventChecker); LqSysPollUnuseCurrent(&EventChecker); } }LqWrkEnumChangesEvntWhile(this); LqWrkWaitEvntsChanges(this); } RemoveClient((LqClientHdr*)&NotifyEvent); CloseAllClientsSync(); ClearQueueCommands(); Lock(); LqSysPollThreadUninit(&EventChecker); Unlock(); LqLogInfo("LqWrk::BeginThread()#%llu end worker thread\n", Id); LqThreadYield(); LqThreadYield(); } bool LqWrk::RemoveClientsOnTimeOutAsync(LqTimeMillisec TimeLiveMilliseconds) { if(!CommandQueue.Push<LqTimeMillisec>(LQWRK_CMD_RM_CONN_ON_TIME_OUT, TimeLiveMilliseconds)) return false; NotifyThread(); return true; } size_t LqWrk::RemoveClientsOnTimeOutSync(LqTimeMillisec TimeLiveMilliseconds) { size_t Res = 0; LqClientHdr* Evnt; auto CurTime = LqTimeGetLocMillisec(); #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT const LqEvntFlag NowExec = IsThisThread() ? ((LqEvntFlag)0) : _LQEVNT_FLAG_NOW_EXEC; #endif LqWrkEnumEvntDo(this, i) { Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i); if(LqClientIsConn(Evnt)) { #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT while(LqClientGetFlags(Evnt) & NowExec) { Unlock(); LqThreadYield(); Lock(); if(LqSysPollGetHdrByInterator(&EventChecker, &i) != Evnt) goto lblContinue; } #endif if(((LqConn*)Evnt)->Proto->KickByTimeOutProc((LqConn*)Evnt, CurTime, TimeLiveMilliseconds)) { LqLogInfo("LqWrk::RemoveConnOnTimeOut()#%llu remove connection by timeout\n", Id); LqWrkRemoveByInterator(this, &i); LqWrkUnsetWrkOwner(Evnt); LqWrkCallConnCloseHandler(Evnt, this); Res++; } lblContinue:; } }LqWrkEnumEvntWhile(this); return Res; } bool LqWrk::RemoveClientsOnTimeOutAsync(const LqProto* Proto, LqTimeMillisec TimeLiveMilliseconds) { if(!CommandQueue.Push<LqWrkCmdCloseByTimeout>(LQWRK_CMD_RM_CONN_ON_TIME_OUT_PROTO, Proto, TimeLiveMilliseconds)) return false; NotifyThread(); return true; } size_t LqWrk::RemoveClientsOnTimeOutSync(const LqProto* Proto, LqTimeMillisec TimeLiveMilliseconds) { size_t Res = 0; LqClientHdr* Evnt; LqTimeMillisec CurTime = LqTimeGetLocMillisec(); #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT const LqEvntFlag NowExec = IsThisThread() ? ((LqEvntFlag)0) : _LQEVNT_FLAG_NOW_EXEC; #endif LqWrkEnumEvntDo(this, i) { Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i); if(LqClientIsConn(Evnt) && (((LqConn*)Evnt)->Proto == Proto)) { #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT while(Evnt->Flag & NowExec) { Unlock(); LqThreadYield(); //Wait until worker thread leave read/write handler Lock(); if(LqSysPollGetHdrByInterator(&EventChecker, &i) != Evnt) goto lblContinue; } #endif if(Proto->KickByTimeOutProc((LqConn*)Evnt, CurTime, TimeLiveMilliseconds)) { LqLogInfo("LqWrk::RemoveConnOnTimeOut()#%llu remove connection by timeout\n", Id); LqWrkRemoveByInterator(this, &i); LqWrkUnsetWrkOwner(Evnt); LqWrkCallConnCloseHandler(Evnt, this); Res++; } lblContinue:; } }LqWrkEnumEvntWhile(this); return Res; } bool LqWrk::AddClientAsync(LqClientHdr* EvntHdr) { if(!EvntFdQueue.Push(EvntHdr, this)) return false; CountConnectionsInQueue++; NotifyThread(); return true; } bool LqWrk::AddClientSync(LqClientHdr* EvntHdr) { bool Res; if(LqClientGetFlags(EvntHdr) & LQEVNT_FLAG_END) { LqClientCallCloseHandler(EvntHdr); return true; } LqLogInfo("LqWrk::AddEvnt()#%llu event {%i, %llx} recived\n", Id, EvntHdr->Fd, (unsigned long long)EvntHdr->Flag); Lock(); LqWrkSetWrkOwner(EvntHdr, this); LqWrkWaiterLock(this); Res = LqSysPollAddHdr(&EventChecker, EvntHdr); LqWrkWaiterUnlock(this); Unlock(); return Res; } bool LqWrk::RemoveClient(LqClientHdr* EvntHdr) { bool Res = false; LqClientHdr* Evnt; #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT const LqEvntFlag NowExec = IsThisThread() ? ((LqEvntFlag)0) : _LQEVNT_FLAG_NOW_EXEC; #endif LqWrkEnumEvntDo(this, i) { if((Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i)) == EvntHdr) { #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT while(LqClientGetFlags(Evnt) & NowExec) { Unlock(); LqThreadYield(); //Wait until worker thread leave read/write handler Lock(); if(LqSysPollGetHdrByInterator(&EventChecker, &i) != Evnt) goto lblContinue; } #endif LqWrkRemoveByInterator(this, &i); LqWrkUnsetWrkOwner(EvntHdr); Res = true; break; lblContinue:; } }LqWrkEnumEvntWhile(this); return Res; } bool LqWrk::CloseClient(LqClientHdr* EvntHdr) { intptr_t Res = ((intptr_t)0); #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT const LqEvntFlag NowExec = IsThisThread() ? ((LqEvntFlag)0) : _LQEVNT_FLAG_NOW_EXEC; #endif while(true) { LqWrkEnumEvntDo(this, i) { if(LqSysPollGetHdrByInterator(&EventChecker, &i) == EvntHdr) { #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT if(LqClientGetFlags(EvntHdr) & NowExec) { Res = -((intptr_t)1); } else #endif { LqWrkRemoveByInterator(this, &i); LqWrkUnsetWrkOwner(EvntHdr); Res = ((intptr_t)1); } break; } }LqWrkEnumEvntWhile(this); if(Res == ((intptr_t)1)) { LqClientCallCloseHandler(EvntHdr); } else if(Res == -((intptr_t)1)) { LqThreadYield(); continue; } break; } return Res == ((intptr_t)1); } bool LqWrk::UpdateAllClientFlagAsync() { uintptr_t Expected = ((uintptr_t)0); LqAtmCmpXchg(IsSyncAllFlags, Expected, (uintptr_t)1); NotifyThread(); return true; } int LqWrk::UpdateAllClientFlagSync() { int Res; LqWrkUpdateAllMask(this, DelProc, Res); return Res; } bool LqWrk::AsyncCall(void(LQ_CALL*AsyncProc)(void*), void* UserData) { if(!CommandQueue.Push<LqWrkCmdWaitEvnt>(LQWRK_CMD_ASYNC_CALL, AsyncProc, UserData)) return false; NotifyThread(); return true; } bool LqWrk::AsyncCall11(std::function<void()> Proc) { if(!CommandQueue.Push<std::function<void()>>(LQWRK_CMD_ASYNC_CALL_11, Proc)) return false; NotifyThread(); return true; } size_t LqWrk::CancelAsyncCall(void(LQ_CALL*AsyncProc)(void*), void* UserData, bool IsAll) { size_t Res = 0; auto Command = CommandQueue.LocketFork(); LqQueueCmd<uint8_t>::Interator NewQueueCmd; while(Command) { switch(Command.Type) { case LQWRK_CMD_ASYNC_CALL: { if((IsAll || (Res == 0)) && (Command.Val<LqWrkCmdWaitEvnt>().EventAct == AsyncProc) && (Command.Val<LqWrkCmdWaitEvnt>().UserData == UserData)) { Command.Pop<LqWrkCmdWaitEvnt>(); Res++; } else { Command.Move(NewQueueCmd); } } break; default: /* Otherwise return current command in list*/ Command.Move(NewQueueCmd); } } CommandQueue.LocketUnfork(NewQueueCmd); return Res; } bool LqWrk::CloseAllClientsAsync() { if(!CommandQueue.Push(LQWRK_CMD_CLOSE_ALL_CONN)) return false; NotifyThread(); return true; } size_t LqWrk::CloseAllClientsSync() { size_t Ret = ((size_t)0); LqClientHdr* Evnt; #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT const LqEvntFlag NowExec = IsThisThread() ? ((LqEvntFlag)0) : _LQEVNT_FLAG_NOW_EXEC; #endif LqWrkEnumEvntDo(this, i) { Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i); #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT while(LqClientGetFlags(Evnt) & NowExec) { Unlock(); LqThreadYield(); Lock(); if(LqSysPollGetHdrByInterator(&EventChecker, &i) != Evnt) goto lblContinue; } #endif LqWrkRemoveByInterator(this, &i); LqWrkUnsetWrkOwner(Evnt); LqWrkCallEvntHdrCloseHandler(Evnt, this); Ret++; lblContinue:; }LqWrkEnumEvntWhile(this); return Ret; } size_t LqWrk::CloseClientsByIpSync(const sockaddr* Addr) { size_t Res = ((size_t)0); LqClientHdr* Evnt; switch(Addr->sa_family) { case AF_INET: case AF_INET6: break; default: return Res; } #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT const LqEvntFlag NowExec = IsThisThread() ? ((LqEvntFlag)0) : _LQEVNT_FLAG_NOW_EXEC; #endif LqWrkEnumEvntDo(this, i) { Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i); if(LqClientIsConn(Evnt) && (((LqConn*)Evnt)->Proto->CmpAddressProc((LqConn*)Evnt, Addr))) { #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT while(LqClientGetFlags(Evnt) & NowExec) { Unlock(); LqThreadYield(); Lock(); if(LqSysPollGetHdrByInterator(&EventChecker, &i) != Evnt) goto lblContinue; } #endif LqWrkRemoveByInterator(this, &i); LqWrkUnsetWrkOwner(Evnt); LqWrkCallConnCloseHandler(Evnt, this); Res++; lblContinue:; } }LqWrkEnumEvntWhile(this); return Res; } bool LqWrk::CloseClientsByIpAsync(const sockaddr* Addr) { StartThreadLocker.LockWriteYield(); switch(Addr->sa_family) { case AF_INET: { LqConnAddr s; s.AddrInet = *(sockaddr_in*)Addr; if(!CommandQueue.Push<LqConnAddr>(LQWRK_CMD_RM_CONN_BY_IP, s)) { StartThreadLocker.UnlockWrite(); return false; } } break; case AF_INET6: { LqConnAddr s; s.AddrInet6 = *(sockaddr_in6*)Addr; if(!CommandQueue.Push<LqConnAddr>(LQWRK_CMD_RM_CONN_BY_IP, s)) { StartThreadLocker.UnlockWrite(); return false; } } break; default: StartThreadLocker.UnlockWrite(); return false; } StartThreadLocker.UnlockWrite(); NotifyThread(); return true; } bool LqWrk::EnumClientsAsync( int(LQ_CALL*EventAct)(void*, size_t, void*, LqClientHdr*, LqTimeMillisec), void* UserData, size_t UserDataSize ) { bool Res; Res = CommandQueue.Push<LqWrkAsyncEventForAllFd>(LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD, UserData, UserDataSize, EventAct); NotifyThread(); return Res; } bool LqWrk::EnumClientsAndCallFinAsync( int(LQ_CALL*EventAct)(void*, size_t, void*, LqClientHdr*, LqTimeMillisec), uintptr_t(LQ_CALL*FinFunc)(void*, size_t), void * UserData, size_t UserDataSize ) { bool Res; LqShdPtr<LqWrkAsyncCallFin, LqFastAlloc::Delete, true, false, uintptr_t> FinObject = LqFastAlloc::New<LqWrkAsyncCallFin>(FinFunc, UserData, UserDataSize); Res = CommandQueue.Push<LqWrkAsyncEventForAllFdAndCallFin>(LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD_FIN, UserData, UserDataSize, EventAct, FinObject); NotifyThread(); return Res; } static uintptr_t LQ_CALL __LqWrkEmptyFin(void*, size_t) { return 0; } bool LqWrkBoss::EnumClientsAndCallFinAsync( int(LQ_CALL*EventAct)(void*, size_t, void*, LqClientHdr*, LqTimeMillisec), uintptr_t(LQ_CALL*FinFunc)(void*, size_t), void * UserData, size_t UserDataSize ) const { bool Res = false; const LqWrkPtr* Arr; intptr_t Count; LqShdPtr<LqWrkAsyncCallFin, LqFastAlloc::Delete, true, false, uintptr_t> FinObject = LqFastAlloc::New<LqWrkAsyncCallFin>(FinFunc, UserData, UserDataSize); Wrks.begin_locket_enum(&Arr, &Count); for(intptr_t i = 0; i < Count; i++) { Res |= Arr[i]->CommandQueue.Push<LqWrkAsyncEventForAllFdAndCallFin>(LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD_FIN, UserData, UserDataSize, EventAct, FinObject); Arr[i]->NotifyThread(); } Wrks.end_locket_enum(-((intptr_t)1)); if(!Res) { FinObject->EventFin = __LqWrkEmptyFin; } return Res; } bool LqWrkBoss::EnumClientsAndCallFinAsync11(std::function<int(LqWrkPtr&, LqClientHdr*)> EventAct, std::function<uintptr_t()> FinFunc) const { bool Res = false; const LqWrkPtr* Arr; intptr_t Count; LqShdPtr<LqWrkAsyncCallFin11, LqFastAlloc::Delete, true, false, uintptr_t> FinObject = LqFastAlloc::New<LqWrkAsyncCallFin11>(FinFunc); Wrks.begin_locket_enum(&Arr, &Count); for(intptr_t i = 0; i < Count; i++) { Res |= Arr[i]->CommandQueue.Push<LqWrkAsyncEventForAllFdAndCallFin11>(LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD_FIN11, EventAct, FinObject); Arr[i]->NotifyThread(); } Wrks.end_locket_enum(-((intptr_t)1)); if(!Res) { FinObject->FinFunc = [] { return 0; }; } return Res; } bool LqWrkBoss::EnumClientsAndCallFinForMultipleBossAsync( LqWrkBoss* Bosses, size_t BossesSize, int(LQ_CALL*EventAct)(void*, size_t, void*, LqClientHdr*, LqTimeMillisec), uintptr_t(LQ_CALL*FinFunc)(void*, size_t), /* You can return module handle for delete them */ void * UserData, size_t UserDataSize ) { bool Res = false; const LqWrkPtr* Arr; intptr_t Count; LqShdPtr<LqWrkAsyncCallFin, LqFastAlloc::Delete, true, false, uintptr_t> FinObject = LqFastAlloc::New<LqWrkAsyncCallFin>(FinFunc, UserData, UserDataSize); for(intptr_t j = 0; j < BossesSize; j++) { Bosses[j].Wrks.begin_locket_enum(&Arr, &Count); for(intptr_t i = 0; i < Count; i++) { Res |= Arr[i]->CommandQueue.Push<LqWrkAsyncEventForAllFdAndCallFin>(LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD_FIN, UserData, UserDataSize, EventAct, FinObject); Arr[i]->NotifyThread(); } Bosses[j].Wrks.end_locket_enum(-((intptr_t)1)); } if(!Res) { FinObject->EventFin = __LqWrkEmptyFin; } return Res; } bool LqWrkBoss::EnumClientsAndCallFinForMultipleBossAsync11(LqWrkBoss* Bosses, size_t BossesSize, std::function<int(LqWrkPtr&, LqClientHdr*)> EventAct, std::function<uintptr_t()> FinFunc) const { bool Res = false; const LqWrkPtr* Arr; intptr_t Count; LqShdPtr<LqWrkAsyncCallFin11, LqFastAlloc::Delete, true, false, uintptr_t> FinObject = LqFastAlloc::New<LqWrkAsyncCallFin11>(FinFunc); for(intptr_t j = 0; j < BossesSize; j++) { Bosses[j].Wrks.begin_locket_enum(&Arr, &Count); for(intptr_t i = 0; i < Count; i++) { Res |= Arr[i]->CommandQueue.Push<LqWrkAsyncEventForAllFdAndCallFin11>(LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD_FIN11, EventAct, FinObject); Arr[i]->NotifyThread(); } Bosses[j].Wrks.end_locket_enum(-((intptr_t)1)); } if(!Res) { FinObject->FinFunc = [] { return 0; }; } return Res; } bool LqWrk::EnumClientsAndCallFinAsync11(std::function<int(LqWrkPtr&, LqClientHdr*)> EventAct, std::function<uintptr_t()> FinFunc) { LqShdPtr<LqWrkAsyncCallFin11, LqFastAlloc::Delete, true, false, uintptr_t> FinObject = LqFastAlloc::New<LqWrkAsyncCallFin11>(FinFunc); bool Res = CommandQueue.Push<LqWrkAsyncEventForAllFdAndCallFin11>(LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD_FIN11, EventAct, FinObject); NotifyThread(); return Res; } bool LqWrk::EnumClientsAsync11(std::function<int(LqWrkPtr&, LqClientHdr*)> EventAct) { bool Res = CommandQueue.Push<LqWrkAsyncEventForAllFd11>(LQWRK_CMD_ASYNC_EVENT_FOR_ALL_FD11, EventAct); NotifyThread(); return Res; } size_t LqWrk::EnumClients11(std::function<int(LqClientHdr*)> EventAct, bool* IsIterrupted) { return EnumClients( [](void* UserData, LqClientHdr* Hdr) -> int { std::function<int(LqClientHdr*)>* Func = (std::function<int(LqClientHdr*)>*)UserData; return Func->operator()(Hdr); }, &EventAct, IsIterrupted ); } size_t LqWrk::EnumClientsByProto11(std::function<int(LqClientHdr*)> EventAct, const LqProto* Proto, bool* IsIterrupted) { return EnumClientsByProto( [](void* UserData, LqClientHdr* Hdr) -> int { std::function<int(LqClientHdr*)>* Func = (std::function<int(LqClientHdr*)>*)UserData; return Func->operator()(Hdr); }, Proto, &EventAct, IsIterrupted ); } bool LqWrk::TransferClientsAndRemoveFromBossAsync(LqWrkBoss * TargetBoss, bool IsTransferClients) { auto Res = CommandQueue.Push<LqWrkDeleteFromBossCmd>(LQWRK_CMD_TRANSFER_CLIENTS_AND_DELETE_FROM_BOSS, TargetBoss, IsTransferClients); NotifyThread(); return Res; } bool LqWrk::CloseClientsByProtoAsync(const LqProto* Proto) { StartThreadLocker.LockWriteYield(); auto Res = CommandQueue.Push<const LqProto*>(LQWRK_CMD_CLOSE_CONN_BY_PROTO, Proto); StartThreadLocker.UnlockWrite(); NotifyThread(); return Res; } size_t LqWrk::CloseClientsByProtoSync(const LqProto* Proto) { size_t Res = 0; LqClientHdr* Evnt; #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT const LqEvntFlag NowExec = IsThisThread() ? ((LqEvntFlag)0) : _LQEVNT_FLAG_NOW_EXEC; #endif LqWrkEnumEvntDo(this, i) { Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i); if(LqClientIsConn(Evnt) && (((LqConn*)Evnt)->Proto == Proto)) { #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT while(LqClientGetFlags(Evnt) & NowExec) { Unlock(); LqThreadYield(); Lock(); if(LqSysPollGetHdrByInterator(&EventChecker, &i) != Evnt) goto lblContinue; } #endif LqLogInfo("LqWrk::CloseConnByProto()#%llu remove connection by protocol\n", Id); LqWrkRemoveByInterator(this, &i); LqWrkUnsetWrkOwner(Evnt); LqWrkCallConnCloseHandler(Evnt, this); Res++; lblContinue:; } }LqWrkEnumEvntWhile(this); return Res; } size_t LqWrk::EnumClients(int(LQ_CALL*Proc)(void *, LqClientHdr*), void* UserData, bool* IsIterrupted) { size_t Res = 0; int Act = 0; bool IsAsyncDel = false; LqClientHdr* Evnt; LqEvntFlag ExpectedEvntFlag, NewEvntFlag; #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT const LqEvntFlag NowExec = IsThisThread() ? ((LqEvntFlag)0) : _LQEVNT_FLAG_NOW_EXEC; #endif LqWrkEnumEvntDo(this, i) { Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i); #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT while(LqClientGetFlags(Evnt) & NowExec) { Unlock(); LqThreadYield(); Lock(); if(LqSysPollGetHdrByInterator(&EventChecker, &i) != Evnt) goto lblContinue; } #endif Act = Proc(UserData, Evnt); /* !! Not unlocket for safety !! in @Proc not call @LqEvntHdrClose (If you want, use async method or just return 2)*/ if(Act > 0) { Res++; if(Act == 3) { IsAsyncDel = true; ExpectedEvntFlag = LqClientGetFlags(Evnt); do { NewEvntFlag = ExpectedEvntFlag | LQEVNT_FLAG_END; } while(!LqAtmCmpXchg(Evnt->Flag, ExpectedEvntFlag, NewEvntFlag)); } else { LqWrkRemoveByInterator(this, &i); LqWrkUnsetWrkOwner(Evnt); if(Act == 2) LqWrkCallEvntHdrCloseHandler(Evnt, this); } } else if(Act < 0) { break; } lblContinue:; }LqWrkEnumEvntWhile(this); if(IsAsyncDel) UpdateAllClientFlagAsync(); *IsIterrupted = Act < 0; return Res; } size_t LqWrk::EnumClientsByProto(int(LQ_CALL*Proc)(void *, LqClientHdr *), const LqProto* Proto, void* UserData, bool* IsIterrupted) { size_t Res = ((size_t)0); LqClientHdr* Evnt; int Act = 0; bool IsAsyncDel = false; LqEvntFlag ExpectedEvntFlag, NewEvntFlag; #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT const LqEvntFlag NowExec = IsThisThread() ? ((LqEvntFlag)0) : _LQEVNT_FLAG_NOW_EXEC; #endif LqWrkEnumEvntDo(this, i) { Evnt = LqSysPollGetHdrByInterator(&EventChecker, &i); if(LqClientIsConn(Evnt) && (((LqConn*)Evnt)->Proto == Proto)) { #ifdef LQWRK_ENABLE_RW_HNDL_PROTECT while(LqClientGetFlags(Evnt) & NowExec) { Unlock(); LqThreadYield(); Lock(); if(LqSysPollGetHdrByInterator(&EventChecker, &i) != Evnt) goto lblContinue; } #endif Act = Proc(UserData, Evnt); /* !! Not unlocket for safety !! in @Proc not call @LqEvntHdrClose (If you want, use async method or just return 2)*/ if(Act > 0) { Res++; if(Act == 3) { IsAsyncDel = true; ExpectedEvntFlag = LqClientGetFlags(Evnt); do { NewEvntFlag = ExpectedEvntFlag | LQEVNT_FLAG_END; } while(!LqAtmCmpXchg(Evnt->Flag, ExpectedEvntFlag, NewEvntFlag)); } else { LqWrkRemoveByInterator(this, &i); LqWrkUnsetWrkOwner(Evnt); if(Act == 2) LqWrkCallEvntHdrCloseHandler(Evnt, this); } } else if(Act < 0) { break; } lblContinue:; } }LqWrkEnumEvntWhile(this); if(IsAsyncDel) UpdateAllClientFlagAsync(); *IsIterrupted = Act < 0; return Res; } LqString LqWrk::DebugInfo() const { char Buf[1024]; size_t ccip = LqSysPollCount(&EventChecker); size_t cciq = CountConnectionsInQueue; auto CurrentTimeMillisec = LqTimeGetLocMillisec(); LqFbuf_snprintf( Buf, sizeof(Buf), "--------------\n" " Worker Id: %llu\n" " Time start: %s (%s)\n" " Count conn. & event obj. in process: %u\n" " Count conn. & event obj. in queue: %u\n" " Common conn. & event obj.: %u\n", Id, LqTimeLocSecToStlStr(TimeStart / 1000).c_str(), LqTimeDiffMillisecToStlStr(TimeStart, CurrentTimeMillisec).c_str(), (unsigned)ccip, (unsigned)cciq, (unsigned)(ccip + cciq) ); return Buf; } LqString LqWrk::AllDebugInfo() { LqString r = "~~~~~~~~~~~~~~\n Common worker info\n" + DebugInfo() + "--------------\n Thread info\n" + LqThreadBase::DebugInfo() + "--------------\n"; int k = 0; LqWrkEnumEvntDo(this, i) { auto Conn = LqSysPollGetHdrByInterator(&EventChecker, &i); if(LqClientIsConn(Conn)) { r += " Conn #" + LqToString(k) + "\n"; char* DbgInf = ((LqConn*)Conn)->Proto->DebugInfoProc((LqConn*)Conn); /*!!! Not call another worker methods in this function !!!*/ if(DbgInf != nullptr) { r += DbgInf; r += "\n"; free(DbgInf); } k++; } }LqWrkEnumEvntWhile(this); r += "~~~~~~~~~~~~~~\n"; return r; } size_t LqWrk::GetAssessmentBusy() const { return CountConnectionsInQueue + LqSysPollCount(&EventChecker); } size_t LqWrk::CountClients() const { return LqSysPollCount(&EventChecker); } void LqWrk::NotifyThread() { LqEventSet(NotifyEvent.Fd); }
#include "stdafx.h" #include "MultipliersMgr.h" #include "Multipliers.h" #include "Station.h" #include "Qso.h" #include "Contest.h" MultipliersMgr::MultipliersMgr() : m_multipliersType(eMultUnknown), m_station(nullptr), m_instate(false), m_multipliersBase(nullptr) { } MultipliersMgr::~MultipliersMgr() { } // Setup the Multipliers bool MultipliersMgr::SetupMultipliers(Station *station, MultipliersType multType) { m_station = station; m_instate = station->InState(); m_multipliersType = multType; Contest *contest = station->GetContest(); bool status = false; if (m_multipliersType == eMultPerMode) { if (m_instate) { m_multipliersBase = new MultipliersPerModeInstate(); } else { m_multipliersBase = new MultipliersPerModeOutstate(); } } if (m_multipliersBase != nullptr) { status = m_multipliersBase->SetupMultipliers(m_station); // Are bonus stations multipliers? bool bonusStationMults = contest->GetBonusStationMultipliers(); if (bonusStationMults) { list<string> bonusStations = contest->GetBonusStations(); m_multipliersBase->SetBonusStations(bonusStations); } } return status; } bool MultipliersMgr::FindMultipliers(vector<Qso>& qsos) { bool status = false; if (m_multipliersBase != nullptr) { status = m_multipliersBase->FindMultipliers(qsos); } return status; } int MultipliersMgr::MultiplierPoints() const { if (m_multipliersBase != nullptr) { return m_multipliersBase->MultiplierPoints(); } return 0; } int MultipliersMgr::DxccMultipliers() const { if (m_multipliersBase != nullptr) { return m_multipliersBase->DxccMultipliers(); } return 0; } // The number of unique bonus stations worked int MultipliersMgr::BonusStationsWorked() const { if (m_multipliersBase != nullptr) { return m_multipliersBase->BonusStationsWorked(); } return 0; }
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "CryptoNoteBasicImpl.h" #include "CryptoNoteFormatUtils.h" #include "CryptoNoteTools.h" #include "CryptoNoteSerialization.h" #include "Common/Base58.h" #include "crypto/hash.h" #include "Common/int-util.h" using namespace crypto; using namespace common; namespace cn { /************************************************************************/ /* cn helper functions */ /************************************************************************/ //----------------------------------------------------------------------------------------------- uint64_t getPenalizedAmount(uint64_t amount, size_t medianSize, size_t currentBlockSize) { static_assert(sizeof(size_t) >= sizeof(uint32_t), "size_t is too small"); assert(currentBlockSize <= 2 * medianSize); assert(medianSize <= std::numeric_limits<uint32_t>::max()); assert(currentBlockSize <= std::numeric_limits<uint32_t>::max()); if (amount == 0) { return 0; } if (currentBlockSize <= medianSize) { return amount; } uint64_t productHi; uint64_t productLo = mul128(amount, currentBlockSize * (UINT64_C(2) * medianSize - currentBlockSize), &productHi); uint64_t penalizedAmountHi; uint64_t penalizedAmountLo; div128_32(productHi, productLo, static_cast<uint32_t>(medianSize), &penalizedAmountHi, &penalizedAmountLo); div128_32(penalizedAmountHi, penalizedAmountLo, static_cast<uint32_t>(medianSize), &penalizedAmountHi, &penalizedAmountLo); assert(0 == penalizedAmountHi); assert(penalizedAmountLo < amount); return penalizedAmountLo; } //----------------------------------------------------------------------- std::string getAccountAddressAsStr(uint64_t prefix, const AccountPublicAddress& adr) { BinaryArray ba; bool r = toBinaryArray(adr, ba); assert(r); return tools::base_58::encode_addr(prefix, common::asString(ba)); } //----------------------------------------------------------------------- bool is_coinbase(const Transaction& tx) { if(tx.inputs.size() != 1) { return false; } if(tx.inputs[0].type() != typeid(BaseInput)) { return false; } return true; } //----------------------------------------------------------------------- bool parseAccountAddressString(uint64_t& prefix, AccountPublicAddress& adr, const std::string& str) { std::string data; return tools::base_58::decode_addr(str, prefix, data) && fromBinaryArray(adr, asBinaryArray(data)) && // ::serialization::parse_binary(data, adr) && check_key(adr.spendPublicKey) && check_key(adr.viewPublicKey); } //----------------------------------------------------------------------- bool operator ==(const cn::Transaction& a, const cn::Transaction& b) { return getObjectHash(a) == getObjectHash(b); } //----------------------------------------------------------------------- bool operator ==(const cn::Block& a, const cn::Block& b) { return cn::get_block_hash(a) == cn::get_block_hash(b); } } //-------------------------------------------------------------------------------- bool parse_hash256(const std::string& str_hash, crypto::Hash& hash) { return common::podFromHex(str_hash, hash); }
#include "GetHistoryProc.h" #include "Logger.h" #include "HallManager.h" #include "Room.h" #include "ErrorMsg.h" //#include "UdpManager.h" #include "ProcessManager.h" #include "GameCmd.h" #include "IProcess.h" REGISTER_PROCESS(CLIENT_MSG_GETHISTORY, GetHistoryProc) GetHistoryProc::GetHistoryProc() { this->name = "GetHistoryProc"; } GetHistoryProc::~GetHistoryProc() { } int GetHistoryProc::doRequest(CDLSocketHandler* clientHandler, InputPacket* pPacket, Context* pt ) { //_NOTUSED(pt); int cmd = pPacket->GetCmdType(); short seq = pPacket->GetSeqNum(); int uid = pPacket->ReadInt(); int tid = pPacket->ReadInt(); short sid = pPacket->ReadShort(); _LOG_INFO_("==>[GetHistoryProc] [0x%04x] uid[%d]\n", cmd, uid); _LOG_DEBUG_("[DATA Parse] sid=[%d]\n", sid); BaseClientHandler* hallhandler = reinterpret_cast<BaseClientHandler*> (clientHandler); Room* room = Room::getInstance(); Table *table = room->getTable(); int i = 0; if(table==NULL) { _LOG_ERROR_("GetHistoryProc: uid[%d] table is NULL\n", uid); sendErrorMsg(hallhandler, cmd, uid, -2,ErrorMsg::getInstance()->getErrMsg(-2),seq); return 0; } Player* player = table->getPlayer(uid); if(player == NULL) { _LOG_ERROR_("GetHistoryProc: uid[%d] Player is NULL\n", uid); sendErrorMsg(hallhandler, cmd, uid, -1,ErrorMsg::getInstance()->getErrMsg(-1),seq); return 0; } // if(player->id != uid) // { // _LOG_ERROR_("Your uid[%d] Not Set In this index sid[%d]\n", uid, sid); // sendErrorMsg(hallhandler, cmd, uid, -3,ErrorMsg::getInstance()->getErrMsg(-3),seq); // return 0; // } player->setActiveTime(time(NULL)); OutputPacket response; response.Begin(cmd, player->id); response.SetSeqNum(seq); response.WriteShort(0); response.WriteString("ok"); response.WriteInt(player->id); response.WriteShort(player->m_nStatus); response.WriteInt(table->id); response.WriteShort(table->m_nStatus); int num = 0; if(table->m_GameRecordArrary[table->m_nRecordLast].cbBanker == 0) { response.WriteShort(table->m_nRecordLast); num = table->m_nRecordLast; for(int i = 0; i < table->m_nRecordLast; ++i) { response.WriteByte(table->m_GameRecordArrary[i].cbBanker); response.WriteByte(table->m_GameRecordArrary[i].cbTian); response.WriteByte(table->m_GameRecordArrary[i].cbDi); response.WriteByte(table->m_GameRecordArrary[i].cbXuan); response.WriteByte(table->m_GameRecordArrary[i].cbHuang); } } else { response.WriteShort(MAX_SCORE_HISTORY); num = MAX_SCORE_HISTORY; for (int i = 0; i < MAX_SCORE_HISTORY; ++i) { int index = (table->m_nRecordLast+i)%MAX_SCORE_HISTORY; response.WriteByte(table->m_GameRecordArrary[index].cbBanker); response.WriteByte(table->m_GameRecordArrary[index].cbTian); response.WriteByte(table->m_GameRecordArrary[index].cbDi); response.WriteByte(table->m_GameRecordArrary[index].cbXuan); response.WriteByte(table->m_GameRecordArrary[index].cbHuang); } } response.End(); _LOG_DEBUG_("<==[GetHistoryProc] [0x%04x]\n", cmd); _LOG_DEBUG_("[Data Response] retcode=[%d] retmsg=[%s]\n", 0, "ok"); _LOG_DEBUG_("[Data Response] uid=[%d]\n", player->id); _LOG_DEBUG_("[Data Response] num=[%d]\n", num); if(HallManager::getInstance()->sendToHall(player->m_nHallid, &response, false) < 0) _LOG_ERROR_("[GetHistoryProc] Send To Uid[%d] Error!\n", player->id); //else //_LOG_DEBUG_("[GetHistoryProc] Send To Uid[%d] Success\n", player->id); return 0; } int GetHistoryProc::doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) { _NOTUSED(clientHandler); _NOTUSED(inputPacket); _NOTUSED(pt); return 0; }
#include "core.h" template<typename Type> int* Minimal(Type* array, int size, int& minimal_quantity) { int* array_of_index = new int[size]; int minimal = 0; minimal_quantity = -1; for (int i = 0; i < size; i++) if (array[i] < array[minimal]) minimal = i; for (int i = 0; i < size; i++) if (array[i] == array[minimal]) { minimal_quantity++; array_of_index[minimal_quantity] = i; } return array_of_index; }
#include "QtExceL.h" #include <ole2.h> QtExcel::QtExcel() { m_pExcel = NULL; m_pWorkbooks = NULL; m_pWorkbook = NULL; m_pWorksheet = NULL; m_strXlsFile = ""; m_nRowCount = 0; m_nColumnCount = 0; m_nStartRow = 0; m_nStartColumn = 0; m_bIsOpen = false; m_bIsValid = false; m_bIsANewFile = false; m_bIsSaveAlready = false; HRESULT r = OleInitialize(0); if (r != S_OK && r != S_FALSE) { qDebug("Qt: Could not initialize OLE (error %x)", (unsigned int)r); } } QtExcel::QtExcel(QString xlsFile) { m_pExcel = NULL; m_pWorkbooks = NULL; m_pWorkbook = NULL; m_pWorksheet = NULL; m_strXlsFile = xlsFile; m_nRowCount = 0; m_nColumnCount = 0; m_nStartRow = 0; m_nStartColumn = 0; m_bIsOpen = false; m_bIsValid = false; m_bIsANewFile = false; m_bIsSaveAlready = false; HRESULT r = OleInitialize(0); if (r != S_OK && r != S_FALSE) { qDebug("Qt: Could not initialize OLE (error %x)", (unsigned int)r); } } QtExcel::~QtExcel() { if (m_bIsOpen) { //析构前,先保存数据,然后关闭workbook Close(); } OleUninitialize(); } bool QtExcel::Open(UINT nSheet, bool visible) { if (m_bIsOpen) { Close(); } m_nCurrSheet = nSheet; m_bIsVisible = visible; if (NULL == m_pExcel) { m_pExcel = new QAxObject("Excel.Application"); if (m_pExcel) { m_bIsValid = true; } else { m_bIsValid = false; m_bIsOpen = false; return m_bIsOpen; } m_pExcel->dynamicCall("SetVisible(bool)", m_bIsVisible); } if (!m_bIsValid) { m_bIsOpen = false; return m_bIsOpen; } if (m_strXlsFile.isEmpty()) { m_bIsOpen = false; return m_bIsOpen; } /*如果指向的文件不存在,则需要新建一个*/ QFile f(m_strXlsFile); if (!f.exists()) { m_bIsANewFile = true; } else { m_bIsANewFile = false; } if (!m_bIsANewFile) { m_pWorkbooks = m_pExcel->querySubObject("WorkBooks"); //获取工作簿 m_pWorkbook = m_pWorkbooks->querySubObject("Open(QString, QVariant)", m_strXlsFile, QVariant(0)); //打开xls对应的工作簿 } else { m_pWorkbooks = m_pExcel->querySubObject("WorkBooks"); //获取工作簿 m_pWorkbooks->dynamicCall("Add"); //添加一个新的工作薄 m_pWorkbook = m_pExcel->querySubObject("ActiveWorkBook"); //新建一个xls } m_pWorksheet = m_pWorkbook->querySubObject("WorkSheets(int)", m_nCurrSheet);//打开第一个sheet //至此已打开,开始获取相应属性 QAxObject *usedrange = m_pWorksheet->querySubObject("UsedRange"); //获取该sheet的使用范围对象 QAxObject *rows = usedrange->querySubObject("Rows"); QAxObject *columns = usedrange->querySubObject("Columns"); //因为excel可以从任意行列填数据而不一定是从0,0开始,因此要获取首行列下标 m_nStartRow = usedrange->property("Row").toInt(); //第一行的起始位置 m_nStartColumn = usedrange->property("Column").toInt(); //第一列的起始位置 m_nRowCount = rows->property("Count").toInt(); //获取行数 m_nColumnCount = columns->property("Count").toInt(); //获取列数 m_bIsOpen = true; return m_bIsOpen; } bool QtExcel::Open(QString xlsFile, UINT nSheet, bool visible) { m_strXlsFile = xlsFile; m_nCurrSheet = nSheet; m_bIsVisible = visible; return Open(m_nCurrSheet, m_bIsVisible); } void QtExcel::Save() { if (m_pWorkbook) { if (m_bIsSaveAlready) { return; } if (!m_bIsANewFile) { m_pWorkbook->dynamicCall("Save()"); } else /*如果该文档是新建出来的,则使用另存为COM接口*/ { m_pWorkbook->dynamicCall("SaveAs (const QString&,int,const QString&,const QString&,bool,bool)", m_strXlsFile, 56, QString(""), QString(""), false, false); } m_bIsSaveAlready = true; } } void QtExcel::SaveAs(QString path, bool isXls) { if (m_pWorkbook) { int XlFileFormat = isXls ? 56 : 51; if (m_bIsSaveAlready) { return; } else /*如果该文档是新建出来的,则使用另存为COM接口*/ { m_pWorkbook->dynamicCall("SaveAs (const QString&,int,const QString&,const QString&,bool,bool)", path, XlFileFormat, QString(""), QString(""), false, false); } m_bIsSaveAlready = true; } } void QtExcel::Close() { Save();//关闭前先保存数据 if (m_pExcel && m_pWorkbook) { m_pWorkbook->dynamicCall("Close(bool)", true); m_pExcel->dynamicCall("Quit()"); delete m_pExcel; m_pExcel = NULL; m_bIsOpen = false; m_bIsValid = false; m_bIsANewFile = false; m_bIsSaveAlready = true; } } QVariant QtExcel::GetCellData(UINT row, UINT column) { QVariant data; QAxObject *cell = m_pWorksheet->querySubObject("Cells(int,int)", row, column);//获取单元格对象 if (cell) { data = cell->dynamicCall("Value2()"); } return data; } QVariantList QtExcel::GetCellData(QString strRange) { QVariantList data; // strRange = "a1:C10" QAxObject *cell = m_pWorksheet->querySubObject("Range(QString)", strRange);//获取单元格对象 if (cell) { data = cell->property("Value").toList(); } return data; } bool QtExcel::SetCellData(UINT row, UINT column, QVariant data) { bool op = false; QAxObject *cell = m_pWorksheet->querySubObject("Cells(int,int)", row, column);//获取单元格对象 if (cell) { QString strData = data.toString(); //excel 居然只能插入字符串和整型,浮点型无法插入 cell->dynamicCall("SetValue(const QVariant&)", strData); //修改单元格的数据 op = true; } else { op = false; } return op; } void QtExcel::Clear() { m_strXlsFile = ""; m_nRowCount = 0; m_nColumnCount = 0; m_nStartRow = 0; m_nStartColumn = 0; } bool QtExcel::IsOpen() { return m_bIsOpen; } bool QtExcel::IsValid() { return m_bIsValid; }
/* sha1.cpp Copyright (c) 2005 Michael D. Leonhard http://tamale.net/ This file is licensed under the terms described in the accompanying LICENSE file. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <liblas/detail/sha1.hpp> namespace liblas { namespace detail { // print out memory in hexadecimal void SHA1::hexPrinter( unsigned char* c, int l ) { assert( c ); assert( l > 0 ); while( l > 0 ) { printf( " %02x", *c ); l--; c++; } } // circular left bit rotation. MSB wraps around to LSB Uint32 SHA1::lrot( Uint32 x, int bits ) { return (x<<bits) | (x>>(32 - bits)); }; // Save a 32-bit unsigned integer to memory, in big-endian order void SHA1::storeBigEndianUint32( unsigned char* byte, Uint32 num ) { assert( byte ); byte[0] = (unsigned char)(num>>24); byte[1] = (unsigned char)(num>>16); byte[2] = (unsigned char)(num>>8); byte[3] = (unsigned char)num; } // Constructor ******************************************************* SHA1::SHA1() { // make sure that the data type is the right size assert( sizeof( Uint32 ) * 5 == 20 ); // initialize H0 = 0x67452301; H1 = 0xefcdab89; H2 = 0x98badcfe; H3 = 0x10325476; H4 = 0xc3d2e1f0; unprocessedBytes = 0; size = 0; } // Destructor ******************************************************** SHA1::~SHA1() { // erase data H0 = H1 = H2 = H3 = H4 = 0; for( int c = 0; c < 64; c++ ) bytes[c] = 0; unprocessedBytes = size = 0; } // process *********************************************************** void SHA1::process() { assert( unprocessedBytes == 64 ); //printf( "process: " ); hexPrinter( bytes, 64 ); printf( "\n" ); int t; Uint32 a, b, c, d, e, K, f, W[80]; // starting values a = H0; b = H1; c = H2; d = H3; e = H4; // copy and expand the message block for( t = 0; t < 16; t++ ) W[t] = (bytes[t*4] << 24) +(bytes[t*4 + 1] << 16) +(bytes[t*4 + 2] << 8) + bytes[t*4 + 3]; for(; t< 80; t++ ) W[t] = lrot( W[t-3]^W[t-8]^W[t-14]^W[t-16], 1 ); /* main loop */ Uint32 temp; for( t = 0; t < 80; t++ ) { if( t < 20 ) { K = 0x5a827999; f = (b & c) | ((b ^ 0xFFFFFFFF) & d);//TODO: try using ~ } else if( t < 40 ) { K = 0x6ed9eba1; f = b ^ c ^ d; } else if( t < 60 ) { K = 0x8f1bbcdc; f = (b & c) | (b & d) | (c & d); } else { K = 0xca62c1d6; f = b ^ c ^ d; } temp = lrot(a,5) + f + e + W[t] + K; e = d; d = c; c = lrot(b,30); b = a; a = temp; //printf( "t=%d %08x %08x %08x %08x %08x\n",t,a,b,c,d,e ); } /* add variables */ H0 += a; H1 += b; H2 += c; H3 += d; H4 += e; //printf( "Current: %08x %08x %08x %08x %08x\n",H0,H1,H2,H3,H4 ); /* all bytes have been processed */ unprocessedBytes = 0; } // addBytes ********************************************************** void SHA1::addBytes( const char* data, int num ) { assert( data ); assert( num > 0 ); // add these bytes to the running total size += num; // repeat until all data is processed while( num > 0 ) { // number of bytes required to complete block int needed = 64 - unprocessedBytes; assert( needed > 0 ); // number of bytes to copy (use smaller of two) int toCopy = (num < needed) ? num : needed; // Copy the bytes memcpy( bytes + unprocessedBytes, data, toCopy ); // Bytes have been copied num -= toCopy; data += toCopy; unprocessedBytes += toCopy; // there is a full block if( unprocessedBytes == 64 ) process(); } } // digest ************************************************************ unsigned char* SHA1::getDigest() { // save the message size Uint32 totalBitsL = size << 3; Uint32 totalBitsH = size >> 29; // add 0x80 to the message addBytes( "\x80", 1 ); unsigned char footer[64] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // block has no room for 8-byte filesize, so finish it if( unprocessedBytes > 56 ) addBytes( (char*)footer, 64 - unprocessedBytes); assert( unprocessedBytes <= 56 ); // how many zeros do we need int neededZeros = 56 - unprocessedBytes; // store file size (in bits) in big-endian format storeBigEndianUint32( footer + neededZeros , totalBitsH ); storeBigEndianUint32( footer + neededZeros + 4, totalBitsL ); // finish the final block addBytes( (char*)footer, neededZeros + 8 ); // allocate memory for the digest bytes unsigned char* digest = (unsigned char*)malloc( 20 ); // copy the digest bytes storeBigEndianUint32( digest, H0 ); storeBigEndianUint32( digest + 4, H1 ); storeBigEndianUint32( digest + 8, H2 ); storeBigEndianUint32( digest + 12, H3 ); storeBigEndianUint32( digest + 16, H4 ); // return the digest return digest; } }} // liblas::detail
#include<iostream> #include<cstdlib> using namespace std; class Queue { struct node { int data; node* link; }*front,*rear; public: Queue(); void addNode(int); void deleteNode(); void display(); }; Queue::Queue() { front = NULL; rear = NULL; } void Queue::deleteNode() { if(front == NULL) { cout << "Invalid deletion" << endl; } else { node* temp; temp = front; front = front->link; cout << "deleted " << temp->data << endl; delete temp; } } void Queue::addNode(int x) { node *temp; temp = new node; temp->data = x; temp->link = NULL; if(front == NULL) { front = temp; rear = temp; } else { rear->link = temp; rear = temp; } } void Queue::display() { node* temp; temp = front; while(front != NULL) { cout << front->data << " "; temp = front; front = front->link; delete temp; } } int main() { Queue q; q.addNode(10); q.addNode(20); q.addNode(30); q.addNode(40); q.addNode(50); q.deleteNode(); q.deleteNode(); q.display(); system("pause"); return 0; }
/* replay Software Library Copyright (c) 2010-2019 Marius Elvert Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <deque> #include <mutex> #include <condition_variable> #include <optional> namespace replay { /** Single-producer, single-consumer concurrent queue. */ template <class T> class concurrent_queue { public: void push(T value) { std::unique_lock<std::mutex> lock(m_mutex); m_queue.push_back(std::move(value)); m_push_signal.notify_one(); } void push(T value, std::size_t max_size) { std::unique_lock<std::mutex> lock(m_mutex); if (m_queue.size() >= max_size) { m_pop_signal.wait(lock, [this, max_size] { return m_queue.size() < max_size; }); } m_queue.push_back(std::move(value)); m_push_signal.notify_one(); } T pop() { std::unique_lock<std::mutex> lock(m_mutex); if (m_queue.empty()) { m_push_signal.wait(lock, [this] { return !m_queue.empty(); }); } T result = std::move(m_queue.front()); m_queue.pop_front(); m_pop_signal.notify_one(); return result; } std::optional<T> pop_optional() { std::unique_lock<std::mutex> lock(m_mutex); if (m_queue.empty()) { return {}; } auto value = std::move(m_queue.front()); m_queue.pop_front(); m_pop_signal.notify_one(); return std::make_optional(std::move(value)); } private: std::mutex m_mutex; std::condition_variable m_push_signal; std::condition_variable m_pop_signal; std::deque<T> m_queue; }; } // namespace replay
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #if defined UPDATERS_ENABLE_MANAGER #include "modules/updaters/update_man.h" AutoFetch_Element::~AutoFetch_Element() { if(InList()) Out(); } void AutoFetch_Element::PostFinished(MH_PARAM_2 result) { finished = TRUE; if(finished_msg != MSG_NO_MESSAGE) g_main_message_handler->PostMessage(finished_msg, Id(), result); } void AutoFetch_Manager::InitL() { } void AutoFetch_Manager::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { AutoFetch_Element *item, *next_item; next_item = (AutoFetch_Element *) updaters.First(); if(next_item) { while(next_item) { item = next_item; next_item = next_item->Suc(); if(item->Id() == par1 || item->IsFinished()) { OP_DELETE(item); break; } } if(updaters.Empty()) OnAllUpdatersFinished(); } } void AutoFetch_Manager::OnAllUpdatersFinished() { if(updaters.Empty() && fin_msg != MSG_NO_MESSAGE) g_main_message_handler->PostMessage(fin_msg, fin_id,0); } OP_STATUS AutoFetch_Manager::AddUpdater(AutoFetch_Element *new_updater, BOOL is_started) { if(new_updater) { if(!is_started) { OP_STATUS op_err = new_updater->StartLoading(); if(OpStatus::IsError(op_err)) { OP_DELETE(new_updater); return op_err; } } new_updater->Into(&updaters); return OpStatus::OK; } return OpStatus::ERR_NULL_POINTER; } #ifdef UPDATERS_ENABLE_MANAGER_CLEANUP void AutoFetch_Manager::Cleanup() { AutoFetch_Element *item, *next_item; next_item = (AutoFetch_Element *) updaters.First(); if(next_item) { while(next_item) { item = next_item; next_item = next_item->Suc(); if(item->IsFinished()) { OP_DELETE(item); break; } } if(updaters.Empty() && fin_msg != MSG_NO_MESSAGE) g_main_message_handler->PostMessage(fin_msg, 0,0); } } #endif #endif
#pragma once #include "Analysis.hpp" #include "Bispectrum.hpp" #include "LISW.hpp" #include "Helper.hpp" #include <armadillo> #include <string> #include "stdafx.h" #include "interpolation.h" #include <fstream> using namespace alglib; using namespace arma; using namespace std; class Bispectrum_Fisher { public: Bispectrum_Fisher(AnalysisInterface* analysis, Bispectrum_LISW* LISW, Bispectrum* NLG,\ vector<string> param_keys_considered, string fisherPath); ~Bispectrum_Fisher(); double compute_F_matrix(double nu_min, double nu_stepsize,\ int n_points_per_thread, int n_threads, Bispectrum_Effects effects, bool limber); /** * This function computes the Fisher elements in all frequency bins for all parameter combinations * using parallelization at the level of the frequency bin rather than the l modes. It is therefore * important to have the number of frequency bins in the analysis to be a multiple op the cores used * for optimal usage. Basically, otherwise there will be idle cores waiting for longer computations * to finish. */ double compute_F_matrix_parallel_nu(double nu_min, double nu_stepsize,\ int n_points_per_thread, int n_threads, Bispectrum_Effects effects, bool limber); virtual double compute_Fnu(double nu, string param_key1, string param_key2,\ int *Pk_index, int *Tb_index, int *q_index, Bispectrum_Effects effects, bool limber); spline1dinterpolant compute_Fl_interpolator(double nu, string param_key1, string param_key2,\ int *Pk_index, int *Tb_index, int *q_index, Bispectrum_Effects effects, bool limber); virtual double Fisher_element(int l1, int l2, int l3, double nu, string param_key1, string param_key2,\ int *Pk_index, int *Tb_index, int *q_index, Bispectrum_Effects effects, bool limber,\ vector<mu_data>& data_vector1, vector<mu_data>& data_vector2); virtual double Fisher_element(int l1, int l2, int l3, double nu, string param_key1, string param_key2,\ int *Pk_index, int *Tb_index, int *q_index, Bispectrum_Effects effects, bool limber); vector<double> set_range(int l, double xmin, double xmax); // this needs to be here for test-suite purposes. map<string,double> fiducial_params, var_params; vector<string> model_param_keys; //protected: // same as calc_mu but doesn't rely on any interpolation. double calc_mu_direct(int l1, int l2, int l3, double nu, double nu_stepsize,double deriv, string param_key,\ int *Pk_index, int *Tb_index, int *q_index, Bispectrum_Effects effects, bool limber); virtual double calc_mu(int l1, int l2, int l3, double nu, string param_key,\ int *Pk_index, int *Tb_index, int *q_index, Bispectrum_Effects effects, bool limber,\ vector<mu_data>& data_vector); virtual double calc_mu(int l1, int l2, int l3, double nu, string param_key,\ int *Pk_index, int *Tb_index, int *q_index, Bispectrum_Effects effects, bool limber); double Cl(int l, double nu); double Cl_fg(int l, double nu); bool mu_computed(int l1, int l2, int l3,int nu, string param_key); void read_mu_data_from_file(vector<mu_data>& data_vector, int nu, string param_key); double calc_mu_read(int l1, int l2, int l3, int nu, string param_key, vector<mu_data>& data_vector); ofstream time_file; AnalysisInterface* analysis; Bispectrum_LISW* LISW; Bispectrum* NLG; bool interpolation_done; int lmax_CLASS; int nu_steps_CLASS; double nu_min_CLASS, nu_stepsize_CLASS; string fisherPath; }; class TEST_Bispectrum_Fisher : public Bispectrum_Fisher { public: TEST_Bispectrum_Fisher(AnalysisInterface* analysis, Bispectrum_LISW* LISW, Bispectrum* NLG,\ vector<string> param_keys_considered, string fisherPath); ~TEST_Bispectrum_Fisher(); double Fisher_element(int l1, int l2, int l3, double nu, string param_key1, string param_key2,\ int *Pk_index, int *Tb_index, int *q_index, Bispectrum_Effects effects, bool limber) override; double calc_mu(int l1, int l2, int l3, double nu, string param_key,\ int *Pk_index, int *Tb_index, int *q_index, Bispectrum_Effects effects, bool limber) override; double compute_Fnu(double nu, string param_key1, string param_key2,\ int *Pk_index, int *Tb_index, int *q_index, Bispectrum_Effects effects, bool limber) override; };
#include <iostream> using namespace std; int main() { long long t, x, y; cin >> t; for (int i = 0; i < t; i++) { cin >> x >> y; cout << x << " " << x * 2 << endl; } }
#pragma once #include "led.h" #include <stdexcept> #include <iostream> #include <Windows.h> SetUrl_t * SetUrl; SetLed_t * SetLed; Clear_t * Clear; Show_t * Show; Wait_t * Wait; SetChar_t * SetChar; ShowMotioningText1_t * ShowMotioningText1; ShowFirework_t * ShowFirework; inline void loadLibrary(const char * lib) { HMODULE mod = LoadLibraryA(lib); if(0 == mod){ throw std::runtime_error("Failed to load library"); } SetUrl = reinterpret_cast<SetUrl_t*>(GetProcAddress(mod, "SetUrl")); SetLed = reinterpret_cast<SetLed_t*>(GetProcAddress(mod, "SetLed")); Clear = reinterpret_cast<Clear_t*>(GetProcAddress(mod, "Clear")); Show = reinterpret_cast<Show_t*>(GetProcAddress(mod, "Show")); Wait = reinterpret_cast<Wait_t*>(GetProcAddress(mod, "Wait")); SetChar = reinterpret_cast<SetChar_t*>(GetProcAddress(mod, "SetChar")); ShowMotioningText1 = reinterpret_cast<ShowMotioningText1_t*>(GetProcAddress(mod, "ShowMotioningText1")); ShowFirework = reinterpret_cast<ShowFirework_t*>(GetProcAddress(mod, "ShowFirework")); }
// ----------------------------------------------------------------------------- // G4_QPIX | TrackingSD.cpp // // TODO: Class description // * Author: Justo Martin-Albo // * Creation date: 13 Feb 2019 // ----------------------------------------------------------------------------- #include "TrackingSD.h" #include "TrackingHit.h" // Q-Pix includes #include "MCTruthManager.h" #include "MCParticle.h" // GEANT4 includes #include "G4SDManager.hh" #include "G4SystemOfUnits.hh" #include <G4OpticalPhoton.hh> #include "G4VProcess.hh" // C++ includes #include <vector> TrackingSD::TrackingSD(const G4String& sd_name, const G4String& hc_name): G4VSensitiveDetector(sd_name), Event_Cutoff_(0.0) // hc_(nullptr) { collectionName.insert(hc_name); msg_ = new G4GenericMessenger(this, "/Supernova/", "Control commands of the supernova generator."); msg_->DeclareProperty("Event_Cutoff", Event_Cutoff_, "window to simulate the times").SetUnit("ns"); } TrackingSD::~TrackingSD() { delete msg_; } // void TrackingSD::Initialize(G4HCofThisEvent* hce) // { // // Create hits collection // hc_ = new TrackingHitsCollection(SensitiveDetectorName, collectionName[0]); // // Add this collection in hce // G4int hcid = G4SDManager::GetSDMpointer()->GetCollectionID(collectionName[0]); // hce->AddHitsCollection(hcid, hc_); // } G4bool TrackingSD::ProcessHits(G4Step* aStep, G4TouchableHistory*) { G4Track* track = aStep->GetTrack(); if (track->GetParticleDefinition() == G4OpticalPhoton::Definition()) return false; G4double edep = aStep->GetTotalEnergyDeposit(); if (edep==0.) return false; // if (edep < 1. *keV ) return false; if (Event_Cutoff_ != 0.0) { // G4StepPoint* preStepPoint = aStep->GetPreStepPoint(); G4StepPoint* preStepPoint = aStep->GetPostStepPoint(); G4double hitTime = preStepPoint->GetGlobalTime(); // if (hitTime<0. || hitTime>Event_Cutoff_) return false; if (hitTime>Event_Cutoff_) return false; } //--------------------------------------------------------------------------- // begin add hit to MCParticle //--------------------------------------------------------------------------- // get MC truth manager MCTruthManager * mc_truth_manager = MCTruthManager::Instance(); // get MC particle MCParticle * particle = mc_truth_manager->GetMCParticle(aStep->GetTrack()->GetTrackID()); // add hit to MC particle particle->AddTrajectoryHit(aStep); // G4double time = aStep->GetPostStepPoint()->GetGlobalTime()/CLHEP::ns; // G4double MyX = aStep->GetPostStepPoint()->GetPosition().x()/CLHEP::cm; // G4double MyY = aStep->GetPostStepPoint()->GetPosition().y()/CLHEP::cm; // G4double MyZ = aStep->GetPostStepPoint()->GetPosition().z()/CLHEP::cm; // G4double MyE = aStep->GetTotalEnergyDeposit() / CLHEP::MeV; // G4String pro = aStep->GetPostStepPoint()->GetProcessDefinedStep()->GetProcessName(); // G4cout << "HIT TIME, " << time <<"\t"<< MyX <<"\t"<< MyY <<"\t"<< MyZ <<"\t"<< MyE <<"\t"<< pro << G4endl; //--------------------------------------------------------------------------- // end add hit to MCParticle //--------------------------------------------------------------------------- return true; } // void TrackingSD::EndOfEvent(G4HCofThisEvent*) // { // G4int nofHits = hc_->entries(); // G4cout // << G4endl // << "-------->Hits Collection: in this event there are " << nofHits // << " hits in the tracker." << G4endl; // }
#include <stdio.h> void main() { int a,q=1,w,N; do { printf("enter number of kuan\n"); scanf("%d",&N); while(w<=N) { printf("%d ",q); q=q*w; } printf("\ntry again?"); scanf("%d",&a); }while (a==1); }
#define _CRT_SECURE_NO_WARNINGS #include <SFML/Graphics.hpp> #include <zmq.hpp> #include <string> #include <iostream> #include <windows.h> #include "gameTime.h" #include "GameObject.h" #include "positionComponents.h" #include "colorComponents.h" #include "sizeComponents.h" #include "movementComponents.h" #include "Event.h" #include "eventHandler.h" #include "charEventHandler.h" #include "collisionEvent.h" #include "platfEventHandler.h" #include "deathEvent.h" #include "spawnEvent.h" #include "userInputEvent.h" #include "eventManager.h" #include "scriptEvent.h" #include "ScriptManager.h" #include "scriptObject.h" using namespace std; // Reference: http://zguide.zeromq.org/page:all std::string s_recv(zmq::socket_t& socket) { zmq::message_t message; socket.recv(message); return std::string(static_cast<char*>(message.data()), message.size()); } // Reference: http://zguide.zeromq.org/page:all void s_send(zmq::socket_t& socket, const std::string& string) { zmq::message_t message(string.size()); memcpy(message.data(), string.data(), string.size()); socket.send(message, zmq::send_flags::dontwait); } // Reference: http://zguide.zeromq.org/page:all void s_sendmore(zmq::socket_t& socket, const std::string& string) { zmq::message_t message(string.size()); memcpy(message.data(), string.data(), string.size()); socket.send(message, zmq::send_flags::sndmore); } // globle boolean variable to detect collision bool upcoli; bool downcoli; bool leftcoli; bool rightcoli; bool targetupcoli; bool targetdowncoli; bool targetleftcoli; bool targetrightcoli; bool pause = false; bool unpause = false; float scale = 1.0; int halfSpeed = 0; int normalSpeed = 1; int doubleSpeed = 0; int left_count = 0; int right_count = 0; int up_count = 0; int down_count = 0; //recording bool isrecording; bool isReplay; sf::Vector2f startRecPosition; bool scriptingEnable = false; // instances of needed components sizeComponents upWallSize(800.f, 10.f); sizeComponents side_boundarySize(10.f, 600.f); sizeComponents death_zoneSize(1600.f, 1.f); sizeComponents groundSize(300.f, 100.f); sizeComponents characterSize(30.0f, 30.0f); sizeComponents movingPlatformSize(100.f, 10.f); sizeComponents cloudSize(200.f, 100.f); positionComponents side_boundary_leftPos(0.f, 0.f); positionComponents side_boundary_rightPos(400.f, 0.f); positionComponents upWallPos(0.f, 250.f); positionComponents rightWallPos(790.f, 0.f); positionComponents death_zonePos(0.f, 599.f); positionComponents groundPos(0.f, 500.f); positionComponents characterPos(20.f, 465.f); positionComponents movingPlatformPos1(400.f, 400.f); positionComponents movingPlatformPos2(650.f, 550.f); positionComponents SpawnPos(200.f, 465.f); positionComponents cloudpos(150.f, 30.f); colorComponents wallColor(128, 128, 128); colorComponents charactorColor(0, 255, 0); colorComponents movingPlatformColor(255, 0, 0); sizeComponents level2_Ground_size(300.f, 50.f); positionComponents level2_Ground_pos(900.f, 200.f); int main() { sf::RenderWindow window(sf::VideoMode(800, 600), "zmei_HW"); zmq::context_t context(1); zmq::socket_t subscriber(context, ZMQ_SUB); subscriber.connect("tcp://localhost:5563"); subscriber.setsockopt(ZMQ_SUBSCRIBE, "1", 1); zmq::socket_t client(context, ZMQ_REQ); client.connect("tcp://localhost:5564"); s_send(client, ""); std::string str = s_recv(client); int time = 0; std::string control = ""; int step_size = 500; float fps = 60; int period = 1000 / fps; float velocity = step_size / fps; sf::Texture cloud_t; cloud_t.loadFromFile("cloud.png"); // Reference: pngimg.com/download/4323 //sf::Texture tank; //tank.loadFromFile("tank.png"); // Reference: pngimg.com/download/4323 // create multiple staticPlatforms GameObject staticPlatform1; // left wall staticPlatform1.setSizeComponent(side_boundarySize); staticPlatform1.setPositionComponent(side_boundary_leftPos); staticPlatform1.setColorComponent(wallColor); GameObject staticPlatform2; // up wall staticPlatform2.setSizeComponent(upWallSize); staticPlatform2.setPositionComponent(upWallPos); staticPlatform2.setColorComponent(wallColor); GameObject staticPlatform5; // platform staticPlatform5.setSizeComponent(groundSize); staticPlatform5.setPositionComponent(groundPos); staticPlatform5.setColorComponent(wallColor); // create side_boundary object GameObject side_boundary; // side_boundary side_boundary.setSizeComponent(side_boundarySize); side_boundary.setPositionComponent(rightWallPos); // create death_zone object GameObject death_zone; // death zone death_zone.setSizeComponent(death_zoneSize); death_zone.setPositionComponent(death_zonePos); death_zone.setColorComponent(wallColor); // create characters GameObject character; character.setSizeComponent(characterSize); character.setPositionComponent(characterPos); character.setColorComponent(charactorColor); // create movingPlatforms GameObject movingPlatform1; movingPlatform1.setSizeComponent(movingPlatformSize); movingPlatform1.setPositionComponent(movingPlatformPos1); movingPlatform1.setColorComponent(movingPlatformColor); GameObject movingPlatform2; movingPlatform2.setSizeComponent(movingPlatformSize); movingPlatform2.setPositionComponent(movingPlatformPos2); movingPlatform2.setColorComponent(movingPlatformColor); GameObject cloud; cloud.setSizeComponent(cloudSize); cloud.setPositionComponent(cloudpos); //cloud.setColorComponent(movingPlatformColor); // Spawn points GameObject SpawnPoints; SpawnPoints.setSizeComponent(characterSize); SpawnPoints.setPositionComponent(SpawnPos); SpawnPoints.setColorComponent(charactorColor); // objects for level 2 GameObject staticPlatform6; // platform staticPlatform6.setSizeComponent(level2_Ground_size); staticPlatform6.setPositionComponent(level2_Ground_pos); staticPlatform6.setColorComponent(wallColor); GameObject staticPlatform7; // ground staticPlatform7.setSizeComponent(groundSize); staticPlatform7.setPositionComponent(level2_Ground_pos); staticPlatform7.setColorComponent(wallColor); eventManager em; vector<Event*> eventQueue = em.getQueue(); while (window.isOpen()) { gameTime gt = gameTime(step_size); eventHandler* eh_character = new charEventHandler(); Event* coli_ground_1 = new collisionEvent(character, staticPlatform5); Event* coli_ground_2 = new collisionEvent(character, staticPlatform6); Event* coli_ground_3 = new collisionEvent(character, staticPlatform7); Event* coli_mvplatf_1 = new collisionEvent(character, movingPlatform1); Event* coli_mvplatf_2 = new collisionEvent(character, movingPlatform2); Event* coli_sideBound_left = new collisionEvent(character, staticPlatform1); Event* coli_sideBound_right = new collisionEvent(character, side_boundary); Event* char_death = new deathEvent(character, death_zone); Event* char_spawn = new spawnEvent(character, SpawnPoints); Event* key_Left = new userInputEvent(sf::Keyboard::Key::Left); Event* key_Right = new userInputEvent(sf::Keyboard::Key::Right); Event* key_Up = new userInputEvent(sf::Keyboard::Key::Up); Event* key_Down = new userInputEvent(sf::Keyboard::Key::Down); Event* key_Space = new userInputEvent(sf::Keyboard::Key::Space); Event* key_R = new userInputEvent(sf::Keyboard::Key::R); Event* key_S = new userInputEvent(sf::Keyboard::Key::S); Event* key_E = new userInputEvent(sf::Keyboard::Key::E); Event* key_M = new userInputEvent(sf::Keyboard::Key::M); eventHandler* eh_platform = new platfEventHandler(); Event* mvp1_coli_char = new collisionEvent(movingPlatform1, character); Event* mvp1_coli_upwall = new collisionEvent(movingPlatform1, staticPlatform2); Event* mvp1_coli_downwall = new collisionEvent(movingPlatform1, death_zone); Event* mvp2_coli_char = new collisionEvent(movingPlatform2, character); Event* mvp2_coli_upwall = new collisionEvent(movingPlatform2, staticPlatform2); Event* mvp2_coli_downwall = new collisionEvent(movingPlatform2, death_zone); Event* cloud_coli_left = new collisionEvent(cloud, staticPlatform1); Event* cloud_coli_right = new collisionEvent(cloud, side_boundary); Event* scriptOn = new scriptEvent(); // walls sf::RectangleShape side_boundary_left = staticPlatform1.drawObject(); sf::RectangleShape wall_2 = staticPlatform2.drawObject(); // Ground sf::RectangleShape ground_1 = staticPlatform5.drawObject(); // right side boundary sf::RectangleShape side_boundary_right = side_boundary.drawObject(); // death_zone_1 sf::RectangleShape death_zone_1 = death_zone.drawObject(); // character sf::RectangleShape character_1 = character.drawObject(); //character_1.setTexture(&tank); //character_1.setScale(1.5, 1.5); // Spawn Point 1 sf::RectangleShape SpawnPoints_1 = SpawnPoints.drawObject(); // moving platform sf::RectangleShape movePlatform_1 = movingPlatform1.drawObject(); sf::RectangleShape movePlatform_2 = movingPlatform2.drawObject(); sf::RectangleShape cloud_1 = cloud.drawObject(); cloud_1.setTexture(&cloud_t); // level 2 sf::RectangleShape ground_2 = staticPlatform6.drawObject(); sf::RectangleShape ground_3 = staticPlatform7.drawObject(); sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } if (halfSpeed == 1) { if (eh_character->onEvent(key_Space)) { // sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Space) halfSpeed = 0; normalSpeed = 1; doubleSpeed = 0; scale = 0.5; } } else if (normalSpeed == 1) { if (eh_character->onEvent(key_Space)) { halfSpeed = 0; normalSpeed = 0; doubleSpeed = 1; scale = 1.0; } } else if (doubleSpeed == 1) { if (eh_character->onEvent(key_Space)) { halfSpeed = 1; normalSpeed = 0; doubleSpeed = 0; scale = 2.0; } } if (pause == true) { velocity = 0; } else { velocity = scale * step_size / fps; } // start/end recording if (eh_character->onEvent(key_S)) { isrecording = true; std::cout << "Start Recording!!!!" << std::endl; // record start position startRecPosition = character.drawObject().getPosition(); } if (eh_character->onEvent(key_E)) { isrecording = false; std::cout << "End Recording!!!!" << std::endl; } // press M to enable scripting for character if (eh_character->onEvent(key_M) && scriptingEnable == false) { if (eh_character->onEvent(scriptOn)) { std::cout << "Scripting Enabled!" << std::endl; // call scriptManager ScriptManager sm; sm.scriptChangeColor(); colorComponents new_color_fromScript(sm.getR_fromScript(), sm.getG_fromScript(), sm.getB_fromScript()); sizeComponents new_size_fromScript(sm.getLength_fromScript(), sm.getWidth_fromScript()); character.setColorComponent(new_color_fromScript); character.setSizeComponent(new_size_fromScript); } scriptingEnable = true; } string s = ""; if (eh_character->onEvent(key_Left)) { // sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left) if (isrecording == true) { eventQueue.push_back(key_Left); } s = "l"; } else if (eh_character->onEvent(key_Right)) { // sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right) if (isrecording == true) { eventQueue.push_back(key_Right); } s = "r"; } else if (eh_character->onEvent(key_Up)) { // sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up) if (isrecording == true) { eventQueue.push_back(key_Up); } s = "u"; } else if (eh_character->onEvent(key_Down)) { // sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down) if (isrecording == true) { eventQueue.push_back(key_Down); } s = "d"; } //std::cout << s << std::endl; s_send(client, s); string res = s_recv(client); //std::cout << res << std::endl; string m = s_recv(subscriber); string sub = s_recv(subscriber); //std::cout << sub << std::endl; if (sub.compare("l") == 0) { character.updateLeft(velocity); } else if (sub.compare("r") == 0) { character.updateRight(velocity); } else if (sub.compare("u") == 0) { character.updateUp(velocity); } else if (sub.compare("d") == 0) { if (eh_character->onEvent(coli_ground_1)) { // character_1.getGlobalBounds().intersects(ground_1.getGlobalBounds()) //std::cout << "Collision!" << std::endl; } else if (eh_character->onEvent(coli_ground_2)) { // character_1.getGlobalBounds().intersects(ground_2.getGlobalBounds()) //std::cout << "Collision!" << std::endl; } else if (eh_character->onEvent(coli_ground_3)) { // character_1.getGlobalBounds().intersects(ground_3.getGlobalBounds()) //std::cout << "Collision!" << std::endl; } else { character.updateDown(velocity); } } else { if (eh_character->onEvent(char_death)) { // character_1.getGlobalBounds().intersects(death_zone_1.getGlobalBounds()) //std::cout << character_1.getPosition().y << std::endl; std::cout << "You dead!" << std::endl; std::cout << "Start again at the spawn point!!" << std::endl; } if (eh_character->onEvent(coli_ground_1)) { // character_1.getGlobalBounds().intersects(ground_1.getGlobalBounds()) //std::cout << "Collision!" << std::endl; } else if (eh_character->onEvent(coli_ground_2)) { // character_1.getGlobalBounds().intersects(ground_2.getGlobalBounds()) //std::cout << "Collision!" << std::endl; } else if (eh_character->onEvent(coli_ground_3)) { // character_1.getGlobalBounds().intersects(ground_3.getGlobalBounds()) //std::cout << "Collision!" << std::endl; } else if (eh_character->onEvent(coli_mvplatf_1)) { // character_1.getGlobalBounds().intersects(movePlatform_1.getGlobalBounds()) //std::cout << "Collision!" << std::endl; } else if (eh_character->onEvent(coli_mvplatf_2)) { // character_1.getGlobalBounds().intersects(movePlatform_2.getGlobalBounds()) //std::cout << "Collision!" << std::endl; } else if (!eh_character->onEvent(char_death)) { // !character_1.getGlobalBounds().intersects(death_zone_1.getGlobalBounds()) character.updateDown(velocity); } else { if (eh_character->onEvent(char_spawn)) { character.resetPosition(SpawnPoints_1.getPosition().x, SpawnPoints_1.getPosition().y); } } } // Moving platform1 start from up to down if (eh_platform->onEvent(mvp1_coli_upwall)) { // movePlatform_1.getGlobalBounds().intersects(wall_2.getGlobalBounds()) upcoli = true; downcoli = false; } else if (eh_platform->onEvent(mvp1_coli_downwall)) { // movePlatform_1.getGlobalBounds().intersects(death_zone_1.getGlobalBounds()) downcoli = true; upcoli = false; } if (upcoli == true) { movingPlatform1.updateDown(velocity); if (downcoli == true) { upcoli = false; } } else { if (eh_platform->onEvent(mvp1_coli_char)) { // movePlatform_1.getGlobalBounds().intersects(character_1.getGlobalBounds()) //std::cout << "Collision!" << std::endl; character.updateUp(velocity); } else { movingPlatform1.updateUp(velocity); } } // Moving platform2 start from down to up if (eh_platform->onEvent(mvp2_coli_upwall)) { // movePlatform_2.getGlobalBounds().intersects(wall_2.getGlobalBounds()) targetupcoli = true; targetdowncoli = false; } else if (eh_platform->onEvent(mvp2_coli_downwall)) { // movePlatform_2.getGlobalBounds().intersects(death_zone_1.getGlobalBounds()) targetdowncoli = true; targetupcoli = false; } if (targetdowncoli == true) { if (eh_platform->onEvent(mvp2_coli_char)) { // movePlatform_2.getGlobalBounds().intersects(character_1.getGlobalBounds()) //std::cout << "Collision!" << std::endl; character.updateUp(velocity); } else { movingPlatform2.updateUp(velocity); } if (targetupcoli == true) { targetdowncoli = false; } } else { movingPlatform2.updateDown(velocity); } // cloud move from left to right if (eh_platform->onEvent(cloud_coli_left)) { // cloud_1.getGlobalBounds().intersects(side_boundary_left.getGlobalBounds()) targetleftcoli = true; targetrightcoli = false; } else if (eh_platform->onEvent(cloud_coli_right)) { // cloud_1.getGlobalBounds().intersects(side_boundary_right.getGlobalBounds()) targetrightcoli = true; targetleftcoli = false; } if (targetleftcoli == true) { cloud.updateRight(4); if (targetrightcoli == true) { targetleftcoli = false; } } else { cloud.updateLeft(4); } if (eh_character->onEvent(coli_sideBound_right)) { // character_1.getGlobalBounds().intersects(side_boundary_right.getGlobalBounds()) positionComponents p(-1000.f, -1000.f); positionComponents p2(300.f, 300.f); positionComponents p3(300.f, 270.f); positionComponents p4(0.f, 500.f); staticPlatform5.setPositionComponent(p); movingPlatform1.setPositionComponent(p); movingPlatform2.setPositionComponent(p); staticPlatform6.setPositionComponent(p2); staticPlatform7.setPositionComponent(p4); character.setPositionComponent(p3); } if (eh_character->onEvent(coli_sideBound_left)) { // character_1.getGlobalBounds().intersects(side_boundary_left.getGlobalBounds()) staticPlatform5.setPositionComponent(groundPos); movingPlatform1.setPositionComponent(movingPlatformPos1); movingPlatform2.setPositionComponent(movingPlatformPos2); staticPlatform6.setPositionComponent(level2_Ground_pos); staticPlatform7.setPositionComponent(level2_Ground_pos); character.setPositionComponent(SpawnPos); } if (eventQueue.size() != 0) { for (auto i = eventQueue.begin(); i != eventQueue.end(); i++) { if (*i == key_Left) { left_count++; std::cout << "record_left" << std::endl; } else if (*i == key_Right) { right_count++; std::cout << "record_right" << std::endl; } else if (*i == key_Up) { up_count++; std::cout << "record_up" << std::endl; } else if (*i == key_Down) { down_count++; std::cout << "record_down" << std::endl; } } } // Event about replay if (eh_character->onEvent(key_R) && eventQueue.size() != 0) { std::cout << "Replaying!!!!" << std::endl; character.resetPosition(startRecPosition.x, startRecPosition.y); isReplay = true; } else if (isReplay && eventQueue.size() != 0) { for (int a = left_count; a > 0; a--) { character.updateLeft(velocity); } for (int b = right_count; b > 0; b--) { character.updateRight(velocity); } for (int c = up_count; c > 0; c--) { character.updateUp(velocity); } for (int d = down_count; d > 0; d--) { character.updateDown(velocity); } // remove all events after each replay eventQueue.clear(); left_count = 0; right_count = 0; up_count = 0; down_count = 0; isReplay = false; } int deltaT = gt.getTime(); //std::cout << deltaT << std::endl; window.clear(); //window.draw(side_boundary_left); //window.draw(wall_2); //window.draw(side_boundary_right); //window.draw(death_zone_1); window.draw(ground_1); window.draw(ground_2); window.draw(ground_3); //std::cout << character_1.getPosition().x << " : " << character_1.getPosition().y << std::endl; window.draw(character_1); window.draw(movePlatform_1); window.draw(movePlatform_2); window.draw(cloud_1); //window.draw(SpawnPoints_1); window.display(); if (deltaT <= period) { Sleep(period - deltaT); } else if (deltaT > period) { Sleep(2 * period - deltaT); } } return 0; }
// // Created by micky on 15. 5. 24. // #include "Timer.h"
// // FriendCAPI.cpp // SwitchServer // // Created by Joel Liang on 2018/9/1. // #include <stdio.h> #include <elastos/core/Object.h> #include "ElastosCore.h" #include "elatypes.h" #include "FriendCAPI.h" ECode friendGetUid(IFriend *iFriend, const char** pUid) { String uid; ECode ec = iFriend->GetUid(&uid); if (SUCCEEDED(ec)) { *pUid = strdup(uid.string()); } return ec; } ECode friendIsOnline(IFriend *iFriend, Boolean* online) { return iFriend->IsOnline(online); }
// Copyright (C) 2014 Agustin Berge // // 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) #include <pika/future.hpp> #include <pika/init.hpp> #include <pika/testing.hpp> #include <chrono> #include <functional> int global; int& foo() { return global; } void test_make_ready_future() { pika::future<int&> f = pika::make_ready_future(std::ref(global)); PIKA_TEST_EQ(&f.get(), &global); #if 0 // Timed make_ready_future is not supported pika::future<int&> f_at = pika::make_ready_future_at( std::chrono::system_clock::now() + std::chrono::seconds(1), std::ref(global)); PIKA_TEST_EQ(&f_at.get(), &global); pika::future<int&> f_after = pika::make_ready_future_after(std::chrono::seconds(1), std::ref(global)); PIKA_TEST_EQ(&f_after.get(), &global); #endif } void test_async() { pika::future<int&> f = pika::async(&foo); PIKA_TEST_EQ(&f.get(), &global); pika::future<int&> f_sync = pika::async(pika::launch::sync, &foo); PIKA_TEST_EQ(&f_sync.get(), &global); } int pika_main() { test_make_ready_future(); test_async(); return pika::finalize(); } int main(int argc, char* argv[]) { PIKA_TEST_EQ_MSG(pika::init(pika_main, argc, argv), 0, "pika main exited with non-zero status"); return 0; }
// Author: WangZhan -> wangzhan.1985@gmail.com #pragma once #include "MessagePump.h" #include "BasicTypes.h" #include "ScopedHandle.h" // Typical use #1: // // Use only when there are no user's buffers involved on the actual IO, // // so that all the cleanup can be done by the message pump. // class MyFile : public IOHandler { // MyFile() { // ... // context_ = new IOContext; // context_->handler = this; // message_pump->RegisterIOHandler(file_, this); // } // ~MyFile() { // if (pending_) { // // By setting the handler to NULL, we're asking for this context // // to be deleted when received, without calling back to us. // context_->handler = NULL; // } else { // delete context_; // } // } // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered, // DWORD error) { // pending_ = false; // } // void DoSomeIo() { // ... // // The only buffer required for this operation is the overlapped // // structure. // ConnectNamedPipe(file_, &context_->overlapped); // pending_ = true; // } // bool pending_; // IOContext* context_; // HANDLE file_; // }; class MessagePumpForIO : public MessagePumpForMsg { public: MessagePumpForIO(); ~MessagePumpForIO(); class IOHandler; struct IOContext { OVERLAPPED overlapped; IOHandler *pHandler; }; class IOHandler { public: virtual ~IOHandler() {} virtual void OnIOCompleted(IOContext *pContext, DWORD dwBytesTranfered, DWORD dwError) = 0; }; void RegisterIOHandler(HANDLE fileHandle, IOHandler *pHandler); bool WaitForIOCompletion(DWORD dwTimeout); virtual void ScheduleWork(); virtual void ScheduleDelayedWork(DWORD dwDelayedWorkTime); protected: virtual void DoRunLoop(); bool WaitForWork(); private: ScopedHandle m_IOCompletionPort; DISALLOW_COPY_AND_ASSIGN(MessagePumpForIO); };
/* * * * * * * * * * * * * * * *\ * Title: A programming demo * * Author: Alex Shank * * Date: 2007 * \* * * * * * * * * * * * * * * */ #include "Variables.h" #include <stdio.h> #include <stdlib.h> #include <string> #include <iostream> gamevars::gamevars(void) { } gamevars::~gamevars(void) { } void gamevars::cleanup() { for (int i=0;i<(int)vars.size();i++) if (vars[i]) delete (vars[i]); vars.clear(); } var *gamevars::getValue(const char *variable) { for (int i=0;i<(int)vars.size();i++) { if (strcmp(variable,vars[i]->variable.c_str())==0) { return (vars[i]); } } std::cout << "request for gamevar that isn't defined: " << variable << std::endl; // log_addline("*** Request for game variable not defined \"%s\"",variable); return NULL; } int gamevars::getIntValue(const char *variable) { int v; var *value = getValue(variable); if (!value) { return 0; } sscanf(value->value.c_str(), "%d", &v); return v; } float gamevars::getFloatValue(const char *variable) { float v; var *value = getValue(variable); if (!value) return 0; sscanf(value->value.c_str(), "%f", &v); return v; } void gamevars::setValue(const char *variable, const char *value, bool create = false) { var *varvalue; if (create || !(varvalue = getValue(variable))) { // this variable name doesn't exist, create it. varvalue = new var; varvalue->variable = variable; varvalue->value = value; vars.push_back(varvalue); } else { varvalue->value = value; } } void gamevars::setValue(const char *variable, int value) { var *varvalue = getValue(variable); if (!varvalue) { // this variable name doesn't exist, create it. varvalue = new var; varvalue->variable = variable; char buffer[1024]; sprintf(buffer,"%d",value); varvalue->value = buffer; vars.push_back(varvalue); } else { varvalue->value = value; } } void gamevars::setValue(const char *variable, float value) { var *varvalue = getValue(variable); if (!value) { // this variable name doesn't exist, create it. varvalue = new var; varvalue->variable = variable; char buffer[1024]; sprintf(buffer,"%f",value); varvalue->value = buffer; vars.push_back(varvalue); } else { char buf[50]; sprintf(buf,"%f",value); varvalue->value = buf; } } void gamevars::setValue(var *variable) { vars.push_back(variable); } bool gamevars::loadCfgFile(const char *filename) { FILE *fin = fopen(filename,"r"); if (!fin) { std::cout << "failed to open configuration file " << filename << std::endl; return false; } std::cout << "loading configuration file " << filename << std::endl; fseek(fin,0,SEEK_END); long size = ftell(fin); fseek(fin,0,SEEK_SET); char *buffer = new char[size]; buffer[fread((void *)buffer,1,size,fin)] = 0; fclose(fin); return processCfgScript(buffer); } bool gamevars::processCfgScript(const char *script) { int i=0; // script buffer index int o=0; // current line index int varname_start=-1; int value_start=-1; var *new_var = new var; bool set_varname = false; bool set_value = false; while (script[i]) { if (script[i] == 0 || script[i] == '\n' || script[i] == '\r' || (set_value && script[i] == '"')) { if ((set_varname && set_value)) { setValue(new_var); // log_addline("--- new variable '%s' -> '%s'",new_var->variable.c_str(), new_var->value.c_str()); new_var = new var; } set_varname = false; set_value = false; } if (script[i] == '#') // ignore comments... skip to next line { for (;(script[i]) && (script[i] != '\n' && script[i] != '\r'); i++); set_varname = false; set_value = false; new_var->variable.clear(); new_var->value.clear(); i++; } if (!set_varname && isalpha(script[i])) { set_varname = true; } // else { if (set_varname && !set_value) { if (script[i] == ' ' || script[i] == '=') { for (;(script[i]) && (script[i] == ' ' || script[i] == '=' || script[i] == '"' || script[i] == '\''); i++); set_value = true; } else { char b[2]; b[0] = script[i]; b[1] = 0; new_var->variable += b; } } if (set_value) { new_var->value += script[i]; } } if (script[i] == 0) break; i++; } return true; }
class Solution { public: vector<vector<int>> getFactors(int n) { vector<vector<int>> factors; helper(factors, {}, n, 2); return factors; } /* bool divisible(int n){ if(n != 2 && n%2 == 0) return true; for(int i = 3; i*i <= n; i+=2){ if(n%i == 0) return true; } return false; } */ void helper(vector<vector<int>>& v, vector<int> head, int n, int prev){ for(int i = prev; i*i <= n; ++i){ if(n%i == 0){ head.push_back(i); //if(divisible(n/i)){ helper(v, head, n/i, i); //} head.push_back(n/i); v.push_back(head); head.pop_back(); head.pop_back(); } } } }; /*Question: Numbers can be regarded as product of its factors. For example, 8 = 2 x 2 x 2; = 2 x 4. Write a function that takes an integer n and return all possible combinations of its factors. Note: You may assume that n is always positive. Factors should be greater than 1 and less than n. Examples: input: 1 output: [] input: 37 output: [] input: 12 output: [ [2, 6], [2, 2, 3], [3, 4] ] input: 32 output: [ [2, 16], [2, 2, 8], [2, 2, 2, 4], [2, 2, 2, 2, 2], [2, 4, 4], [4, 8] ] */
#pragma once #include <string> #include <vector> #include "Cargo.h" /** * ステージを表すクラス */ class Stage { public: // コンストラクタ /** * init_data 文字列で表した初期ステージ構成 */ Stage(const std::string& init_data); Stage(const Stage&) = delete; Stage(Stage&&) = delete; // デストラクタ ~Stage() = default; // 代入演算子 Stage& operator=(const Stage&) = delete; Stage& operator=(Stage&&) = delete; size_t Width() const { return width_; }; size_t Height() const { return height_; }; /** * 指定した座標にあるオブジェクトを取得 * * 不正な座標を指定した場合は'\0'を返す * * x X座標 * y Y座標 */ char getObject(int x, int y) const; /** * 荷物を移動する * * 移動が成功したかどうかを返す * * cargo_x 移動したい荷物のX座標 * cargo_y 移動したい荷物のY座標 * direction 移動したい方向 */ bool moveCargo(int cargo_x, int cargo_y, char direction); /** * クリア判定 */ bool isClear(); /** * 描画関数 * * drawing_area 描画先 */ void draw(std::string& drawing_area); private: std::string data_; // ステージ構成 size_t width_; // ステージ幅 size_t height_; // ステージ高 std::vector<Cargo> cargoes_; // ステージ中の荷物 };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #ifndef NS4P_COMPONENT_PLUGINS #include "platforms/windows/pi/WindowsOpMessageLoopLegacy.cpp" #else // NS4P_COMPONENT_PLUGINS #include "platforms/windows/pi/WindowsOpMessageLoop.h" #include "adjunct/quick/managers/kioskmanager.h" #include "adjunct/quick/windows/BrowserDesktopWindow.h" #include "adjunct/desktop_util/filelogger/desktopfilelogger.h" #include "modules/ns4plugins/src/plugin.h" #include "modules/dragdrop/dragdrop_manager.h" #include "platforms/windows/CustomWindowMessages.h" #include "platforms/windows/pi/WindowsOpDragManager.h" #include "platforms/windows/pi/WindowsOpPluginAdapter.h" #include "platforms/windows/pi/WindowsOpSystemInfo.h" #include "platforms/windows/windows_ui/IntMouse.h" #define WM_APPCOMMAND 0x0319 #define FAPPCOMMAND_MOUSE 0x8000 #define FAPPCOMMAND_MASK 0xF000 #define GET_APPCOMMAND_LPARAM(lParam) ((short)(HIWORD(lParam) & ~FAPPCOMMAND_MASK)) #define GET_DEVICE_LPARAM(lParam) ((WORD)(HIWORD(lParam) & FAPPCOMMAND_MASK)) WindowsOpMessageLoop* g_windows_message_loop = NULL; /*********************************************************************************** ** ** WindowsOpMessageLoop ** ***********************************************************************************/ WindowsOpMessageLoop::WindowsOpMessageLoop() : m_pending_app_command(NULL) , m_use_RTL_shortcut(FALSE) , m_wait_for_this_dialog_to_close(NULL) , m_destructing(FALSE) /* Support for "new" key events. */ , m_rshift_scancode(0) , m_keyvalue_vk_table(NULL) , m_keyvalue_table(NULL) , m_keyvalue_table_index(0) { g_sleep_manager->SetStayAwakeListener(this); this->SetWMListener(WM_DEAD_COMPONENT_MANAGER, this); m_rshift_scancode = MapVirtualKeyEx(VK_RSHIFT, MAPVK_VK_TO_VSC, GetKeyboardLayout(0)); } /*********************************************************************************** ** ** ~WindowsOpMessageLoop ** ***********************************************************************************/ WindowsOpMessageLoop::~WindowsOpMessageLoop() { OP_DELETE(m_pending_app_command); g_sleep_manager->SetStayAwakeListener(NULL); m_known_processes_list_access.Enter(); m_destructing = TRUE; m_known_processes_list_access.Leave(); // If this asserts and we are left with stray plugin wrapper processes // after that then consider signaling shared memory handle maybe. OP_ASSERT(m_known_processes_list.GetCount() == 0); m_known_processes_list.DeleteAll(); this->RemoveWMListener(WM_DEAD_COMPONENT_MANAGER); OP_DELETEA(m_keyvalue_vk_table); OP_DELETEA(m_keyvalue_table); } /*********************************************************************************** ** ** Init ** ***********************************************************************************/ OP_STATUS WindowsOpMessageLoop::Init() { RETURN_IF_ERROR(WindowsOpComponentPlatform::Init()); { OP_PROFILE_METHOD("Got keyboard layout list"); //We need this to know if we want to support the RTL shortcuts(Ctrl+Left/Right Shift) UINT n_lang = GetKeyboardLayoutList(0, NULL); HKL *langs = new HKL[n_lang]; GetKeyboardLayoutList(n_lang, langs); for (unsigned i = 0; i < n_lang; i++) { DWORD lcid = MAKELCID(langs[i], SORT_DEFAULT); LOCALESIGNATURE localesig; if (GetLocaleInfoW(lcid, LOCALE_FONTSIGNATURE, (LPWSTR)&localesig, (sizeof(localesig)/sizeof(WCHAR))) && (localesig.lsUsb[3] & 0x08000000)) { m_use_RTL_shortcut = TRUE; break; } } delete[] langs; } m_keyvalue_vk_table = OP_NEWA(WPARAM, 0x100); RETURN_OOM_IF_NULL(m_keyvalue_vk_table); op_memset(m_keyvalue_vk_table, 0, 0x100 * sizeof(WPARAM)); m_keyvalue_table = OP_NEWA(KeyValuePair, MAX_KEYUP_TABLE_LENGTH); RETURN_OOM_IF_NULL(m_keyvalue_table); m_keyvalue_table_index = 0; return OpStatus::OK; } /*********************************************************************************** ** ** Run ** ***********************************************************************************/ OP_STATUS WindowsOpMessageLoop::Run(WindowsOpWindow* wait_for_this_dialog_to_close) { if (wait_for_this_dialog_to_close) { m_dialog_hash_table.Add(wait_for_this_dialog_to_close); } WindowsOpWindow* old_wait_for_this_dialog_to_close = m_wait_for_this_dialog_to_close; m_wait_for_this_dialog_to_close = wait_for_this_dialog_to_close; OP_STATUS ret = WindowsOpComponentPlatform::Run(); m_wait_for_this_dialog_to_close = old_wait_for_this_dialog_to_close; m_exit_loop = FALSE; return ret; } OP_STATUS WindowsOpMessageLoop::ProcessMessage(MSG &msg) { #ifdef _SSL_SEED_FROMMESSAGE_LOOP_ SSLSeedFromMessageLoop(&msg); #endif //If we need to give a specific treatment to some messages, add a switch here andmake the code below be the default case. BOOL called_translate; if (!TranslateOperaMessage(&msg, called_translate)) { // Nothing ate the message, so translate and dispatch it if (!called_translate) TranslateMessage(&msg); DispatchMessage(&msg); } return OpStatus::OK; } OP_STATUS WindowsOpMessageLoop::DoLoopContent(BOOL ran_core) { if ((m_wait_for_this_dialog_to_close && !m_dialog_hash_table.Contains(m_wait_for_this_dialog_to_close))) m_exit_loop = TRUE; if (m_pending_app_command != NULL && m_event_flags != PROCESS_IPC_MESSAGES) { //Don't process the message again if we happen to reenter. AppCommandInfo* pending_app_command = m_pending_app_command; m_pending_app_command = NULL; g_input_manager->InvokeAction(pending_app_command->m_action, pending_app_command->m_action_data, NULL, pending_app_command->m_input_context); OP_DELETE(pending_app_command); } return OpStatus::OK; } void WindowsOpMessageLoop::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam) { OP_ASSERT (uMsg == WM_DEAD_COMPONENT_MANAGER); OP_ASSERT (IsInitialProcess()); INT32 pid = wParam; if (WindowsSharedMemoryManager::GetInstance()) WindowsSharedMemoryManager::GetInstance()->CloseMemory(OpMessageAddress(pid, 0, 0)); g_component_manager->PeerGone(pid); } /*********************************************************************************** ** ** RequestPeer ** ***********************************************************************************/ OP_STATUS WindowsOpMessageLoop::RequestPeer(int& peer, OpMessageAddress requester, OpComponentType type) { OP_ASSERT (IsInitialProcess()); if (!IsInitialProcess()) return OpStatus::ERR; if (!m_shared_mem) return g_component_manager->HandlePeerRequest(requester, type); switch (type) { case COMPONENT_TEST: case COMPONENT_PLUGIN: case COMPONENT_PLUGIN_WIN32: { OpFile executable; if (type == COMPONENT_PLUGIN) executable.Construct(UNI_L("opera_plugin_wrapper.exe"), OPFILE_PLUGINWRAPPER_FOLDER); else if (type == COMPONENT_PLUGIN_WIN32) executable.Construct(UNI_L("opera_plugin_wrapper_32.exe"), OPFILE_PLUGINWRAPPER_FOLDER); else executable.Construct(UNI_L("opera.exe"), OPFILE_RESOURCES_FOLDER); BOOL exists; RETURN_IF_ERROR(executable.Exists(exists)); if (!exists) return OpStatus::ERR; OpString log_folder; RETURN_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_CRASHLOG_FOLDER, log_folder)); if (log_folder[log_folder.Length() - 1] == PATHSEPCHAR) log_folder[log_folder.Length() - 1] = 0; UniString params; params.AppendFormat(UNI_L("\"%s\" -newprocess \"%d %d %d %d %d\" -logfolder \"%s\""), executable.GetFullPath(), GetCurrentProcessId(), type, requester.cm, requester.co, requester.ch, log_folder.CStr()); OpAutoArray<uni_char> params_ptr = OP_NEWA(uni_char, params.Length()+1); params.CopyInto(params_ptr.get(), params.Length()); params_ptr[params.Length()] = 0; STARTUPINFO startup_info = {0}; startup_info.cb = sizeof(startup_info); PROCESS_INFORMATION pi; if (!CreateProcess(NULL, params_ptr.get(), NULL, NULL, FALSE, 0, NULL, NULL, &startup_info, &pi)) return OpStatus::ERR; peer = pi.dwProcessId; CloseHandle(pi.hThread); ProcessDetails* details = OP_NEW(ProcessDetails, ()); RETURN_OOM_IF_NULL(details); details->pid = pi.dwProcessId; details->process_handle = pi.hProcess; details->message_loop = this; m_known_processes_list_access.Enter(); OpStatus::Ignore(m_known_processes_list.Add(details)); m_known_processes_list_access.Leave(); //In the unlikely event where this fails, we'll only be unable to know if the process crash, so let's ignore the error. RegisterWaitForSingleObject(&(details->process_wait), pi.hProcess, ReportDeadPeer, details, INFINITE, WT_EXECUTEONLYONCE); return OpStatus::OK; } default: return g_component_manager->HandlePeerRequest(requester, type); } } /*static*/ VOID WindowsOpMessageLoop::ReportDeadPeer(PVOID process_details, BOOLEAN timeout) { ProcessDetails* details = static_cast<ProcessDetails*>(process_details); ::SendNotifyMessage(details->message_loop->GetMessageWindow(), WM_DEAD_COMPONENT_MANAGER, details->pid, 0); OpCriticalSection &sync_section = details->message_loop->m_known_processes_list_access; sync_section.Enter(); if (!details->message_loop->m_destructing) { details->pid = 0; //To make the destructor of ProcessDetails use the non-waiting UnregisterWait. (prevents deadlocks) OpStatus::Ignore(details->message_loop->m_known_processes_list.Delete(details)); } sync_section.Leave(); } /*********************************************************************************** ** ** OnStayAwakeStatusChanged ** ***********************************************************************************/ void WindowsOpMessageLoop::OnStayAwakeStatusChanged(BOOL stay_awake) { SetThreadExecutionState(stay_awake ? ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED : ES_CONTINUOUS); } void WindowsOpMessageLoop::DispatchAllPostedMessagesNow() { while (g_component_manager->RunSlice() != 0); } #endif // NS4P_COMPONENT_PLUGINS /** Bits 16-23 contains the key scancode. */ static inline unsigned char GetKeyScancode(LPARAM lParam) { return (lParam >> 16) & 0xff; } /** Returns TRUE if the LPARAM is for a repeating keydown. */ static inline BOOL IsKeyRepeat(LPARAM lParam) { return (HIWORD(lParam) & KF_REPEAT) == KF_REPEAT; } static OpKey::Location GetKeyLocation(WPARAM vk, LPARAM lParam) { switch (vk) { case VK_SHIFT: { unsigned scancode = (lParam & 0xFF0000) >> 16; if (scancode == MapVirtualKey(VK_LSHIFT, 0)) return OpKey::LOCATION_LEFT; else if (scancode == MapVirtualKey(VK_RSHIFT, 0)) return OpKey::LOCATION_RIGHT; } break; case VK_MENU: if (GetKeyState(VK_LMENU) & 0x8000) return OpKey::LOCATION_LEFT; else if (GetKeyState(VK_RMENU) & 0x8000) return OpKey::LOCATION_RIGHT; else if (lParam & (0x1 << 24)) return OpKey::LOCATION_RIGHT; else return OpKey::LOCATION_LEFT; break; case VK_CONTROL: if (GetKeyState(VK_LCONTROL) & 0x8000) return OpKey::LOCATION_LEFT; else if (GetKeyState(VK_RCONTROL) & 0x8000) return OpKey::LOCATION_RIGHT; else if (lParam & (0x1 << 24)) return OpKey::LOCATION_RIGHT; else return OpKey::LOCATION_LEFT; break; case VK_RETURN: if (lParam & (0x1 << 24)) return OpKey::LOCATION_NUMPAD; break; case VK_CLEAR: return OpKey::LOCATION_NUMPAD; } return OpKey::LOCATION_STANDARD; } /*********************************************************************************** ** ** Key and character translation. ** ***********************************************************************************/ void WindowsOpMessageLoop::AddKeyValue(WPARAM wParamDown, WPARAM wParamChar) { if (wParamDown <= 0xff) { m_keyvalue_vk_table[wParamDown] = wParamChar; return; } unsigned int last_available = UINT_MAX; for (unsigned int i = 0; i < m_keyvalue_table_index; i++) { WPARAM keydown_wParam = m_keyvalue_table[i].keydown_wParam; if (keydown_wParam == wParamDown) { m_keyvalue_table[i].char_wParam = wParamChar; return; } else if (!keydown_wParam) last_available = i; } OP_ASSERT(m_keyvalue_table_index < MAX_KEYUP_TABLE_LENGTH || !"Exhausted key value table"); if (last_available != UINT_MAX) { m_keyvalue_table[last_available].keydown_wParam = wParamDown; m_keyvalue_table[last_available].char_wParam = wParamChar; } else if (m_keyvalue_table_index < MAX_KEYUP_TABLE_LENGTH) { m_keyvalue_table[m_keyvalue_table_index].keydown_wParam = wParamDown; m_keyvalue_table[m_keyvalue_table_index].char_wParam = wParamChar; m_keyvalue_table_index++; } } BOOL WindowsOpMessageLoop::LookupKeyCharValue(WPARAM virtual_key, WPARAM &wParamChar) { if (virtual_key <= 0xff) { wParamChar = m_keyvalue_vk_table[virtual_key]; return TRUE; } for (unsigned int i = 0; i < m_keyvalue_table_index; i++) { if (m_keyvalue_table[i].keydown_wParam == virtual_key) { wParamChar = m_keyvalue_table[i].char_wParam; m_keyvalue_table[i].keydown_wParam = 0; return TRUE; } } return FALSE; } void WindowsOpMessageLoop::ClearKeyValues() { m_keyvalue_table_index = 0; } BOOL WindowsOpMessageLoop::HasCharacterValue(OpKey::Code vkey, ShiftKeyState shiftkeys, WPARAM wParam, LPARAM lParam) { if (vkey == OP_KEY_BACKSPACE || vkey == OP_KEY_ESCAPE) return TRUE; else if ((shiftkeys & (SHIFTKEY_CTRL | SHIFTKEY_ALT)) == (SHIFTKEY_CTRL | SHIFTKEY_ALT)) { /* If Ctrl-Alt is active, three kinds of keys possible: * - a composition dead key. * - a key not producing any character value. (Alt-Ctrl-G on a US keyboard.) * - a normal key producing a character value (Alt-Ctrl-E on a Norwegian keyboard.) * * The middle option doesn't produce a value, the other two do (the first one * only upon the next key pressed.) Single out the middle one by doing the * key translation & checking if the outcome is empty. If so, the handling * of its keydown must generate an event right away (i.e., there won't be a * follow-up WM_CHAR message that will handle it.) */ BYTE key_state[256]; if (GetKeyboardState(key_state)) { WCHAR key_value[5]; int length = ToUnicodeEx(wParam, lParam, key_state, key_value, 4, 0, GetKeyboardLayout(0)); /* If this was a dead key, ToUnicodeEx() will have side-effected * the keyboard buffer. The state of that buffer must be left * undisturbed for subsequent key input, so repeat the call to * ToUnicodeEx() to undo the side-effect the dead key had. * [Non-stateful APIs are to be preferred on the whole, but have * no option but to use ToUnicodeEx() here.] * * This is unnecessary if the key produced no translation to start with. */ if (length != 0) ToUnicodeEx(wParam, lParam, key_state, key_value, 4, 0, GetKeyboardLayout(0)); return length != 0; } } else if (shiftkeys == SHIFTKEY_CTRL) { if (vkey >= OP_KEY_A && vkey <= OP_KEY_Z) return TRUE; else if (vkey == OP_KEY_OEM_4 || vkey == OP_KEY_OEM_6 || vkey == OP_KEY_OEM_5) return TRUE; } else if ((shiftkeys & (SHIFTKEY_CTRL | SHIFTKEY_SHIFT)) == (SHIFTKEY_CTRL | SHIFTKEY_SHIFT)) { if (vkey >= OP_KEY_A && vkey <= OP_KEY_Z) return TRUE; else if (vkey == OP_KEY_2 || vkey == OP_KEY_6 || vkey == OP_KEY_OEM_MINUS || vkey == OP_KEY_OEM_2 || vkey == OP_KEY_OEM_102) return TRUE; } else if (!(OpKey::IsFunctionKey(vkey) || OpKey::IsModifier(vkey))) return TRUE; return FALSE; } //#pragma PRAGMA_OPTIMIZE_SPEED extern BOOL IsPluginWnd(HWND hWnd, BOOL fTestParents); extern int IntelliMouse_GetLinesToScroll(HWND hwnd, short zDelta, BOOL* scroll_as_page); #if 0 #ifdef _DEBUG static void OutputKeyMessage(MSG *pMsg) { OpString debug; switch (pMsg->message) { case WM_KEYDOWN: debug.Set(UNI_L("WM_KEYDOWN: ")); break; case WM_KEYUP: debug.Set(UNI_L("WM_KEYUP: ")); break; case WM_CHAR: debug.Set(UNI_L("WM_CHAR: ")); break; case WM_DEADCHAR: debug.Set(UNI_L("WM_DEADCHAR: ")); break; case WM_SYSKEYDOWN: debug.Set(UNI_L("WM_SYSKEYDOWN: ")); break; case WM_SYSKEYUP: debug.Set(UNI_L("WM_SYSKEYUP: ")); break; case WM_SYSCHAR: debug.Set(UNI_L("WM_SYSCHAR: ")); break; case WM_SYSDEADCHAR: debug.Set(UNI_L("WM_SYSDEADCHAR: ")); break; } debug.AppendFormat(UNI_L("%d\n"), pMsg->wParam); OutputDebugString(debug.CStr()); } #endif // _DEBUG #endif // 0 /*********************************************************************************** ** ** TranslateOperaMessage ** ***********************************************************************************/ BOOL WindowsOpMessageLoop::TranslateOperaMessage(MSG *pMsg, BOOL &called_translate) { called_translate = FALSE; #ifndef NS4P_COMPONENT_PLUGINS if (pMsg->message == WM_KEYUP || pMsg->message == WM_KEYDOWN) if (WindowsOpPluginWindow::HandleFocusedPluginWindow(pMsg)) return TRUE; #endif // !NS4P_COMPONENT_PLUGINS // Send keyboard input to OpInputManager. // InvokeKeyDown() when a key is pressed down, and on repeat. // InvokeKeyUp() when a key is released // InvokeKeyPressed() when a key is pressed down, with repeating // For more documentation: http://wiki/developerwiki/Platform/windows/KeyboardHandling static OpKey::Location s_new_rtl_direction = OpKey::LOCATION_STANDARD; if (pMsg->message >= WM_KEYFIRST && pMsg->message <= WM_KEYLAST) { ShiftKeyState shift_keys = g_op_system_info->GetShiftKeyState(); // The inputmethod hacks requires the current state so we cannot use what g_op_system_info returns. ShiftKeyState async_shift_keys = SHIFTKEY_NONE; if(HIBYTE(GetAsyncKeyState(VK_SHIFT))) async_shift_keys |= SHIFTKEY_SHIFT; if(HIBYTE(GetAsyncKeyState(VK_MENU))) async_shift_keys |= SHIFTKEY_ALT; if(HIBYTE(GetAsyncKeyState(VK_CONTROL))) async_shift_keys |= SHIFTKEY_CTRL; OpKey::Code key = ConvertKey_VK_To_OP(pMsg->wParam); #if 0 #ifdef _DEBUG OutputKeyMessage(pMsg); #endif // _DEBUG #endif BOOL ignore = FALSE; #ifdef WIDGETS_IME_SUPPORT // ===== Some Input Method hacks ============================= static BOOL ctrl_backspace_undo = FALSE; // IMEs in WinME send a keydown with char 229 when ctrl+backspace is pressed. We must ignore this event since we don't want it. if (pMsg->message == WM_KEYDOWN && (async_shift_keys & SHIFTKEY_CTRL) && key == 229) ignore = TRUE; extern BOOL compose_started; /* NOTE: do want keydown + up delivered during IME composition (but not keypresses.) */ if (pMsg->message == WM_KEYDOWN && key == VK_BACK && (async_shift_keys & SHIFTKEY_CTRL) && g_input_manager) { // Japanese IMEs allow the user to ctrl+backspace to start composing the previous submitted string. // Windows sends backspaces for each character that should be removed in the previous string. (The IME somehow caches that) // This hack bypasses the inputmanager because it screws up the order of IME messages and keymessages. // // I haven't found any documented way to know if this ctrl+backspace will start to undo the IME. // These 2 ways work with Microsofts IME and ATOK. // // emil@opera.com MSG peekmsg; BOOL waiting_compose_start2 = ::PeekMessage(&peekmsg, NULL, WM_IME_STARTCOMPOSITION, WM_IME_STARTCOMPOSITION, PM_NOREMOVE|PM_NOYIELD); BOOL waiting_compose_start1 = ::PeekMessage(&peekmsg, NULL, WM_KEYDOWN, WM_KEYDOWN, PM_NOREMOVE|PM_NOYIELD); if((waiting_compose_start1 && peekmsg.wParam == VK_BACK) || waiting_compose_start2) { ctrl_backspace_undo = TRUE; OpInputContext* ic = g_input_manager->GetKeyboardInputContext(); if (ic && ic->GetInputContextName()) if (op_strcmp(ic->GetInputContextName(), "Edit Widget") == 0) { OpInputAction action(OpInputAction::ACTION_BACKSPACE); ic->OnInputAction(&action); } ignore = TRUE; } else if (ctrl_backspace_undo) { OpInputContext* ic = g_input_manager->GetKeyboardInputContext(); if (ic && ic->GetInputContextName()) if (op_strcmp(ic->GetInputContextName(), "Edit Widget") == 0) { OpInputAction action(OpInputAction::ACTION_BACKSPACE); ic->OnInputAction(&action); } ignore = TRUE; } } if (pMsg->message == WM_KEYDOWN && key == VK_BACK && !(async_shift_keys & SHIFTKEY_CTRL)) ctrl_backspace_undo = FALSE; #endif // WIDGETS_IME_SUPPORT // =========================================================== char *key_value = NULL; int key_value_length = 0; OpKey::Location location = GetKeyLocation(pMsg->wParam, pMsg->lParam); OpStringS8 str; if (pMsg->message == WM_KEYDOWN && g_drag_manager && g_drag_manager->IsDragging()) { WindowsOpWindow *window = WindowsOpWindow::FindWindowUnderCursor(); if(window && window->m_mde_screen) { //Esc stops dragging if(key == OP_KEY_ESCAPE) { window->m_mde_screen->TrigDragCancel(g_op_system_info->GetShiftKeyState()); } else { // if a modifier has changed, core needs to know about it // during drag so the cursor can be updated window->m_mde_screen->TrigDragUpdate(); } } } //We ignore the input if it's not for any of our windows ignore = ignore || (!WindowsOpWindow::GetWindowFromHWND(pMsg->hwnd) #ifdef EMBROWSER_SUPPORT // && IsPluginWnd(pMsg->hwnd, TRUE) && !WindowsOpWindow::GetAdoptedWindowFromHWND(pMsg->hwnd) #endif // EMBROWSER_SUPPORT ); OpPlatformKeyEventData *key_event_data = NULL; if (!ignore && g_input_manager) { //Happens when a key is pressed or held pressed down. Invoke keydown for both. if (pMsg->message == WM_KEYDOWN || pMsg->message == WM_SYSKEYDOWN) { //Attempt to get the corresponding WM_(SYS)(DEAD)CHAR called_translate = TRUE; MSG translated_message; if (TranslateMessage(pMsg) && (PeekMessage(&translated_message, pMsg->hwnd, WM_CHAR, WM_DEADCHAR, PM_REMOVE) || PeekMessage(&translated_message, pMsg->hwnd, WM_SYSCHAR, WM_SYSDEADCHAR, PM_REMOVE)) && //Skip control char generated by ctrl+symbol key combination. It's very unlikely for them to be used //for anything useful and they screw shortcut handling. ((shift_keys & (SHIFTKEY_CTRL | SHIFTKEY_ALT)) != SHIFTKEY_CTRL || translated_message.wParam <= 0x1A)) { //Once we enter here, we are going to handle one or more WM_(SYS)(DEAD)CHAR instead. We dispatch the //previous message and make sure to dispatch the translated message if relevant, then always return TRUE DispatchMessage(pMsg); do { uni_char value_buffer[2] = {0}; value_buffer[0] = static_cast<uni_char>(translated_message.wParam); char simple_value; OpString8 str; if (key == OP_KEY_BACKSPACE || key == OP_KEY_ESCAPE) key_value_length = 0; else if (translated_message.wParam < 0x80) { simple_value = static_cast<char>(translated_message.wParam); key_value = &simple_value; key_value_length = 1; } else if (OpStatus::IsError(str.SetUTF8FromUTF16(value_buffer))) { DispatchMessage(&translated_message); return TRUE; } else { key_value = str.CStr(); key_value_length = str.Length(); } if (compose_started) key = OP_KEY_PROCESSKEY; HWND old_focus = GetFocus(); BOOL handled = FALSE; if (OpStatus::IsError(OpPlatformKeyEventData::Create(&key_event_data, pMsg))) { DispatchMessage(&translated_message); return TRUE; } handled = g_input_manager->InvokeKeyDown(key, key_value, key_value_length, key_event_data, shift_keys, (translated_message.lParam & 0xffff) > 1, location, TRUE); if (translated_message.message != WM_DEADCHAR && translated_message.message != WM_SYSDEADCHAR) handled = g_input_manager->InvokeKeyPressed(key, key_value, key_value_length, shift_keys, (translated_message.lParam & 0xffff) > 1, TRUE); OpPlatformKeyEventData::DecRef(key_event_data); AddKeyValue(pMsg->wParam, translated_message.wParam); //We do not dispatch if a shortcut was handled or if the focus was changed ShiftKeyState ctrl_alt_state = shift_keys & (SHIFTKEY_ALT | SHIFTKEY_CTRL); if (((ctrl_alt_state != SHIFTKEY_ALT && ctrl_alt_state != SHIFTKEY_CTRL) || !handled) && old_focus == GetFocus()) DispatchMessage(&translated_message); //Always dispatch WM_SYS_(DEAD)CHAR messages. //This is because core tends to be overeager in returning TRUE from InvokeKeyDown/InvokeKeyPressed else if (translated_message.message == WM_SYSCHAR || translated_message.message == WM_SYSDEADCHAR) DispatchMessage(&translated_message); } while (PeekMessage(&translated_message, pMsg->hwnd, WM_CHAR, WM_DEADCHAR, PM_REMOVE) || PeekMessage(&translated_message, pMsg->hwnd, WM_SYSCHAR, WM_SYSDEADCHAR, PM_REMOVE)); return TRUE; } //(julienp) This is to support the (apparently standard) behavior on windows that //Pressing Ctrl+ one of the shift keys, then releasing any of them switches to //RTL or LTR (depeding on which shift key) //When pressing Shift while Ctrl is being held, we record that we should be ready //to change direction (and which direction). If any other key should be held down //after that, we cancel this. s_new_rtl_direction = OpKey::LOCATION_STANDARD; if (m_use_RTL_shortcut && key == OP_KEY_SHIFT && async_shift_keys == (SHIFTKEY_SHIFT | SHIFTKEY_CTRL)) { s_new_rtl_direction = location; } key_value = NULL; key_value_length = 0; OpString8 str; if (!OpKey::IsFunctionKey(key) && !OpKey::IsModifier(key) && (key < OP_KEY_A || key > OP_KEY_Z) && (key < OP_KEY_NUMPAD0 || key > OP_KEY_NUMPAD9 || shift_keys != SHIFTKEY_ALT)) { uni_char converted[4]; byte vk_state[256]; op_memset(vk_state, 0, sizeof(vk_state)); vk_state[key] = 0x80; if (shift_keys & SHIFTKEY_SHIFT) vk_state[VK_SHIFT] = 0x80; if (key_value_length = ToUnicode(key, 0, vk_state, converted, 4, 0)) { str.SetUTF8FromUTF16(converted, key_value_length); key_value = str.CStr(); } } if (OpStatus::IsError(OpPlatformKeyEventData::Create(&key_event_data, pMsg))) return FALSE; g_input_manager->InvokeKeyDown(key, key_value, key_value_length, key_event_data, shift_keys, IsKeyRepeat(pMsg->lParam), location, TRUE); BOOL handled = g_input_manager->InvokeKeyPressed(key, key_value, key_value_length, shift_keys, IsKeyRepeat(pMsg->lParam), TRUE); OpPlatformKeyEventData::DecRef(key_event_data); //To prevent activating the window menu, return true if the F10 key was handled. if (handled && key == OP_KEY_F10) return TRUE; } //WM_CHAR that isn't associated to any WM_KEYDOWN (which can happen with e.g. Alt+numbers combinations) else if (pMsg->message == WM_CHAR || pMsg->message == WM_DEADCHAR) { key = OP_KEY_UNICODE; location = OpKey::LOCATION_STANDARD; uni_char value_buffer[2] = {0}; value_buffer[0] = static_cast<uni_char>(pMsg->wParam); char simple_value; OpString8 str; if (pMsg->wParam < 0x80) { simple_value = static_cast<char>(pMsg->wParam); key_value = &simple_value; key_value_length = 1; } else if (OpStatus::IsError(str.SetUTF8FromUTF16(value_buffer))) return FALSE; else { key_value = str.CStr(); key_value_length = str.Length(); } if (compose_started) key = OP_KEY_PROCESSKEY; HWND old_focus = GetFocus(); BOOL handled = FALSE; if (pMsg->message == WM_DEADCHAR) handled = g_input_manager->InvokeKeyDown(key, key_value, key_value_length, NULL, shift_keys, (pMsg->lParam & 0xffff) > 1, location, TRUE); else handled = g_input_manager->InvokeKeyPressed(key, key_value, key_value_length, shift_keys, (pMsg->lParam & 0xffff) > 1, TRUE); //We return true if a shortcut was handled or if the focus was changed ShiftKeyState ctrl_alt_state = shift_keys & (SHIFTKEY_ALT | SHIFTKEY_CTRL); if (((ctrl_alt_state == SHIFTKEY_ALT || ctrl_alt_state == SHIFTKEY_CTRL) && handled) || old_focus == GetFocus()) return TRUE; } //Happens when a key is released, we invoke key up if (pMsg->message == WM_KEYUP || pMsg->message == WM_SYSKEYUP) { WPARAM last_char_wParam = 0; if (HasCharacterValue(key, shift_keys, pMsg->wParam, pMsg->lParam)) LookupKeyCharValue(pMsg->wParam, last_char_wParam); uni_char value_buffer[2] = {0}; value_buffer[0] = static_cast<uni_char>(last_char_wParam); char simple_value; OpString8 str; if (last_char_wParam == 0) { key_value = NULL; key_value_length = 0; } else if (last_char_wParam < 0x80) { simple_value = static_cast<char>(last_char_wParam); key_value = &simple_value; key_value_length = 1; } else if (OpStatus::IsError(str.SetUTF8FromUTF16(value_buffer))) return FALSE; else { key_value = str.CStr(); key_value_length = str.Length(); } if (OpStatus::IsError(OpPlatformKeyEventData::Create(&key_event_data, pMsg))) return FALSE; g_input_manager->InvokeKeyUp(key, key_value, key_value_length, key_event_data, shift_keys, FALSE, location, TRUE); OpPlatformKeyEventData::DecRef(key_event_data); //Second part of the RTL support mentioned in WMSYSKEYDOWN //When releasing Ctrl or shift, if we recorded earlier that we are preparing a //direction change, do it. Then make sure we unregister the fact that we are ready. if (s_new_rtl_direction != OpKey::LOCATION_STANDARD && (key == OP_KEY_SHIFT || key == OP_KEY_CTRL)) { if (s_new_rtl_direction == OpKey::LOCATION_LEFT) g_input_manager->InvokeAction(OpInputAction::ACTION_CHANGE_DIRECTION_TO_LTR); else g_input_manager->InvokeAction(OpInputAction::ACTION_CHANGE_DIRECTION_TO_RTL); } s_new_rtl_direction = OpKey::LOCATION_STANDARD; } #if defined(MDE_DEBUG_INFO) // Enable/disable debugging of invalidation rectangles. else if (key == OP_KEY_F12 && shift_keys == (SHIFTKEY_SHIFT | SHIFTKEY_CTRL)) { BrowserDesktopWindow *bw = g_application->GetActiveBrowserDesktopWindow(); if (bw && bw->GetOpWindow()) { MDE_Screen *screen = ((MDE_OpWindow*)bw->GetOpWindow())->GetMDEWidget()->m_screen; int flags = screen->m_debug_flags; if (screen->m_debug_flags & MDE_DEBUG_INVALIDATE_RECT) flags &= ~MDE_DEBUG_INVALIDATE_RECT; else flags |= MDE_DEBUG_INVALIDATE_RECT; screen->SetDebugInfo(flags); } } #endif // defined(MDE_DEBUG_INFO) } } // close popup if clicking outside it if (g_input_manager && WindowsOpWindow::s_popup_window && (pMsg->message == WM_LBUTTONDOWN || pMsg->message == WM_NCLBUTTONDOWN || pMsg->message == WM_ACTIVATE)) { if (WindowsOpWindow::s_popup_window->m_hwnd != pMsg->hwnd) { HWND hWndNextWindow = NULL; if (pMsg->message == WM_ACTIVATE) hWndNextWindow = LOWORD(pMsg->wParam) == WA_INACTIVE ? (HWND)pMsg->lParam : pMsg->hwnd; WindowsOpWindow::ClosePopup(hWndNextWindow); g_input_manager->ResetInput(); } } if(pMsg->message == g_IntelliMouse_MsgMouseWheel) { IntelliMouse_TranslateWheelMessage(pMsg); } if (pMsg->message == WM_MOUSEWHEEL) { short zDelta = (short) HIWORD(pMsg->wParam); // Wheel rotation if (g_input_manager && g_input_manager->IsKeyDown(g_input_manager->GetGestureButton())) { g_input_manager->SetFlipping(TRUE); g_input_manager->InvokeAction(zDelta >= 0 ? OpInputAction::ACTION_CYCLE_TO_PREVIOUS_PAGE : OpInputAction::ACTION_CYCLE_TO_NEXT_PAGE); return TRUE; } } // handle app command if (pMsg->message == WM_APPCOMMAND) { if (OnAppCommand(pMsg->lParam)) return TRUE; } // hide task manager dialog if needed if (KioskManager::GetInstance()->GetNoExit()) { HWND task_manager = FindWindow(UNI_L("#32770"), NULL); if (task_manager) { // check that the title matches "Windows Task Manager", or otherwise verify again // since "iTunes Helper" and a few other apps are known to use "#32770" as class name too. OpString window_title; const int TITLE_LEN = 21; window_title.Reserve(TITLE_LEN); GetWindowText(task_manager, window_title.CStr(), TITLE_LEN); if (window_title.Compare("Windows Task Manager") == 0) { ShowWindow(task_manager, SW_MINIMIZE); EnableWindow(task_manager, FALSE); } } } return FALSE; } /*********************************************************************************** ** ** SSLSeedFromMessageLoop ** ***********************************************************************************/ void WindowsOpMessageLoop::SSLSeedFromMessageLoop(const MSG *msg) { extern void SSL_Process_Feeder(); UINT message = msg->message; if (SSL_RND_feeder_len) { if (message == WM_MOUSEMOVE || message == WM_KEYDOWN) { if(SSL_RND_feeder_pos +2 > SSL_RND_feeder_len) SSL_Process_Feeder(); if (message == WM_MOUSEMOVE) { SSL_RND_feeder_data[SSL_RND_feeder_pos++] = msg->lParam; } SSL_RND_feeder_data[SSL_RND_feeder_pos++] = GetTickCount(); } // solve bug #298947 else if(SSL_RND_feeder_pos == 0) { // would be nice to use rand_s here, but that depends on the RtlGenRandom API, // which is only available in Windows XP and later, and will simply crash the process // if it can't import that (thanks MS!) // no srand(time) in this fallback, it's seeded in other places already, e.g. OperaEntry(), // and seeding with current time here when we already used GetTickCount() is not clever SSL_RND_feeder_data[SSL_RND_feeder_pos++] = (unsigned)rand() << 17 ^ rand() << 7 ^ rand(); SSL_RND_feeder_data[SSL_RND_feeder_pos++] = GetTickCount(); } } } /*********************************************************************************** ** ** OnAppCommand ** ***********************************************************************************/ #define APPCOMMAND_BROWSER_BACKWARD 1 #define APPCOMMAND_BROWSER_FORWARD 2 #define APPCOMMAND_BROWSER_REFRESH 3 #define APPCOMMAND_BROWSER_STOP 4 #define APPCOMMAND_BROWSER_SEARCH 5 #define APPCOMMAND_BROWSER_FAVORITES 6 #define APPCOMMAND_BROWSER_HOME 7 #define APPCOMMAND_VOLUME_MUTE 8 #define APPCOMMAND_VOLUME_DOWN 9 #define APPCOMMAND_VOLUME_UP 10 #define APPCOMMAND_MEDIA_NEXTTRACK 11 #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12 #define APPCOMMAND_MEDIA_STOP 13 #define APPCOMMAND_MEDIA_PLAY_PAUSE 14 #define APPCOMMAND_LAUNCH_MAIL 15 #define APPCOMMAND_LAUNCH_MEDIA_SELECT 16 #define APPCOMMAND_LAUNCH_APP1 17 #define APPCOMMAND_LAUNCH_APP2 18 #define APPCOMMAND_BASS_DOWN 19 #define APPCOMMAND_BASS_BOOST 20 #define APPCOMMAND_BASS_UP 21 #define APPCOMMAND_TREBLE_DOWN 22 #define APPCOMMAND_TREBLE_UP 23 #define APPCOMMAND_MICROPHONE_VOLUME_MUTE 24 #define APPCOMMAND_MICROPHONE_VOLUME_DOWN 25 #define APPCOMMAND_MICROPHONE_VOLUME_UP 26 #define APPCOMMAND_HELP 27 #define APPCOMMAND_FIND 28 #define APPCOMMAND_NEW 29 #define APPCOMMAND_OPEN 30 #define APPCOMMAND_CLOSE 31 #define APPCOMMAND_SAVE 32 #define APPCOMMAND_PRINT 33 #define APPCOMMAND_UNDO 34 #define APPCOMMAND_REDO 35 #define APPCOMMAND_COPY 36 #define APPCOMMAND_CUT 37 #define APPCOMMAND_PASTE 38 #define APPCOMMAND_REPLY_TO_MAIL 39 #define APPCOMMAND_FORWARD_MAIL 40 #define APPCOMMAND_SEND_MAIL 41 #define APPCOMMAND_SPELL_CHECK 42 #define APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE 43 #define APPCOMMAND_MIC_ON_OFF_TOGGLE 44 #define APPCOMMAND_CORRECTION_LIST 45 #define APPCOMMAND_MEDIA_PLAY 46 #define APPCOMMAND_MEDIA_PAUSE 47 #define APPCOMMAND_MEDIA_RECORD 48 #define APPCOMMAND_MEDIA_FAST_FORWARD 49 #define APPCOMMAND_MEDIA_REWIND 50 #define APPCOMMAND_MEDIA_CHANNEL_UP 51 #define APPCOMMAND_MEDIA_CHANNEL_DOWN 52 BOOL WindowsOpMessageLoop::OnAppCommand(UINT32 lParam) { INT32 command = GET_APPCOMMAND_LPARAM(lParam); BOOL mouse = GET_DEVICE_LPARAM(lParam) & FAPPCOMMAND_MOUSE; OpInputAction::Action action = OpInputAction::ACTION_UNKNOWN; INTPTR action_data = 0; // try pause first for this special double app command switch (command) { case APPCOMMAND_BROWSER_BACKWARD: action = OpInputAction::ACTION_BACK; break; case APPCOMMAND_BROWSER_FORWARD: action = OpInputAction::ACTION_FORWARD; break; case APPCOMMAND_BROWSER_FAVORITES: action = OpInputAction::ACTION_ACTIVATE_HOTLIST_WINDOW; break; case APPCOMMAND_BROWSER_HOME: action = OpInputAction::ACTION_GO_TO_HOMEPAGE; break; case APPCOMMAND_BROWSER_REFRESH: action = OpInputAction::ACTION_RELOAD; break; case APPCOMMAND_BROWSER_STOP: action = OpInputAction::ACTION_STOP; break; case APPCOMMAND_BROWSER_SEARCH: action = OpInputAction::ACTION_FOCUS_SEARCH_FIELD; break; case APPCOMMAND_COPY: action = OpInputAction::ACTION_COPY; break; case APPCOMMAND_FIND: action = OpInputAction::ACTION_FIND; break; case APPCOMMAND_UNDO: action = OpInputAction::ACTION_UNDO; break; case APPCOMMAND_REDO: action = OpInputAction::ACTION_REDO; break; case APPCOMMAND_CUT: action = OpInputAction::ACTION_CUT; break; case APPCOMMAND_PASTE: action = OpInputAction::ACTION_PASTE; break; case APPCOMMAND_HELP: action = OpInputAction::ACTION_SHOW_HELP; break; case APPCOMMAND_NEW: action = OpInputAction::ACTION_NEW_PAGE; break; case APPCOMMAND_OPEN: action = OpInputAction::ACTION_OPEN_DOCUMENT; break; case APPCOMMAND_CLOSE: action = OpInputAction::ACTION_CLOSE_PAGE; break; case APPCOMMAND_PRINT: action = OpInputAction::ACTION_PRINT_DOCUMENT; break; case APPCOMMAND_SAVE: action = OpInputAction::ACTION_SAVE_DOCUMENT_AS; break; #ifdef HAS_REMOTE_CONTROL case APPCOMMAND_VOLUME_MUTE: { g_input_manager->InvokeKeyPressed(OP_KEY_MUTE, 0); } break; case APPCOMMAND_MEDIA_NEXTTRACK: { g_input_manager->InvokeKeyPressed(OP_KEY_NEXT, 0); } break; case APPCOMMAND_MEDIA_PREVIOUSTRACK: { g_input_manager->InvokeKeyPressed(OP_KEY_PREVIOUS, 0); } break; case APPCOMMAND_MEDIA_STOP: { g_input_manager->InvokeKeyPressed(OP_KEY_STOP, 0); } break; case APPCOMMAND_MEDIA_PLAY: case APPCOMMAND_MEDIA_PLAY_PAUSE: { g_input_manager->InvokeKeyPressed(OP_KEY_PLAY, 0); } break; case APPCOMMAND_MEDIA_PAUSE: { g_input_manager->InvokeKeyPressed(OP_KEY_PAUSE, 0); } break; case APPCOMMAND_MEDIA_FAST_FORWARD: { g_input_manager->InvokeKeyPressed(OP_KEY_FASTFORWARD, 0); } break; case APPCOMMAND_MEDIA_REWIND: { g_input_manager->InvokeKeyPressed(OP_KEY_REWIND, 0); } break; case APPCOMMAND_MEDIA_RECORD: { g_input_manager->InvokeKeyPressed(OP_KEY_RECORD, 0); } break; case APPCOMMAND_MEDIA_CHANNEL_UP: { g_input_manager->InvokeKeyPressed(OP_KEY_CHANNELUP, 0); } break; case APPCOMMAND_MEDIA_CHANNEL_DOWN: { g_input_manager->InvokeKeyPressed(OP_KEY_CHANNELDOWN, 0); } break; case APPCOMMAND_VOLUME_UP: { g_input_manager->InvokeKeyPressed(OP_KEY_VOLUMEUP, 0); } break; case APPCOMMAND_VOLUME_DOWN: { g_input_manager->InvokeKeyPressed(OP_KEY_VOLUMEDOWN, 0); } break; #endif // HAS_REMOTE_CONTROL #ifdef M2_SUPPORT case APPCOMMAND_LAUNCH_MAIL: action = OpInputAction::ACTION_READ_MAIL; break; case APPCOMMAND_REPLY_TO_MAIL: action = OpInputAction::ACTION_REPLY; break; case APPCOMMAND_FORWARD_MAIL: action = OpInputAction::ACTION_FORWARD_MAIL; break; case APPCOMMAND_SEND_MAIL: action = OpInputAction::ACTION_SEND_MAIL; break; #endif } if (action != OpInputAction::ACTION_UNKNOWN) { // Performing this action immediately might lead to Opera hanging / crashing (see bug #193727). // Could be because we potentially end up here through DispatchMessage() in Run(), and when the // plugin tries to destroy itself it does things that it shouldn't do at the wrong time, or // something. Either way, we solve that by remembering the app command to invoke, and then // invoke it at the end of Run() (when we're well out of DispatchMessage()). OP_ASSERT(m_pending_app_command == NULL); m_pending_app_command = OP_NEW(AppCommandInfo, (action, mouse ? g_input_manager->GetMouseInputContext() : g_input_manager->GetKeyboardInputContext(), action_data)); if (m_pending_app_command == NULL) return FALSE; return TRUE; } return FALSE; } /*********************************************************************************** ** ** ConvertKey_VK_To_OP ** ***********************************************************************************/ OpKey::Code WindowsOpMessageLoop::ConvertKey_VK_To_OP(UINT32 vk_key) { /* The Windows virtual key mapping is now equal to the keycodes in OpKey. Consistent values across platforms..and a simpler mapping function for this particular one. */ return static_cast<OpKey::Code>(vk_key); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ /** * @file OpTrustAndSecurityButton.cpp * @author rfz@opera.com * * Contains function definitions for the classes defined in the corresponding * header file. */ #include "core/pch.h" #include "adjunct/quick/dialogs/SecurityInformationDialog.h" #include "adjunct/quick/managers/DesktopSecurityManager.h" #include "adjunct/quick/widgets/OpTrustAndSecurityButton.h" #include "modules/doc/doc.h" #include "modules/dochand/win.h" #include "modules/locale/locale-enum.h" #include "modules/locale/oplanguagemanager.h" /*static*/ OP_STATUS OpTrustAndSecurityButton::Construct(OpTrustAndSecurityButton ** obj) { *obj = OP_NEW(OpTrustAndSecurityButton, ()); if (!*obj) return OpStatus::ERR_NO_MEMORY; if (OpStatus::IsError((*obj)->init_status)) { OP_DELETE(*obj); return OpStatus::ERR_NO_MEMORY; } return OpStatus::OK; } /*********************************************************************************** ** ** OpTrustAndSecurityButton ** ***********************************************************************************/ OpTrustAndSecurityButton::OpTrustAndSecurityButton() : OpButton(OpButton::TYPE_CUSTOM), m_sec_mode(OpDocumentListener::UNKNOWN_SECURITY), m_suppress_text(FALSE) #ifdef TRUST_RATING , m_trust_mode(OpDocumentListener::TRUST_NOT_SET) #endif // TRUST_RATING #ifdef SECURITY_INFORMATION_PARSER , m_url_type(OpWindowCommander::WIC_URLType_Unknown) #endif // SECURITY_INFORMATION_PARSER { OpInputAction* action; if (OpStatus::IsSuccess(OpInputAction::CreateInputActionsFromString("Trust Unknown", action))) SetAction(action); SetButtonStyle(OpButton::STYLE_IMAGE_AND_TEXT_ON_RIGHT); SetFixedImage(FALSE); GetBorderSkin()->SetImage("Low Security Button Skin"); GetBorderSkin()->SetForeground(TRUE); SetText(UNI_L("")); } /*********************************************************************************** ** ** SetTrustAndSecurityLevel ** ***********************************************************************************/ BOOL OpTrustAndSecurityButton::SetTrustAndSecurityLevel( const OpString & button_text, OpWindowCommander* wic, OpAuthenticationCallback* callback /* = NULL*/, BOOL show_server_name/* = FALSE*/, BOOL always_visible /* = FALSE*/) { if (!wic && !callback) return FALSE; SetText(UNI_L("")); OpDocumentListener::SecurityMode old_sec_mode = m_sec_mode; if (wic) { m_sec_mode = wic->GetSecurityMode(); m_server_name.Set(wic->GetCurrentURL(FALSE)); m_trust_mode = wic->GetTrustMode(); #ifdef SECURITY_INFORMATION_PARSER m_url_type = wic->GetWicURLType(); #endif // SECURITY_INFORMATION_PARSER } else // if (auth_info) { #ifdef SECURITY_INFORMATION_PARSER if ( callback->GetType() != OpAuthenticationCallback::PROXY_AUTHENTICATION_NEEDED && callback->GetType() != OpAuthenticationCallback::PROXY_AUTHENTICATION_WRONG) m_sec_mode = (OpDocumentListener::SecurityMode) callback->GetSecurityMode(); #endif // SECURITY_INFORMATION_PARSER m_server_name.Set(callback->ServerUniName()); #ifdef SECURITY_INFORMATION_PARSER m_trust_mode = (OpDocumentListener::TrustMode) callback->GetTrustMode(); m_url_type = (OpWindowCommander::WIC_URLType) callback->GetWicURLType(); #endif // SECURITY_INFORMATION_PARSER } OpDocumentListener::TrustMode old_trust_mode = m_trust_mode; // Set the buttons appearance. if (always_visible || ButtonNeedsToBeVisible()) { if (m_trust_mode == OpDocumentListener::PHISHING_DOMAIN) { SetFraudAppearance(); } else if (g_desktop_security_manager->IsEV(m_sec_mode)) { SetHighAssuranceAppearance(button_text); } else if (m_sec_mode == OpDocumentListener::HIGH_SECURITY) { SetSecureAppearance(button_text); } else if (m_sec_mode == OpDocumentListener::NO_SECURITY) { SetInsecureAppearance(); } else { SetUnknownAppearance(); } if (show_server_name) SetText(button_text.CStr()); } return ((old_sec_mode != m_sec_mode) || (old_trust_mode != m_trust_mode)); } /*********************************************************************************** ** ** ButtonNeedsToBeVisible ** ***********************************************************************************/ BOOL OpTrustAndSecurityButton::ButtonNeedsToBeVisible() { if(m_trust_mode == OpDocumentListener::PHISHING_DOMAIN) return TRUE; // Don't display if // - The button has been disabled and the page is insecure. // or // - The page has no server name // or // - The page is not of type http nor https if ( (m_server_name.IsEmpty()) #ifdef SECURITY_INFORMATION_PARSER || ((m_url_type != OpWindowCommander::WIC_URLType_HTTP) && (m_url_type != OpWindowCommander::WIC_URLType_HTTPS) && (m_url_type != OpWindowCommander::WIC_URLType_FTP)) #endif // SECURITY_INFORMATION_PARSER ) { return FALSE; } // if there is no security or trust problems hide the button anyway if (m_sec_mode == OpDocumentListener::NO_SECURITY && m_trust_mode != OpDocumentListener::PHISHING_DOMAIN) { return FALSE; } return TRUE; } /*********************************************************************************** ** ** SetFraudAppearance ** ***********************************************************************************/ void OpTrustAndSecurityButton::SetFraudAppearance() { GetBorderSkin()->SetImage("Untrusted Site Security Button Skin"); GetBorderSkin()->SetForeground(TRUE); OpInputAction* fraud_action; if (OpStatus::IsSuccess(OpInputAction::CreateInputActionsFromString("Trust Fraud", fraud_action))) SetAction(fraud_action); OpString text; g_languageManager->GetString(Str::D_NEW_SECURITY_INFORMATION_FRAUD_SITE, text); SetText(text.CStr()); } /*********************************************************************************** ** ** SetSecureAppearance ** ***********************************************************************************/ void OpTrustAndSecurityButton::SetSecureAppearance(const OpString &button_text) { // The site has high security (encryption wise), therefore is must be ok. // A cert should should indicate even more trust, so we don't really // care if it is known or unknown. GetBorderSkin()->SetImage("Security Button Skin"); GetBorderSkin()->SetForeground(TRUE); OpInputAction* security_action; if (OpStatus::IsSuccess(OpInputAction::CreateInputActionsFromString("High Security,,,,High Security Simple", security_action))) SetAction(security_action); SetText(button_text.CStr()); } /*********************************************************************************** ** ** SetInsecureAppearance ** ***********************************************************************************/ void OpTrustAndSecurityButton::SetInsecureAppearance() { GetBorderSkin()->SetImage("Low Security Button Skin"); GetBorderSkin()->SetForeground(TRUE); OpInputAction* unknown_action; if (OpStatus::IsSuccess(OpInputAction::CreateInputActionsFromString("No Security", unknown_action))) SetAction(unknown_action); SetText(UNI_L("")); } /*********************************************************************************** ** ** SetUnknownAppearance ** ***********************************************************************************/ void OpTrustAndSecurityButton::SetUnknownAppearance() { GetBorderSkin()->SetImage("Low Security Button Skin"); GetBorderSkin()->SetForeground(TRUE); OpInputAction* unknown_action; #ifdef TRUST_RATING if (OpStatus::IsSuccess(OpInputAction::CreateInputActionsFromString("Trust Unknown", unknown_action))) #else // !TRUST_RATING if (OpStatus::IsSuccess(OpInputAction::CreateInputActionsFromString("No Security", unknown_action))) #endif // !TRUST_RATING SetAction(unknown_action); SetText(UNI_L("")); } /*********************************************************************************** ** ** SetKnownAppearance ** ***********************************************************************************/ void OpTrustAndSecurityButton::SetKnownAppearance() { GetBorderSkin()->SetImage("Low Security Button Skin"); GetBorderSkin()->SetForeground(TRUE); OpInputAction* information_action; if (OpStatus::IsSuccess(OpInputAction::CreateInputActionsFromString("Trust Information", information_action))) SetAction(information_action); SetText(UNI_L("")); } /*********************************************************************************** ** ** SetHighAssuranceAppearance ** ***********************************************************************************/ void OpTrustAndSecurityButton::SetHighAssuranceAppearance(const OpString &button_text) { GetBorderSkin()->SetImage("High Assurance Security Button Skin"); GetBorderSkin()->SetForeground(TRUE); OpInputAction* security_action; if (OpStatus::IsSuccess(OpInputAction::CreateInputActionsFromString("Extended Security", security_action))) SetAction(security_action); SetText(button_text.CStr()); } /*********************************************************************************** ** ** SetText ** ***********************************************************************************/ OP_STATUS OpTrustAndSecurityButton::SetText(const uni_char* text) { RETURN_IF_ERROR(m_button_text.Set(text)); if (m_suppress_text) return OpButton::SetText(UNI_L("")); else return OpButton::SetText(text); } /*********************************************************************************** ** ** SuppressText ** ***********************************************************************************/ void OpTrustAndSecurityButton::SuppressText(BOOL suppress) { if (suppress == m_suppress_text) return; m_suppress_text = suppress; if (suppress) OpButton::SetText(UNI_L("")); else OpButton::SetText(m_button_text.CStr()); } /*********************************************************************************** ** ** GetScaledRequiredSize ** ***********************************************************************************/ void OpTrustAndSecurityButton::GetRequiredSize(INT32& width, INT32& height) { INT32 in_width = width; INT32 in_height = height; INT32 suppressed_text_width; INT32 scaled_suppressed_text_width; // GetRequiredSize if (!m_suppress_text) OpButton::SetText(UNI_L("")); OpButton::GetRequiredSize(suppressed_text_width, height); // ignore this value of height OpButton::SetText(m_button_text.CStr()); OpButton::GetRequiredSize(width, height); // use this value of height if (m_suppress_text) OpButton::SetText(UNI_L("")); if (height != in_height) { // We are going to scale the security button image, so // we should scale the width as well as the height float image_scale_factor = ((float)in_height) / ((float)height); scaled_suppressed_text_width = (INT32) (image_scale_factor * (float)suppressed_text_width); } else scaled_suppressed_text_width = suppressed_text_width; width -= suppressed_text_width - scaled_suppressed_text_width; if (in_width - width < 200) { width = scaled_suppressed_text_width; SuppressText(TRUE); } else SuppressText(FALSE); }
#include <iostream> #include <cstring> #include <set> const int DAY = 1440; int parse_time(const std::string &t) { return stoi(t.substr(0, 2)) * 60 + stoi(t.substr(3, 5)); } int main() { std::cin.sync_with_stdio(false); std::cin.tie(NULL); std::string s, e, q, s_Time, s_Name; std::set<std::string> book; int S, E, Q, ans = 0; std::cin >> s >> e >> q; S = parse_time(s); E = parse_time(e); Q = parse_time(q); while(!(std::cin >> s_Time).eof()) { std::cin >> s_Name; int time = parse_time(s_Time); if(S >= time) { if(book.find(s_Name) == book.end()) { book.insert(s_Name); } } else if(E <= time && time <= Q) { auto idx = book.find(s_Name); if(idx != book.end()) { ans++; book.erase(idx); } } } std::cout << ans << '\n'; return 0; }
#include <iostream> using namespace std ; int array[10][10] ; int count [10] ; void add_graph(int a , int b, int array[10][10], int count[10]) { array[a][b] = 1 ; array[b][a] = 1 ; count[a] = 1 ; count[b] = 1 ; } void show_graph(int array[10][10]){ for (int i = 1; i < 10; i++) { int temp = 0 ; if (count[i] == 1){ cout << i << " : "; } for (int j = 1; j < 10; j++) { if(array[i][j] == 1 ) { if (temp > 0) { cout << " -> " ; } cout << j ; temp++ ; } } cout << endl ; } } int main(int argc, char const *argv[]) { add_graph(1,2,array,count) ; add_graph(4,1,array,count) ; add_graph(3,2,array,count) ; add_graph(6,5,array,count) ; add_graph(7,5,array,count) ; show_graph(array) ; return 0; }
#ifndef epic_image_h__ #define epic_image_h__ #include <SDL.h> #include <string> class Image { public: // These two functions are such a bad idea (for at least two reasons) static SDL_Renderer *sdl_renderer(SDL_Renderer *ren = nullptr) { static SDL_Renderer *renderer = ren; return renderer; } static SDL_Window *sdl_window(SDL_Window *win = nullptr) { static SDL_Window *window = win; return window; } /// \brief Create an image from the image at imgFilePath. /// \return nullptr if failure, otherwise a valid Image. static Image *load(const std::string &imgFilePath); Image(); virtual ~Image(); void draw(); /// \brief Translate the image to given destination. /// \param p Where the upper-left corner of this Image should be. // void scale(const SDL_Point &p); void scale(float s); /// \brief Upscale this image as large as possible for the SDL_window size. void maximize(); /// \brief Zoom by a factor of provided value. // void zoom(float); /// \brief Pan the source rectangle around by the given amount. void panBy(const SDL_Point &delta); void panBy(int dx, int dy); /// \brief Translate the image by the provided delta. /// \param delta How much to move the upper-left corner of this Image. void translateBy(const SDL_Point &delta); void translateBy(int dx, int dy); /// \brief Set the size of this image. void setSize(const SDL_Point &p); void setSize(int w, int h); /// \brief Set the position of upper left corner. void setPos(const SDL_Point &p); void setPos(int x, int y); /// \brief Get the upper left corner SDL_Point getPos() const; /// \brief Compute and return center coordinate. SDL_Point getCenter() const; /// \brief Get the bounding rectangle for this image. const SDL_Rect &getBounds() const; void setBounds(const SDL_Rect &r); /// \brief Get the texture from SDL that is this image. SDL_Texture *getTexture() const; /// \brief int getWidth() const; /// \brief int getHeight() const; /// \brief int getTexWidth() const; /// \brief int getTexHeight() const; float getScaleFactor() const; void setBaseScaleFactor(float baseScaleFactor); float getBaseScaleFactor() const; private: SDL_Texture *m_texture; SDL_Rect m_bbox; ///< The bounding box for this image SDL_Rect m_src; ///< The cropping rectangle for this image. SDL_Point m_texDims; float m_scaleFactor; float m_baseScaleFactor; }; #endif // ! epic_image_h__
#include <fstream> int main() { std::fstream i("input.txt"), o("output.txt", 2); int n, j, s = 0; i >> n; for (j = 1; j <= n; j++) { if (n % j == 0) s += j; } o << s; }
// 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 <pika/config.hpp> #include <pika/assert.hpp> #include <pika/coroutines/thread_enums.hpp> #include <pika/errors/try_catch_exception_ptr.hpp> #include <pika/execution/algorithms/execute.hpp> #include <pika/execution/algorithms/schedule_from.hpp> #include <pika/execution/executors/execution_parameters.hpp> #include <pika/execution_base/receiver.hpp> #include <pika/execution_base/sender.hpp> #include <pika/threading_base/annotated_function.hpp> #include <pika/threading_base/register_thread.hpp> #include <pika/threading_base/thread_description.hpp> #include <cstddef> #include <exception> #include <string> #include <type_traits> #include <utility> namespace pika::execution::experimental { struct thread_pool_scheduler { constexpr thread_pool_scheduler() = default; explicit thread_pool_scheduler(pika::threads::detail::thread_pool_base* pool) : pool_(pool) { } /// \cond NOINTERNAL bool operator==(thread_pool_scheduler const& rhs) const noexcept { return pool_ == rhs.pool_ && priority_ == rhs.priority_ && stacksize_ == rhs.stacksize_ && schedulehint_ == rhs.schedulehint_; } bool operator!=(thread_pool_scheduler const& rhs) const noexcept { return !(*this == rhs); } pika::threads::detail::thread_pool_base* get_thread_pool() { PIKA_ASSERT(pool_); return pool_; } // support with_priority property friend thread_pool_scheduler tag_invoke(pika::execution::experimental::with_priority_t, thread_pool_scheduler const& scheduler, pika::execution::thread_priority priority) { auto sched_with_priority = scheduler; sched_with_priority.priority_ = priority; return sched_with_priority; } friend pika::execution::thread_priority tag_invoke( pika::execution::experimental::get_priority_t, thread_pool_scheduler const& scheduler) { return scheduler.priority_; } // support with_stacksize property friend thread_pool_scheduler tag_invoke(pika::execution::experimental::with_stacksize_t, thread_pool_scheduler const& scheduler, pika::execution::thread_stacksize stacksize) { auto sched_with_stacksize = scheduler; sched_with_stacksize.stacksize_ = stacksize; return sched_with_stacksize; } friend pika::execution::thread_stacksize tag_invoke( pika::execution::experimental::get_stacksize_t, thread_pool_scheduler const& scheduler) { return scheduler.stacksize_; } // support with_hint property friend thread_pool_scheduler tag_invoke(pika::execution::experimental::with_hint_t, thread_pool_scheduler const& scheduler, pika::execution::thread_schedule_hint hint) { auto sched_with_hint = scheduler; sched_with_hint.schedulehint_ = hint; return sched_with_hint; } friend pika::execution::thread_schedule_hint tag_invoke( pika::execution::experimental::get_hint_t, thread_pool_scheduler const& scheduler) { return scheduler.schedulehint_; } // support with_annotation property friend constexpr thread_pool_scheduler tag_invoke( pika::execution::experimental::with_annotation_t, thread_pool_scheduler const& scheduler, char const* annotation) { auto sched_with_annotation = scheduler; sched_with_annotation.annotation_ = annotation; return sched_with_annotation; } friend thread_pool_scheduler tag_invoke(pika::execution::experimental::with_annotation_t, thread_pool_scheduler const& scheduler, std::string annotation) { auto sched_with_annotation = scheduler; sched_with_annotation.annotation_ = pika::detail::store_function_annotation(PIKA_MOVE(annotation)); return sched_with_annotation; } // support get_annotation property friend constexpr char const* tag_invoke(pika::execution::experimental::get_annotation_t, thread_pool_scheduler const& scheduler) noexcept { return scheduler.annotation_; } template <typename F> void execute(F&& f, char const* fallback_annotation) const { pika::detail::thread_description desc(f, fallback_annotation); threads::detail::thread_init_data data( threads::detail::make_thread_function_nullary(PIKA_FORWARD(F, f)), desc, priority_, schedulehint_, stacksize_); threads::detail::register_work(data, pool_); } template <typename F> friend void tag_invoke(execute_t, thread_pool_scheduler const& sched, F&& f) { sched.execute(PIKA_FORWARD(F, f), sched.get_fallback_annotation()); } template <typename Scheduler, typename Receiver> struct operation_state { PIKA_NO_UNIQUE_ADDRESS std::decay_t<Scheduler> scheduler; PIKA_NO_UNIQUE_ADDRESS std::decay_t<Receiver> receiver; char const* fallback_annotation; template <typename Scheduler_, typename Receiver_> operation_state( Scheduler_&& scheduler, Receiver_&& receiver, char const* fallback_annotation) : scheduler(PIKA_FORWARD(Scheduler_, scheduler)) , receiver(PIKA_FORWARD(Receiver_, receiver)) , fallback_annotation(fallback_annotation) { PIKA_ASSERT(fallback_annotation != nullptr); } operation_state(operation_state&&) = delete; operation_state(operation_state const&) = delete; operation_state& operator=(operation_state&&) = delete; operation_state& operator=(operation_state const&) = delete; friend void tag_invoke(start_t, operation_state& os) noexcept { pika::detail::try_catch_exception_ptr( [&]() { os.scheduler.execute( [receiver = PIKA_MOVE(os.receiver)]() mutable { pika::execution::experimental::set_value(PIKA_MOVE(receiver)); }, os.fallback_annotation); }, [&](std::exception_ptr ep) { pika::execution::experimental::set_error( PIKA_MOVE(os.receiver), PIKA_MOVE(ep)); }); } }; template <typename Scheduler> struct sender { using is_sender = void; PIKA_NO_UNIQUE_ADDRESS std::decay_t<Scheduler> scheduler; // We explicitly get the fallback annotation when constructing the // sender so that if the scheduler has no annotation, the annotation // is instead taken from the context creating the sender, not from // the context when the task is actually spawned (if different). char const* fallback_annotation = scheduler.get_fallback_annotation(); template <template <typename...> class Tuple, template <typename...> class Variant> using value_types = Variant<Tuple<>>; template <template <typename...> class Variant> using error_types = Variant<std::exception_ptr>; static constexpr bool sends_done = false; using completion_signatures = pika::execution::experimental::completion_signatures< pika::execution::experimental::set_value_t(), pika::execution::experimental::set_error_t(std::exception_ptr)>; template <typename Receiver> friend operation_state<Scheduler, Receiver> tag_invoke(connect_t, sender&& s, Receiver&& receiver) { return {PIKA_MOVE(s.scheduler), PIKA_FORWARD(Receiver, receiver), s.fallback_annotation}; } template <typename Receiver> friend operation_state<Scheduler, Receiver> tag_invoke(connect_t, sender const& s, Receiver&& receiver) { return {s.scheduler, PIKA_FORWARD(Receiver, receiver), s.fallback_annotation}; } struct env { PIKA_NO_UNIQUE_ADDRESS std::decay_t<Scheduler> scheduler; friend std::decay_t<Scheduler> tag_invoke( pika::execution::experimental::get_completion_scheduler_t< pika::execution::experimental::set_value_t>, env const& e) noexcept { return e.scheduler; } }; friend env tag_invoke( pika::execution::experimental::get_env_t, sender const& s) noexcept { return {s.scheduler}; } }; friend sender<thread_pool_scheduler> tag_invoke(schedule_t, thread_pool_scheduler&& sched) { return {PIKA_MOVE(sched)}; } friend sender<thread_pool_scheduler> tag_invoke( schedule_t, thread_pool_scheduler const& sched) { return {sched}; } // We customize schedule_from to customize transfer. We want transfer to // take the annotation from the calling context of transfer if needed // and available. If we don't customize schedule_from the schedule // customization will be called much later by the schedule_from default // implementation, and the annotation may no longer come from the // calling context of transfer. // // This updates the annotation of the scheduler with // get_fallback_annotation. If scheduler already has an annotation it // will simply set the same annotation. However, if scheduler doesn't // have an annotation set it will get it from the context calling // transfer if available, and otherwise fall back to the default // annotation. Once the scheduler annotation has been updated we // construct a sender from the default schedule_from implementation. // // TODO: Can we simply dispatch to the default implementation? This is // disabled with stdexec because we don't want to use implementation // details of it. #if !defined(PIKA_HAVE_STDEXEC) template <typename Sender, PIKA_CONCEPT_REQUIRES_(is_sender_v<Sender>)> friend auto tag_invoke(schedule_from_t, thread_pool_scheduler&& scheduler, Sender&& predecessor_sender) { return schedule_from_detail::schedule_from_sender<Sender, thread_pool_scheduler>{ PIKA_FORWARD(Sender, predecessor_sender), with_annotation(PIKA_MOVE(scheduler), scheduler.get_fallback_annotation())}; } template <typename Sender, PIKA_CONCEPT_REQUIRES_(is_sender_v<Sender>)> friend auto tag_invoke( schedule_from_t, thread_pool_scheduler const& scheduler, Sender&& predecessor_sender) { return schedule_from_detail::schedule_from_sender<Sender, thread_pool_scheduler>{ PIKA_FORWARD(Sender, predecessor_sender), with_annotation(scheduler, scheduler.get_fallback_annotation())}; } #endif /// \endcond private: /// \cond NOINTERNAL char const* get_fallback_annotation() const { // Scheduler annotations have priority if (annotation_) { return annotation_; } // Next is the annotation from the current context scheduling work pika::threads::detail::thread_id_type id = pika::threads::detail::get_self_id(); if (id) { pika::detail::thread_description desc = pika::threads::detail::get_thread_description(id); if (desc.kind() == pika::detail::thread_description::data_type_description) { return desc.get_description(); } } // If there are no annotations in the scheduler or scheduling // context, use "<unknown>". Explicitly do not use nullptr here to // avoid thread_description taking the current annotation from the // spawning context. return "<unknown>"; } pika::threads::detail::thread_pool_base* pool_ = pika::threads::detail::get_self_or_default_pool(); pika::execution::thread_priority priority_ = pika::execution::thread_priority::normal; pika::execution::thread_stacksize stacksize_ = pika::execution::thread_stacksize::small_; pika::execution::thread_schedule_hint schedulehint_{}; char const* annotation_ = nullptr; /// \endcond }; } // namespace pika::execution::experimental
#pragma once #include<memory> #include <gvc.h> class Situation; /** * A Transition describes the transition and the output between two situations */ class Transition { public: /** * Constructs a new Transition with the given predecessor, successor, transition count and transition probability. * Used when retrieving Transitions from the data storage. * @param from Pointer to the predecessor Situation. * @param to Pointer to the successor Situation. * @param count Number of times this Transition was recorded. * @param probability Probability that this Transition occurs in the predecessor Situation. */ Transition(std::shared_ptr<Situation> from, std::shared_ptr<Situation> to, int count, double probability); /** * Constructs a new Transition with the given predecessor, successor and no transition probability. * Used when recording a new Transition. * @param from Pointer to the predecessor Situation. * @param to Pointer to the successor Situation. */ Transition(std::shared_ptr<Situation> from, std::shared_ptr<Situation> to); /** * Standard Deconstructor. */ ~Transition(); /** * Getter for predecessor situation * @returns Predecessor situation */ std::shared_ptr<Situation> getFromSituation() const; /** * Getter for successor situation * @returns Successor situation */ std::shared_ptr<Situation> getToSituation() const; /** * Getter for the proability of the occurrence of this transition. * @returns Probability of the occurrence of this transition. */ double getProbability() const; /** * Override operator == * @param other Transition this one is compared to. * @return true if both predecessor and successor Situations are equal. The probability is not considered. */ bool operator==(const Transition &other) const; /** * Override operator != * @param other Transition this one is compared to. * @return true iff == returns false */ bool operator!=(const Transition &other) const; /** * Adds the edge representation of this Transition to the graph. * @param graph Pointer to the graph struct this Transition should be added to. * @param id Unique ID of the resulting edge struct in the graph. * @return Pointer to the resulting edge struct. */ Agedge_t * addAsEdge(Agraph_t *graph, const int id); private: std::shared_ptr<Situation> fromSituation; std::shared_ptr<Situation> toSituation; double probability; int count; Agedge_t *edge; };
#include "2-1.h" #include <stdlib.h> enum Gender { MALE=1, FEMALE=2}; typedef struct { char Name[20]; Gender Sex; int Age; char Phone_Number[20]; } Profile; int main() { int sex; Profile H_Class[10]; // Profile *H_Class2; Profile* H_Class3; H_Class3 = new Profile [10]; cin >> H_Class[0].Name; cin >> H_Class[1].Name; cin >> sex; // H_Class2 = H_Class; // H_Class2++; // cout << H_Class2->Name; if(sex == MALE) H_Class[0].Sex = MALE; else H_Class[0].Sex = FEMALE; cin >> H_Class[0].Age; cin >> H_Class[0].Phone_Number; cout << endl; cout << H_Class[0].Name << endl; cout << H_Class[0].Sex << endl; cout << H_Class[0].Age << endl; cout << H_Class[0].Phone_Number << endl; delete[] H_Class3; return 0; }
#include<bits/stdc++.h> #define rep(i,n) for (int i =0; i <(n); i++) using namespace std; using ll = long long; const double PI = 3.14159265358979323846; const ll MOD = 1000000007; int main(){ string S; cin >> S; int N = (int)S.size(); for(int i = 0; i < N/2; i++){ if(S.at(i) != S.at(N-i-1)){ cout << "NO" << endl; return 0; } } cout << "YES" << endl; return 0; }
#ifndef REGISTRO_H #define REGISTRO_H #include <stdlib.h> #include <fstream> #include <sstream> #include "Hora.h" #include "Fecha.h" class Registro { private: Fecha f, fUTC; Hora h, hUTC; float magnitud, latitud, longitud, profundidad; string referenciaDeLocalizacion, estatus; public: Registro(void); void muestraTusDatos(void); void pideleAlUsuarioTusDatos(void); void modificaTuMagnitud(float m); void modificaTuLatitud(float l); void modificaTuLongitud(float l); void modificaTuProfundidad(float p); void modificaTuHora(Hora h1); void modificaTuHoraUTC(Hora h1); void modificaTuFecha(Fecha f1); void modificaTuFechaUTC(Fecha f1); void modificaTuReferencia(string r); void modificaTuEstatus(string e); void leeDatos(void); }; Registro::Registro(void){ magnitud = 0; latitud = 0; longitud = 0; profundidad = 0; referenciaDeLocalizacion = "N/A"; estatus = "N/A"; } void Registro::muestraTusDatos(void){ cout << "Fecha: " << f << endl << "Hora: " << h << endl << "Magnitud: " << magnitud << endl << "Latitud: " << latitud << endl << "Longitud: " << longitud << endl << "Profundidad: " << profundidad << endl << "Referencia de localizacion: " << referenciaDeLocalizacion << endl << "Fecha UTC: " << fUTC << endl << "Hora UTC: " << hUTC << endl << "Estatus: " << estatus << endl << endl; } void Registro::pideleAlUsuarioTusDatos(void){ cout << "Dame mi fecha: "; cin >> f; cout << "Dame mi hora: "; cin >> h; cout << "Dame mi magnitud: "; cin >> magnitud; cout << "Dame mi latitud: "; cin >> latitud; cout << "Dame mi longitud: "; cin >> longitud; cout << "Dame mi profundidad: "; cin >> profundidad; cout << "Dame mi referencia de localizacion: "; cin >> referenciaDeLocalizacion; cout << "Dame mi fecha UTC: "; cin >> fUTC; cout << "Dame mi hora UTC: "; cin >> hUTC; cout << "Dame mi estatus: "; cin >> estatus; } void Registro::modificaTuMagnitud(float m){ magnitud = m; } void Registro::modificaTuLatitud(float l){ latitud = l; } void Registro::modificaTuLongitud(float l){ longitud = l; } void Registro::modificaTuProfundidad(float p){ profundidad = p; } void Registro::modificaTuHora(Hora h1){ this->h = h1; } void Registro::modificaTuHoraUTC(Hora h1){ this->hUTC = h1; } void Registro::modificaTuFecha(Fecha f1){ this->f = f1; } void Registro::modificaTuFechaUTC(Fecha f1){ this->fUTC = f1; } void Registro::modificaTuReferencia(string r){ this->referenciaDeLocalizacion = r; } void Registro::modificaTuEstatus(string e){ this->estatus = e; } void Registro::leeDatos(void){ Fecha fx; Hora hx; int entero; char car; float flotante; string cadena; ifstream archivo_in; stringstream datosRegistro; string datos, dato, dato2, dato3; archivo_in.open("SSNMX_catalogo_20181001_20181026.csv"); datosRegistro.str(datos); //Secuencia para leer fecha archivo_in >> entero; fx.modificaTuA(entero); archivo_in >> car; archivo_in >> entero; fx.modificaTuM(entero); archivo_in >> car; archivo_in >> entero; fx.modificaTuD(entero); archivo_in >> car; f = fx; //Secuencia para leer hora archivo_in >> entero; hx.modificaTuH(entero); archivo_in >> car; archivo_in >> entero; hx.modificaTuM(entero); archivo_in >> car; archivo_in >> entero; hx.modificaTuS(entero); archivo_in >> car; h = hx; //Secuencia para otros datos archivo_in >> flotante; magnitud = flotante; archivo_in >> car; archivo_in >> flotante; latitud = flotante; archivo_in >> car; archivo_in >> flotante; longitud = flotante; archivo_in >> car; archivo_in >> flotante; profundidad = flotante; archivo_in >> car; archivo_in >> car; //Leer cadena (referencia) //getline(archivo_in,dato,','); getline(archivo_in,dato2,'"'); //referenciaDeLocalizacion = dato + "," + dato2; referenciaDeLocalizacion = dato2; archivo_in >> car; //Secuencia para leer fecha archivo_in >> entero; fx.modificaTuA(entero); archivo_in >> car; archivo_in >> entero; fx.modificaTuM(entero); archivo_in >> car; archivo_in >> entero; fx.modificaTuD(entero); archivo_in >> car; fUTC = fx; //Secuencia para leer hora archivo_in >> entero; hx.modificaTuH(entero); archivo_in >> car; archivo_in >> entero; hx.modificaTuM(entero); archivo_in >> car; archivo_in >> entero; hx.modificaTuS(entero); archivo_in >> car; hUTC = hx; //Secuencia para leer estatus archivo_in >> cadena; estatus = cadena; archivo_in >> car; archivo_in.close(); } #endif // REGISTRO_H
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2018 Lee Clagett <https://github.com/vtnerd> * Copyright 2018-2021 SChernykh <https://github.com/SChernykh> * Copyright 2016-2021 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef XMRIG_ALGORITHM_H #define XMRIG_ALGORITHM_H #include <vector> #include "3rdparty/rapidjson/fwd.h" namespace xmrig { class Algorithm { public: // Changes in following file is required if this enum changed: // // src/backend/opencl/cl/cn/algorithm.cl // enum Id : int { CN_0, // "cn/0" CryptoNight (original). CN_1, // "cn/1" CryptoNight variant 1 also known as Monero7 and CryptoNightV7. CN_2, // "cn/2" CryptoNight variant 2. CN_R, // "cn/r" CryptoNightR (Monero's variant 4). CN_FAST, // "cn/fast" CryptoNight variant 1 with half iterations. CN_HALF, // "cn/half" CryptoNight variant 2 with half iterations (Masari/Torque). CN_XAO, // "cn/xao" CryptoNight variant 0 (modified, Alloy only). CN_RTO, // "cn/rto" CryptoNight variant 1 (modified, Arto only). CN_RWZ, // "cn/rwz" CryptoNight variant 2 with 3/4 iterations and reversed shuffle operation (Graft). CN_ZLS, // "cn/zls" CryptoNight variant 2 with 3/4 iterations (Zelerius). CN_DOUBLE, // "cn/double" CryptoNight variant 2 with double iterations (X-CASH). CN_LITE_0, // "cn-lite/0" CryptoNight-Lite variant 0. CN_LITE_1, // "cn-lite/1" CryptoNight-Lite variant 1. CN_HEAVY_0, // "cn-heavy/0" CryptoNight-Heavy (4 MB). CN_HEAVY_TUBE, // "cn-heavy/tube" CryptoNight-Heavy (modified, TUBE only). CN_HEAVY_XHV, // "cn-heavy/xhv" CryptoNight-Heavy (modified, Haven Protocol only). CN_PICO_0, // "cn-pico" CryptoNight-Pico CN_PICO_TLO, // "cn-pico/tlo" CryptoNight-Pico (TLO) CN_CCX, // "cn/ccx" Conceal (CCX) CN_GPU, // "cn/gpu" CryptoNight-GPU (Ryo). CN_UPX2, // "cn/upx2" Uplexa (UPX2) // CryptoNight variants must be above this line // (index of RX_0 is used in loops as "end of all CN families" marker) // next line MUST be RX_0 RX_0, // "rx/0" RandomX (reference configuration). RX_WOW, // "rx/wow" RandomWOW (Wownero). RX_ARQ, // "rx/arq" RandomARQ (Arqma). RX_SFX, // "rx/sfx" RandomSFX (Safex Cash). RX_KEVA, // "rx/keva" RandomKEVA (Keva). AR2_CHUKWA, // "argon2/chukwa" Argon2id (Chukwa). AR2_CHUKWA_V2, // "argon2/chukwav2" Argon2id (Chukwa v2). AR2_WRKZ, // "argon2/wrkz" Argon2id (WRKZ) ASTROBWT_DERO, // "astrobwt" AstroBWT (Dero) KAWPOW_RVN, // "kawpow/rvn" KawPow (RVN) RX_XLA, // "panthera" Panthera (Scala2). MAX, MIN = 0, INVALID = -1, }; enum Family : int { UNKNOWN, CN, CN_LITE, CN_HEAVY, CN_PICO, CN_FEMTO, RANDOM_X, ARGON2, ASTROBWT, KAWPOW }; inline Algorithm() = default; inline Algorithm(const char *algo) : m_id(parse(algo)) {} inline Algorithm(Id id) : m_id(id) {} Algorithm(const rapidjson::Value &value); inline bool isCN() const { auto f = family(); return f == CN || f == CN_LITE || f == CN_HEAVY || f == CN_PICO || f == CN_FEMTO; } inline bool isEqual(const Algorithm &other) const { return m_id == other.m_id; } inline bool isValid() const { return m_id != INVALID && family() != UNKNOWN; } inline const char *name() const { return name(false); } inline const char *shortName() const { return name(true); } inline Family family() const { return family(m_id); } inline Id id() const { return m_id; } inline bool operator!=(Algorithm::Id id) const { return m_id != id; } inline bool operator!=(const Algorithm &other) const { return !isEqual(other); } inline bool operator==(Algorithm::Id id) const { return m_id == id; } inline bool operator==(const Algorithm &other) const { return isEqual(other); } inline operator Algorithm::Id() const { return m_id; } rapidjson::Value toJSON() const; rapidjson::Value toJSON(rapidjson::Document &doc) const; size_t l2() const; size_t l3() const; uint32_t maxIntensity() const; static Family family(Id id); static Id parse(const char *name); private: const char *name(bool shortName) const; Id m_id = INVALID; }; using Algorithms = std::vector<Algorithm>; } /* namespace xmrig */ #endif /* XMRIG_ALGORITHM_H */
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <android/asset_manager.h> #include <sys/stat.h> #include "common.hpp" #include "loading_thread.hpp" LoadingThread::LoadingThread(AAssetManager *assetManager) { mAssetManager = assetManager; LaunchThread(); } LoadingThread::~LoadingThread() { std::lock_guard<std::mutex> threadLock(mThreadMutex); TerminateThread(); } void LoadingThread::StartAssetLoad(const char *assetName, const char *assetPath, const size_t bufferSize, void *loadBuffer, LoadingCompleteCallback callback, bool useAssetManager) { std::lock_guard<std::mutex> workLock(mWorkMutex); LoadingJob *loadingJob = new LoadingJob(); loadingJob->assetName = assetName; loadingJob->assetPath = assetPath; loadingJob->bufferSize = bufferSize; loadingJob->loadBuffer = loadBuffer; loadingJob->callback = callback; loadingJob->useAssetManager = useAssetManager; mWorkQueue.emplace(loadingJob); mWorkCondition.notify_all(); } void LoadingThread::LaunchThread() { std::lock_guard<std::mutex> threadLock(mThreadMutex); if (mThread.joinable()) { TerminateThread(); } mThread = std::thread([this]() { ThreadMain(); }); } void LoadingThread::TerminateThread() REQUIRES(mThreadMutex) { { std::lock_guard<std::mutex> workLock(mWorkMutex); mIsActive = false; mWorkCondition.notify_all(); } mThread.join(); } void LoadingThread::ThreadMain() { pthread_setname_np(pthread_self(), "LoadingThread"); std::lock_guard<std::mutex> lock(mWorkMutex); while (mIsActive) { mWorkCondition.wait( mWorkMutex, [this]() REQUIRES(mWorkMutex) { return !mWorkQueue.empty() || !mIsActive; }); if (!mWorkQueue.empty()) { LoadingJob *loadingJob = mWorkQueue.front(); mWorkQueue.pop(); // Drop the mutex while we execute mWorkMutex.unlock(); LoadingCompleteMessage loadingCompleteMessage; loadingCompleteMessage.assetName = loadingJob->assetName; loadingCompleteMessage.bytesRead = 0; loadingCompleteMessage.loadBuffer = loadingJob->loadBuffer; loadingCompleteMessage.loadSuccessful = false; if (loadingJob->useAssetManager) { AAsset *asset = AAssetManager_open(mAssetManager, loadingJob->assetName, AASSET_MODE_STREAMING); if (asset != NULL) { size_t assetSize = AAsset_getLength(asset); if (assetSize <= loadingJob->bufferSize) { AAsset_read(asset, loadingJob->loadBuffer, assetSize); loadingCompleteMessage.bytesRead = assetSize; loadingCompleteMessage.loadSuccessful = true; } AAsset_close(asset); } } else { FILE *fp = fopen(loadingJob->assetPath, "rb"); if (fp != NULL) { struct stat fileStats; size_t assetSize = 0; int statResult = fstat(fileno(fp), &fileStats); if (statResult == 0) { assetSize = fileStats.st_size; if (assetSize <= loadingJob->bufferSize) { fread(loadingJob->loadBuffer, assetSize, 1, fp); loadingCompleteMessage.bytesRead = assetSize; loadingCompleteMessage.loadSuccessful = true; } } fclose(fp); } delete[] loadingJob->assetPath; } loadingJob->callback(&loadingCompleteMessage); delete loadingJob; mWorkMutex.lock(); } } }
#include <iostream> #include <string> using std::cout; // end of recursion: print the rest void myPrintfImpl(char const *rest) { while (*rest) { if (*rest == '%') { ++rest; } cout << *rest++; } } template<typename T, typename... Ts> void myPrintfImpl(char const *fmt, T val, Ts... args) { while (*fmt) { if (*fmt == '%') { ++fmt; if (*fmt != '%') { cout << val; myPrintfImpl(fmt, args...); return; } } cout << *fmt++; } } template<typename... Ts> inline void myPrintf(const std::string &fmt, Ts... args) { myPrintfImpl(fmt.c_str(), args...); } int main() { std::string s{"Hello!"}; myPrintf("string: %, char *: %, double: %, int: % and a bare %%\n", s, "C++", 3.14159, 42); return 0; }
#include "adaptive_heat_equation.hpp" #include <iomanip> #include "../tools/linalg.hpp" namespace applications { AdaptiveHeatEquation::AdaptiveHeatEquation( std::shared_ptr<TypeXVector> vec_Xd, std::unique_ptr<TypeYLinForm> &&g_lin_form, std::unique_ptr<TypeXLinForm> &&u0_lin_form, const AdaptiveHeatEquationOptions &opts) : vec_Xd_(vec_Xd), vec_Xdd_(std::make_shared<TypeXVector>( GenerateXDeltaUnderscore(*vec_Xd_, opts.estimate_saturation_layers))), vec_Ydd_(std::make_shared<TypeYVector>( GenerateYDelta<DoubleTreeVector>(*vec_Xdd_))), heat_d_dd_(std::make_unique<HeatEquation>(vec_Xd_, vec_Ydd_, opts)), g_lin_form_(std::move(g_lin_form)), u0_lin_form_(std::move(u0_lin_form)), opts_(opts) {} Eigen::VectorXd AdaptiveHeatEquation::RHS() { Eigen::VectorXd rhs = g_lin_form_->Apply(heat_d_dd_->vec_Y()); rhs = heat_d_dd_->P_Y()->Apply(rhs); rhs = heat_d_dd_->BT()->Apply(rhs); rhs += u0_lin_form_->Apply(heat_d_dd_->vec_X()); return rhs; } std::pair<Eigen::VectorXd, tools::linalg::SolverData> AdaptiveHeatEquation::Solve(const Eigen::VectorXd &x0, const Eigen::VectorXd &rhs, double tol, enum tools::linalg::StoppingCriterium crit) { assert(heat_d_dd_); return tools::linalg::PCG(*heat_d_dd_->S(), rhs, *heat_d_dd_->P_X(), x0, opts_.solve_maxit, tol, crit); } auto AdaptiveHeatEquation::Estimate(const Eigen::VectorXd &u_dd_d) -> std::pair<TypeXVector *, std::pair<double, ErrorEstimator::GlobalError>> { ErrorEstimator::GlobalError global_error; { assert(heat_d_dd_); // Create heat equation with X_dd and Y_dd. HeatEquation heat_dd_dd(vec_Xdd_, vec_Ydd_, heat_d_dd_->A(), heat_d_dd_->P_Y(), /* Ydd_is_GenerateYDelta_Xdd */ true, opts_); // Prolongate u_dd_d from X_d to X_dd. vec_Xd_->FromVectorContainer(u_dd_d); vec_Xdd_->FromVector(*vec_Xd_); Eigen::VectorXd u_dd_dd = vec_Xdd_->ToVectorContainer(); // Calculate the residual and store inside the dbltree. Eigen::VectorXd g_min_Bu = g_lin_form_->Apply(vec_Ydd_.get()) - heat_dd_dd.B()->Apply(u_dd_dd); Eigen::VectorXd PY_g_min_Bu = heat_dd_dd.P_Y()->Apply(g_min_Bu); // \gamma_0' (u0 - \gamma_0 u^\delta) Eigen::VectorXd u0 = u0_lin_form_->Apply(vec_Xdd_.get()); Eigen::VectorXd G_u_dd_dd = heat_dd_dd.G()->Apply(u_dd_dd); Eigen::VectorXd residual = heat_dd_dd.BT()->Apply(PY_g_min_Bu) + (u0 - G_u_dd_dd); // Calculate the global error using the interpolant. vec_Xdd_->FromVectorContainer(u_dd_dd); double error_Yprime_sq = PY_g_min_Bu.dot(g_min_Bu); double error_t0 = ErrorEstimator::ComputeTraceError( 0.0, u0_lin_form_->SpaceLF().Function(), vec_Xdd_.get()); global_error.error = sqrt(error_Yprime_sq + error_t0); global_error.error_Yprime = sqrt(error_Yprime_sq); global_error.error_t0 = sqrt(error_t0); vec_Xdd_->FromVectorContainer(residual); // Let heat_dd_dd go out of scope.. } double residual_error = ErrorEstimator::ComputeLocalErrors( vec_Xdd_.get(), opts_.estimate_mean_zero); // We know that the residual on Xd should be small, so set it zero explicitly. auto vec_Xd_nodes = vec_Xdd_->Union(*vec_Xd_, /*call_filter*/ datastructures::func_false); assert(vec_Xd_nodes.size() == vec_Xd_->container().size()); for (auto &dblnode : vec_Xd_nodes) dblnode->set_value(0.0); return {vec_Xdd_.get(), {residual_error, global_error}}; } auto AdaptiveHeatEquation::Mark(TypeXVector *residual) -> std::vector<TypeXNode *> { auto nodes = vec_Xdd_->Bfs(); std::sort(nodes.begin(), nodes.end(), [](auto n1, auto n2) { return std::abs(n1->value()) > std::abs(n2->value()); }); double sq_norm = 0.0; for (auto node : nodes) sq_norm += node->value() * node->value(); double cur_sq_norm = 0.0; size_t last_idx = 0; for (; last_idx < nodes.size(); last_idx++) { cur_sq_norm += nodes[last_idx]->value() * nodes[last_idx]->value(); if (cur_sq_norm >= opts_.mark_theta * opts_.mark_theta * sq_norm) { nodes.resize(last_idx + 1); break; } } return nodes; } RefineInfo AdaptiveHeatEquation::Refine( const std::vector<TypeXNode *> &nodes_to_add) { RefineInfo info; size_t Xd_size = 0; // Calculate information before the conforming refinement. { double sq_norm = 0.0; info.nodes_marked = nodes_to_add.size(); for (auto n : nodes_to_add) sq_norm += n->value() * n->value(); info.res_norm_marked = sqrt(sq_norm); Xd_size = std::count_if(vec_Xd_->container().begin(), vec_Xd_->container().end(), [](const auto &n) { return !n.is_metaroot(); }); } // Refine the solution vector, requires vec_Xdd_. auto nodes_conforming = vec_Xd_->ConformingRefinement(*vec_Xdd_, nodes_to_add); // Calculate information after the conforming refinement. { double sq_norm = 0.0; for (auto n : nodes_conforming) sq_norm += n->value() * n->value(); info.res_norm_conforming = sqrt(sq_norm); size_t Xd_conf_size = std::count_if(vec_Xd_->container().begin(), vec_Xd_->container().end(), [](const auto &n) { return !n.is_metaroot(); }); info.nodes_conforming = Xd_conf_size - Xd_size; } // Reset the objects that we no longer need, this will free the memory. heat_d_dd_.reset(); vec_Xdd_.reset(); vec_Ydd_.reset(); vec_Xdd_ = std::make_shared<TypeXVector>( GenerateXDeltaUnderscore(*vec_Xd_, opts_.estimate_saturation_layers)); vec_Ydd_ = std::make_shared<TypeYVector>( GenerateYDelta<DoubleTreeVector>(*vec_Xdd_)); #ifdef VERBOSE std::cerr << std::left; std::cerr << std::endl << "AdaptiveHeatEquation::Refine" << std::endl; std::cerr << " vec_Xd: #bfs = " << std::setw(10) << vec_Xd_->Bfs().size() << "#container = " << vec_Xd_->container().size() << std::endl; std::cerr << " vec_Xdd: #bfs = " << std::setw(10) << vec_Xdd_->Bfs().size() << "#container = " << vec_Xdd_->container().size() << std::endl; std::cerr << " vec_Ydd: #bfs = " << std::setw(10) << vec_Ydd_->Bfs().size() << "#container = " << vec_Ydd_->container().size() << std::endl; std::cerr << std::right; #endif heat_d_dd_ = std::make_unique<HeatEquation>(vec_Xd_, vec_Ydd_, opts_); return info; } }; // namespace applications
#include <ezLCDLib.h> ezLCD3 lcd; int xPos = 25; // horizontal position int yPos = 50; // vertical position int width = 250; int height = 35; int option = 1; // 1=draw horizontal, 2=horizontal disabled, 3=vertical, // 4=vertical disabled, 5=redraw horizontal, // 6=redraw horizontal disabled, 7=redraw vertical, // 8=redraw vertical disabled int value = 0; int max= 128; int newvalue = 0; void setup() { lcd.begin( EZM_BAUD_RATE ); lcd.fontw( 1, "2" );//medium font lcd.theme( 1, 110, 106, 99, 0, 0, 105, 107, 0, 0, 1 ); lcd.cls( BLACK, WHITE ); lcd.string(1,"%"); //set string 1 to % for progress bar lcd.progressBar( 1, xPos, yPos, width, height, option, value, max, 1 ,1); } void loop() { int value = analogRead(0)/8; // value = map(value, 0, 1023, 0, 100); // scale it to use it with the servo (value between 0 and 180) if ( newvalue != value ) { lcd.wvalue(1, value); newvalue = value; } // value = map(value, 0, 1023, 0, 99); // scale it to use it with the servo (value between 0 and 180) // lcd.wvalue(1, value); delay(10); }
// // TCVec4f.cpp // threecpp // // Created by CastingJ on 16/9/21. // // #include "TCVec4f.h"
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef _SVG_MOTIONPATH_H_ #define _SVG_MOTIONPATH_H_ #ifdef SVG_SUPPORT #include "modules/svg/src/OpBpath.h" #include "modules/svg/src/SVGValue.h" #include "modules/svg/src/SVGMatrix.h" #include "modules/libvega/vegafixpoint.h" class VEGAPath; class SVGVector; class SVGKeySpline; struct FlattenedPathIndex; class SVGMotionPath { public: SVGMotionPath(); ~SVGMotionPath(); struct PositionDescriptor { PositionDescriptor(); SVGNumber where; SVGNumber next_where; SVGCalcMode calcMode; SVGVector* keyTimes; SVGVector* keyPoints; SVGVector* keySplines; SVGRotate* rotate; }; /** * Set which OpBpath to use. */ OP_STATUS Set(OpBpath* path, SVGNumber path_length, BOOL account_moveto = FALSE); /** * Set additional transform. */ void SetTransform(const SVGMatrix &matrix) { m_transform = matrix; } SVGMatrix GetMatrix() { return m_transform; } OP_STATUS GetCurrentTransformationValue(PositionDescriptor& pos, SVGMatrix &target); void SetFlatness(SVGNumber flatness) { m_flatness = flatness; } static SVGNumber CalculateKeySpline(SVGKeySpline* keyspline, SVGNumber flatness, SVGNumber q1); /** * Get the path segment at a certain length */ unsigned int GetSegmentIndexAtLength(SVGNumber len); /** * Distance is in pathlength coordinates */ void CalculateTransformAtDistance(SVGNumber distance, SVGRotate* rotate, SVGMatrix& target); void CalculateTransformAtDistance(SVGNumber distance, SVGMatrix& target) { SVGRotate rot(SVGROTATE_AUTO); CalculateTransformAtDistance(distance, &rot, target); } SVGNumber CalculateRotationAtDistance(SVGNumber distance); SVGNumber GetLength() { return m_vega_path_length; } #ifdef SVG_FULL_11 OP_STATUS Warp(const OpBpath* inpath, OpBpath** outpath, SVGNumber startDist, SVGNumber expansionFactor, SVGNumber half_width); #endif // SVG_FULL_11 BOOL HasPath(SVGObject* obj) { return m_path == obj; } BOOL HasPathLength(SVGNumber path_length) { return m_path_length == path_length; } private: OpBpath* m_path; SVGMatrix m_transform; VEGAPath* m_vega_path; SVGNumber m_vega_path_length; unsigned int m_vega_line_segments; unsigned int* m_vega_segment_indexes; SVGNumber* m_vega_segment_lengths; SVGNumber m_flatness; SVGNumber m_path_length; void Reset(); /** * Construct the VEGA path */ VEGAPath* ConstructVegaPath(BOOL account_moveto); /** * Get the length of the path */ static SVGNumber GetSubLength(VEGAPath* path, unsigned int start_idx, unsigned int end_idx); /** * Map distance along path to index in flattened path */ BOOL DistanceToLineIndex(SVGNumber distance, FlattenedPathIndex& fpi); #ifdef SVG_FULL_11 /** * Calculate factors used in path/glyph warping */ void CalculateWarpFactors(SVGNumber midpoint, SVGNumber half_width, SVGNumber& left_sf, SVGNumber& right_sf); #endif // SVG_FULL_11 /** * Calculate how far along the path we have come */ OP_STATUS CalculateCurrentDistanceAlongPath(PositionDescriptor& pos, SVGNumber& distance); /** * Get command count */ SVGNumber GetSegmentLength(unsigned int idx); /** * Get the accumulated length up to an interval */ SVGNumber GetAccumulatedSegmentLength(unsigned int idx); /** * Calculate position according to key times */ SVGNumber CalculateKeyTimes(PositionDescriptor& pos); /** * Calculate position according to key splines */ SVGNumber CalculateKeySplines(PositionDescriptor& pos, unsigned int whichInterval, SVGNumber& q1); }; #endif // SVG_SUPPORT && !SVG_USE_DEFAULT_MOTION_PATH #endif // _SVG_MOTIONPATH_H_
/* Name: ������ʵ�� Copyright: Author: Hill bamboo Date: 2019/8/17 12:42:44 Description: */ #include <bits/stdc++.h> using namespace std; class BigInteger { public: vector<int> data; BigInteger(int size) { data = vector<int>(size, 0); } BigInteger(string nums) { for (int i = nums.size() - 1; i >= 0; --i) { data.push_back(nums[i] - '0'); } } BigInteger(vector<int>& other) { data = other; } BigInteger operator + (const BigInteger& rhs) const { int n = data.size(); int m = rhs.data.size(); vector<int> res; int carry = 0; for (int i = 0; i < n || i < m; ++i) { if (i < m && i < n) { res.push_back((carry + data[i] + rhs.data[i]) % 10); carry = (carry + data[i] + rhs.data[i]) / 10; } else if (m <= i && i < n){ res.push_back((carry + data[i]) % 10); carry = (carry + data[i]) / 10; } else if (n <= i && i < m) { res.push_back((carry + rhs.data[i]) % 10); carry = (carry + rhs.data[i]) / 10; } } return BigInteger(res); } BigInteger operator * (const BigInteger& rhs) const { int n = data.size(), m = rhs.data.size(); int len = m + n - 1; BigInteger a(len, 0); BigInteger b(len, 0); // todo // int carry = 0; // for (int i = 0; i < n || i < m; ++i) { // if (i < m && i < n) { // res.push_back((carry + data[i] + rhs.data[i]) % 10); // carry = (carry + data[i] + rhs.data[i]) / 10; // } else if (m <= i && i < n){ // res.push_back((carry + data[i]) % 10); // carry = (carry + data[i]) / 10; // } else if (n <= i && i < m) { // res.push_back((carry + rhs.data[i]) % 10); // carry = (carry + rhs.data[i]) / 10; // } // } } ostream& operator << (ostream& out) { for (int i = data.size() - 1; i >= 0; --i) out << data[i]; return out; } }; int main() { BigInteger a("123"); BigInteger b("23"); auto c = a + b; for (int i = a.data.size() - 1; i >= 0; --i) cout << a.data[i]; cout << endl; for (int i = b.data.size() - 1; i >= 0; --i) cout << b.data[i]; cout << endl; for (int i = c.data.size() - 1; i >= 0; --i) cout << c.data[i]; cout << endl; return 0; }
#include "core.h" void out(char** text) { for (int i = 0; i < 10; i++) cout << text[i]; }
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "SamplingProfiler.h" #include "CaptureData.h" #include "OrbitClientData/FunctionUtils.h" using orbit_client_protos::CallstackEvent; using orbit_client_protos::FunctionInfo; using orbit_client_protos::LinuxAddressInfo; namespace { std::multimap<int, CallstackID> SortCallstacks(const ThreadSampleData& data, const std::set<CallstackID>& callstacks) { std::multimap<int, CallstackID> sorted_callstacks; for (CallstackID id : callstacks) { auto it = data.callstack_count.find(id); if (it != data.callstack_count.end()) { int count = it->second; sorted_callstacks.insert(std::make_pair(count, id)); } } return sorted_callstacks; } } // namespace uint32_t ThreadSampleData::GetCountForAddress(uint64_t address) const { auto res = raw_address_count.find(address); if (res == raw_address_count.end()) { return 0; } return (*res).second; } std::multimap<int, CallstackID> SamplingProfiler::GetCallstacksFromAddress( uint64_t address, ThreadID thread_id) const { const auto& callstacks_it = function_address_to_callstack_.find(address); const auto& sample_data_it = thread_id_to_sample_data_.find(thread_id); if (callstacks_it == function_address_to_callstack_.end() || sample_data_it == thread_id_to_sample_data_.end()) { return std::multimap<int, CallstackID>(); } return SortCallstacks(sample_data_it->second, callstacks_it->second); } const CallStack& SamplingProfiler::GetResolvedCallstack(CallstackID raw_callstack_id) const { auto resolved_callstack_id_it = original_to_resolved_callstack_.find(raw_callstack_id); CHECK(resolved_callstack_id_it != original_to_resolved_callstack_.end()); auto resolved_callstack_it = unique_resolved_callstacks_.find(resolved_callstack_id_it->second); CHECK(resolved_callstack_it != unique_resolved_callstacks_.end()); return *resolved_callstack_it->second; } std::unique_ptr<SortedCallstackReport> SamplingProfiler::GetSortedCallstackReportFromAddress( uint64_t address, ThreadID thread_id) const { std::unique_ptr<SortedCallstackReport> report = std::make_unique<SortedCallstackReport>(); std::multimap<int, CallstackID> multi_map = GetCallstacksFromAddress(address, thread_id); size_t unique_callstacks_count = multi_map.size(); report->callstacks_count.resize(unique_callstacks_count); size_t index = unique_callstacks_count; for (const auto& pair : multi_map) { CallstackCount* callstack = &report->callstacks_count[--index]; callstack->count = pair.first; callstack->callstack_id = pair.second; report->callstacks_total_count += callstack->count; } return report; } const int32_t SamplingProfiler::kAllThreadsFakeTid = -1; void SamplingProfiler::SortByThreadUsage() { sorted_thread_sample_data_.reserve(thread_id_to_sample_data_.size()); for (auto& pair : thread_id_to_sample_data_) { ThreadSampleData& data = pair.second; data.thread_id = pair.first; sorted_thread_sample_data_.push_back(data); } sort(sorted_thread_sample_data_.begin(), sorted_thread_sample_data_.end(), [](const ThreadSampleData& a, const ThreadSampleData& b) { return a.samples_count > b.samples_count; }); } void SamplingProfiler::ProcessSamples(const CallstackData& callstack_data, const CaptureData& capture_data, bool generate_summary) { // Unique call stacks and per thread data callstack_data.ForEachCallstackEvent( [this, &callstack_data, generate_summary](const CallstackEvent& event) { CHECK(callstack_data.HasCallStack(event.callstack_hash())); ThreadSampleData* thread_sample_data = &thread_id_to_sample_data_[event.thread_id()]; thread_sample_data->samples_count++; thread_sample_data->callstack_count[event.callstack_hash()]++; callstack_data.ForEachFrameInCallstack(event.callstack_hash(), [&thread_sample_data](uint64_t address) { thread_sample_data->raw_address_count[address]++; }); if (generate_summary) { ThreadSampleData* all_thread_sample_data = &thread_id_to_sample_data_[kAllThreadsFakeTid]; all_thread_sample_data->samples_count++; all_thread_sample_data->callstack_count[event.callstack_hash()]++; callstack_data.ForEachFrameInCallstack( event.callstack_hash(), [&all_thread_sample_data](uint64_t address) { all_thread_sample_data->raw_address_count[address]++; }); } }); ResolveCallstacks(callstack_data, capture_data); for (auto& sample_data_it : thread_id_to_sample_data_) { ThreadSampleData* thread_sample_data = &sample_data_it.second; // Address count per sample per thread for (const auto& callstack_count_it : thread_sample_data->callstack_count) { const CallstackID callstack_id = callstack_count_it.first; const uint32_t callstack_count = callstack_count_it.second; CallstackID resolved_callstack_id = original_to_resolved_callstack_[callstack_id]; std::shared_ptr<CallStack>& resolved_callstack = unique_resolved_callstacks_[resolved_callstack_id]; // exclusive stat thread_sample_data->exclusive_count[resolved_callstack->GetFrame(0)] += callstack_count; std::set<uint64_t> unique_addresses; for (uint64_t address : resolved_callstack->GetFrames()) { unique_addresses.insert(address); } for (uint64_t address : unique_addresses) { thread_sample_data->address_count[address] += callstack_count; } } // sort thread addresses by count for (const auto& address_count_it : thread_sample_data->address_count) { const uint64_t address = address_count_it.first; const uint32_t count = address_count_it.second; thread_sample_data->address_count_sorted.insert(std::make_pair(count, address)); } } FillThreadSampleDataSampleReports(capture_data); SortByThreadUsage(); } void SamplingProfiler::ResolveCallstacks(const CallstackData& callstack_data, const CaptureData& capture_data) { callstack_data.ForEachUniqueCallstack([this, &capture_data](const CallStack& call_stack) { // A "resolved callstack" is a callstack where every address is replaced // by the start address of the function (if known). std::vector<uint64_t> resolved_callstack_data; for (uint64_t address : call_stack.GetFrames()) { if (exact_address_to_function_address_.find(address) == exact_address_to_function_address_.end()) { MapAddressToFunctionAddress(address, capture_data); } uint64_t function_address = exact_address_to_function_address_.at(address); resolved_callstack_data.push_back(function_address); function_address_to_callstack_[function_address].insert(call_stack.GetHash()); } CallStack resolved_callstack(std::move(resolved_callstack_data)); CallstackID resolved_callstack_id = resolved_callstack.GetHash(); if (unique_resolved_callstacks_.find(resolved_callstack_id) == unique_resolved_callstacks_.end()) { unique_resolved_callstacks_[resolved_callstack_id] = std::make_shared<CallStack>(resolved_callstack); } original_to_resolved_callstack_[call_stack.GetHash()] = resolved_callstack_id; }); } const ThreadSampleData* SamplingProfiler::GetSummary() const { auto summary_it = thread_id_to_sample_data_.find(kAllThreadsFakeTid); if (summary_it == thread_id_to_sample_data_.end()) { return nullptr; } return &(summary_it->second); } uint32_t SamplingProfiler::GetCountOfFunction(uint64_t function_address) const { auto addresses_of_functions_itr = function_address_to_exact_addresses_.find(function_address); if (addresses_of_functions_itr == function_address_to_exact_addresses_.end()) { return 0; } uint32_t result = 0; const ThreadSampleData* summary = GetSummary(); if (summary == nullptr) { return 0; } const auto& function_addresses = addresses_of_functions_itr->second; for (uint64_t address : function_addresses) { auto count_itr = summary->raw_address_count.find(address); if (count_itr != summary->raw_address_count.end()) { result += count_itr->second; } } return result; } void SamplingProfiler::MapAddressToFunctionAddress(uint64_t absolute_address, const CaptureData& capture_data) { const LinuxAddressInfo* address_info = capture_data.GetAddressInfo(absolute_address); const FunctionInfo* function = capture_data.FindFunctionByAddress(absolute_address, false); // Find the start address of the function this address falls inside. // Use the Function returned by Process::GetFunctionFromAddress, and // when this fails (e.g., the module containing the function has not // been loaded) use (for now) the LinuxAddressInfo that is collected // for every address in a callstack. SamplingProfiler relies heavily // on the association between address and function address held by // exact_address_to_function_address_, otherwise each address is // considered a different function. uint64_t absolute_function_address; if (function != nullptr) { absolute_function_address = FunctionUtils::GetAbsoluteAddress(*function); } else if (address_info != nullptr) { absolute_function_address = absolute_address - address_info->offset_in_function(); } else { absolute_function_address = absolute_address; } exact_address_to_function_address_[absolute_address] = absolute_function_address; function_address_to_exact_addresses_[absolute_function_address].insert(absolute_address); } void SamplingProfiler::FillThreadSampleDataSampleReports(const CaptureData& capture_data) { for (auto& data : thread_id_to_sample_data_) { ThreadSampleData* thread_sample_data = &data.second; std::vector<SampledFunction>* sampled_functions = &thread_sample_data->sampled_function; for (auto sorted_it = thread_sample_data->address_count_sorted.rbegin(); sorted_it != thread_sample_data->address_count_sorted.rend(); ++sorted_it) { uint32_t num_occurences = sorted_it->first; uint64_t absolute_address = sorted_it->second; float inclusive_percent = 100.f * num_occurences / thread_sample_data->samples_count; SampledFunction function; function.name = capture_data.GetFunctionNameByAddress(absolute_address); function.inclusive = inclusive_percent; function.exclusive = 0.f; auto it = thread_sample_data->exclusive_count.find(absolute_address); if (it != thread_sample_data->exclusive_count.end()) { function.exclusive = 100.f * it->second / thread_sample_data->samples_count; } function.absolute_address = absolute_address; function.module_path = capture_data.GetModulePathByAddress(absolute_address); const FunctionInfo* function_info = capture_data.FindFunctionByAddress(absolute_address, false); if (function_info != nullptr) { function.line = function_info->line(); function.file = function_info->file(); } sampled_functions->push_back(function); } } }
// // Created by 周华 on 2021/5/1. // #ifndef RAYTRACING_VECTOR_H #define RAYTRACING_VECTOR_H #include <cassert> class Vector3 { public: // 默认构造,初始化所有的值为0 Vector3() { x = 0; y = 0; z = 0; } // 带参数的构造,以参数里的x、y、z初始化内部的值 Vector3(float x, float y, float z) { this->x = x; this->y = y; this->z = z; } // 乘法重载,方便写 vSelf + vTarget(rhs) 这样的等式 Vector3 operator+ (const Vector3& rhs) const { return Vector3(x + rhs.x, y + rhs.y, z + rhs.z); } // 乘法重载,方便写 vSelf * 系数(rhs)这样的等式 Vector3 operator* (float rhs) const { return Vector3(x * rhs, y * rhs, z * rhs); } // 除法重载,格式: vResult = vSelf / float Vector3 operator/ (float rhs) const { assert(rhs != 0.0f); float inverse = 1 / rhs; return Vector3(x * inverse, y * inverse, z * inverse); } // 作为引用的返回,必须让编译器看到不是临时的变量 Vector3 operator- (const Vector3& rhs) const { return Vector3(x-rhs.x, y-rhs.y, z-rhs.z); } // 点乘,结果是一个浮点数。该方法不会修改成员方法所对应实例的任何成员变量。 float Dot(const Vector3& rhs) const { return x * rhs.x + y * rhs.y + z * rhs.z; } // 叉乘,结果是向量。该方法不会修改成员方法所对应实例的任何成员变量。 Vector3 Cross(const Vector3& rhs) const { return Vector3(y*rhs.z-z*rhs.y, z*rhs.x-x*rhs.z, x*rhs.y-y*rhs.x); } // 运算较快的长度相关方法,返回 x*x + y*y + z*z float SqrLength() { return x*x + y*y + z*z; } // 向量的长度 float Length() { return sqrt(x*x + y*y + z*z); } // 3维向量的内部存储,x、y、z在实际意义上可能是向量、位置、三原色的r、g、b等等 float x = 0, y = 0, z = 0; static float Dot(const Vector3& lhs, const Vector3& rhs); static Vector3 Cross(const Vector3& lhs, const Vector3& rhs); }; #endif //RAYTRACING_VECTOR_H
#ifndef VECTOR_H #define VECTOR_H /*Обобщенное программирование - это создание кода. работающего с разными типами. заданными в виде аргументов, причем эти типы должны соответствовать специфическим синтаксическим и семантическим требованиям.*/ /*Обобщенное программирование поддерживается шаблонами, основываясь на разрешении вызовов времени компиляции. */ /*Объектно-ориентированное программирован11е поддерживается иерархиями классов и виртуальными функциями. основываясь на разрешении вызовов времени выполнения. */ /*Используйте шаблоны. когда важную роль играет производительность программы (например. при интенсивных вычислениях или в программах реального времени; подробнее об этом речь пойдет в главах 24 и 25).*/ /*Используйте шаблоны. когда важна гибкость сочетания информации из разных типов (например. в стандартной библиотеке С++: эта тема будет обсуждаться в главах 20 и 21 ). */ #include <algorithm> #include <iostream> #include <memory> #include <initializer_list> #include <string> #include <stdexcept> #include <stdio.h> using namespace std; /*необходимо пред,усмотреть объект. который будет владеть объектом класса vector<int> и сможет его удалить, если возникнет исключение. В заголовочном файле <memory> стандартной библиотеки на этот случай предоставлен класс unique_ptr.*/ //в итоге для работы с встроенными классами: //allocator Создание контейнера с пользовательским распределителем //дает возможность управлять выделением и освобождением памяти //для элементов контейнера. // класс vector _ base работает с памятью, а не //с типизированными объектами. template<typename T, typename A>struct vector_base { A alloc; //Распределение памяти T* elem; //Начало выделенной памяти size_t sz; //Количество элементов size_t space; //Размер выделенной памяти vector_base(); vector_base(vector_base &&a); vector_base(const A& a, size_t s); vector_base& operator = (vector_base&& a); ~vector_base(); }; //template<class T> тоже самое template<typename T> template<typename T, typename A = allocator<T>> class Vector : private vector_base<T, A> { /* * Инвариант: * для 0<=n<sz значение elem[n] является n-м элементом * sz<=space; * усли sz<space, то после elem[sz-1] есть место * для (space-sz) чисел типа double */ public: Vector():vector_base<T, A>(A(), 0) { } //конструктор по умолчанию // Конструктор: размещаает в памяти s чисел // типа double, направляет на них указатель // elem и сохраняет s в член sz //Конструктор со словом explicit не допускает неявные преобразования Vector(size_t s); Vector(const Vector& a); //Конструктор копирования (копирующая инициализация) Vector& operator=(const Vector& a); //Конструктор присваивания (копирующее присваивание) Vector(Vector&& a); //Перемещающий конструктор Vector& operator=(Vector&& a); //Перемещающее присваивание T &operator[](int n) //Для неконстантных векторов, Доступ без проверки { return this->elem[n]; } const T& operator[] (int n) const //для константных векторов без проверки { return this->elem[n]; } //Конструктор со списком инициализации Vector(initializer_list<T> lst); size_t size() const //Текущий размер { return this->sz; } size_t capacity() const //Узнать размер доступной памяти (Сколько свободного места осталось) { return this->space; } void reserve(size_t newalloc); //добавляет память для новых элементов void resize(size_t newsize, T val=T()); //resize () добавляет / удаляет элементы в зависимости от заданного им размера void push_back(const T& val); //Увеличивает размер вектора на 1 //инициализирует новый элемент значением d T get(int n) const; //Чтение void set(int n, T v); //Запись ~Vector(); //Деструктор, освобождает память }; #endif // VECTOR_H
#pragma once #include <thero/optional.hpp> #include <vector> template <typename T> void emplaceOptional(th::Optional<T> data, std::vector<T>& storage) { if(data) storage.emplace_back(std::move(*data)); } template <typename T, typename Func> T* findIf(std::vector<T>& storage, Func func) { auto result = std::find_if(storage.begin(), storage.end(), func); if(result != storage.end()) return &*result; else return nullptr; } template <typename T, typename Func> const T* findIf(const std::vector<T>& storage, Func func) { auto result = std::find_if(storage.begin(), storage.end(), func); if(result != storage.end()) return &*result; else return nullptr; }
#ifndef RECOGNIZER_H #define RECOGNIZER_H #include "pixel.h" #include "alphalevel.h" #include "filereader.h" #include <vector> #include "dissimilarity.h" class Recognizer{ public: //Constructors Recognizer(); Recognizer(FileReader fileReader); //Functions bool isTriangle(int sizeOfTriangle, std::vector<std::vector<int>> cluster); bool isRed(int sizeOfTriangle, std::vector<std::vector<std::vector<int>>> cluster); private: //Variables bool triangle; bool red; }; #endif
#include "Bubble.h" #include <QMessageBox> #include <QTime> #include <QMouseEvent> Bubble::Bubble(QWidget *parent) : QWidget(parent) { Q_CHECK_PTR(parent); qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime())); diameter = 30 + qrand() % 60; setGeometry(qrand() % (parent->size().width() - diameter), qrand() % (parent->size().height() - diameter), diameter, diameter); setMask(QRegion(0, 0, diameter, diameter, QRegion::RegionType::Ellipse)); setAutoFillBackground(true); setPalette(QPalette(QPalette::Background, Qt::red)); animation = new QPropertyAnimation(this, "pos"); connect(animation, SIGNAL(finished()), this, SLOT(AnimationFinished())); } Bubble::~Bubble() { delete animation; } void Bubble::mousePressEvent(QMouseEvent * event) { if (event->button() == Qt::MouseButton::LeftButton) emit mousePress(*this); else { clickPoint = event->pos(); emit startMove(); } } void Bubble::mouseReleaseEvent(QMouseEvent *event) { if (event->button() == Qt::MouseButton::RightButton) emit finishedMove(); } void Bubble::mouseMoveEvent(QMouseEvent *event) { this->move(x() + event->x() - clickPoint.x(), y() + event->y() - clickPoint.y()); } void Bubble::animationMove(QPoint p) { emit startAnimation(); animation->setDuration(speed); animation->setStartValue(pos()); animation->setEndValue(pos() + p); animation->start(); } void Bubble::AnimationFinished() { emit finishedAnimation(); } double Bubble::getRadius() { return diameter / 2; } QPoint Bubble::getCenter() { return QPoint(x() + diameter / 2, y() + diameter / 2); }
#include<bits/stdc++.h> using namespace std; #define INF 100000000000 long long ans=INF; long long n,a,b,c; void dfs(long long num,long long cost){ if(num%4==0){ ans=min(ans,cost); // cout<<ans<<endl; } if(num>3*n) return; dfs(num+1,cost+a); dfs(num+2,cost+b); dfs(num+3,cost+c); } int main(){ cin>>n>>a>>b>>c; n=n%4; dfs(n,0); cout<<ans; return 0; }
#include<iostream> #include<cstdio> using namespace std; int main(){ int test; cin >> test; for(int i = 0; i < test; i++){ } return 0; }
// // Created by new on 2016/11/8. // #ifndef HTTPSVR_HELPER_H #define HTTPSVR_HELPER_H #include <string> #include <vector> #include "json/json.h" using namespace std; class Helper { public: /** * 过滤用户输入字符中的不合法字符 * 目前主要直接把一些特殊字符替换成空格,并去掉前后空格 * @param string $str 用户输入的字符 * @return string 过滤后输出的字符 */ static string filterInput(string str); static int strtotime(string datestr); static vector<string> explode(const char * str, const char * sep); static string implode(const char* sep, const vector<string>& strarr); static string implode(const char* sep, const Json::Value& strarr); static string implode(const char* sep, const std::vector<int>& vec); static string strtolower(const char* str); static string trim(const char *str); static bool isUsername(const char *str); static long ip2long(const char* ip); static std::string long2ip(long ip); static string replace(const string& str, const string& src, const string& dest); static int time2morning(); void unsetUserFiled(Json::Value& jvUser); static std::string GetPeerMac(int sockFd); //获得当前月初的时间戳 static int32_t getCurMonthTimeStamp(); //获得下个月月初的时间戳 static int32_t getNextMonthTimeStamp(); //通过时间戳获得年月字符串 static std::string getTimeStampToYearMonthTime(int timestamp); //获得当前年月 static std::string getCurYearMonthTime(); }; #endif //HTTPSVR_HELPER_H
#ifndef SYSTEM_H #define SYSTEM_H /* * System.h * * Emulates the connections between each of the processors and memory * */ class system { // processors // memory }; #endif
// Datastructures.hh #ifndef DATASTRUCTURES_HH #define DATASTRUCTURES_HH #include <string> #include <vector> struct TownData { std::string name; int x; int y; }; class Datastructures { public: Datastructures(); ~Datastructures(); // Estimate of performance: constant. // Short rationale for estimate: uses the std::vector::size function which is // of constant complexity. unsigned int size(); // Estimate of performance: O(n). // Short rationale for estimate: Goes through elements one by one and removes the // pointers which is linear, and then clears the vectors, which is also linear. void clear(); // Estimate of performance: constant. // Short rationale for estimate: just returns the towns list. std::vector<TownData*> all_towns(); // Estimate of performance: constant time when adding for the first time and // O(log(n)) when adding after calling for sorted lists. // Short rationale for estimate: Smart adding procedure maintains the sorted // list if the sorted list exists through binary search for finding the index // to insert the element at. TownData* add_town(std::string const& name, int x, int y); // Estimate of performance: theta(n.log(n)) in the best and worst case, constant // if sorted list exists. // Short rationale for estimate: The sort function used is a variant of intro sort // similar to the C++ std lib implementation. It uses a modified quick sorting // algorithm to maintain the worst case condition at n.log(n). std::vector<TownData*> towns_alphabetically(); // Estimate of performance: theta(n.log(n)) if sorted list doesn't exist, constant // if sorted list exists. // Short rationale for estimate: The sort function used is a variant of intro sort // similar to the C++ std lib implementation. It uses a modified quick sorting // algorithm to maintain the worst case condition at n.log(n). std::vector<TownData*> towns_distance_increasing(); // Estimate of performance: O(n) if sorted list is unavailable and O(log(n)) // if the sorted list is available. // Short rationale for estimate: If the alphabatically sorted list is available, // implements binary search to find the town. TownData* find_town(std::string const& name); // Estimate of performance: constant if sorted list exists, O(n.log(n)) otherwise. // Short rationale for estimate: Removed the introselect implementation // to maintain a sorted list as it is more efficient in the overall scenario. TownData* min_distance(); // Estimate of performance: constant if sorted list exists, O(n.log(n)) otherwise. // Short rationale for estimate: Removed the introselect implementation to // maintain a sorted list as it is more efficient in the overall scenario. TownData* max_distance(); // Estimate of performance: constant if sorted list exists, O(n.log(n)) otherwise. // Short rationale for estimate: Removed the introselect implementation // to maintain a sorted list as it is more efficient in the overall scenario. TownData* nth_distance(unsigned int n); // Non-compulsory operations // Estimate of performance: O(n). // Short rationale for estimate: Finding the element and erasing uses linear time. void remove_town(std::string const& town_name); // Estimate of performance: theta(n.log(n)) in the best and worst case. // Short rationale for estimate: The sort function used is a variant of // intro sort similar to the C++ std lib implementation. It uses a modified // quick sorting algorithm to maintain the worst case condition at n.log(n). std::vector<TownData*> towns_distance_increasing_from(int x, int y); private: // Add stuff needed for your class implementation here std::vector<TownData*> towns; std::vector<TownData*> alphalist; std::vector<TownData*> distlist; bool distlistUpdated = false; bool alphalistUpdated = false; TownData* pivot; std::vector<TownData*> mysort(std::vector<TownData*> towns, const bool& alpha, const int& left, const int& right, const int& x = 0, const int& y = 0); void introsort(std::vector<TownData*> &towns, unsigned int maxDepth, const int& left, const int& right, const bool& alpha, const int& x = 0, const int& y = 0); void heapsort(std::vector<TownData*> &towns, const bool& alpha, const int& left, const int& right, const int& x = 0, const int& y = 0); void buildMaxHeap(std::vector<TownData*> &towns, const int& left, const int& right, const bool& alpha, const int& x, const int& y); void maxHeapify(std::vector<TownData*> &towns, const int& left, const int& right, const bool& alpha, const int& x, const int& y, const int& i, const int& n); void insertionsort(std::vector<TownData*> &towns, const bool& alpha, const int& left, const int& right, const int& x = 0, const int& y = 0); unsigned int part(std::vector<TownData*> &towns, const int& left, const int& right, const bool& alpha, const int& x = 0, const int& y = 0); // TownData* myselect(std::vector<TownData*> towns, const int& left, // const int& right, unsigned int n); // TownData* introselect(std::vector<TownData*> towns, unsigned int left, // unsigned int right, const unsigned int& n, unsigned int maxDepth); // TownData* heapselect(std::vector<TownData*> towns, unsigned int left, // unsigned int right, unsigned int n); // void heapMove(std::vector<TownData*> towns, // unsigned int first, unsigned int last); unsigned int binSearch(const int& x, const int& y, const bool& alpha = false, std::string const& townName = ""); }; #endif // DATASTRUCTURES_HH
#include "stdafx.h" #include "head.h" ICBCBank::ICBCBank() { int result; char * errmsg = NULL; char **dbResult; //是 char ** 类型,两个*号 int nRow, nColumn; int i, j; int index; result = sqlite3_open("ICBCData.db", &db); //TODO:这里的逻辑有问题 if (result != SQLITE_CANTOPEN) //若打开失败,则创建 { //若原来已经存在有这张表格,则不会创建表格,即不会影响正确运行,所以不用错误检测 //TODO:一开始假定已有数据结构 取消所有create语句 /*string SQLCode = "create table ICBC "; SQLCode = SQLCode + "(bank_name varchar(25), card_num varchar(25), password varchar(25), "; SQLCode = SQLCode + "client_Id varchar(25), deposit double(20) );"; result = sqlite3_exec(db, SQLCode.c_str(), 0, 0, &errmsg); */ /*SQLCode = "create table setting (item varchar(25), num int(25));"; result = sqlite3_exec(db, SQLCode.c_str(), 0, 0, &errmsg);*/ /*if (result != SQLITE_OK) //若创建失败 则报错 { cout << "Open database fail: " << sqlite3_errmsg(db); //goto QUIT; } else { }*/ } //result = sqlite3_get_table(db, "select * from setting where item = \"cardNumCnt\"", &dbResult, &nRow, &nColumn, &errmsg); /*if (SQLITE_OK == result) { //查询成功 index = nColumn; //前面说过 dbResult 前面第一行数据是字段名称,从 nColumn 索引开始才是真正的数据 printf("查到%d条记录\n", nRow); for (i = 0; i < nRow; i++) { printf("第 %d 条记录\n", i + 1); for (j = 0; j < nColumn; j++) { printf("字段名:%s > 字段值:%s\n", dbResult[j], dbResult[index]); ++index; // dbResult 的字段值是连续的,从第0索引到第 nColumn - 1索引都是字段名称,从第 nColumn 索引开始,后面都是字段值,它把一个二维的表(传统的行列表示法)用一个扁平的形式来表示 } printf("------ - \n"); } }*/ cardNumCnt = this->loadCardNumCnt(); /*string SQLCode = "insert into setting (item, num) values (\"cardNumCnt\", 0);"; result = sqlite3_exec(db, SQLCode.c_str(), 0, 0, &errmsg);*/ //cout << errmsg; } ICBCBank::~ICBCBank() { sqlite3_close(db); } void ICBCBank::saveCardNumCnt() { char tmp[20]; string tmp2; sprintf(tmp, "%d", cardNumCnt); tmp2 = tmp; int result; char * errmsg = NULL; string SQLCode = "update setting set num = " + tmp2 + " where item = \"cardNumCnt\""; result = sqlite3_exec(db, SQLCode.c_str(), 0, 0, &errmsg); } int ICBCBank::loadCardNumCnt() { int result; char * errmsg = NULL; char **dbResult; //是 char ** 类型,两个*号 int nRow, nColumn; result = sqlite3_get_table(db, "select * from setting where item = \"cardNumCnt\"", &dbResult, &nRow, &nColumn, &errmsg); return atoi(dbResult[3]); //根据表的结构 dbResult[3]这个位置存放的是cardNumCnt的值 } bool ICBCBank::addClient() { char tmpBuf[BUF_LEN]; cout << "password:"; cin >> tmpBuf; string password = tmpBuf; cout << "clientId:"; cin >> tmpBuf; string clientId = tmpBuf; createRecord("ICBC", password, clientId); string cardNum = int2string(this->cardNumCnt, PSW_LEN); cout << "your cardNum:" << cardNum.c_str() << endl; return true; } bool ICBCBank::deleteClient(string cardNum) //暂无用处 { return true; } void ICBCBank::clientInfoUpdate() //用户信息展示 用户信息修改 用户删除 { char tmpBuf[BUF_LEN]; cout << "cardNum:"; string cardNum; cin >> tmpBuf; cardNum = tmpBuf; cout << "password:"; string inputPassword; cin >> tmpBuf; inputPassword = tmpBuf; if (!verifyPassword(cardNum, inputPassword)) //若密码错误,直接返回 { return; } double deposit = this->getDeposit(cardNum); string clientId = this->getClientId(cardNum); cout << "1.nothing 2.change password 3.change clientId 4.delete clientId:"; int n; cin >> n; if (n == 2) { char tmpBuf[BUF_LEN]; string newPassword; cin >> tmpBuf; newPassword = tmpBuf; this->setPassword(cardNum, newPassword); } else if (n == 3) { char tmpBuf[BUF_LEN]; string newClientId; cin >> tmpBuf; newClientId = tmpBuf; this->setPassword(cardNum, newClientId); } else if (n == 4) { char tmpBuf[BUF_LEN]; cout << "password:"; string inputPassword; cin >> tmpBuf; inputPassword = tmpBuf; if (!verifyPassword(cardNum, inputPassword)) //若密码错误,直接返回 { return; } this->deleteRecord(cardNum); } } bool ICBCBank::checkClient() { return true; } bool ICBCBank::transaction() { char tmpBuf[BUF_LEN]; cout << "cardNum:"; string cardNum; cin >> tmpBuf; cardNum = tmpBuf; cout << "password:"; string inputPassword; cin >> tmpBuf; inputPassword = tmpBuf; if (!verifyPassword(cardNum, inputPassword)) //若密码错误,直接返回 { return false; } cout << "1.check money 2.save 3.take 4.nothing : "; int n; cin >> n; if (n == 1) { double deposit = this->getDeposit(cardNum); cout << "deposit:" << deposit << endl; } else if (n == 2) { double amount; cin >> amount; this->changeDeposit(cardNum, amount); } else if (n == 3) { double amount; cin >> amount; this->changeDeposit(cardNum, -amount); } return true; } bool ICBCBank::changeDeposit(string cardNum, double amount) { double preDeposit = this->getDeposit(cardNum); double curDeposit = preDeposit + amount; if (curDeposit < 0 - eps) //若存款小于0元 return false; else { this->setDeposit(cardNum, curDeposit); return true; } } bool ICBCBank::createRecord(string bankName, string password, string clientId) { string cardNum = int2string(cardNumCnt, PSW_LEN); int result; char * errmsg = NULL; string SQLCode = "insert into ICBC "; SQLCode = SQLCode + "(bank_name, card_num, password, client_Id, deposit)"; SQLCode = SQLCode + "values(\"" + bankName + "\", \"" + cardNum + "\", \"" + password + "\", \"" + clientId + "\", 0);"; result = sqlite3_exec(db, SQLCode.c_str(), 0, 0, &errmsg); if (result == SQLITE_OK) { cardNumCnt++; this->saveCardNumCnt(); //cout << errmsg; return true; } else { cout << errmsg; return false; } //insert into coffee(id, coffee_name, taste, rank) value("1", "BlueMountain",“well”,“5”) } bool ICBCBank::deleteRecord(string cardNum) { int result; char * errmsg = NULL; char **dbResult; //是 char ** 类型,两个*号 int nRow, nColumn; //计算此次要删掉多少条目,nRow即为检索到的条目数目,即要删除的条目数目 result = sqlite3_get_table(db, "select * from setting where item = \"cardNumCnt\"", &dbResult, &nRow, &nColumn, &errmsg); string SQLCode = "delete from ICBC where card_num = \"" + cardNum + "\";"; result = sqlite3_exec(db, SQLCode.c_str(), 0, 0, &errmsg); if (result == SQLITE_OK) { cardNumCnt = cardNumCnt - nRow; this->saveCardNumCnt(); return true; } else { cout << errmsg; return false; } } bool ICBCBank::existJudge(string cardNum) { int result; char * errmsg = NULL; char **dbResult; //是 char ** 类型,两个*号 int nRow, nColumn; string SQLCode = "select * from ICBC where card_num = \"" + cardNum + "\";"; result = sqlite3_get_table(db, SQLCode.c_str(), &dbResult, &nRow, &nColumn, &errmsg); if (nRow > 0) return true; else return false; } bool ICBCBank::verifyPassword(string cardNum, string inputPassword) { string password = this->getPassword(cardNum); if (password == inputPassword) return true; else return false; } double ICBCBank::getDeposit(string cardNum) { int result; char * errmsg = NULL; char **dbResult; //是 char ** 类型,两个*号 int nRow, nColumn; string SQLCode = "select * from ICBC where card_num = \"" + cardNum + "\";"; result = sqlite3_get_table(db, SQLCode.c_str(), &dbResult, &nRow, &nColumn, &errmsg); return atof(dbResult[9]); //根据表的结构 dbResult[9]这个位置存放的是deposit的值 } string ICBCBank::getPassword(string cardNum) //假定卡号一定不会重复,则查询记录只可能有一条 { int result; char * errmsg = NULL; char **dbResult; //是 char ** 类型,两个*号 int nRow, nColumn; string SQLCode = "select * from ICBC where card_num = \"" + cardNum + "\";"; result = sqlite3_get_table(db, SQLCode.c_str(), &dbResult, &nRow, &nColumn, &errmsg); //cout << endl << errmsg << endl; //cout << nRow; string tmp = dbResult[7]; return tmp; //根据表的结构 dbResult[7]这个位置存放的是password的值 } string ICBCBank::getClientId(string cardNum) { int result; char * errmsg = NULL; char **dbResult; //是 char ** 类型,两个*号 int nRow, nColumn; string SQLCode = "select * from ICBC where card_num = \"" + cardNum + "\";"; result = sqlite3_get_table(db, SQLCode.c_str(), &dbResult, &nRow, &nColumn, &errmsg); return dbResult[8]; //根据表的结构 dbResult[8]这个位置存放的是clientId的值 } void ICBCBank::setDeposit(string cardNum, double deposit) { char tmp[20]; string tmp2; sprintf(tmp, "%f", deposit); //TODO:未知可不可行的写法 tmp2 = tmp; int result; char * errmsg = NULL; string SQLCode = "update ICBC set deposit = " + tmp2 + " where card_num = \"" + cardNum + "\""; result = sqlite3_exec(db, SQLCode.c_str(), 0, 0, &errmsg); } void ICBCBank::setPassword(string cardNum, string password) { int result; char * errmsg = NULL; string SQLCode = "update ICBC set password = " + password + " where card_num = \"" + cardNum + "\""; result = sqlite3_exec(db, SQLCode.c_str(), 0, 0, &errmsg); } void ICBCBank::setClientId(string cardNum, string clientId) { int result; char * errmsg = NULL; string SQLCode = "update ICBC set clientId = " + clientId + " where card_num = \"" + cardNum + "\""; result = sqlite3_exec(db, SQLCode.c_str(), 0, 0, &errmsg); } bool bank_connect() { WSADATA wsaData; int iResult; SOCKET ListenSocket = INVALID_SOCKET; SOCKET ClientSocket = INVALID_SOCKET; struct addrinfo *result = NULL; struct addrinfo hints; int iSendResult; char recvbuf[DEFAULT_BUFLEN]; int recvbuflen = DEFAULT_BUFLEN; // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); return 1; } ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; // Resolve the server address and port iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result); if (iResult != 0) { printf("getaddrinfo failed with error: %d\n", iResult); WSACleanup(); return 1; } // Create a SOCKET for connecting to server ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (ListenSocket == INVALID_SOCKET) { printf("socket failed with error: %ld\n", WSAGetLastError()); freeaddrinfo(result); WSACleanup(); return 1; } // Setup the TCP listening socket iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen); if (iResult == SOCKET_ERROR) { printf("bind failed with error: %d\n", WSAGetLastError()); freeaddrinfo(result); closesocket(ListenSocket); WSACleanup(); return 1; } freeaddrinfo(result); iResult = listen(ListenSocket, SOMAXCONN); if (iResult == SOCKET_ERROR) { printf("listen failed with error: %d\n", WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); return 1; } // Accept a client socket ClientSocket = accept(ListenSocket, NULL, NULL); if (ClientSocket == INVALID_SOCKET) { printf("accept failed with error: %d\n", WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); return 1; } // No longer need server socket closesocket(ListenSocket); string sendMsg = "YES!"; // Receive until the peer shuts down the connection do { iResult = recv(ClientSocket, recvbuf, recvbuflen, 0); recvbuf[iResult] = '\0'; cout << recvbuf << endl; if (iResult > 0) { //对接受到的信息进行分析 并返回相应操作的结果 sendMsg = recvMsgAnalyse(recvbuf); printf("Bytes received: %d\n", iResult); // Echo the buffer back to the sender iSendResult = send(ClientSocket, sendMsg.c_str(), sendMsg.length(), 0); if (iSendResult == SOCKET_ERROR) { printf("send failed with error: %d\n", WSAGetLastError()); closesocket(ClientSocket); WSACleanup(); return 1; } printf("Bytes sent: %d\n", iSendResult); } else if (iResult == 0) printf("Connection closing...\n"); else { printf("recv failed with error: %d\n", WSAGetLastError()); closesocket(ClientSocket); WSACleanup(); return 1; } } while (iResult > 0); // shutdown the connection since we're done iResult = shutdown(ClientSocket, SD_SEND); if (iResult == SOCKET_ERROR) { printf("shutdown failed with error: %d\n", WSAGetLastError()); closesocket(ClientSocket); WSACleanup(); return 1; } // cleanup closesocket(ClientSocket); WSACleanup(); return 0; }
//https://projecteuler.net/problem=754 #include<iostream> using namespace std; bool RelativelyPrime (int a, int b) { // Assumes a, b > 0 for ( ; ; ) { if (!(a %= b)) return b == 1 ; if (!(b %= a)) return a == 1 ; } } int gauss_fact(int n) { int ret = 1; for(int i =1;i<n;i++) { if( RelativelyPrime(i, n)) ret*=i; } return ret; } long long int G(int n) { long long int ret =1; for(int i = 1;i <=n; i++) ret*=gauss_fact(i); return ret/1000000007; } int main() { cout<<G(100000000); }
#include "msg_0x82_updatesign_tw.h" namespace MC { namespace Protocol { namespace Msg { UpdateSign::UpdateSign() { _pf_packetId = static_cast<int8_t>(0x82); _pf_initialized = false; } UpdateSign::UpdateSign(int32_t _x, int16_t _y, int32_t _z, const String16& _text1, const String16& _text2, const String16& _text3, const String16& _text4) : _pf_x(_x) , _pf_y(_y) , _pf_z(_z) , _pf_text1(_text1) , _pf_text2(_text2) , _pf_text3(_text3) , _pf_text4(_text4) { _pf_packetId = static_cast<int8_t>(0x82); _pf_initialized = true; } size_t UpdateSign::serialize(Buffer& _dst, size_t _offset) { _pm_checkInit(); if(_offset == 0) _dst.clear(); _offset = WriteInt8(_dst, _offset, _pf_packetId); _offset = WriteInt32(_dst, _offset, _pf_x); _offset = WriteInt16(_dst, _offset, _pf_y); _offset = WriteInt32(_dst, _offset, _pf_z); _offset = WriteString16(_dst, _offset, _pf_text1); _offset = WriteString16(_dst, _offset, _pf_text2); _offset = WriteString16(_dst, _offset, _pf_text3); _offset = WriteString16(_dst, _offset, _pf_text4); return _offset; } size_t UpdateSign::deserialize(const Buffer& _src, size_t _offset) { _offset = _pm_checkPacketId(_src, _offset); _offset = ReadInt32(_src, _offset, _pf_x); _offset = ReadInt16(_src, _offset, _pf_y); _offset = ReadInt32(_src, _offset, _pf_z); _offset = ReadString16(_src, _offset, _pf_text1); _offset = ReadString16(_src, _offset, _pf_text2); _offset = ReadString16(_src, _offset, _pf_text3); _offset = ReadString16(_src, _offset, _pf_text4); _pf_initialized = true; return _offset; } int32_t UpdateSign::getX() const { return _pf_x; } int16_t UpdateSign::getY() const { return _pf_y; } int32_t UpdateSign::getZ() const { return _pf_z; } const String16& UpdateSign::getText1() const { return _pf_text1; } const String16& UpdateSign::getText2() const { return _pf_text2; } const String16& UpdateSign::getText3() const { return _pf_text3; } const String16& UpdateSign::getText4() const { return _pf_text4; } void UpdateSign::setX(int32_t _val) { _pf_x = _val; } void UpdateSign::setY(int16_t _val) { _pf_y = _val; } void UpdateSign::setZ(int32_t _val) { _pf_z = _val; } void UpdateSign::setText1(const String16& _val) { _pf_text1 = _val; } void UpdateSign::setText2(const String16& _val) { _pf_text2 = _val; } void UpdateSign::setText3(const String16& _val) { _pf_text3 = _val; } void UpdateSign::setText4(const String16& _val) { _pf_text4 = _val; } } // namespace Msg } // namespace Protocol } // namespace MC
/************************************************************************* > File Name: tmp/snowflake.cpp > Author: billowqiu > Mail: billowqiu@billowqiu.com > Created Time: 2016-10-25 14:21:52 > Last Changed: 2016-10-25 14:21:52 *************************************************************************/ #include <iostream> #include <fstream> #include <sys/time.h> #include <stdint.h> #include <stdlib.h> class Snowflake { public: Snowflake(uint64_t worker_id, uint64_t region_id) { this->worker_id = worker_id; this->region_id = region_id; this->twepoch = 1288834974657; this->last_timestamp = 0; this->sequence = 0; } uint64_t generate(uint64_t bus_id = 0) { uint64_t timestamp = get_time(); uint64_t padding_num = this->region_id; bool is_padding = (bus_id!=0) ? true : false; if (is_padding) { padding_num = bus_id; } if (timestamp < this->last_timestamp) { std::cerr << "clock moved backworad!!!" << std::endl; } if (timestamp == this->last_timestamp) { this->sequence = (this->sequence+1) & SEQUENCE_MASK; if (this->sequence == 0) { timestamp = tail_next_micros(); } } else { srandom(time(NULL)); this->sequence = random() % 10; } this->last_timestamp = timestamp; return ((timestamp - this->twepoch) << TIMESTAMP_LEFT_SHIFT | (padding_num << REGION_ID_SHIFT) | (this->worker_id << WORKER_ID_SHIFT) | this->sequence); return 0; } uint64_t tail_next_micros() { uint64_t timestamp = get_time(); while (timestamp <= this->last_timestamp) { timestamp = get_time(); } return timestamp; } uint64_t get_time() { timeval now; int ret = gettimeofday(&now, NULL); if (-1 == ret) { exit(-1); } return now.tv_sec*1000*1000 + now.tv_usec; } private: const static uint64_t region_id_bits = 2; const static uint64_t worker_id_bits = 10; const static uint64_t sequence_bits = 11; const static uint64_t MAX_REGION_ID = -1 ^ (-1 << region_id_bits); const static uint64_t MAX_WORKER_ID = -1 ^ (-1 << worker_id_bits); const static uint64_t SEQUENCE_MASK = -1 ^ (-1 << sequence_bits); const static uint64_t WORKER_ID_SHIFT = sequence_bits; const static uint64_t REGION_ID_SHIFT = sequence_bits + worker_id_bits; const static uint64_t TIMESTAMP_LEFT_SHIFT = (sequence_bits + worker_id_bits + region_id_bits); uint64_t twepoch; uint64_t last_timestamp; uint64_t sequence; uint64_t worker_id; uint64_t region_id; }; int main(int argc, const char* argv[]) { if (argc != 2) { std::cout << "Usage: %s uid_count" << argv[0] << std::endl; return 0; } uint32_t uid_count = atoi(argv[1]); Snowflake uid(1,0); std::ofstream ofs("uidlog"); timeval begin; gettimeofday(&begin, NULL); for(uint32_t i=0; i<uid_count; ++i) { ofs << uid.generate() << std::endl; } timeval end; gettimeofday(&end, NULL); ofs << "elapse " << (end.tv_sec - begin.tv_sec)*1000 + (end.tv_usec - begin.tv_usec)/1000 << "ms" << std::endl; ofs.close(); return 0; }
#include <algorithm> #include "Client.h" #include "Log.h" #include "protocol.h" #include "../JsonPacket.h" #include "Helper.h" using namespace evwork; extern struct g_args_s g_args; static const char *log_level_map[] = {"ERROR", "INFO", "DEBUG"}; static const char *action_map[] = {"过", "吃", "碰", "偎", "跑", "提", "胡"}; //static const char *eattype_map[] = {"吃", "碰", "偎", "臭偎", "跑", "提"}; #define sendData(data, len) \ do { \ evwork::IConn* pConn = g_args.conMap[m_fd]; \ if (pConn) { \ pConn->sendBin(data, len); \ } \ } while (0) enum _Action_code { ACTION_CHI = 1, ACTION_PENG , ACTION_WEI , ACTION_PAO , ACTION_TI , ACTION_HU , ACTION_END , // 初始值,表示没做出选择 ACTION_PASS =0, }; Client::Client(int uid) :m_uid(uid), m_playing(false) { open_log(); _startTimers(); int vid = g_args.robots[m_uid].vid; std::vector<int> &loadQueue = g_args.queues[vid].randomUids; loadQueue.erase(loadQueue.begin()); gameSvrInfo_t &svr = g_args.gameSvrs[g_args.robots[m_uid].vid]; m_pConn = CEnv::getConnManager()->connectServer(svr.host, svr.port); if (!m_pConn) { DBUG(ERROR, "机器人:%d 构造完成,连接服务器失败 vid:%d 排队数:%d\n", m_uid, vid, loadQueue.size()); delete this; } m_fd = m_pConn->getfd(); if (g_args.cmap.find(m_fd) != g_args.cmap.end()) { Client *pClient = g_args.cmap[m_fd]; DBUG(ERROR, "与机器人:%d fd重复:%d", pClient->m_uid, m_fd); } g_args.cmap[m_fd] = this; DBUG(INFO, "机器人:%d 构造完成, fd:%d vid:%d 排队数:%d\n", m_uid, m_fd, vid, loadQueue.size()); } Client::~Client() { if (m_fd > 0) { g_args.cmap.erase(m_fd); } if (g_args.robots.find(m_uid) != g_args.robots.end()) { int vid = g_args.robots[m_uid].vid; std::vector<int> &loadQueue = g_args.queues[vid].randomUids; loadQueue.push_back(m_uid); DBUG(INFO, "机器人:%d 析构后排队 vid:%d\n", m_uid, vid); } else { DBUG(INFO, "机器人:%d 析构后不再排队\n", m_uid); } _stopTimers(); close_log(); DBUG(INFO, "机器人:%d 析构完成\n", m_uid); } void Client::__doLogin() { log(INFO, "登录"); // 连接失败(服务器繁忙或是根本连不上) if (g_args.conMap.find(m_fd) == g_args.conMap.end()) { DBUG(DEBUG, "连接服务器失败"); // 避免CClientconn对象内存泄露,通过全局方法清理 if (g_args.conMap.find(m_fd) != g_args.conMap.end()) { Client *pClient = g_args.cmap[m_fd]; DBUG(ERROR, "%s 与机器人:%d fd重复:%d", __FUNCTION__, pClient->m_uid, m_fd); } g_args.conMap[m_fd] = m_pConn; __disConnectLater(); return; } // 进入房间 Jpacket packet; packet.val["cmd"] = CLIENT_LOGIN; packet.val["uid"] = m_uid; packet.val["skey"] = g_args.robots[m_uid].skey; packet.val["room"] = g_args.robots[m_uid].tid; packet.val["index"] = g_args.robots[m_uid].index; packet.end(); sendData(packet.tostring().c_str(), packet.tostring().size()); DBUG(INFO, "机器人:%d 请求进入游戏:%d 房间:%d index:%d fd:%d\n", m_uid, g_args.robots[m_uid].vid, g_args.robots[m_uid].tid, g_args.robots[m_uid].index, m_fd); } void Client::__beReady() { log(INFO, "准备"); Jpacket packet; packet.val["cmd"] = CLIENT_READY; packet.end(); sendData(packet.tostring().c_str(), packet.tostring().size()); } void Client::__doHeartBeat() { Jpacket packet; packet.val["cmd"] = SYSTEM_ECHO; packet.end(); sendData(packet.tostring().c_str(), packet.tostring().size()); } void Client::__doAction() { // TODO:根据packetAction发送决策 Json::Value &val = packetAction.tojson(); std::string str; std::vector<int> actions; int choose; int chiIdx, biIdx; for (unsigned int i = 0; i < val["actionList"].size(); i++) { int action = val["actionList"][i].asInt(); actions.push_back(action); str += action_map[action]; str += ","; } log(INFO, "收到选项[%s]", str.c_str()); if (std::find(actions.begin(), actions.end(), ACTION_HU) != actions.end()) { choose = ACTION_HU; } else if (find(actions.begin(), actions.end(), ACTION_PENG) != actions.end()) { choose = ACTION_PENG; } else if (find(actions.begin(), actions.end(), ACTION_CHI) != actions.end()) { if (__wiseEat(val, chiIdx, biIdx)) { choose = ACTION_CHI; } else { choose = ACTION_PASS; } } else { choose = ACTION_PASS; } log(INFO, "选择[%s]", action_map[choose]); Jpacket packetr; packetr.val["cmd"] = CLIENT_GAME_ACTION; packetr.val["action"] = choose; packetr.val["sn"] = val["sn"].asInt(); if (choose == ACTION_CHI) { // 吃、比ID packetr.val["params"].append(chiIdx); if (biIdx >= 0) { packetr.val["params"].append(biIdx); } } packetr.end(); sendData(packetr.tostring().c_str(), packetr.tostring().size()); } void Client::__outCard() { // TODO:出牌策略 HANDCARDS_t vcards = handcards.getHandCards(); Card cardval; for (HANDCARDS_t::const_iterator ito = vcards.begin(); ito != vcards.end(); ito++) { if (ito->size() >= 3 && ito->front() != ito->back() && ito->front() != 27) { cardval = ito->front(); break; } } for (HANDCARDS_t::const_iterator ito = vcards.begin(); ito != vcards.end(); ito++) { if (ito->size() == 2 && ito->front() == ito->back() && ito->front() != 27) { cardval = ito->front(); break; } } for (HANDCARDS_t::const_iterator ito = vcards.begin(); ito != vcards.end(); ito++) { if (ito->size() == 2 && ito->front() != ito->back() && ito->front() != 27) { cardval = ito->front(); break; } } for (HANDCARDS_t::const_iterator ito = vcards.begin(); ito != vcards.end(); ito++) { if (ito->size() == 1 && ito->front() != 27) { cardval = ito->front(); break; } } if (cardval == 0) { log(INFO, "打不出牌,出BUG了."); return; } log(INFO, "从手里打出牌[%d]", cardval.getVal()); Jpacket packetr; packetr.val["cmd"] = CLIENT_GAME_OUTCARD; packetr.val["card"] = cardval.getVal(); packetr.end(); sendData(packetr.tostring().c_str(), packetr.tostring().size()); } bool Client::__wiseEat(Json::Value& val, int& chiIdx, int& biIdx) { std::map< int, int > chiXiMP; std::map< int, std::map<int, int> > biXiMP; Card card; if (val["params"].size() == 0) { return false; } if (val["params"].size() >= 1) { Json::Value &chiArray = val["params"][0]; for (unsigned int i = 0; i < chiArray.size(); i++) { int cardval = chiArray[i]["card"].asInt(); int idx = chiArray[i]["idx"].asInt(); int sum = 0; int xi = 0; for (unsigned int j = 0; j < chiArray[i]["handCards"].size(); j++) { sum += chiArray[i]["handCards"][j].asInt(); } // 只吃1、2、3、7、10 if (!Card(cardval).IsXiCard()) { log(INFO, "牌:%d 吃后没有息", cardval); continue; } card = Card(cardval); if (sum == 6 || (sum == 19 && card.getPoint() != 1)) { xi = 3; } else if (sum == 54 || sum == 67) { xi = 6; } log(INFO, "吃牌:%d idx:%d sum:%d xi:%d", cardval, idx, sum, xi); chiXiMP[idx] = xi; } } if (val["params"].size() > 1) { Json::Value &biArray = val["params"][1]; int lastIdx = -1; int offset = 0; for (unsigned int i = 0; i < biArray.size(); i++) { int idx = biArray[i]["idx"].asInt(); if (idx == lastIdx) { offset++; } else { lastIdx = idx; offset = 0; } int sum1 = 0; int sum2 = 0; int xi = 0; for (unsigned int j = 0; j < biArray[i]["hand1"].size(); j++) { sum1 += biArray[i]["hand1"][j].asInt(); } for (unsigned int j = 0; j < biArray[i]["hand2"].size(); j++) { sum2 += biArray[i]["hand2"][j].asInt(); } // 去掉 1 1 壹 if (sum1 == 6 || (sum1 == 19 && card.getPoint() != 1)) { xi += 3; } else if (sum1 == 54 || sum1 == 67) { xi += 6; } if (sum2 == 6 || (sum2 == 19 && card.getPoint() != 1)) { xi += 3; } else if (sum2 == 54 || sum2 == 67) { xi += 6; } std::map<int, int>& ref = biXiMP[idx]; // 第idx种吃法对应的比法集合 ref[offset] = xi; // 第idx种吃法对应的第offset种比法 log(INFO, "比牌 idx:%d i:%d xi:%d sum1:%d sum2:%d", idx, i, xi, sum1, sum2); } } //------------------ for (std::map<int, int>::const_iterator cit = chiXiMP.begin(); cit != chiXiMP.end(); cit++) { std::map<int, int> &tmp = biXiMP[cit->first]; log(DEBUG, "chiIdx:%d chiXi:%d ", cit->first, cit->second); for (std::map<int, int>::const_iterator bit = tmp.begin(); bit != tmp.end(); bit++) { log(DEBUG, "chiIdx:%d chiXi:%d biIdx:%d biXi:%d", cit->first, cit->second, bit->first, bit->second); } } //------------------ // 选最优的吃idx int maxXi = 0; int chiBest = -1; for (std::map<int, int>::const_iterator cit = chiXiMP.begin(); cit != chiXiMP.end(); cit++) { int max = cit->second; std::map<int, int> &tmp = biXiMP[cit->first]; int maxBiXi = 0; for (std::map<int, int>::const_iterator bit = tmp.begin(); bit != tmp.end(); bit++) { if (bit->second >= maxBiXi) { maxBiXi = bit->second; } } if (max + maxBiXi >= maxXi) { maxXi = max + maxBiXi; chiBest = cit->first; } } log(INFO, "maxXi:%d chiBest:%d ", maxXi, chiBest); if (maxXi <= 0 || chiBest < 0) { return false; } // 选最优的比idx maxXi = 0; int biBest = -1; std::map<int, int> &tmp = biXiMP[chiBest]; for (std::map<int, int>::const_iterator bit = tmp.begin(); bit != tmp.end(); bit++) { if (bit->second >= maxXi) { maxXi = bit->second; biBest = bit->first; } } log(INFO, "maxXi:%d biBest:%d ", maxXi, biBest); chiIdx = chiBest; biIdx = biBest; return true; } void Client::__doLogout() { log(INFO, "退出房间"); Jpacket packetr; packetr.val["cmd"] = CLIENT_LOGOUT; packetr.end(); sendData(packetr.tostring().c_str(), packetr.tostring().size()); } void Client::__disConnectLater() { //ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerHeartBeat); int vid = g_args.robots[m_uid].vid; std::vector<int> &killQueue = g_args.queues[vid].dels; DBUG(DEBUG, "机器人:%d fd:%d vid:%d 等待断开", m_uid, m_fd, vid); if (std::find(killQueue.begin(), killQueue.end(), m_fd) != killQueue.end()) { DBUG(ERROR, "待断开队列异常,重复的fd:%d ", m_fd); return; } killQueue.push_back(m_fd); } void Client::__dumpHandCards() { std::ostringstream ostst; handcards.dumpHandsCards(ostst); log(INFO, "手牌[%s]", ostst.str().c_str()); } void Client::readyLater() { int start = rand() % 6 + 3; ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerReady); ev_timer_init(&m_evTimerReady, Client::__cbTimerReady, start, 0); ev_timer_start(CEnv::getEVLoop()->getEvLoop(), &m_evTimerReady); // 进入房间成功之后才发心跳 ev_timer_start(CEnv::getEVLoop()->getEvLoop(), &m_evTimerHeartBeat); } void Client::__logoutLater(int low, int up) { int start = rand() % (up - low + 1) + low; ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerLogout); ev_timer_init(&m_evTimerLogout, Client::__cbTimerLogout, start, 0); ev_timer_start(CEnv::getEVLoop()->getEvLoop(), &m_evTimerLogout); } void Client::cancelReady() { if (m_playing) { // 正在玩牌的机器人打完后再退出 return; } log(INFO, "取消准备"); m_playing = false; Jpacket packetr; packetr.val["cmd"] = CLIENT_LOGOUT; packetr.end(); sendData(packetr.tostring().c_str(), packetr.tostring().size()); // 制造被动断开 __disConnectLater(); } void Client::cbAction(Jpacket& packet) { int start = rand() % 4 + 1; packetAction = packet; ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerAction); ev_timer_init(&m_evTimerAction, Client::__cbTimerAction, start, 0); ev_timer_start(CEnv::getEVLoop()->getEvLoop(), &m_evTimerAction); } void Client::cbEnterRoom(Jpacket& packet) { Json::Value &val = packet.tojson(); log(INFO, "进入房间"); if (val["code"].asInt() != 0) { log(ERROR, "进入房间失败:[%d] ", val["code"].asInt()); // 进入房间失败不发心跳,由服务器超时断开 return; } // 获取房间信息 Jpacket packetr; packetr.val["cmd"] = CLIENT_TABLE_INFO; packetr.end(); sendData(packetr.tostring().c_str(), packetr.tostring().size()); // 延迟准备 readyLater(); } void Client::cbEnterRoomFail(Jpacket& packet) { Json::Value &val = packet.tojson(); log(ERROR, "进入房间失败:[%d] ", val["code"].asInt()); __disConnectLater(); } void Client::cbChangeTableFail(Jpacket& packet) { Json::Value &val = packet.tojson(); log(ERROR, "换房失败:[%d] ", val["type"].asInt()); __logoutLater(1,4); } void Client::cbReady(Jpacket& packet) { Json::Value &val = packet.tojson(); if (val["uid"].asInt() == m_uid) { log(INFO, "准备成功"); __logoutLater(30, 60); } else { log(INFO, "玩家[%d]准备成功", val["uid"].asInt()); } } void Client::cbReadyFail(Jpacket& packet) { Json::Value &val = packet.tojson(); log(ERROR, "准备失败:[%s] ", val["msg"].asString().c_str()); __logoutLater(1,4); } void Client::cbInitHandCards(Jpacket& packet) { Json::Value &val = packet.tojson(); m_seatid = val["seatid"].asInt(); log(INFO, "初始化手牌"); m_playing = true; // 游戏开始,关闭等待超时退出房间的定时器 ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerLogout); handcards.clear(); for (unsigned int i = 0; i < val["cards"].size(); i++) { for (unsigned int j = 0; j < val["cards"][i].size(); j++) { int cardval = val["cards"][i][j].asInt(); // 放到手牌 handcards.addCard(cardval); } } __dumpHandCards(); } void Client::cbTableInfo(Jpacket& packet) { Json::Value &val = packet.tojson(); std::ostringstream ostst; m_seatid = val["player_seatid"].asInt(); int tid = val["tid"].asInt(); log(INFO, "房间[%d] 座位[%d]", tid, m_seatid); handcards.clear(); for (unsigned int i = 0; i < val["hole_cards"].size(); i++) { for (unsigned int j = 0; j < val["hole_cards"][i].size(); j++) { int cardval = val["hole_cards"][i][j].asInt(); handcards.addCard(cardval); } } __dumpHandCards(); for (unsigned int i = 0; i < val["players"].size(); i++) { int uid = val["players"][i]["uid"].asInt(); int istrust = val["players"][i]["trust"].asInt(); // 取消托管 if ( uid == m_uid && istrust) { Jpacket packetr; packetr.val["cmd"] = CLIENT_CANCEL_TRUST; packetr.end(); sendData(packetr.tostring().c_str(), packetr.tostring().size()); break; } } #if 0 std::ostringstream ostste; for (unsigned int i = 0; i < val["players"].size(); i++) { if (val["players"][i]["seatid"] != m_seatid) { continue; } for (unsigned int j = 0; j < val["players"][i]["eatCards"].size(); j++) { ostste << "("; int cardval = val["players"][i]["eatCards"][j]["card"].asInt(); int type = val["players"][i]["eatCards"][j]["type"].asInt(); ostste << cardval << "," << eattype_map[type]; ostste << ") "; } } log(INFO, "\t吃牌[%s]", ostste.str().c_str()); #endif } void Client::cbNextRound(Jpacket& packet) { Json::Value &val = packet.tojson(); int banker_seatid = val["banker_seatid"].asInt(); int hu_seatid = val["hu_seatid"].asInt(); log(INFO, "小结算, 庄家座位[%d], 胡牌人座位[%d]", banker_seatid, hu_seatid); m_playing = false; // 收到退出信号,退出房间 if (g_args.quitLater == 1 || willChangeTable()) { __logoutLater(1,4); return; } // 概率换房 #if 0 if (willChangeTable()) { log(INFO, "换房间"); Jpacket packetr; packetr.val["cmd"] = CLIENT_CHANGE_TABLE; packetr.end(); sendData(packetr.tostring().c_str(), packetr.tostring().size()); return; } #endif // 延迟准备 log(INFO, "延迟准备"); readyLater(); } void Client::cbLogoutOK(Jpacket& packet) { Json::Value &val = packet.tojson(); if (val["uid"].asInt() == m_uid) { log(INFO, "退出房间成功"); __disConnectLater(); } } void Client::cbSomeOneEat(Jpacket& packet) { std::ostringstream ostst; Json::Value &val = packet.tojson(); int seatid = val["seatid"].asInt(); int action = val["action"].asInt(); log(INFO, "有人进牌"); if (m_seatid == seatid) { log(INFO, "自己操作[%s] ", action_map[action]); } else { // 停止自己的操作选项 ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerAction); log(INFO, "玩家座位[%d] 操作[%s] ", seatid, action_map[action]); } int cardval; for (unsigned int i = 0; i < val["eatCards"].size(); i++) { cardval = val["eatCards"][i]["card"].asInt(); ostst << cardval << ","; } log(INFO, "\t操作的牌[%s]", ostst.str().c_str()); if (m_seatid == seatid) { if (action == ACTION_PENG || action == ACTION_WEI) { handcards.removeCard(cardval, 2); } else if (action == ACTION_PAO || action == ACTION_TI) { handcards.removeCard(cardval, 4); } else if (action == ACTION_CHI) { handcards.removeCard(cardval, -1); for (unsigned int i = 0; i < val["eatCards"].size(); i++) { for (unsigned int j = 0; j < val["eatCards"][i]["cards"].size(); j++) { handcards.removeCard(val["eatCards"][i]["cards"][j].asInt(), 1); } } } __dumpHandCards(); } } void Client::cbNoticeOutCard(Jpacket& packet) { std::ostringstream ostst; std::string str; Json::Value &val = packet.tojson(); log(INFO, "提示出牌"); int seatid = val["seatid"].asInt(); if (seatid != m_seatid) { log(INFO, "等待玩家出牌, 座位[%d]", seatid); return; } int start = rand() % 2 + 1; ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerOutCard); ev_timer_init(&m_evTimerOutCard, Client::__cbTimerOutCard, start, 0); ev_timer_start(CEnv::getEVLoop()->getEvLoop(), &m_evTimerOutCard); } void Client::cbSomeOneOutCard(Jpacket& packet) { Json::Value &val = packet.tojson(); int seatid = val["seatid"].asInt(); int card = val["card"].asInt(); int fetch = val["fetch"].asInt(); log(INFO, "玩家出牌"); if (fetch == 1) { if (seatid != m_seatid) { log(INFO, "玩家座位[%d], 摸出牌[%d]", seatid, card); } else { log(INFO, "摸出牌[%d]", card); } } else { if (seatid != m_seatid) { log(INFO, "玩家座位[%d], 从手中打出牌[%d]", seatid, card); } else { log(INFO, "从手中打出牌[%d]", card); handcards.outHandCard(card); __dumpHandCards(); } } } void Client::cbOutCardOK(Jpacket& packet) { //evwork::IConn* pConn = g_args.conMap[m_fd]; Json::Value &val = packet.tojson(); log(INFO, "出牌结果"); int seat = val["seatid"].asInt(); int cardval = val["card"].asInt(); if (seat == m_seatid) { // 停止出牌定时器,因为可能是服务器主动替玩家出的牌 ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerOutCard); log(INFO, "没人要牌[%d],出牌成功", cardval); if (val["fetch"].isInt() && val["fetch"].asInt() == 0) { // 从手里去掉这张牌 // 已通过4023去掉了这张打出的牌 //handcards.outHandCard(cardval); } } } void Client::cbSyncHandCards(Jpacket& packet) { Json::Value &val = packet.tojson(); std::ostringstream ostst; m_seatid = val["player_seatid"].asInt(); log(INFO, "同步手牌"); handcards.clear(); for (unsigned int i = 0; i < val["cards"].size(); i++) { for (unsigned int j = 0; j < val["cards"][i].size(); j++) { int cardval = val["cards"][i][j].asInt(); handcards.addCard(cardval); } } __dumpHandCards(); } void Client::__cbTimerLogin(struct ev_loop *loop, struct ev_timer *w, int revents) { Client* pThis = (Client*)w->data; pThis->__doLogin(); } void Client::__cbTimerLogout(struct ev_loop *loop, struct ev_timer *w, int revents) { Client* pThis = (Client*)w->data; pThis->__doLogout(); } void Client::__cbTimerHeartBeat(struct ev_loop *loop, struct ev_timer *w, int revents) { Client* pThis = (Client*)w->data; pThis->__doHeartBeat(); } void Client::__cbTimerReady(struct ev_loop *loop, struct ev_timer *w, int revents) { Client* pThis = (Client*)w->data; pThis->__beReady(); } void Client::__cbTimerAction(struct ev_loop *loop, struct ev_timer *w, int revents) { Client* pThis = (Client*)w->data; pThis->__doAction(); } void Client::__cbTimerOutCard(struct ev_loop *loop, struct ev_timer *w, int revents) { Client* pThis = (Client*)w->data; pThis->__outCard(); } Client *findClientByfd(int fd) { std::map<int, Client*>::iterator iter = g_args.cmap.find(fd); if (iter != g_args.cmap.end()) { return iter->second; } return NULL; } void Client::open_log() { char path[64] = "\0"; snprintf(path, 64, "%s/%d", g_args.logdir.c_str(), m_uid); m_logfd = open(path, O_RDWR | O_CREAT | O_APPEND, 0666); } void Client::close_log() { close(m_logfd); } void Client::log(int level, const char *fmt, ...) { time_t iTime = time(NULL); struct tm* pTM = localtime(&iTime); va_list ap; memset(m_logbuf, 0, LOG_BUFF_SIZE); memset(m_msgbuf, 0, MSG_BUFF_SIZE); va_start(ap, fmt); vsnprintf(m_msgbuf, MSG_BUFF_SIZE, fmt, ap); va_end(ap); snprintf(m_logbuf, LOG_BUFF_SIZE, "[%04d-%02d-%02d %02d:%02d:%02d %s] %s\n", pTM->tm_year + 1900, pTM->tm_mon + 1, pTM->tm_mday, pTM->tm_hour, pTM->tm_min, pTM->tm_sec, log_level_map[level], m_msgbuf); write(m_logfd, m_logbuf, strlen(m_logbuf)); //fsync(m_logfd); } void Client::_startTimers() { // 延迟登录 m_evTimerLogin.data = this; ev_timer_init(&m_evTimerLogin, Client::__cbTimerLogin, 2, 0); ev_timer_start(CEnv::getEVLoop()->getEvLoop(), &m_evTimerLogin); m_evTimerLogout.data = this; ev_timer_init(&m_evTimerLogout, Client::__cbTimerLogout, 2, 0); m_evTimerHeartBeat.data = this; ev_timer_init(&m_evTimerHeartBeat, Client::__cbTimerHeartBeat, 20, 20); m_evTimerReady.data = this; ev_timer_init(&m_evTimerReady, Client::__cbTimerReady, 3, 0); m_evTimerAction.data = this; ev_timer_init(&m_evTimerAction, Client::__cbTimerAction, 3, 0); m_evTimerOutCard.data = this; ev_timer_init(&m_evTimerOutCard, Client::__cbTimerOutCard, 3, 0); } void Client::_stopTimers() { ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerOutCard); ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerAction); ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerReady); ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerHeartBeat); ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerLogout); ev_timer_stop(CEnv::getEVLoop()->getEvLoop(), &m_evTimerLogin); }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <quic/server/async_tran/QuicAsyncTransportServer.h> #include <quic/server/QuicServerTransport.h> namespace quic { QuicAsyncTransportServer::QuicAsyncTransportServer( QuicAsyncTransportAcceptor::AsyncTransportHook asyncTransportHook) : asyncTransportHook_(std::move(asyncTransportHook)), quicServer_(quic::QuicServer::createQuicServer()) { CHECK(asyncTransportHook_); } void QuicAsyncTransportServer::setFizzContext( std::shared_ptr<const fizz::server::FizzServerContext> ctx) { fizzCtx_ = std::move(ctx); } void QuicAsyncTransportServer::setTransportSettings( const quic::TransportSettings& ts) { quicServer_->setTransportSettings(ts); } void QuicAsyncTransportServer::start( const folly::SocketAddress& address, size_t numThreads) { if (numThreads == 0) { numThreads = std::thread::hardware_concurrency(); } std::vector<folly::EventBase*> evbs; for (size_t i = 0; i < numThreads; ++i) { auto scopedEvb = std::make_unique<folly::ScopedEventBaseThread>(); evbs.push_back(scopedEvb->getEventBase()); workerEvbs_.push_back(std::move(scopedEvb)); } start(address, std::move(evbs)); } void QuicAsyncTransportServer::start( const folly::SocketAddress& address, std::vector<folly::EventBase*> evbs) { quicServer_->initialize(address, evbs, false /* useDefaultTransport */); quicServer_->waitUntilInitialized(); createAcceptors(evbs); quicServer_->start(); } void QuicAsyncTransportServer::createAcceptors( std::vector<folly::EventBase*>& evbs) { for (auto evb : evbs) { quicServer_->setFizzContext(evb, fizzCtx_); auto acceptor = std::make_unique<QuicAsyncTransportAcceptor>( evb, [this](folly::AsyncTransport::UniquePtr tran) { asyncTransportHook_(std::move(tran)); }); quicServer_->addTransportFactory(evb, acceptor.get()); acceptors_.push_back(std::move(acceptor)); } } void QuicAsyncTransportServer::shutdown() { quicServer_->rejectNewConnections([]() { return true; }); quicServer_->shutdown(); quicServer_.reset(); } } // namespace quic
class Solution { public: vector<int> GetLeastNumbers_Solution(vector<int> input, int k) { priority_queue<int> Q;//½¨Á¢´ó¸ù¶Ñ vector<int> ret; if(k < 1 || input.size() < k){ return ret; } for(int i=0; i<input.size(); ++i){ if(Q.size() < k){ Q.push(input[i]); }else{ if(input[i] < Q.top()){ Q.pop(); Q.push(input[i]); } } } while(Q.empty() == false){ ret.insert(ret.begin(),Q.top()); Q.pop(); } return ret; } };
#include <iostream> #include <cstring> using namespace std; void readline() { char line[10]; cin.getline(line,9); } int getExpression(); int getTerm(); int getFactor(); bool isNum(char c) { if(c>='0' && c<='9') return 1; return 0; } int main() { int N; cin >> N; while(N--) { readline(); cout << getExpression() << endl; } } int getExpression() { char c; int a; a = getTerm(); while(c = cin.peek()) { if(c!='+' && c!='-') break; cin >> c; if(c == '+') a += getTerm(); else if(c == '-') a -= getTerm(); } return a; } int getTerm() { char c; int a; a = getFactor(); while(c = cin.peek()) { if(c!='*' && c!='/') break; cin >> c; if(c == '*') a *= getFactor(); else if(c == '/') a /= getFactor(); } return a; } int getFactor() { char c; int a; c = cin.peek(); if(isNum(c)) cin >> a; else { cin >> c; a = getExpression(); cin >> c; } return a; }
/* TouchKeys: multi-touch musical keyboard control software Copyright (c) 2013 Andrew McPherson 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ===================================================================== MainApplicationController.cpp: contains the overall glue that holds together the various parts of the TouchKeys code. It works together with the user interface to let the user configure the hardware and manage the mappings, but it is kept separate from any particular user interface configuration. */ #include "MainApplicationController.h" #ifndef TOUCHKEYS_NO_GUI #include "Display/KeyboardTesterDisplay.h" #endif #include <cstdlib> #include <sstream> // Strings for pitch classes (two forms for sharps), for static methods const char* kNoteNames[12] = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}; const char* kNoteNamesAlternate[12] = {"C", "Db", "D ", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"}; std::vector<int> gKeysToMonitor; MainApplicationController::MainApplicationController() : midiInputController_(keyboardController_), oscReceiver_(0, "/touchkeys"), touchkeyController_(keyboardController_), // touchkeyEmulator_(keyboardController_, oscReceiver_), // logPlayback_(0), #ifdef TOUCHKEY_ENTROPY_GENERATOR_ENABLE touchkeyEntropyGenerator_(keyboardController_), entropyGeneratorSelected_(false), #endif touchkeyErrorOccurred_(false), touchkeyErrorMessage_(""), touchkeyAutodetecting_(false), touchkeyStandaloneModeEnabled_(false), deviceUpdateCounter_(0), oscReceiveEnabled_(false), oscReceivePort_(kDefaultOscReceivePort), experimentalMappingsEnabled_(false), #ifndef TOUCHKEYS_NO_GUI keyboardDisplayWindow_(0), keyboardTesterDisplay_(0), keyboardTesterWindow_(0), preferencesWindow_(0), #endif segmentCounter_(0), loggingActive_(false), isPlayingLog_(false) { // Set our OSC controller setOscController(&keyboardController_); oscTransmitter_.setEnabled(false); //oscTransmitter_.setDebugMessages(true); // Initialize the links between objects keyboardController_.setOscTransmitter(&oscTransmitter_); keyboardController_.setMidiOutputController(&midiOutputController_); // keyboardController_.setGUI(&keyboardDisplay_); // midiInputController_.setMidiOutputController(&midiOutputController_); // Set up default logging directory // loggingDirectory_ = (File::getSpecialLocation(File::userHomeDirectory).getFullPathName() + "/Desktop").toUTF8(); // // Configure application properties // PropertiesFile::Options options; // options.applicationName = "TouchKeys"; // options.folderName = "TouchKeys"; // options.filenameSuffix = ".properties"; // options.osxLibrarySubFolder = "Application Support"; // applicationProperties_.setStorageParameters(options); // // // Defaults for display, until we get other information // keyboardDisplay_.setKeyboardRange(36, 72); // Add one keyboard segment at the beginning midiSegmentAdd(); // Load the current preferences loadApplicationPreferences(); // Set up an initial OSC transmit host/port if none has been loaded if(oscTransmitter_.addresses().size() == 0) oscTransmitter_.addAddress(kDefaultOscTransmitHost, kDefaultOscTransmitPort); // Listen for control messages by OSC mainOscController_ = new MainApplicationOSCController(*this, oscReceiver_); } MainApplicationController::~MainApplicationController() { #ifdef ENABLE_TOUCHKEYS_SENSOR_TEST if(touchkeySensorTestIsRunning()) touchkeySensorTestStop(); #endif // if(logPlayback_ != 0) // delete logPlayback_; removeAllOscListeners(); // midiInputController_.removeAllSegments(); // Remove segments now to avoid deletion-order problems delete mainOscController_; } // Actions here run in the JUCE initialise() method once the application is loaded void MainApplicationController::initialise() { // Load a preset if enabled // if(getPrefsStartupPresetLastSaved()) { // if(applicationProperties_.getUserSettings()->containsKey("LastSavedPreset")) { // std::string presetFile = applicationProperties_.getUserSettings()->getValue("LastSavedPreset"); // if(presetFile != "") { // loadPresetFromFile(presetFile.toUTF8()); // } // } // } // else if(getPrefsStartupPresetVibratoPitchBend()) { // if(midiInputController_.numSegments() > 0) { // MidiKeyboardSegment *segment = midiInputController_.segment(0); // // MappingFactory *factory = new TouchkeyVibratoMappingFactory(keyboardController_, *segment); // if(factory != 0) // segment->addMappingFactory(factory, true); // factory = new TouchkeyPitchBendMappingFactory(keyboardController_, *segment); // if(factory != 0) // segment->addMappingFactory(factory, true); // } // } // else if(!getPrefsStartupPresetNone()) { // std::string presetFile = getPrefsStartupPreset(); // if(presetFile != "") { // loadPresetFromFile(presetFile.toUTF8()); // } // } // // // Automatically start the TouchKeys if the preferences are enabled // if(getPrefsAutoStartTouchKeys() && applicationProperties_.getUserSettings()->containsKey("TouchKeysDevice")) { // std::string tkDevicePath = applicationProperties_.getUserSettings()->getValue("TouchKeysDevice"); // if(touchkeyDeviceExists(tkDevicePath.toUTF8())) { // // Exists: try to open and run // touchkeyDeviceStartupSequence(tkDevicePath.toUTF8()); // } // } } bool MainApplicationController::touchkeyDeviceStartupSequence(const char * path) { #ifdef TOUCHKEY_ENTROPY_GENERATOR_ENABLE if(!strcmp(path, "/dev/Entropy Generator") || !strcmp(path, "\\\\.\\Entropy Generator")) { entropyGeneratorSelected_ = true; touchkeyEntropyGenerator_.start(); } else { entropyGeneratorSelected_ = false; #endif // Step 1: attempt to open device if(!openTouchkeyDevice(path)) { touchkeyErrorMessage_ = "Failed to open"; touchkeyErrorOccurred_ = true; return false; } // Step 2: see if a real TouchKeys device is present at the other end if(!touchkeyDeviceCheckForPresence()) { touchkeyErrorMessage_ = "Device not recognized"; touchkeyErrorOccurred_ = true; return false; } // Step 3: update the display // keyboardDisplay_.setKeyboardRange(touchkeyController_.lowestKeyPresentMidiNote(), touchkeyController_.highestMidiNote()); #ifndef TOUCHKEYS_NO_GUI if(keyboardDisplayWindow_ != 0) { keyboardDisplayWindow_->getConstrainer()->setFixedAspectRatio(keyboardDisplay_.keyboardAspectRatio()); juce::Rectangle<int> bounds = keyboardDisplayWindow_->getBounds(); if(bounds.getY() < 44) bounds.setY(44); keyboardDisplayWindow_->setBoundsConstrained(bounds); } #endif // Step 4: start data collection from the device if(!startTouchkeyDevice()) { touchkeyErrorMessage_ = "Failed to start"; touchkeyErrorOccurred_ = true; } #ifdef TOUCHKEY_ENTROPY_GENERATOR_ENABLE } #endif // Wait to capture some frames // usleep(1e+6); // Start monitoring some keys // std::vector<int> keysToMonitor; // gKeysToMonitor.push_back(65); // // pianoKeyInfo_.setPianoKeys(gKeysToMonitor); // pianoKeyInfo_.startThread(); // Success! touchkeyErrorMessage_ = ""; touchkeyErrorOccurred_ = false; #ifndef TOUCHKEYS_NO_GUI showKeyboardDisplayWindow(); #endif // Automatically detect the lowest octave if set touchkeyDeviceAutodetectLowestMidiNote(); // if(getPrefsAutodetectOctave()) return true; } std::string MainApplicationController::touchkeyDevicePrefix() { //#ifdef _MSC_VER // return "\\\\.\\"; //#else // if(SystemStats::getOperatingSystemType() == SystemStats::Linux) { return "/dev/serial/by-id/"; // } // else { // return "/dev/"; // } //#endif } // Return a list of available TouchKey devices std::vector<std::string> MainApplicationController::availableTouchkeyDevices() { std::vector<std::string> devices; devices.push_back("serial/by-id/usb-APM_TouchKeys_8D73428C5751-if00"); //#ifdef _MSC_VER // for(int i = 1; i <= 128; i++) { // std::string comPortName("COM"); // comPortName += i; // // DWORD dwSize = 0; // LPCOMMCONFIG lpCC = (LPCOMMCONFIG) new BYTE[1]; // BOOL ret = GetDefaultCommConfig(comPortName.toUTF8(), lpCC, &dwSize); // delete [] lpCC; // // if(ret) // devices.push_back(comPortName.toStdString()); // else { // if(GetLastError() == ERROR_INSUFFICIENT_BUFFER) { // //Logger::writeToLog(std::string::formatted("Found " + comPortName)); // lpCC = (LPCOMMCONFIG) new BYTE[dwSize]; // ret = GetDefaultCommConfig(comPortName.toUTF8(), lpCC, &dwSize); // if(ret) // devices.push_back(comPortName.toStdString()); // else { // int error = GetLastError(); // //Logger::writeToLog(std::string("2Didn't find " + comPortName + "; error " + std::string(error))); // } // delete [] lpCC; // } // else { // int error = GetLastError(); // //Logger::writeToLog(std::string("Didn't find " + comPortName + "; error " + std::string(error))); // } // } // } //#else // if(SystemStats::getOperatingSystemType() == SystemStats::Linux) { // DirectoryIterator devDirectory(File("/dev/serial/by-id"),false,"*"); // // while(devDirectory.next()) { // devices.push_back(string(devDirectory.getFile().getFileName().toUTF8())); // } // } // else { // DirectoryIterator devDirectory(File("/dev"),false,"cu.usbmodem*"); // // while(devDirectory.next()) { // devices.push_back(string(devDirectory.getFile().getFileName().toUTF8())); // } // } //#endif // //#ifdef TOUCHKEY_ENTROPY_GENERATOR_ENABLE // devices.push_back("Entropy Generator"); //#endif // return devices; } void MainApplicationController::touchkeyDeviceClearErrorMessage() { touchkeyErrorMessage_ = ""; touchkeyErrorOccurred_ = false; } // Check whether a given touchkey device exists bool MainApplicationController::touchkeyDeviceExists(const char * path) { std::string pathString(path); // File tkDeviceFile(pathString); // return tkDeviceFile.existsAsFile(); if (FILE* file = fopen(path, "r")) { fclose(file); return true; } else { return false; } } // Select a particular touchkey device bool MainApplicationController::openTouchkeyDevice(const char * path) { bool success = touchkeyController_.openDevice(path); // if(success) // applicationProperties_.getUserSettings()->setValue("TouchKeysDevice", std::string(path)); return success; } // Close the currently open TouchKeys device void MainApplicationController::closeTouchkeyDevice() { #ifdef TOUCHKEY_ENTROPY_GENERATOR_ENABLE if(entropyGeneratorSelected_) touchkeyEntropyGenerator_.stop(); else touchkeyController_.closeDevice(); #else touchkeyController_.closeDevice(); #endif } // Check whether a TouchKey device is present. Returns true if device found. bool MainApplicationController::touchkeyDeviceCheckForPresence(int waitMilliseconds, int tries) { int count = 0; while(1) { if(touchkeyController_.checkIfDevicePresent(waitMilliseconds)) break; if(++count >= tries) { return false; } } return true; } void MainApplicationController::touchkeyDeviceSetVerbosity(int verbose) { touchkeyController_.setVerboseLevel(verbose); } void MainApplicationController::startCalibration(int secondsToCalibrate) { if (secondsToCalibrate > 0) { std::cout << "Running calibration for " << secondsToCalibrate << " seconds..." << std::endl; touchkeyController_.calibrationStart(NULL); usleep(secondsToCalibrate * 1E6); } else { touchkeyController_.calibrationStart(NULL); } } void MainApplicationController::finishCalibration() { touchkeyController_.calibrationFinish(); std::cout << "Calibration finished" << std::endl; } void MainApplicationController::updateQuiescent() { touchkeyController_.calibrationUpdateQuiescent(); } bool MainApplicationController::saveCalibration(std::string const& filename) { return touchkeyController_.calibrationSaveToFile(filename); } bool MainApplicationController::loadCalibration(std::string const& filename) { return touchkeyController_.calibrationLoadFromFile(filename); } // Start/stop the TouchKeys data collection bool MainApplicationController::startTouchkeyDevice() { return touchkeyController_.startAutoGathering(); } void MainApplicationController::stopTouchkeyDevice() { touchkeyController_.stopAutoGathering(); pianoKeyInfo_.stopThread(-1); } // Status queries on TouchKeys // Returns true if device has been opened bool MainApplicationController::touchkeyDeviceIsOpen() { return touchkeyController_.isOpen(); } // Return true if device is collecting data bool MainApplicationController::touchkeyDeviceIsRunning() { #ifdef TOUCHKEY_ENTROPY_GENERATOR_ENABLE if(entropyGeneratorSelected_) return touchkeyEntropyGenerator_.isRunning(); else return touchkeyController_.isAutoGathering(); #else return touchkeyController_.isAutoGathering(); #endif } // Returns true if an error has occurred bool MainApplicationController::touchkeyDeviceErrorOccurred() { return touchkeyErrorOccurred_; } // Return the error message if one occurred std::string MainApplicationController::touchkeyDeviceErrorMessage() { return touchkeyErrorMessage_; } // How many octaves on the current device int MainApplicationController::touchkeyDeviceNumberOfOctaves() { return touchkeyController_.numberOfOctaves(); } // Return the lowest MIDI note int MainApplicationController::touchkeyDeviceLowestMidiNote() { return touchkeyController_.lowestMidiNote(); } // Set the lowest MIDI note for the TouchKeys void MainApplicationController::touchkeyDeviceSetLowestMidiNote(int note) { // keyboardDisplay_.clearAllTouches(); // touchkeyEmulator_.setLowestMidiNote(note); touchkeyController_.setLowestMidiNote(note); // applicationProperties_.getUserSettings()->setValue("TouchKeysLowestMIDINote", note); } // Start an autodetection routine to match touch data to MIDI void MainApplicationController::touchkeyDeviceAutodetectLowestMidiNote() { if(touchkeyAutodetecting_) return; touchkeyAutodetecting_ = true; addOscListener("/midi/noteon"); } // Abort an autodetection routine void MainApplicationController::touchkeyDeviceStopAutodetecting() { if(!touchkeyAutodetecting_) return; removeOscListener("/midi/noteon"); touchkeyAutodetecting_ = false; } bool MainApplicationController::touchkeyDeviceIsAutodetecting() { return touchkeyAutodetecting_; } // Start logging TouchKeys/MIDI data to a file. Filename is autogenerated // based on current time. void MainApplicationController::startLogging() { if(loggingActive_) stopLogging(); std::stringstream out; out << time(NULL); std::string fileId = out.str(); string midiLogFileName = "midiLog_" + fileId + ".bin"; string keyTouchLogFileName = "keyTouchLog_" + fileId + ".bin"; string analogLogFileName = "keyAngleLog_" + fileId + ".bin"; // Create log files with these names // midiInputController_.createLogFile(midiLogFileName, loggingDirectory_); // touchkeyController_.createLogFiles(keyTouchLogFileName, analogLogFileName, loggingDirectory_); // Enable logging from each controller // midiInputController_.startLogging(); // touchkeyController_.startLogging(); loggingActive_ = true; } // Stop a currently running log. void MainApplicationController::stopLogging() { if(!loggingActive_) return; // stop logging data // midiInputController_.stopLogging(); // touchkeyController_.stopLogging(); // close the log files // midiInputController_.closeLogFile(); // touchkeyController_.closeLogFile(); loggingActive_ = false; } void MainApplicationController::setLoggingDirectory(const char *directory) { loggingDirectory_ = directory; } void MainApplicationController::playLogWithDialog() { // if(isPlayingLog_) // return; // // FileChooser tkChooser ("Select TouchKeys log...", // File::nonexistent, // File::getSpecialLocation (File::userHomeDirectory), // "*.bin"); // if(tkChooser.browseForFileToOpen()) { // FileChooser midiChooser ("Select MIDI log...", // File::nonexistent, // File::getSpecialLocation (File::userHomeDirectory), // "*.bin"); // if(midiChooser.browseForFileToOpen()) { // logPlayback_ = new LogPlayback(keyboardController_, midiInputController_); // if(logPlayback_ == 0) // return; // // if(logPlayback_->openLogFiles(tkChooser.getResult().getFullPathName().toRawUTF8(), midiChooser.getResult().getFullPathName().toRawUTF8())) { // logPlayback_->startPlayback(); // isPlayingLog_ = true; //#ifndef TOUCHKEYS_NO_GUI // // Always show 88 keys for log playback since we won't know which keys were actually recorded // keyboardDisplay_.setKeyboardRange(21, 108); // if(keyboardDisplayWindow_ != 0) { // keyboardDisplayWindow_->getConstrainer()->setFixedAspectRatio(keyboardDisplay_.keyboardAspectRatio()); // // juce::Rectangle<int> bounds = keyboardDisplayWindow_->getBounds(); // if(bounds.getY() < 44) // bounds.setY(44); // keyboardDisplayWindow_->setBoundsConstrained(bounds); // } // showKeyboardDisplayWindow(); //#endif // } // } // } } void MainApplicationController::stopPlayingLog() { // if(!isPlayingLog_) // return; // // if(logPlayback_ != 0) { // logPlayback_->stopPlayback(); // logPlayback_->closeLogFiles(); // delete logPlayback_; // logPlayback_ = 0; // } // //#ifndef TOUCHKEYS_NO_GUI // keyboardDisplay_.clearAllTouches(); //#endif // midiInputController_.allNotesOff(); // isPlayingLog_ = false; } // Add a new MIDI keyboard segment. This method also handles numbering of the segments MidiKeyboardSegment* MainApplicationController::midiSegmentAdd() { // For now, the segment counter increments with each new segment. Eventually, we could // consider renumbering every time a segment is removed so that we always have an index // 0-N which corresponds to the indexes within MidiInputController (and also the layout // of the tabs). MidiKeyboardSegment *newSegment = midiInputController_.addSegment(segmentCounter_, 12, 127); // Set up defaults newSegment->setModePassThrough(); newSegment->setPolyphony(8); newSegment->setVoiceStealingEnabled(false); newSegment->enableAllChannels(); newSegment->setOutputTransposition(0); newSegment->setUsesKeyboardPitchWheel(true); // Enable the MIDI output for this segment if it exists in the preferences loadMIDIOutputFromApplicationPreferences(segmentCounter_); // Enable standalone mode on the new segment if generally enabled if(touchkeyStandaloneModeEnabled_) newSegment->enableTouchkeyStandaloneMode(); segmentCounter_++; return newSegment; } // Remove a MIDI keyboard segment. void MainApplicationController::midiSegmentRemove(MidiKeyboardSegment *segment) { if(segment == 0) return; // Check if this segment uses a virtual output port. Right now, we have a unique // output per segment. If it does, then disable the virtual output port. int identifier = segment->outputPort(); if(midiOutputController_.enabledPort(identifier) == MidiOutputController::kMidiVirtualOutputPortNumber) midiOutputController_.disablePort(identifier); midiInputController_.removeSegment(segment); } void MainApplicationController::midiSegmentSetMode(MidiKeyboardSegment *segment, int mode) { segment->setMode(mode); } void MainApplicationController::midiSegmentSetMidiOutputController(MidiKeyboardSegment *segment, MidiOutputController *controller) { segment->setMidiOutputController(controller); } void MainApplicationController::midiSegmentsSetMode(int mode) { for (int i = 0; i < midiInputController_.numSegments(); ++i) { midiSegmentSetMode(midiInputController_.segment(i), mode); } } void MainApplicationController::midiSegmentsSetMidiOutputController(MidiOutputController *controller) { for (int i = 0; i < midiInputController_.numSegments(); ++i) { midiSegmentSetMidiOutputController(midiInputController_.segment(i), controller); } } void MainApplicationController::midiSegmentsSetMidiOutputController() { for (int i = 0; i < midiInputController_.numSegments(); ++i) { midiSegmentSetMidiOutputController(midiInputController_.segment(i), &midiOutputController_); } } // Enable one MIDI input port either as primary or auxiliary void MainApplicationController::enableMIDIInputPort(int portNumber, bool isPrimary) { midiInputController_.enablePort(portNumber, isPrimary); // if(isPrimary) // applicationProperties_.getUserSettings()->setValue("MIDIInputPrimary", // midiInputController_.deviceName(portNumber)); // else // applicationProperties_.getUserSettings()->setValue("MIDIInputAuxiliary", // midiInputController_.deviceName(portNumber)); } // Enable all available MIDI input ports, with one in particular selected as primary void MainApplicationController::enableAllMIDIInputPorts(int primaryPortNumber) { midiInputController_.enableAllPorts(primaryPortNumber); // applicationProperties_.getUserSettings()->setValue("MIDIInputPrimary", // midiInputController_.deviceName(primaryPortNumber)); // applicationProperties_.getUserSettings()->setValue("MIDIInputAuxiliary", "__all__"); } // Disable a particular MIDI input port number // For now, the preferences for auxiliary ports don't update; could add a complete list of enabled aux ports void MainApplicationController::disableMIDIInputPort(int portNumber) { // if(portNumber == selectedMIDIPrimaryInputPort()) // applicationProperties_.getUserSettings()->setValue("MIDIInputPrimary", ""); midiInputController_.disablePort(portNumber); } // Disable the current primary MIDI input port void MainApplicationController::disablePrimaryMIDIInputPort() { // applicationProperties_.getUserSettings()->setValue("MIDIInputPrimary", ""); midiInputController_.disablePrimaryPort(); } // Disable either all MIDI input ports or all auxiliary inputs void MainApplicationController::disableAllMIDIInputPorts(bool auxiliaryOnly) { // applicationProperties_.getUserSettings()->setValue("MIDIInputAuxiliary", ""); // if(!auxiliaryOnly) // applicationProperties_.getUserSettings()->setValue("MIDIInputPrimary", ""); midiInputController_.disableAllPorts(auxiliaryOnly); } // Enable a particular MIDI output port, associating it with a segment void MainApplicationController::enableMIDIOutputPort(int identifier, int deviceNumber) { midiOutputController_.enablePort(identifier, deviceNumber); std::string zoneName = "MIDIOutputZone"; zoneName += identifier; // applicationProperties_.getUserSettings()->setValue(zoneName, midiOutputController_.deviceName(deviceNumber)); } #ifndef JUCE_WINDOWS // Create a virtual (inter-application) MIDI output port void MainApplicationController::enableMIDIOutputVirtualPort(int identifier, const char *name) { midiOutputController_.enableVirtualPort(identifier, name); std::string zoneName = "MIDIOutputZone"; zoneName += identifier; std::string zoneValue = "__virtual__"; zoneValue += std::string(name); // applicationProperties_.getUserSettings()->setValue(zoneName, zoneValue); } #endif // Disable a particular MIDI output port void MainApplicationController::disableMIDIOutputPort(int identifier) { std::string zoneName = "MIDIOutputZone"; zoneName += identifier; // applicationProperties_.getUserSettings()->setValue(zoneName, ""); midiOutputController_.disablePort(identifier); } // Disable all MIDI output ports void MainApplicationController::disableAllMIDIOutputPorts() { std::vector<std::pair<int, int> > enabledPorts = midiOutputController_.enabledPorts(); for(unsigned int i = 0; i < enabledPorts.size(); i++) { // For each active zone, set output port to disabled in preferences std::string zoneName = "MIDIOutputZone"; zoneName += enabledPorts[i].first; // applicationProperties_.getUserSettings()->setValue(zoneName, ""); } midiOutputController_.disableAllPorts(); } // Enable TouchKeys standalone mode void MainApplicationController::midiTouchkeysStandaloneModeEnable() { touchkeyStandaloneModeEnabled_ = true; // Go through all segments and enable standalone mode for(int i = 0; i < midiInputController_.numSegments(); i++) { midiInputController_.segment(i)->enableTouchkeyStandaloneMode(); } // // applicationProperties_.getUserSettings()->setValue("MIDIInputPrimary", "__standalone__"); } void MainApplicationController::midiTouchkeysStandaloneModeDisable() { touchkeyStandaloneModeEnabled_ = false; // Go through all segments and disable standalone mode for(int i = 0; i < midiInputController_.numSegments(); i++) { midiInputController_.segment(i)->disableTouchkeyStandaloneMode(); } // // if(applicationProperties_.getUserSettings()->getValue("MIDIInputPrimary") == "__standalone__") // applicationProperties_.getUserSettings()->setValue("MIDIInputPrimary", ""); } // *** OSC device methods *** // Return whether OSC transmission is enabled bool MainApplicationController::oscTransmitEnabled() { return oscTransmitter_.enabled(); } // Set whether OSC transmission is enabled void MainApplicationController::oscTransmitSetEnabled(bool enable) { oscTransmitter_.setEnabled(enable); // applicationProperties_.getUserSettings()->setValue("OSCTransmitEnabled", enable); } // Return whether raw frame transmission is enabled bool MainApplicationController::oscTransmitRawDataEnabled() { return touchkeyController_.transmitRawDataEnabled(); } // Set whether raw frame transmission is enabled void MainApplicationController::oscTransmitSetRawDataEnabled(bool enable) { touchkeyController_.setTransmitRawData(enable); // applicationProperties_.getUserSettings()->setValue("OSCTransmitRawDataEnabled", enable); } // Return the addresses to which OSC messages are sent std::vector<lo_address> MainApplicationController::oscTransmitAddresses() { return oscTransmitter_.addresses(); } // Add a new address for sending OSC messages to int MainApplicationController::oscTransmitAddAddress(const char * host, const char * port, int proto) { int indexOfNewAddress = oscTransmitter_.addAddress(host, port, proto); if(indexOfNewAddress >= 0) { // Successfully added; update preferences std::string keyName = "OSCTransmitHost"; keyName += indexOfNewAddress; // applicationProperties_.getUserSettings()->setValue(keyName, std::string(host)); keyName = "OSCTransmitPort"; keyName += indexOfNewAddress; // applicationProperties_.getUserSettings()->setValue(keyName, std::string(port)); keyName = "OSCTransmitProtocol"; keyName += indexOfNewAddress; // applicationProperties_.getUserSettings()->setValue(keyName, proto); } return indexOfNewAddress; } // Remove a particular OSC address from the send list void MainApplicationController::oscTransmitRemoveAddress(int index) { oscTransmitter_.removeAddress(index); // // Remove this destination from the preferences, if it exists // std::string keyName = "OSCTransmitHost"; // keyName += index; // // if(applicationProperties_.getUserSettings()->containsKey(keyName)) { // applicationProperties_.getUserSettings()->setValue(keyName, ""); // // keyName = "OSCTransmitPort"; // keyName += index; // applicationProperties_.getUserSettings()->setValue(keyName, ""); // // keyName = "OSCTransmitProtocol"; // keyName += index; // applicationProperties_.getUserSettings()->setValue(keyName, (int)0); // } } // Remove all OSC addresses from the send list void MainApplicationController::oscTransmitClearAddresses() { oscTransmitter_.clearAddresses(); // for(int index = 0; index < 16; index++) { // // Go through and clear preferences for recent OSC hosts; // // 16 hosts is a sanity check // // std::string keyName = "OSCTransmitHost"; // keyName += index; // // if(applicationProperties_.getUserSettings()->containsKey(keyName)) { // applicationProperties_.getUserSettings()->setValue(keyName, ""); // // keyName = "OSCTransmitPort"; // keyName += index; // applicationProperties_.getUserSettings()->setValue(keyName, ""); // // keyName = "OSCTransmitProtocol"; // keyName += index; // applicationProperties_.getUserSettings()->setValue(keyName, (int)0); // } // } } // OSC Input (receiver) methods // Enable or disable on the OSC receive, and report is status bool MainApplicationController::oscReceiveEnabled() { return oscReceiveEnabled_; } // Enable method returns true on success (false only if it was // unable to set the port) bool MainApplicationController::oscReceiveSetEnabled(bool enable) { // applicationProperties_.getUserSettings()->setValue("OSCReceiveEnabled", enable); if(enable && !oscReceiveEnabled_) { oscReceiveEnabled_ = true; return oscReceiver_.setPort(oscReceivePort_); } else if(!enable && oscReceiveEnabled_) { oscReceiveEnabled_ = false; return oscReceiver_.setPort(0); } return true; } // Whether the OSC server is running (false means couldn't open port) bool MainApplicationController::oscReceiveRunning() { return oscReceiver_.running(); } // Get the current OSC receive port int MainApplicationController::oscReceivePort() { return oscReceivePort_; } // Set the current OSC receive port (returns true on success) bool MainApplicationController::oscReceiveSetPort(int port) { // applicationProperties_.getUserSettings()->setValue("OSCReceivePort", port); oscReceivePort_ = port; return oscReceiver_.setPort(port); } // OSC handler method bool MainApplicationController::oscHandlerMethod(const char *path, const char *types, int numValues, lo_arg **values, void *data) { std::cout << path << endl; if(!strcmp(path, "/midi/noteon")) { if(touchkeyAutodetecting_ && numValues > 0) { // std::cout << "/midi/noteon\n"; // Found a MIDI note. Look for a unique touch on this pitch class to // determine which octave the keyboard is set to if(types[0] != 'i') return false; // Ill-formed message int midiNote = values[0]->i; if(midiNote < 0 || midiNote > 127) return false; // Go through each octave and see if a touch is present int midiTestNote = midiNote % 12; int count = 0; int lastFoundTouchNote = 0; while(midiTestNote <= 127) { if(keyboardController_.key(midiTestNote) != 0) { if(keyboardController_.key(midiTestNote)->touchIsActive()) { count++; lastFoundTouchNote = midiTestNote; } } midiTestNote += 12; } // We return success if exactly one note had a touch on this pitch class if(count == 1) { int noteDifference = lastFoundTouchNote - midiNote; int currentMinNote = touchkeyController_.lowestMidiNote(); // std::cout << "Found difference of " << noteDifference << std::endl; currentMinNote -= noteDifference; if(currentMinNote >= 0 && currentMinNote <= 127) { touchkeyController_.setLowestMidiNote(currentMinNote); // applicationProperties_.getUserSettings()->setValue("TouchKeysLowestMIDINote", currentMinNote); } touchkeyDeviceStopAutodetecting(); } return false; // Others may still want to handle this message } } else if(!strcmp(path, "/control/calibration/start")) { std::cout << "Beginning calibration" << std::endl; startCalibration(0); } else if(!strcmp(path, "/control/calibration/finish")) { std::cout << "Finishing calibration..."; finishCalibration(); } else if(!strcmp(path, "/control/calibration/load")) { if(types[0] != 's') { return false; // Ill-formed message } const std::string filename = std::string(&values[0]->s); std::cout << "Loading calibration from '" << filename << "'... "; if (loadCalibration(filename)) { std::cout << "Successful" << std::endl; } else { std::cout << "Failed" << std::endl; } } else if(!strcmp(path, "/control/calibration/save")) { if(types[0] != 's') { return false; // Ill-formed message } const std::string filename = std::string(&values[0]->s); std::cout << "Saving calibration to '" << filename << "' ... "; if (saveCalibration(filename)) { std::cout << "Successful" << std::endl; } else { std::cout << "Failed" << std::endl; } } return false; } // Save the current settings to an XML file // Returns true on success bool MainApplicationController::savePresetToFile(const char *filename) { // File outputFile(filename); // // return savePresetHelper(outputFile); return true; } // Load settings from a saved XML file // Returns true on success bool MainApplicationController::loadPresetFromFile(const char *filename) { // File inputFile(filename); // // return loadPresetHelper(inputFile); return true; } #ifndef TOUCHKEYS_NO_GUI // Present the user with a Save dialog and then save the preset bool MainApplicationController::savePresetWithDialog() { FileChooser myChooser ("Save preset...", File::nonexistent, // File::getSpecialLocation (File::userHomeDirectory), "*.tkpreset"); if(myChooser.browseForFileToSave(true)) { File outputFile(myChooser.getResult()); return savePresetHelper(outputFile); } // User clicked cancel... return true; } // Present the user with a Load dialog and then save the preset bool MainApplicationController::loadPresetWithDialog() { FileChooser myChooser ("Select a preset...", File::nonexistent, // File::getSpecialLocation (File::userHomeDirectory), "*.tkpreset"); if(myChooser.browseForFileToOpen()) { return loadPresetHelper(myChooser.getResult()); } // User clicked cancel... return true; } #endif //bool MainApplicationController::loadPresetHelper(File const& inputFile) { //// if(!inputFile.existsAsFile()) //// return false; //// //// // Load the XML element from the file and check that it is valid //// XmlDocument document(inputFile); //// ScopedPointer<XmlElement> mainElement(document.getDocumentElement()); //// //// if(mainElement == 0) //// return false; //// if(mainElement->getTagName() != "TouchKeysPreset") //// return false; //// XmlElement *segmentsElement = mainElement->getChildByName("KeyboardSegments"); //// if(segmentsElement == 0) //// return false; //// //// // Load the preset from this element //// bool result = midiInputController_.loadSegmentPreset(segmentsElement); //// //// // Loading a preset won't set standalone mode; so re-enable it when finished //// // if needed //// if(touchkeyStandaloneModeEnabled_) { //// midiTouchkeysStandaloneModeEnable(); //// } //// //// return result; //} //bool MainApplicationController::savePresetHelper(File& outputFile) { //// XmlElement mainElement("TouchKeysPreset"); //// mainElement.setAttribute("format", "0.1"); //// //// XmlElement* segmentsElement = midiInputController_.getSegmentPreset(); //// mainElement.addChildElement(segmentsElement); //// //// bool result = mainElement.writeToFile(outputFile, ""); //// //// if(result) { //// applicationProperties_.getUserSettings()->setValue("LastSavedPreset", outputFile.getFullPathName()); //// } //// //// return result; //} // Clear the current preset and restore default settings void MainApplicationController::clearPreset() { // midiInputController_.removeAllSegments(); // //midiOutputController_.disableAllPorts(); // segmentCounter_ = 0; // // // Re-add a new segment, starting at 0 // midiSegmentAdd(); } // Whether to automatically start the TouchKeys on startup bool MainApplicationController::getPrefsAutoStartTouchKeys() { // if(!applicationProperties_.getUserSettings()->containsKey("StartupStartTouchKeys")) // return false; // return applicationProperties_.getUserSettings()->getBoolValue("StartupStartTouchKeys"); return true; } void MainApplicationController::setPrefsAutoStartTouchKeys(bool autoStart) { // applicationProperties_.getUserSettings()->setValue("StartupStartTouchKeys", autoStart); } // Whether to automatically detect the TouchKeys octave when they start bool MainApplicationController::getPrefsAutodetectOctave() { // if(!applicationProperties_.getUserSettings()->containsKey("StartupAutodetectTouchKeysOctave")) // return false; // return applicationProperties_.getUserSettings()->getBoolValue("StartupAutodetectTouchKeysOctave"); return true; } void MainApplicationController::setPrefsAutodetectOctave(bool autoDetect) { // applicationProperties_.getUserSettings()->setValue("StartupAutodetectTouchKeysOctave", autoDetect); } // Which preset (if any) to load at startup void MainApplicationController::setPrefsStartupPresetNone() { // applicationProperties_.getUserSettings()->setValue("StartupPreset", "__none__"); } bool MainApplicationController::getPrefsStartupPresetNone() { // // By default, no prefs means no preset // if(!applicationProperties_.getUserSettings()->containsKey("StartupPreset")) // return true; // if(applicationProperties_.getUserSettings()->getValue("StartupPreset") == "__none__") // return true; // return false; return true; } void MainApplicationController::setPrefsStartupPresetVibratoPitchBend() { // applicationProperties_.getUserSettings()->setValue("StartupPreset", "__vib_pb__"); } bool MainApplicationController::getPrefsStartupPresetVibratoPitchBend() { // if(!applicationProperties_.getUserSettings()->containsKey("StartupPreset")) // return false; // if(applicationProperties_.getUserSettings()->getValue("StartupPreset") == "__vib_pb__") // return true; // return false; return true; } void MainApplicationController::setPrefsStartupPresetLastSaved() { // applicationProperties_.getUserSettings()->setValue("StartupPreset", "__last__"); } bool MainApplicationController::getPrefsStartupPresetLastSaved() { // if(!applicationProperties_.getUserSettings()->containsKey("StartupPreset")) // return false; // if(applicationProperties_.getUserSettings()->getValue("StartupPreset") == "__last__") // return true; // return false; return true; } void MainApplicationController::setPrefsStartupPreset(std::string const& path) { // applicationProperties_.getUserSettings()->setValue("StartupPreset", path); } std::string MainApplicationController::getPrefsStartupPreset() { // if(!applicationProperties_.getUserSettings()->containsKey("StartupPreset")) // return ""; // return applicationProperties_.getUserSettings()->getValue("StartupPreset"); return std::string(); } // Reset application preferences to defaults void MainApplicationController::resetPreferences() { // TODO: reset settings now, not after restart // applicationProperties_.getUserSettings()->clear(); setPrefsStartupPresetVibratoPitchBend(); setPrefsAutodetectOctave(true); } // Load the current devices from a global preferences file void MainApplicationController::loadApplicationPreferences(){ // PropertiesFile *props = applicationProperties_.getUserSettings(); // // if(props == 0) // return; // // // A few first-time defaults if the properties file is missing // if(props->getAllProperties().size() == 0) { // resetPreferences(); // } // // // Load TouchKeys settings // if(props->containsKey("TouchKeysDevice")) { // // TODO // } // if(props->containsKey("TouchKeysLowestMIDINote")) { // int note = props->getIntValue("TouchKeysLowestMIDINote"); // if(note >= 0 && note <= 127) // touchkeyDeviceSetLowestMidiNote(note); // } // // // Load MIDI input settings // if(props->containsKey("MIDIInputPrimary")) { // std::string deviceName = props->getValue("MIDIInputPrimary"); // if(deviceName == "__standalone__") { // midiTouchkeysStandaloneModeEnable(); // } // else { // int index = midiInputController_.indexOfDeviceNamed(deviceName); // // cout << "primary input id " << index << " name " << deviceName << endl; // if(index >= 0) // enableMIDIInputPort(index, true); // } // } // if(props->containsKey("MIDIInputAuxiliary")) { // std::string deviceName = props->getValue("MIDIInputAuxiliary"); // int index = midiInputController_.indexOfDeviceNamed(deviceName); // // cout << "aux input id " << index << " name " << deviceName << endl; // if(index >= 0) // enableMIDIInputPort(index, false); // } // // // MIDI output settings are loaded when segments are created // // // OSC settings // if(props->containsKey("OSCTransmitEnabled")) { // bool enable = props->getBoolValue("OSCTransmitEnabled"); // oscTransmitSetEnabled(enable); // } // if(props->containsKey("OSCTransmitRawDataEnabled")) { // bool enable = props->getBoolValue("OSCTransmitRawDataEnabled"); // oscTransmitSetRawDataEnabled(enable); // } // // for(int i = 0; i < 16; i++) { // std::string keyName = "OSCTransmitHost"; // std::string host, port; // int protocol = LO_UDP; // // keyName += i; // if(props->containsKey(keyName)) { // host = props->getValue(keyName); // } // else // continue; // // keyName = "OSCTransmitPort"; // keyName += i; // if(props->containsKey(keyName)) { // port = props->getValue(keyName); // } // else // continue; // // keyName = "OSCTransmitProtocol"; // keyName += i; // if(props->containsKey(keyName)) { // protocol = props->getIntValue(keyName); // } // // okay to go ahead without protocol; use default // // // Check for validity // if(host != "" && port != "" && (protocol == LO_UDP || protocol == LO_TCP)) { // oscTransmitter_.addAddress(host.toUTF8(), port.toUTF8(), protocol); // } // } // // if(props->containsKey("OSCReceiveEnabled")) { // bool enable = props->getBoolValue("OSCReceiveEnabled"); // oscReceiveSetEnabled(enable); // } // if(props->containsKey("OSCReceivePort")) { // int port = props->getIntValue("OSCReceivePort"); // if(port >= 1 && port <= 65535) // oscReceiveSetPort(port); // } // } // Load the MIDI output device for a given zone void MainApplicationController::loadMIDIOutputFromApplicationPreferences(int zone) { // PropertiesFile *props = applicationProperties_.getUserSettings(); // // std::string keyName = "MIDIOutputZone"; // keyName += zone; // // if(props->containsKey(keyName)) { // std::string output = props->getValue(keyName); // if(output.startsWith("__virtual__")) { //#ifndef JUCE_WINDOWS // // Open virtual port with the name that follows // std::string virtualPortName = output.substring(11); // length of "__virtual__" // midiOutputController_.enableVirtualPort(zone, virtualPortName.toUTF8()); //#endif // } // else { // std::string deviceName = props->getValue(keyName); // int index = midiOutputController_.indexOfDeviceNamed(deviceName); // // cout << "zone " << zone << " id " << index << " name " << deviceName << endl; // if(index >= 0) // enableMIDIOutputPort(zone, index); // } // } } #ifdef ENABLE_TOUCHKEYS_SENSOR_TEST // Start testing the TouchKeys sensors. Returns true on success. bool MainApplicationController::touchkeySensorTestStart(const char *path, int firstKey) { #ifndef TOUCHKEYS_NO_GUI if(path == 0 || firstKey < touchkeyController_.lowestMidiNote()) return false; if(keyboardTesterDisplay_ != 0) return true; // First, close the existing device which stops the data autogathering closeTouchkeyDevice(); // Now reopen the TouchKeys device if(!touchkeyController_.openDevice(path)) { touchkeyErrorMessage_ = "Failed to open"; touchkeyErrorOccurred_ = true; return false; } // Next, see if a real TouchKeys device is present at the other end if(!touchkeyDeviceCheckForPresence()) { touchkeyErrorMessage_ = "Device not recognized"; touchkeyErrorOccurred_ = true; return false; } // Now, create the KeyboardTesterDisplay object which will handle processing // raw data and displaying the results. Also a new window to hold it. keyboardTesterDisplay_ = new KeyboardTesterDisplay(*this, keyboardController_); keyboardTesterDisplay_->setKeyboardRange(touchkeyController_.lowestKeyPresentMidiNote(), touchkeyController_.highestMidiNote()); keyboardTesterWindow_ = new GraphicsDisplayWindow("TouchKeys Sensor Test", *keyboardTesterDisplay_); // Start raw data gathering from the indicated key (converted to octave/key notation) int keyOffset = firstKey - touchkeyController_.lowestMidiNote(); if(keyOffset < 0) // Shouldn't happen... keyOffset = 0; if(!touchkeyController_.startRawDataCollection(keyOffset / 12, keyOffset % 12, 3, 2)) { touchkeyErrorMessage_ = "Failed to start"; touchkeyErrorOccurred_ = true; return false; } keyboardTesterWindow_->addToDesktop(keyboardTesterWindow_->getDesktopWindowStyleFlags() | ComponentPeer::windowHasCloseButton); keyboardTesterWindow_->setVisible(true); keyboardTesterWindow_->toFront(true); touchkeyErrorMessage_ = ""; touchkeyErrorOccurred_ = false; return true; #endif } // Stop testing the TouchKeys sensors void MainApplicationController::touchkeySensorTestStop() { #ifndef TOUCHKEYS_NO_GUI if(keyboardTesterDisplay_ == 0) return; // Stop raw data gathering first and close device touchkeyController_.stopAutoGathering(); touchkeyController_.closeDevice(); // Delete the testing objects delete keyboardTesterWindow_; delete keyboardTesterDisplay_; keyboardTesterWindow_ = 0; keyboardTesterDisplay_ = 0; touchkeyErrorMessage_ = ""; touchkeyErrorOccurred_ = false; #endif } // Is the sensor test running? bool MainApplicationController::touchkeySensorTestIsRunning() { #ifdef TOUCHKEYS_NO_GUI return false; #else return (keyboardTesterDisplay_ != 0); #endif } // Set the current key that is begin tested void MainApplicationController::touchkeySensorTestSetKey(int key) { #ifndef TOUCHKEYS_NO_GUI if(keyboardTesterDisplay_ == 0 || key < touchkeyController_.lowestMidiNote()) return; int keyOffset = key - touchkeyController_.lowestMidiNote(); if(keyOffset < 0) // Shouldn't happen... keyOffset = 0; touchkeyController_.rawDataChangeKeyAndMode(keyOffset / 12, keyOffset % 12, 3, 2); #endif } // Reset the testing state to all sensors off void MainApplicationController::touchkeySensorTestResetState() { #ifndef TOUCHKEYS_NO_GUI if(keyboardTesterDisplay_ == 0) return; for(int key = 0; key < 128; key++) keyboardTesterDisplay_->resetSensorState(key); #endif } #endif // ENABLE_TOUCHKEYS_SENSOR_TEST #ifdef ENABLE_TOUCHKEYS_FIRMWARE_UPDATE // Put TouchKeys controller board into bootloader mode, for receiving firmware updates // (supplied by a different utility) bool MainApplicationController::touchkeyJumpToBootloader(const char *path) { // First, close the existing device which stops the data autogathering closeTouchkeyDevice(); // Now reopen the TouchKeys device if(!touchkeyController_.openDevice(path)) { touchkeyErrorMessage_ = "Failed to open"; touchkeyErrorOccurred_ = true; return false; } touchkeyController_.jumpToBootloader(); // Set an "error" condition to display this message, and because // after jumping to bootloader mode, the device will not open properly // until it has been reset. touchkeyErrorMessage_ = "Firmware update mode"; touchkeyErrorOccurred_ = true; return true; } #endif // ENABLE_TOUCHKEYS_FIRMWARE_UPDATE // Return the name of a MIDI note given its number std::string MainApplicationController::midiNoteName(int noteNumber) { if(noteNumber < 0 || noteNumber > 127) return ""; char name[6]; #ifdef _MSC_VER _snprintf_s(name, 6, _TRUNCATE, "%s%d", kNoteNames[noteNumber % 12], (noteNumber / 12) - 1); #else snprintf(name, 6, "%s%d", kNoteNames[noteNumber % 12], (noteNumber / 12) - 1); #endif return name; } // Get the number of a MIDI note given its name int MainApplicationController::midiNoteNumberForName(std::string const& name) { // Any valid note name will have at least two characters if(name.length() < 2) return -1; // Find the pitch class first, then the octave int pitchClass = -1; int startIndex = 1; if(!name.compare(0, 2, "C#") || !name.compare(0, 2, "c#") || !name.compare(0, 2, "Db") || !name.compare(0, 2, "db")) { pitchClass = 1; startIndex = 2; } else if(!name.compare(0, 2, "D#") || !name.compare(0, 2, "d#") || !name.compare(0, 2, "Eb") || !name.compare(0, 2, "eb")) { pitchClass = 3; startIndex = 2; } else if(!name.compare(0, 2, "F#") || !name.compare(0, 2, "f#") || !name.compare(0, 2, "Gb") || !name.compare(0, 2, "gb")){ pitchClass = 6; startIndex = 2; } else if(!name.compare(0, 2, "G#") || !name.compare(0, 2, "g#") || !name.compare(0, 2, "Ab") || !name.compare(0, 2, "ab")){ pitchClass = 8; startIndex = 2; } else if(!name.compare(0, 2, "A#") || !name.compare(0, 2, "a#") || !name.compare(0, 2, "Bb") || !name.compare(0, 2, "bb")){ pitchClass = 10; startIndex = 2; } else if(!name.compare(0, 1, "C") || !name.compare(0, 1, "c")) pitchClass = 0; else if(!name.compare(0, 1, "D") || !name.compare(0, 1, "d")) pitchClass = 2; else if(!name.compare(0, 1, "E") || !name.compare(0, 1, "e")) pitchClass = 4; else if(!name.compare(0, 1, "F") || !name.compare(0, 1, "f")) pitchClass = 5; else if(!name.compare(0, 1, "G") || !name.compare(0, 1, "g")) pitchClass = 7; else if(!name.compare(0, 1, "A") || !name.compare(0, 1, "a")) pitchClass = 9; else if(!name.compare(0, 1, "B") || !name.compare(0, 1, "b")) pitchClass = 11; if(pitchClass < 0) // No valid note found return -1; int octave = atoi(name.substr(startIndex).c_str()); int noteNumber = (octave + 1) * 12 + pitchClass; if(noteNumber < 0 || noteNumber > 127) return -1; return noteNumber; } // ***** External OSC Control ***** bool MainApplicationOSCController::oscHandlerMethod(const char *path, const char *types, int numValues, lo_arg **values, void *data) { if(!strncmp(path, "/control", 8)) { // OSC messages that start with /touchkeys/control are used to control the operation of the // software and mappings // First check if the message belongs to one of the segments if(!strncmp(path, "/control/segment", 16) && strlen(path) > 16) { // Pick out which segment based on the following number: e.g. /control/segment0/... std::string subpath(&path[16]); unsigned int separatorLoc = subpath.find_first_of('/'); if(separatorLoc == std::string::npos || separatorLoc == subpath.length() - 1) { // Malformed input (no slash or it's the last character): ignore return false; } std::stringstream segmentNumberSStream(subpath.substr(0, separatorLoc)); int segmentNumber = 0; segmentNumberSStream >> segmentNumber; if(segmentNumber < 0) // Unknown segment number return false; // Pass this message onto the corresponding segment in MidiInputController // If the segment doesn't exist, it will return false. All further handling is // done within MidiInputController with its corresponding mutex locked so // the segments can't change while this message is processed. subpath = subpath.substr(separatorLoc); // Start at the '/' if(subpath == "/set-midi-out") { // Special case for setting the MIDI output, which is done in the main controller // rather than in the segment itself if(numValues >= 1) { if(types[0] == 'i') { MidiKeyboardSegment* segment = controller_.midiInputController_.segment(segmentNumber); if(segment == 0) oscControlTransmitResult(1); // Failure response else { if(values[0]->i < 0) { // Negative value means disable controller_.disableMIDIOutputPort(segment->outputPort()); } else { controller_.enableMIDIOutputPort(segment->outputPort(), values[0]->i); } oscControlTransmitResult(0); } } #ifndef JUCE_WINDOWS else if(types[0] == 's') { MidiKeyboardSegment* segment = controller_.midiInputController_.segment(segmentNumber); if(segment == 0) oscControlTransmitResult(1); // Failure response else { if(!strcmp(&values[0]->s, "virtual")) { char st[20]; snprintf(st, 20, "TouchKeys %d", segment->outputPort()); controller_.enableMIDIOutputVirtualPort(segment->outputPort(), st); oscControlTransmitResult(0); } } } #endif } } else { // All other segment messages are handled within MidiKeyboardSegment OscMessage* response = controller_.midiInputController_.oscControlMessageForSegment(segmentNumber, subpath.c_str(), types, numValues, values, data); if(response != 0) { // Add the right prefix to the response. If it is a simple result status, // then give it the generic prefix. Otherwise add the zone beforehand if(!strcmp(response->path(), "/result")) response->prependPath("/touchkeys/control"); else { char prefix[28]; #ifdef _MSC_VER _snprintf_s(prefix, 28, _TRUNCATE, "/touchkeys/control/segment%d", segmentNumber); #else snprintf(prefix, 28, "/touchkeys/control/segment%d", segmentNumber); #endif response->prependPath(prefix); } // Send the message and free it controller_.oscTransmitter_.sendMessage(response->path(), response->type(), response->message()); delete response; } } } else if(!strcmp(path, "/control/preset-load")) { // Load preset from file // Argument 0 is the path to the file if(numValues > 0) { if(types[0] == 's') { bool result = controller_.loadPresetFromFile(&values[0]->s); // Send back a message on success/failure oscControlTransmitResult(result == true ? 0 : 1); return true; } else if(types[0] == 'i') { // TODO: take a second form of the message which has a numerical // input for selecting presets } } return false; } else if(!strcmp(path, "/control/preset-save")) { // Save preset to file if(numValues > 0) { if(types[0] == 's') { bool result = controller_.savePresetToFile(&values[0]->s); // Send back a message on success/failure oscControlTransmitResult(result == true ? 0 : 1); return true; } else if(types[0] == 'i') { // TODO: take a second form of the message which has a numerical // input for selecting presets } } return false; } else if(!strcmp(path, "/control/preset-clear")) { // Clear everything in preset controller_.clearPreset(); oscControlTransmitResult(0); return true; } else if(!strcmp(path, "/control/tk-list-devices")) { // Return a list of TouchKeys devices OscMessage *response = OscTransmitter::createMessage("/touchkeys/control/tk-list-devices/result", "i", controller_.availableTouchkeyDevices().size(), LO_ARGS_END); vector<std::string> devices = controller_.availableTouchkeyDevices(); vector<string>::iterator it; for(it = devices.begin(); it != devices.end(); ++it) { lo_message_add_string(response->message(), it->c_str()); } controller_.oscTransmitter_.sendMessage(response->path(), response->type(), response->message()); delete response; return true; } else if(!strcmp(path, "/control/tk-start")) { // Start the TouchKeys device with the given path if(numValues > 0) { if(types[0] == 's') { char *device = &values[0]->s; bool result = controller_.touchkeyDeviceStartupSequence(device); oscControlTransmitResult(result == true ? 0 : 1); return true; } } } else if(!strcmp(path, "/control/tk-stop")) { // Stop TouchKeys if(controller_.touchkeyDeviceIsOpen()) { controller_.closeTouchkeyDevice(); oscControlTransmitResult(0); } else { // Not running, can't close oscControlTransmitResult(1); } return true; } else if(!strcmp(path, "/control/tk-set-lowest-midi-note")) { // Set TouchKeys octave such that the lowest key is at the // given note. Only 'C' notes are valid. if(numValues > 0) { if(types[0] == 'i') { int note = values[0]->i; if(note % 12 == 0 && note >= 12 && note < 127) { controller_.touchkeyDeviceSetLowestMidiNote(note); oscControlTransmitResult(0); } else { // Invalid note oscControlTransmitResult(1); } return true; } } } else if(!strcmp(path, "/control/tk-autodetect")) { // Autodetect lowest TouchKeys octave controller_.touchkeyDeviceAutodetectLowestMidiNote(); oscControlTransmitResult(0); return true; } else if(!strcmp(path, "/control/tk-autodetect-stop")) { // Stop autodetecting TouchKeys octave controller_.touchkeyDeviceStopAutodetecting(); oscControlTransmitResult(0); return true; } else if(!strcmp(path, "/control/list-midi-in")) { // List available MIDI input devices std::vector<std::pair<int, std::string> > midiInputs = controller_.availableMIDIInputDevices(); OscMessage *response = OscTransmitter::createMessage("/list-midi-in/result", "i", midiInputs.size(), LO_ARGS_END); std::vector<std::pair<int, std::string> >::iterator it; for(it = midiInputs.begin(); it != midiInputs.end(); ++it) { lo_message_add_int32(response->message(), it->first); lo_message_add_string(response->message(), it->second.c_str()); } controller_.oscTransmitter_.sendMessage(response->path(), response->type(), response->message()); delete response; return true; } else if(!strcmp(path, "/control/list-midi-out")) { // List available MIDI output devices std::vector<std::pair<int, std::string> > midiOutputs = controller_.availableMIDIOutputDevices(); OscMessage *response = OscTransmitter::createMessage("/list-midi-out/result", "i", midiOutputs.size(), LO_ARGS_END); std::vector<std::pair<int, std::string> >::iterator it; for(it = midiOutputs.begin(); it != midiOutputs.end(); ++it) { lo_message_add_int32(response->message(), it->first); lo_message_add_string(response->message(), it->second.c_str()); } controller_.oscTransmitter_.sendMessage(response->path(), response->type(), response->message()); delete response; return true; } else if(!strcmp(path, "/control/set-midi-in-keyboard")) { // Set MIDI input device for keyboard if(numValues > 0) { if(types[0] == 'i') { if(controller_.midiTouchkeysStandaloneModeIsEnabled()) controller_.midiTouchkeysStandaloneModeDisable(); if(values[0]->i < 0) { // Negative means disable controller_.disablePrimaryMIDIInputPort(); } else { controller_.enableMIDIInputPort(values[0]->i, true); } oscControlTransmitResult(0); return true; } else if(types[0] == 's') { if(!strncmp(&values[0]->s, "stand", 5)) { // Enable TouchKeys standalone mode in place of MIDI input controller_.disablePrimaryMIDIInputPort(); controller_.midiTouchkeysStandaloneModeEnable(); oscControlTransmitResult(0); return true; } } } } else if(!strcmp(path, "/control/set-midi-in-aux")) { // Set MIDI auxiliary input device if(numValues > 0) { if(types[0] == 'i') { controller_.disableAllMIDIInputPorts(true); if(values[0]->i >= 0) { // Negative values mean leave the port disabled controller_.enableMIDIInputPort(values[0]->i, false); } oscControlTransmitResult(0); return true; } } } else if(!strcmp(path, "/control/add-segment")) { // Add a new keyboard segment if(controller_.midiSegmentsCount() >= 8) { // Max of 8 segments possible oscControlTransmitResult(1); } else { controller_.midiSegmentAdd(); oscControlTransmitResult(0); } return true; } else if(!strcmp(path, "/control/delete-segment")) { // Remove a keyboard segment by number if(numValues > 0) { if(types[0] == 'i') { int segmentNumber = values[0]->i; bool result = controller_.midiInputController_.removeSegment(segmentNumber); oscControlTransmitResult(result == true ? 0 : 1); return true; } } } } return false; } // Send back an OSC message to indicate the result of a control command void MainApplicationOSCController::oscControlTransmitResult(int result) { controller_.oscTransmitter_.sendMessage("/touchkeys/control/result", "i", result, LO_ARGS_END); }